// a replacement for stobin...
// taken from a special version of TEO, the thomson TO8 emulator...
#include <stdio.h>
#include <stdlib.h>

/*
 *    Loader au format S19 de Motorola
 */
unsigned char fill=0x00; 
enum {vectrex,to8} bin_mode;
 
static int
LoadS19File(char *S19Fname,char *binFname)
{
   unsigned char mem[0x10000];
   int low=0xFFFF;
   int high=0x0000;
   int i;
   FILE *f;
   char c;

   // clears mem
   for (i=0;i<0x10000;i++) mem[i]=fill;
   
   f=fopen(S19Fname,"r");

   if (f==NULL) return -1;

   while (!feof(f))
   {
      while (!feof(f) && ((c=fgetc(f))!='S'));

      if (!feof(f))
      {
         int adr;
         int lg;
         int i;
         int val;

         c=fgetc(f);

         if (c=='1')
         {
            fscanf(f,"%2x%4x",&lg,&adr);
            for (i=0;i<lg-3;i++)
            {
               fscanf(f,"%2x",&val);
               mem[adr+i]=val;
			   if (adr+i>high) high=adr+i;
			   if (adr+i<low) low=adr+i;
            }
            // reads checksum
            fscanf(f,"%2x",&val);
         }
      }
   }
   fclose(f);
   // we now have bin in mem from low to high... that is basiicaly what an stobin is supposed to do...
   f=fopen(binFname,"wb");
   
   switch (bin_mode) {
   case vectrex :
   for (i=low;i<=high;i++)
       fputc(mem[i],f);
       break;
   case to8 :
   fputc(0x00,f);
   // size 16bit big endian
   fputc((((high-low+1)&0xFF00)>>8),f);
   fputc(((high-low+1)&0xFF),f);
   // begin address
   fputc(((low&0xFF00)>>8),f);
   fputc((low&0xFF),f);
   // data
   for (i=low;i<=high;i++)
       fputc(mem[i],f);
   fputc(0xFF,f);
   fputc(0x00,f);
   fputc(0x00,f);
   // run address (ie begin address here)
   fputc(((low&0xFF00)>>8),f);
   fputc((low&0xFF),f);
   break;
   }
            
   fclose(f);

}

int 
main(int argc, char *argv[]) {
	char *file_in=NULL;
	char *file_out=NULL;
	
	int start=-1;
	int end=-1;
	int exec=-1;
	
	int argnum;
	bin_mode=vectrex;
	
	for (argnum=1;argnum<argc;argnum++) {
		if (strncmp(argv[argnum],"-o",2)==0) file_out=&argv[argnum][2];
		if (strncmp(argv[argnum],"-i",2)==0) file_in=&argv[argnum][2];
		if (strcmp(argv[argnum],"-to8")==0) bin_mode=to8;
	}
	
	if (file_in==NULL) { fprintf(stderr,"No input file");exit(-1);};
	if (file_out==NULL) { fprintf(stderr,"No output file");exit(-1);};

	LoadS19File(file_in,file_out);
	
}
