/* 
Uload Version 2 for the VMEs10 Emulator
Compile with Alcyon C for CP/M-68k 
*/

#include <stdio.h>
#include <ctype.h>

FILE *fopen();
FILE *fopena();
FILE *fopenb();

/*
ULOAD/DLOAD

$F1A070 - $F1A077

RegUD + offset
'00  01 ro  Download input data port
'02  03 rw  Download input status/control port 0=NOT EOF, 1=EOF / 0xff=rewind file
'04  05 wo  Upload output data port
'06  07 rw  Upload input status/control port 0=NOT EOF, 1=EOF / 0xff=rewind file
*/

#define ULCTRL ((char *)0xf1a077)
#define ULSTS ((char *)0xf1a077)
#define ULDATA ((char *)0xf1a075)

/* void Exit(int code, char * message1, char * message2)*/
Exit(code,message1,message2)
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[]) */
main(argc,argv)
int argc;
char **argv;
{
FILE *fp;
int  i, option;
char InByte;
char *fn;

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

printf("\n Uload Version 2.0 for CPM68k on VME10 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
		fn = argv[i];
}			
if (argc < 2 )
{
	Exit(1,0,0);
}
if ( strlen(fn) == 0 )
{
	Exit(1,0,0);
}

if (*ULSTS != 0) /* EOF == 0 */
{
   Exit(2,"No Uload file open",0);
}

if( (fp = fopenb(fn,"r"))==NULL ) 
{
	Exit(3,"Can't open ",fn);
}
if (option==0)
{
 	printf("\n   Uploading as Binary...");
	while (*ULSTS == 0 && !feof(fp))
	{
		InByte=fgetc(fp);
		if (!feof(fp)) *ULDATA = InByte;
	}
}
if (option==1)
{
	printf("\n   Uploading as Text...");
	InByte=0;
	while (*ULSTS == 0 && InByte!=26 && !feof(fp))
	{
		InByte=fgetc(fp);
		if (InByte!=26 && !feof(fp)) *ULDATA = InByte;
	}
}
fclose(fp);

printf("Finished\n");
}
