/* js.c: Produces javascript versions of various
 * Zusie resources, for use in the simulator.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
   FILE *fin, *fout;
   int i, d;
   unsigned char b;
   int first = 1;
   char buf[201];
   char *p, *var;

   if (argc != 4)
      return 1;

   /*
    * --mc
    *
    * Turn binary microcode into js array
    *
    */

   if (!strcmp(argv[1], "--mc")) {
      if (!(fin = fopen(argv[2], "rb")) ||
          !(fout = fopen(argv[3], "wt")))
         return 1;
      fprintf(fout, "// Autogenerated by js.c - Do not edit!\n// See nablaman.com/relay/ for more information.\n");
      for (i=0 ; fread(&b, 1, 1, fin) ; i++) {
         d = (int)b;
         if (d != 0)
            fprintf(fout, "mc[%d] = %d;\n", i, d);
      }
   }

   /*
    * --ctrl
    *
    * Turn control signals into js vars
    *
    */

   else if (!strcmp(argv[1], "--ctrl")) {
      if (!(fin = fopen(argv[2], "rt")) ||
          !(fout = fopen(argv[3], "wt")))
         return 1;
      fprintf(fout, "// Autogenerated by js.c - Do not edit!\n// See nablaman.com/relay/ for more information.\n");
      while (fgets(buf, 200, fin)) {
         if (strncmp(buf, "#define", 7))
            continue;
         if ((p = strchr(buf, '\r')) || (p = strchr(buf, '\n')))
            *p = '\0';
         p = buf + 7;
         while (isspace(*p))
            p++;
         var = p;
         while (*p && !isspace(*p))
            p++;
         *p++ = '\0';
         while (isspace(*p))
            p++;
         if (p[0] == 'h' && isdigit(p[1]))   // OUCH! convert h to 0x
            fprintf(fout, "var %s = 0x%s;\n", var, p+1);
         else
            fprintf(fout, "var %s = %s;\n", var, p);
      }
   }

   /*
    * --mnem
    *
    * Turn mnemonic table into js array
    *
    */

   else if (!strcmp(argv[1], "--mnem")) {  
      if (!(fin = fopen(argv[2], "rt")) ||
          !(fout = fopen(argv[3], "wt")))
         return 1;
      fprintf(fout, "// Autogenerated by js.c - Do not edit!\n// See nablaman.com/relay/ for more information.\n");
      fprintf(fout, "var mnem = new Array(\n");
      while (fgets(buf, 200, fin) && strncmp(buf, "/*START", 7));
      while (fgets(buf, 200, fin) && strncmp(buf, "/*END", 5)) {
         if ((p = strchr(buf, '\r')) || (p = strchr(buf, '\n')))
            *p = '\0';
         if ((p = strchr(buf, '}')))
            *p = '\0';
         if ((p = strchr(buf, '{'))) {
            fprintf(fout, "%snew Array(%s)\n", (first ? "" : ","), p+1);
            first = 0;
         }
         else
            fprintf(fout, "%s\n", buf);
      }
      fprintf(fout, ");\n");
   }

   else
      return 1;

   fclose(fout);
   fclose(fin);
   return 0;
   
}
