#include <EDK.h>
#include "General.h"


struct LICENSE {
  char acName[80];
  char acNumber[40];
  short fSharewareMessage;
  short fEnableLink;
  short fEnableJoysticks;
  word wNumber;
  short aiChecksum[192];
} License;


// read License.dat and return true if it is valid
flag IsValidLicense() {
  static flag fFirstTime = true;
  static flag fReturn = false;
  HANDLE hFile = INVALID_HANDLE_VALUE;
  if (fFirstTime) try {
    fFirstTime = false;

    // read license file
    hFile = OpenFile(GetProgramDirectory("License.dat"));
    ReadFile(hFile, &License, 512);
    win(CloseHandle(hFile));
    hFile = INVALID_HANDLE_VALUE;

    // undecode data
    byte* pb = (byte*)&License;
    for (int i = 0; i < 511; i++) {
      pb[i] = (byte)((pb[i] + pb[i + 1]) ^ i);
    }

    // check for valid checksum
    srand(0x309E);
    for (i = 6; i <= 177; i += 4) {
      srand((word)(pb[i] + (rand() ^ 0xAE51)));
    }
    if (License.aiChecksum[26] != rand()) {
      error("Invalid license file");
    }

    // skip disabled licenses
    static const word awDisabled[] = {
      27010 ^ 0xBABE, 27011 ^ 0xBABE, 27108 ^ 0xBABE, 27153 ^ 0xBABE,
      27295 ^ 0xBABE, 27300 ^ 0xBABE, 27341 ^ 0xBABE, 27443 ^ 0xBABE,
      27450 ^ 0xBABE, 27547 ^ 0xBABE, 27561 ^ 0xBABE, 27603 ^ 0xBABE,
      27620 ^ 0xBABE, 27638 ^ 0xBABE, 27704 ^ 0xBABE, 27943 ^ 0xBABE,
      27946 ^ 0xBABE, 28008 ^ 0xBABE, 28056 ^ 0xBABE, 28184 ^ 0xBABE,
      28241 ^ 0xBABE, 28261 ^ 0xBABE, 28377 ^ 0xBABE, 28378 ^ 0xBABE,
      28479 ^ 0xBABE, 28486 ^ 0xBABE, 28495 ^ 0xBABE, 28502 ^ 0xBABE,
      28514 ^ 0xBABE, 28527 ^ 0xBABE, 28626 ^ 0xBABE, 28628 ^ 0xBABE,
      28768 ^ 0xBABE, 28771 ^ 0xBABE, 28863 ^ 0xBABE, 28930 ^ 0xBABE,
      28991 ^ 0xBABE, 29092 ^ 0xBABE, 29097 ^ 0xBABE,
      0
    };
    for (i = 0; awDisabled[i] != 0; i++) {
      if (License.wNumber == awDisabled[i]) {
        error("Your license has been disabled. Please contact pc64@compuserve.com (Wolfgang Lorenz)");
      }
    }

    trace("%s\\License.dat is OK", GetProgramDirectory());
    fReturn = true;
  } catch (...) {
    if (hFile != INVALID_HANDLE_VALUE) {
      CloseHandle(hFile);
      hFile = INVALID_HANDLE_VALUE;
    }
    MessageBox(NULL, "Unregistered version\n\nJoysticks have been disabled (use white arrows and Right Ctrl)", "No valid License.dat found", MB_ICONINFORMATION | MB_OK);
  }
  return fReturn;
}
