#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>

//----------------------------------------
//IECLoad 1.0
//
//Reads a file from the disk inserted in
//the 1541 drive, and writes it to AmigaDos.
//
//----------------------------------------


struct iecbase *IECBase;

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


FILE *fp;	//Output file

struct RDArgs *rda;
LONG argv[3]={0,0,0};
char device=8;	//Default 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(DestName,"wb");	//Open file to write (AmigaDos)

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


	//LOAD "<SourceName>",<device>
	Listen(device);
	Second(CMD_OPEN+0);


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


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

	//Receive data
	Talk(device);
	TkSA(CMD_DATA+0);

		while (IECBase->iec_ST==ST_OK)
		{
		c=ACPtr();					//Read a byte from 1541
			if (IECBase->iec_ST==ST_READ_TIMEOUT)	//On file not found break.
			{
			printf ("?FILE NOT FOUND ERROR\n\n");
			break;
			}
		if (EOF==putc(c,fp)) break;	//Write the byte to AmigaDos
		if (IECBase->iec_ST!=ST_OK) break;	//On error or EOF break
		}

	UnTalk();

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

	fclose(fp);
	}
}


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)
	{
	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);

}