#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exec/exec.h>
#include <exec/execbase.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <proto/exec.h>
#include <proto/dos.h>

#include <iec/iec.h>

//----------------------------------------
//IECSave 1.0
//
//Writes a file to the disk inserted in
//the 1541 drive.
//
//----------------------------------------


struct iecbase *IECBase;

char Version[]="$VER:IECSave 1.0 (01.09.96) by Fabrizio Farenga";
UWORD BlockSize;
int c;
char* SourceName;	//File to read (from AmigaDos)
char* DestName;		//File to write (to 1541)


FILE *fp;	//File di uscita

struct RDArgs *rda;
LONG argv[3]={0,0,0};
char device=8;	//Defalt device #

//******************************************
// Send a null-terminated string to the 1541
//******************************************
void SendString(char* string)
{
int t;
for (t=0;string[t]!=0;t++) CIOut(string[t]); 
}

void ReadFile(void)
{

fp=fopen(SourceName,"rb");	//Open the file to read (from AmigaDos)

	if (fp!=0)
	{
	printf ("\n");

	//SAVE "<DestName>",<device>,1
	Listen(device);
	Second(CMD_OPEN+1);


	if (IECBase->iec_ST!=ST_OK)
		{
		printf ("?DEVICE NOT PRESENT\n\n");
		return;
		}


	//Send the filename
	SendString(DestName);
	UnListen();


	//Send data
	Listen(device);
	Second(CMD_DATA+1);

		while (IECBase->iec_ST==ST_OK)
		{
		c=getc(fp);	//Read a byte from AmigaDos until EOF
			if (c==EOF) break;
		CIOut(c);	//Write the byte to 1541
			if (IECBase->iec_ST!=ST_OK)	//If error writing...
			{
			printf ("?SAVE ERROR\n\n");
			break;
			}
		}

	UnListen();

	Listen(device);	//CLOSE
	Second(CMD_CLOSE+1);
	UnListen();


	fclose(fp);
	}
	else
	{
	printf ("Can't open %s for input",SourceName);
	}
}


void main(void)
{


if ((rda = ReadArgs("FROM/A,TO,DEVICE/N",argv,NULL)) != NULL)
	{
	if (argv[0]!=0) SourceName=(char*)argv[0];	//Source filename

	if (argv[1]!=0) DestName=(char *)argv[1];	//Destination filename
	else DestName=(char *)argv[0];				//If none, use the source name

	if (argv[2]!=0) device=*(LONG *)argv[2];	//Device (if none, device = 8)
	}
else
	{
	printf ("Required argument missing\n\n");
	return;
	}


if ((device<4)||(device>30))
	{
	printf ("\n?DEVICE NOT PRESENT\n\n");
	return;
	}

IECBase = (struct iecbase*)OpenLibrary("iec.library",0L);

if (IECBase!=0)
	{

	ReadFile();

	CloseLibrary((struct Library*)IECBase);
	}
else
	{
	printf ("Can't open iec.library\n");
	return;
	}

	if (rda!=0) FreeArgs(rda);

}
