/*qin.c*/
#include<termios.h>
#include<stdio.h>
#include<math.h>
#include<sys/errno.h>
#include<stdlib.h>

main(argc,argv)
int argc;
char *argv[];
{
FILE *sfp,*ofp; /*serial port and output file pointers*/
FILE *kfp;      /*file to write when qin is over*/
struct termios i_set,n_set;

char c;
char ofile[80];
int lc;

if (argc!=2)
    { 
    printf("I need (only) an output file name on the command line.\n");
    return;
    }
strcpy(ofile,argv[1]);

/*Change the /dev/* entry if needed for your serial port*/
sfp=fopen("/dev/ttyS0","r");
switch ( (int) sfp)
    {
    case ENXIO: {printf("Port does not exist.\n");
                 return;}
    case EBUSY: {printf("Device busy.\n");
                 return;}
    case EINTR: {printf("Open Interrupted.\n");
                 return;}
    case NULL:  {printf("Could not open device.\n");
                 return;}
    }
ofp=fopen(ofile,"w");
if (ofp==NULL)
    {
    printf("Could not open output file %s.\n",ofile);        
    return;
    }

tcgetattr(fileno(sfp),&i_set);
n_set=i_set;
n_set.c_lflag &= ~ECHO;
if (tcsetattr(fileno(stdin),TCSANOW, &n_set) !=0)
    fprintf(stderr,"could not set attributes\n");

lc=0;
while (((c=fgetc(sfp))!='e') || (lc<18))  /*Q9 sends eot at end*/
   {
   if (c=='\n')
       /*{*/
       /*c=fgetc(sfp);*/
       lc++;
       /*}*/
   putchar(c); 
   fputc(c,ofp); 
   fflush(ofp);
   }
fclose(sfp);
fclose(ofp);
kfp=fopen("kill.kill","w");
fputs("Qin is done.\n",kfp);
fclose(kfp);
tcsetattr(fileno(stdin),TCSANOW,&i_set);
exit(0);
}
