#include "stdio.h";

FILE *fstart();

#define _DATAREADY 1
#define _OVERRUN 2
#define _PARITY 4
#define _FRAME 8
#define _BREAK 16
#define _DTR 1
#define _RTS 2
#define PORTBASE 0x02F8                          /* For COM1. 0x03F8 for CO*/
#define BUFSIZE 512

main(argc, argv)
int argc;
char *argv[];
{
FILE *f;
unsigned char parmbyte;
int count;
char buf[BUFSIZE];

   f = fstart(argc, argv);
   if (f == NULL) 
      exit();

/* Calculate and set the parameter byte */

   comparm(1200, 0, 1, 8);                       /* Program 16.6           */

   printf("%s \n", "Press any key to start download");
   getch();

   printf("%s \n", "Press 'ESC' to stop download");

   while (count = readbuf(buf) == BUFSIZE) { 
      if (count > 0)
         fwrite(buf, count, 1, f);
   }

   fclose(f);                                    /* Close the File         */

   printf("%s \n", "Finished");
      
}

readbuf(buf)
char *buf;
{
int count = 0;
int lstat;                                       /* Line Status            */
int mstat;                                       /* Modem Status           */

   outp(PORTBASE + 4, _DTR | _RTS);              /* Handshaking on         */

   while (count <= BUFSIZE) {

      if (kbhit()) {
         if (getch() == 27) 
            return;                              /* Hit ESC                */
      }

      lstat = inp(PORTBASE + 5);                 /* Read Line Status       */

      if (lstat & _OVERRUN) {
         printf("%s \n", "overrun error");
         return(-1);
      }

      if (lstat & _PARITY) {
         printf("%s \n", "parity error");
         return(-1);
      }

      if (lstat & _FRAME) {
         printf("%s \n", "framing error");
         return(-1);
      }

      if (lstat & _BREAK) {
         printf("%s \n", "break received");
         return(-1);
      }

/*
* Read the Modem Status (not needed but here for completeness)
* We can test for incoming handshaking if we wish.
*/
      mstat = inp(PORTBASE + 6);

      if (!(lstat & _DATAREADY))                 /* Nothing There          */
         continue;

/* So we have received a character */

      buf[count++] = inp(PORTBASE);              /* read the character     */
   }

/* We have filled the buffer, or hit ESCAPE */

   outp(PORTBASE + 4, 0);                        /* Handshaking off        */

   return(count);
}


/* Figure 16.10: DOWNL3.C */
