#include <exec/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <dlg/crypt.h>

void MyEncrypt(char *,char *,int);


UBYTE CRC;

void main(int argc,char **argv)

{int   hfd;
 UBYTE filename[256];
 UBYTE buf     [80];
 UBYTE outbuf  [80];

 UBYTE mychar;
 UBYTE found;
 UBYTE SN[4];
 UBYTE XORSN[4];
 ULONG serialnumber;
 ULONG xorserialnumber;

 long  numchars;
 long  pos;

 if (argc < 3)
    {printf("\n Usage: License <serial#> <owner> [<handler>]\n\n");
     exit(5);
    }

 serialnumber = (ULONG)atol(argv[1]+2);
 printf("number is %lu\n",serialnumber);
 xorserialnumber = serialnumber^0xffffffff;

 SN[0]    = (serialnumber&0xff000000)>>24;
 SN[1]    = (serialnumber&0x00ff0000)>>16;
 SN[2]    = (serialnumber&0x0000ff00)>>8;
 SN[3]    = (serialnumber&0x000000ff)>>0;

 XORSN[0] = (xorserialnumber&0xff000000)>>24;
 XORSN[1] = (xorserialnumber&0x00ff0000)>>16;
 XORSN[2] = (xorserialnumber&0x0000ff00)>>8;
 XORSN[3] = (xorserialnumber&0x000000ff)>>0;


 if (argc > 3)
     strcpy(filename, argv[3]);
   else
     strcpy(filename, "l:tpt-handler");

 if ((hfd=open(filename, O_RDWR))==-1)
    {printf("Couldn't open handler\n");
     exit(10);
    }

 pos   = lseek(hfd,-5000,2);
 found = FALSE;
 while(read(hfd,&mychar,1)==1)
      {if (mychar==':')
          {read(hfd,&mychar,1);
           if (mychar=='-')
              {read(hfd,&mychar,1);
               if (mychar==')')
                  {found = TRUE;
                   break;
                  }
              }
          }
      }

 if (!found)
    {printf("Unable to find location for string\n");
     close(hfd);
     exit(10);
    }

 pos = lseek(hfd,131L,1);

 sprintf(buf,"Serial #%s", argv[1]);
 numchars = strlen(buf);
 
 MyEncrypt(buf,outbuf,numchars);
 write(hfd,  outbuf, numchars+1);
 write(hfd, &hfd, 19-numchars);
 write(hfd, &CRC, 1);

 lseek(hfd, pos,   0);
 lseek(hfd, 26,    1);
 write(hfd, SN,    4);
 write(hfd, XORSN, 4);

 if (serialnumber)
     sprintf(buf, "Registered to %s", argv[2]);
   else
     strcpy(buf, argv[2]);
 numchars = strlen(buf);

 MyEncrypt(buf, outbuf, numchars);
 write(hfd,  outbuf, numchars+1);
 write(hfd, &hfd, 78-numchars);
 write(hfd, &CRC, 1);

 strcpy(buf, "Unregistered pirated version -- it's not going to work");
 numchars = strlen(buf);
 MyEncrypt(buf, outbuf, numchars);

 write(hfd,  outbuf, numchars+1);
 write(hfd, &hfd, 78-numchars);
 write(hfd, &CRC, 1);

 printf("\nHandler modified successfully\n");
 close(hfd);
}


void MyEncrypt(char *inbuf,char *outbuf,int size)

{int counter;
 UBYTE shift;

 outbuf[size] = '\0';
 outbuf[0]    = size;
 shift        = size;

 for(counter=0;counter<size;counter++)
    {outbuf[counter+1] = inbuf[counter]+shift;
     shift             = outbuf[counter+1]-CRYPTOFFSET;
    }

 CRC = shift+MAGICNUMBER;
}
