#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.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>

//----------------------------------------
//IECDir 1.1
//
//Displays the directory of the disk inserted
//the 1541 drive.
//
//----------------------------------------

struct iecbase *IECBase;

char Version[]="$VER:IECDir 1.1 (06.10.96) by Fabrizio Farenga";
UWORD BlockSize;
unsigned char c1,c2;


struct RDArgs *rda;
LONG argv[1]={0};
char device=8;	//Default device #

/* Break Handler */
int brk(void)
{
/* On break, close all */

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

CloseLibrary((struct Library*)IECBase);

printf ("\nBreak received.\n\n");
return (1);
}


void ReadDir(void)
{
printf ("\n");

//Ask for the directory (LOAD"$",device)
Listen(device);
Second(CMD_OPEN+0);

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

Talk(device);	//Start receiving data
TkSA(CMD_DATA+0);

ACPtr();	//Ignore load-address
ACPtr();

	while (IECBase->iec_ST==ST_OK)
	{
	ACPtr();	//Ignore line-start 1st byte
	if (IECBase->iec_ST!=ST_OK) break;
	ACPtr();	//Ignore line-start 2nd byte
	if (IECBase->iec_ST!=ST_OK) break;

	c1=ACPtr();	//Read the block size low-byte
	if (IECBase->iec_ST!=ST_OK) break;
	c2=ACPtr(); //Read the block size hi-byte
	if (IECBase->iec_ST!=ST_OK) break;

	//Print the block size
	BlockSize=c1+(c2<<8);
	printf ("%d ",BlockSize);

		//Get the first character of the line
		c1=ACPtr();
		do
		{

			//If character is 0x12 (REVSON), turn on the REVERSE-VIDEO mode
			if (c1!=0x12) printf ("%c",c1);
			else printf ("[;7m");

		//Get the next character
		c1=ACPtr();
		if (IECBase->iec_ST!=ST_OK) break;
		} while (c1!=0);	//Wait for end of line (NULL)
	printf ("[;27m\n");	//Turn off the REVERSE-VIDEO mode
	}

UnTalk();

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

printf ("\n");
}


void main(void)
{

if ((rda = ReadArgs("Device/N",argv,NULL)) != NULL)
	{
	if (argv[0]!=0) device=*(LONG *)argv[0];	//Get the device number
	FreeArgs(rda);
	}

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

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

if (IECBase!=0)
	{

	/*Set the break handler*/
	onbreak(&brk);

	ReadDir();

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