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

#include <iec/iec.h>

//----------------------------------------
//64Unit 1.0
//
//Change the device number of drive 1541
//
//----------------------------------------


struct iecbase *IECBase;

struct RDArgs *rda;
LONG argv[2]={0,0};
char device=8;		//Default device number
char newdevice=8;	//New device number
char string[40];	//Command string buffer


char Version[]="$VER:64Unit 1.0 (01.09.96) by Fabrizio Farenga";

//******************************************
// 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 ChangeUnit(void)
{
	//Open the command channel
	//OPEN 15,8,15
	Listen(device);
	Second(CMD_OPEN+15);

	if (IECBase->iec_ST==ST_OK)
		{
		UnListen();

		Listen(device);
		Second(CMD_DATA+15);

		//Send the Memory-Write Command.
		sprintf(string,"M-W");

		SendString(string);

		//Send the memory address of the device number (in the 1541 RAM)
		CIOut(119);
		CIOut(0);

		//Send the number of bytes to change (2)
		CIOut(2);

		//Write the newdevice number (for Listen and Talk)
		CIOut(newdevice+32);
		CIOut(newdevice+64);

		UnListen();


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

		printf ("Device %d is now known as %d\n\n",device,newdevice);

		}
	else
		{
		printf ("\n?DEVICE NOT PRESENT\n\n");
		}

}


void main(void)
{

if ((rda = ReadArgs("NEWDEVICE/N/A,OLDDEVICE/N",argv,NULL)) != NULL)
	{
	if (argv[0]!=0) newdevice=*(LONG *)argv[0];	//New device number
	if (argv[1]!=0) device=*(LONG *)argv[1];	//Old device number
	}
	else
	{
	printf ("Required argument missing!\n\n");
	return;
	}

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

if (newdevice<4)
	{
	printf ("\nArgumento out of range\n\n");
	return;
	}

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

if (IECBase!=0)
	{

	ChangeUnit();

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

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


}
