#include <exec/types.h>

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

#include <proto/utility.h>

#include <private/privs.h>

//#define  SERFILE  "DLGConfig:Misc/DLGSerial"
//#define  SERFILE  "Test/Don/DLGSerial"
#define  SERFILE  "Test/Tom/DLGSerial"

extern   char  SERIAL[];
extern   char  OWNER[];


BOOL  GenerateKeyFile(void)
{
   int   Lines = 0;
   int   Groups = 0;
   int   Chars = 0;
   int   FirstChar = 0;

   int   line, group, mychar;

   char  temp[7];

   FILE  *fp   =  NULL;

   fp =  fopen(SERFILE,"a");

   if(!fp)  {  printf("Cannot open output file!\n"); return(FALSE);   }

   fprintf(fp,"\n; DLG Keyfile -- do not edit anything other than\n; your name or DLG will quit working!\n\n");

   fprintf(fp,"%s\n",SERIAL);
   fprintf(fp,"OWNER %s\n\n",OWNER);

   strncpy(temp,SERIAL+2,1);
   Lines = atoi(temp) + 2;

   strncpy(temp,SERIAL+3,1);
   Groups = atoi(temp) + 2;

   strncpy(temp,SERIAL+4,1);
   Chars = atoi(temp) + 2;

   strncpy(temp,SERIAL+5,1);
   FirstChar = atoi(temp) + 2;

//   printf("Lines = %d\nGroups = %d\nChars = %d\nFirst Char = %d\n",Lines,Groups,Chars,FirstChar);

   for(line = 0; line < Lines; line++)
   {
      for(group = 0; group < Groups; group++)
      {
         for(mychar = 0; mychar < Chars; mychar++)
         {
            if((line == 0) && (group == 0) && (mychar == 0))
            {
               fprintf(fp,"%X",FirstChar);
               continue;
            }

            if((line == 1) && (group == 0) && (mychar == 0))
            {
               // lower capability word
               fprintf(fp,"%X",(BASIC | FIDO));
               continue;
            }

/* Uncomment this when upper capability word is used
            if((line == 1) && (group == 0) && (mychar == 1))
            {
               // upper capability word
               fprintf(fp,"%X",15);
               continue;
            }
*/

            fprintf(fp,"%X",(0xF & GetUniqueID()));
         }

         fprintf(fp," ");
      }

      fprintf(fp,"\n");

   }



   if(fp)   {  fclose(fp); fp = NULL;   }
   return(TRUE);
}

