/* Compile with HiTech C for CP/M-80 v3.09 */

#include <cpm.h>
#include <stddef.h>
#include <ctype.h>
#include <stat.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h> 
#include <unixio.h>

char inp(unsigned port);

void outp(unsigned, unsigned data);


void Exit(int code, char * message1, char * message2)
{
	if (message1 !=0) 
		{
		fprintf (stderr,"\n   %s", message1);
		if (message2 !=0) fprintf (stderr," %s", message2);
		fprintf (stderr,"\n");
		}
	if ( code ==1 ) 
		{
		fprintf (stderr,"\n    Usage: dload [-b|t] <filename> <cr>\n");
		};
	exit (code);
}

int main(int argc, char * argv[], char * env[])
{
FILE *fp;

int cntz;
int InByte;
int fd;
int RecCnt;
int option;
int i;
int ISZ;
char *fn;

fn = NULL;
option = 0; /* 0= binary 1= text */

printf("\n Dload Version 2.1 for CPM on Z80 Emulator\n");

for (i = 1; i < argc; i++)
{
	if (argv[i][0] == '-')
	{
		if ( (argv[i][1] == 't') || (argv[i][1] == 'T') )
			option=1;
		else if ( (argv[i][1] == 'b') || (argv[i][1] == 'B') )
			option=0;
		else
			Exit(1,0,0);
	}
	else if (fn)
		Exit(1,0,0);
	else
		fn = argv[i];
}			
if (argc < 2 || !fn )
{
	Exit(1,0,0);
}

outp(0xa1,0xff); /* rewind */

if (inp(0xa1)==0)
{
   Exit(2,"No Dload file open",0);
}
if( (fd = open(fn,0))!=-1 )
{
   close(fd);
   printf("\nFile Exists - Overwrite? (Y or N) - ");
   InByte=getche();
   if ( (InByte != 'Y') && (InByte != 'y' ) ) Exit(0,0,0);
}

if( (fp = fopen(fn,"wb"))==NULL ) 	
{
   Exit(3,"Can't open ",fn);
}

if (option==0)
{
	printf("\n   Downloading as Binary...");

	cntz=0x80;
	RecCnt=0;

	while (inp(0xa1)==1)
	{
		InByte=inp(0xa0);
		if (inp(0xa1)==1) 
		{
	 	fputc(InByte,fp);
	 	cntz--;
	 	if (cntz==0){ cntz=0x80; RecCnt++; }
		};
	}
	while (cntz !=0 && cntz !=0x80) 
	{
 	fputc(0x1a,fp); cntz--; 
 	if (cntz==0)RecCnt++;
	}
}
if (option==1)
{
	printf("\n   Downloading as Text...");

	cntz=0x80;
	RecCnt=0;
	InByte=0;
	ISZ=0;

	while (inp(0xa1)==1 && InByte!=0x1a)
	{
		InByte=inp(0xa0);
		if (inp(0xa1)==1) 
		{
		ISZ=(InByte==0x1a);
	 	fputc(InByte,fp);
	 	cntz--;
	 	if (cntz==0){ cntz=0x80; RecCnt++; }
		};
	}
	if (ISZ)
	{
	while (cntz !=0 && cntz !=0x80) 
		{
 		fputc(0x1a,fp); cntz--; 
 		if (cntz==0)RecCnt++;
		}
	}
	else
	{
	cntz=0x80;
	while (cntz !=0 ) 
		{
 		fputc(0x1a,fp); cntz--; 
 		if (cntz==0)RecCnt++;
		}
	}
}
fclose(fp);

printf("Finished\n   %d Records Written\n",RecCnt);
}
 
