#include <stdio.h>
#include <dos.h>
#define PORT 0

unsigned int filesize();

void sport();
void send_file();
void send_file_name();
void port_init();
void wait();

main (argc,argv)
int argc;
char *argv[];
{
 if (argc != 2)
 {
  printf ("Usage: PUT <filename>");
  exit (1);
 }
 port_init(PORT);
 send_file(argv[1]);
}

/*********************************/
void send_file(fname)
char *fname;
{
 FILE *fp;
 char ch;

 union
 {
 char c[2];
 unsigned int count;
 } cnt;
 if (!(fp=fopen(fname,"rb")))
 {
  printf ("Cannot open output file!");
  exit (1);
 }
 printf ("Sending file: %s\n",fname);

 sport (PORT,'r');
 wait (PORT);

 send_file_name(fname);
 if (rport(PORT)!='.')
 {
  printf ("Remote file failure!\n");
  exit (1);
 }
 cnt.count = filesize(fp);

 sport (PORT,cnt.c[0]);
 wait (PORT);
 sport (PORT,cnt.c[1]);
 do
 {
  ch = getc(fp);
  if (ferror(fp))
  {
   wait(PORT);
   sport (PORT,ch);
  }
 }
 while (!feof(fp));
 wait (PORT);
 fclose (fp);
}

/**********************************/
unsigned int filesize(fp)
FILE *fp;
{
 unsigned long i;
 i = 0;
 do
 {
  getc(fp);
  i++;
 }
 while (!feof(fp));
 rewind(fp);
 return i-1;
}

/*********************************/
void send_file_name(f)
char *f;
{
 do
 {
  sport (PORT,'?');
 }
 while (!kbhit() && ! (check_stat(PORT) & 256));
 if (kbhit())
 {
  getch();
  exit (1);
 }
 wait(PORT);
 while (*f)
 {
  sport(PORT,*f++);
  wait(PORT);
 }
 sport(PORT,'\0');
 wait(PORT);
}

/*************************/
void wait(port)
int port;
{
 if (rport(port) != '.')
 {
  printf ("Communication error!=n");
  exit (1);
 }
}

/******************************/
void sport (port,c)
int port;
char c;
{
 union REGS r;
 r.x.dx = port;
 r.h.al = c;
 r.h.ah = 1;
 int86(0x14,&r,&r);
 if (r.h.ah & 128)
 {
  printf ("Send error detected in serial port!\n");
  exit(1);
 }
}

/*****************************/
rport(port)
int port;
{
 union REGS r;
 while (!(check_stat(PORT) & 256))
 if (kbhit())
 {
  getch();
  exit(1);
 }
 r.x.dx = port;
 r.h.ah = 2;
 int86 (0x14,&r,&r);
 if (r.h.ah & 128) printf ("Read error detected in the serial port!\n");
 return r.h.al;
}

/*******************************/
check_stat(port)
int port;
{
 union REGS r;
 r.x.dx = port;
 r.h.ah = 3;
 int86 (0x14,&r,&r);
 return r.x.ax;
}

/*******************************/
void port_init(port)
int port;
{
 union REGS r;
 r.x.dx = port;
 r.h.ah = 0;
 r.h.al = 251;
 int86(0x14,&r,&r);
}