/********************************************************************
*
* FTOC V1.0                                  Salim Alam: 90.02.08
*
* Converts assembler output from DASM to Motorola S Record format.
* The code should have been assembled using the -f2 option.  The
* processor should be defined as 68HC11.
*
* Usage:
*
* ftoc <infile> [outfile]
*
* where "infile" is the filename of the assembler output, and
* "outfile" is the name of the file to which the S record will
* be output.
*
* If outfile is not specified, "out.s" will be used for the
* output file.
*
*********************************************************************/

#include <stdio.h>
#include <ctype.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>

main(argc,argv)
int argc;
char *argv[];
{

   char infilename[100],outfilename[100];
   struct FileHandle *infile;
   FILE *outfile;
   unsigned short Org, Len, CurrAdd, ToGo;
   unsigned char  CheckSum, RLen;
   unsigned char buffer[100];
   int blen, i;


   /* Check args */

   if ((argc < 2) || (argc > 3)) {
       printf("Usage: ftoc <infile> [outfile]\n");
	   exit(10);
   };

   strcpy(infilename,argv[1]);
   if (argc==3) 
     strcpy(outfilename,argv[2]);
   else
     strcpy(outfilename,"out.s");



   /* Open files */

   if ( (infile=Open(infilename,MODE_OLDFILE)) == 0L) {
      printf("Unable to open input file '%s'\n",infilename);
	  exit(5);
   };

   if ( (outfile=fopen(outfilename,"w")) == 0L) {
      printf("Unable to open output file '%s'\n",outfilename);
	  exit(5);
   };



   /* Main loop */

   fprintf(outfile,"S00600004844521B\n");

   for (;;) {
     blen=Read(infile,buffer,4);
     if (blen != 4) break;  /* Exit if EOF */

     Org = CurrAdd = (buffer[0]+(256*buffer[1]));
     Len = ToGo    = (buffer[2]+(256*buffer[3]));

     while (ToGo > 0) {  /* Process a line */
        RLen = (ToGo > 16)? 16 : ToGo;
	    ToGo -= RLen;
	    blen=Read(infile,buffer,RLen);
	    CheckSum = RLen+3+HexAdd(CurrAdd);
	    fprintf(outfile,"S1");
	    PrintHex(outfile,(RLen + 3));
	    PrintHex(outfile,CurrAdd / 256);
	    PrintHex(outfile,CurrAdd % 256);
	    for (i=0; i < RLen; i++) {
	      PrintHex(outfile,buffer[i]);
	  	  CheckSum += buffer[i];
	    };
	    CheckSum = ~CheckSum;
	    PrintHex(outfile,CheckSum);
	    fprintf(outfile,"\n");
		CurrAdd += RLen;
     }; /* while */

   }; /* for */


   /* Clean up & exit */

   fprintf(outfile,"S9030000FC\n");

   Close(infile);
   fclose(outfile);

} /* main */



PrintHex(fp,num)
FILE *fp;
unsigned char num;
{

  unsigned char hi,lo;
  static char *hexmap[] = {'0','1','2','3','4','5','6','7',
                           '8','9','A','B','C','D','E','F'};
  hi = num / 16;
  lo = num % 16;

  fprintf(fp,"%c%c",hexmap[hi],hexmap[lo]);

}



HexAdd(wnum)
unsigned short wnum;
{

   int hi,lo;

   hi = wnum / 256;
   lo = wnum % 256;

   return(lo+hi);

}

