/* 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> 

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: uload [-b|t] <filename> <cr>\n");
		};
	exit (code);
}

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

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

printf("\n Uload Version 2.2 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);
}

if (inp(0xa3)==0)
{
   Exit(2,"No Uload file open",0);
}

if( (fp = fopen(fn,"rb"))==NULL ) 
{
	Exit(3,"Can't open ",fn);
}
if (option==0)
{
 	printf("\n   Uploading as Binary...");
	while (inp(0xa3)==1 && !feof(fp))
	{
		InByte=fgetc(fp);
		if (!feof(fp)) outp(0xa2,InByte);
	}
}
if (option==1)
{
	printf("\n   Uploading as Text...");
	InByte=0;
	while (inp(0xa3)==1 && InByte!=26 && !feof(fp))
	{
		InByte=fgetc(fp);
		if (InByte!=26 && !feof(fp)) outp(0xa2,InByte);
	}
}
fclose(fp);

printf("Finished\n");
}
