// GridTracker Copyright © 2023 GridTracker.org
// All rights reserved.
// See LICENSE for more information.

GT.lotwCallsigns = Object();
GT.lotwFile = "";
GT.lotwWhenDate = 0;
GT.lotwLoadTimer = null;
GT.eqslCallsigns = Object();
GT.eqslFile = "";
GT.eqslWhenDate = 0;
GT.eqslLoadTimer = null;
GT.ulsCallsignsCount = 0;

GT.ulsWhenDate = 0;
GT.ulsLoadTimer = null;

GT.oqrsCallsigns = Object();
GT.oqrsFile = "";
GT.oqrsWhenDate = 0;
GT.oqrsLoadTimer = null;

function dumpFile(file)
{
  try
  {
    if (fs.existsSync(file)) fs.unlinkSync(file);
  }
  catch (e) {}
}

function dumpDir(dir)
{
  try
  {
    if (fs.existsSync(dir)) fs.rmdirSync(dir);
  }
  catch (e) {}
}

function callsignServicesInit()
{
  // Dump old data files we no longer reference
  dumpFile(GT.jsonDir + "uls-callsigns.json");
  dumpFile(GT.jsonDir + "us-callsigns.json");
  dumpFile(GT.jsonDir + "lotw-callsigns.json");
  dumpFile(GT.jsonDir + "lotw-ts-callsigns.json");
  dumpFile(GT.jsonDir + "eqsl-callsigns.json");
  dumpFile(GT.jsonDir + "cloqrs-callsigns.json");
  dumpFile(GT.jsonDir + "internal_qso.json");
  dumpFile(GT.jsonDir + "spots.json");
  dumpDir(GT.jsonDir);

  GT.lotwFile = GT.NWappData + "lotw-ts-callsigns.json";
  GT.eqslFile = GT.NWappData + "eqsl-callsigns.json";
  GT.oqrsFile = GT.NWappData + "cloqrs-callsigns.json";

  if (GT.callsignLookups.lotwUseEnable)
  {
    lotwLoadCallsigns();
  }
  if (GT.callsignLookups.eqslUseEnable)
  {
    eqslLoadCallsigns();
  }
  if (GT.callsignLookups.ulsUseEnable)
  {
    ulsLoadCallsigns();
  }
  if (GT.callsignLookups.oqrsUseEnable)
  {
    oqrsLoadCallsigns();
  }

  lotwSettingsDisplay();
  eqslSettingsDisplay();
  ulsSettingsDisplay();
  oqrsSettingsDisplay();
}

function saveCallsignSettings()
{
  localStorage.callsignLookups = JSON.stringify(GT.callsignLookups);
}

function lotwLoadCallsigns()
{
  var now = timeNowSec();
  if (now - GT.callsignLookups.lotwLastUpdate > 86400 * 7)
  { GT.callsignLookups.lotwLastUpdate = 0; }
  else
  {
    var lotwWhenTimer = 86400 * 7 - (now - GT.callsignLookups.lotwLastUpdate);
    GT.lotwWhenDate = now + lotwWhenTimer;
    GT.lotwLoadTimer = nodeTimers.setTimeout(lotwDownload, lotwWhenTimer * 1000);
  }

  try
  {
    if (!fs.existsSync(GT.lotwFile))
    {
      GT.callsignLookups.lotwLastUpdate = 0;
    }
    else
    {
      var data = fs.readFileSync(GT.lotwFile);
      GT.lotwCallsigns = JSON.parse(data);
      if (Object.keys(GT.lotwCallsigns).length < 100)
      {
        lotwDownload();
      }
    }
    if (GT.callsignLookups.lotwLastUpdate == 0)
    {
      lotwDownload();
    }
  }
  catch (e)
  {
    console.log(e);
    GT.callsignLookups.lotwLastUpdate = 0;
    lotwDownload();
  }
}

function lotwSettingsDisplay()
{
  lotwUseEnable.checked = GT.callsignLookups.lotwUseEnable;

  if (GT.callsignLookups.lotwLastUpdate == 0)
  {
    lotwUpdatedTd.innerHTML = "Never";
  }
  else
  {
    lotwUpdatedTd.innerHTML = userTimeString(
      GT.callsignLookups.lotwLastUpdate * 1000
    );
  }

  if (!GT.callsignLookups.lotwUseEnable)
  {
    if (GT.lotwLoadTimer != null) nodeTimers.clearTimeout(GT.lotwLoadTimer);
    GT.lotwLoadTimer = null;
    GT.lotwCallsigns = Object();
  }
  lotwCountTd.innerHTML = Object.keys(GT.lotwCallsigns).length;
}

function lotwValuesChanged()
{
  GT.callsignLookups.lotwUseEnable = lotwUseEnable.checked;
  saveCallsignSettings();
  if (GT.callsignLookups.lotwUseEnable == true)
  {
    lotwLoadCallsigns();
  }
  lotwSettingsDisplay();

  setAlertVisual();
  goProcessRoster();
  if (GT.rosterInitialized) GT.callRosterWindowHandle.window.resize();
}

function lotwDownload(fromSettings)
{
  lotwUpdatedTd.innerHTML = "<b><i>Downloading...</i></b>";
  getBuffer(
    "https://lotw.arrl.org/lotw-user-activity.csv",
    processLotwCallsigns,
    null,
    "https",
    443
  );
}

function processLotwCallsigns(result, flag)
{
  // var result = String(buffer);
  var lines = Array();
  lines = result.split("\n");

  var lotwCallsigns = Object();
  for (x in lines)
  {
    var breakout = lines[x].split(",");
    if (breakout.length == 3)
    {
      var dateTime = new Date(
        Date.UTC(
          breakout[1].substr(0, 4),
          parseInt(breakout[1].substr(5, 2)) - 1,
          breakout[1].substr(8, 2),
          0,
          0,
          0
        )
      );
      lotwCallsigns[breakout[0]] = parseInt(dateTime.getTime() / 1000) / 86400;
    }
  }

  GT.callsignLookups.lotwLastUpdate = timeNowSec();

  var now = timeNowSec();
  if (GT.lotwLoadTimer != null) nodeTimers.clearTimeout(GT.lotwLoadTimer);

  var lotwWhenTimer = 86400 * 7 - (now - GT.callsignLookups.lotwLastUpdate);
  GT.lotwWhenDate = now + lotwWhenTimer;
  GT.lotwLoadTimer = nodeTimers.setTimeout(lotwDownload, lotwWhenTimer * 1000);

  if (Object.keys(lotwCallsigns).length > 100)
  {
    GT.lotwCallsigns = lotwCallsigns;
    fs.writeFileSync(GT.lotwFile, JSON.stringify(GT.lotwCallsigns));
  }

  lotwSettingsDisplay();
}

function oqrsLoadCallsigns()
{
  var now = timeNowSec();
  if (now - GT.callsignLookups.oqrsLastUpdate > 86400 * 7)
  { GT.callsignLookups.oqrsLastUpdate = 0; }
  else
  {
    var oqrsWhenTimer = 86400 * 7 - (now - GT.callsignLookups.oqrsLastUpdate);
    GT.oqrsWhenDate = now + oqrsWhenTimer;
    GT.oqrsLoadTimer = nodeTimers.setTimeout(oqrsDownload, oqrsWhenTimer * 1000);
  }

  try
  {
    if (!fs.existsSync(GT.oqrsFile))
    {
      GT.callsignLookups.oqrsLastUpdate = 0;
    }
    else
    {
      var data = fs.readFileSync(GT.oqrsFile);
      GT.oqrsCallsigns = JSON.parse(data);
    }
    if (GT.callsignLookups.oqrsLastUpdate == 0)
    {
      oqrsDownload();
    }
  }
  catch (e)
  {
    GT.callsignLookups.oqrsLastUpdate = 0;
    oqrsDownload();
  }
}

function oqrsSettingsDisplay()
{
  oqrsUseEnable.checked = GT.callsignLookups.oqrsUseEnable;

  if (GT.callsignLookups.oqrsLastUpdate == 0)
  {
    oqrsUpdatedTd.innerHTML = "Never";
  }
  else
  {
    oqrsUpdatedTd.innerHTML = userTimeString(
      GT.callsignLookups.oqrsLastUpdate * 1000
    );
  }

  if (!GT.callsignLookups.oqrsUseEnable)
  {
    if (GT.oqrsLoadTimer != null) nodeTimers.clearTimeout(GT.oqrsLoadTimer);
    GT.oqrsLoadTimer = null;
    GT.oqrsCallsigns = Object();
  }
  oqrsCountTd.innerHTML = Object.keys(GT.oqrsCallsigns).length;
}

function oqrsValuesChanged()
{
  GT.callsignLookups.oqrsUseEnable = oqrsUseEnable.checked;
  saveCallsignSettings();
  if (GT.callsignLookups.oqrsUseEnable == true)
  {
    oqrsLoadCallsigns();
  }
  oqrsSettingsDisplay();

  setAlertVisual();
  goProcessRoster();
  if (GT.rosterInitialized) GT.callRosterWindowHandle.window.resize();
}

function oqrsDownload(fromSettings)
{
  oqrsUpdatedTd.innerHTML = "<b><i>Downloading...</i></b>";
  getBuffer(
    "https://storage.googleapis.com/gt_app/callsigns/clublog.json",
    processoqrsCallsigns,
    null,
    "http",
    80
  );
}

function processoqrsCallsigns(buffer, flag)
{
  GT.oqrsCallsigns = JSON.parse(buffer);

  GT.callsignLookups.oqrsLastUpdate = timeNowSec();

  var now = timeNowSec();
  if (GT.oqrsLoadTimer != null) nodeTimers.clearTimeout(GT.oqrsLoadTimer);

  var oqrsWhenTimer = 86400 * 7 - (now - GT.callsignLookups.oqrsLastUpdate);
  GT.oqrsWhenDate = now + oqrsWhenTimer;
  GT.oqrsLoadTimer = nodeTimers.setTimeout(oqrsDownload, oqrsWhenTimer * 1000);

  fs.writeFileSync(GT.oqrsFile, JSON.stringify(GT.oqrsCallsigns));
  oqrsSettingsDisplay();
}

function eqslLoadCallsigns()
{
  var now = timeNowSec();
  if (now - GT.callsignLookups.eqslLastUpdate > 86400 * 7)
  { GT.callsignLookups.eqslLastUpdate = 0; }
  else
  {
    var eqslWhenTimer = 86400 * 7 - (now - GT.callsignLookups.eqslLastUpdate);
    GT.eqslWhenDate = now + eqslWhenTimer;
    GT.eqslLoadTimer = nodeTimers.setTimeout(eqslDownload, eqslWhenTimer * 1000);
  }

  try
  {
    if (!fs.existsSync(GT.eqslFile))
    {
      GT.callsignLookups.eqslLastUpdate = 0;
    }
    else
    {
      var data = fs.readFileSync(GT.eqslFile);
      GT.eqslCallsigns = JSON.parse(data);
    }
    if (GT.callsignLookups.eqslLastUpdate == 0)
    {
      eqslDownload();
    }
  }
  catch (e)
  {
    console.log(e);
    GT.callsignLookups.eqslLastUpdate = 0;
    eqslDownload();
  }
}

function eqslSettingsDisplay()
{
  eqslUseEnable.checked = GT.callsignLookups.eqslUseEnable;

  if (GT.callsignLookups.eqslLastUpdate == 0)
  {
    eqslUpdatedTd.innerHTML = "Never";
  }
  else
  {
    eqslUpdatedTd.innerHTML = userTimeString(
      GT.callsignLookups.eqslLastUpdate * 1000
    );
  }

  if (!GT.callsignLookups.eqslUseEnable)
  {
    if (GT.eqslLoadTimer != null) nodeTimers.clearTimeout(GT.eqslLoadTimer);
    GT.eqslLoadTimer = null;
    GT.eqslCallsigns = Object();
  }
  eqslCountTd.innerHTML = Object.keys(GT.eqslCallsigns).length;
}

function eqslValuesChanged()
{
  GT.callsignLookups.eqslUseEnable = eqslUseEnable.checked;
  saveCallsignSettings();
  if (GT.callsignLookups.eqslUseEnable == true)
  {
    eqslLoadCallsigns();
  }
  eqslSettingsDisplay();

  setAlertVisual();
  goProcessRoster();
  if (GT.rosterInitialized) GT.callRosterWindowHandle.window.resize();
}

function eqslDownload(fromSettings)
{
  eqslUpdatedTd.innerHTML = "<b><i>Downloading...</i></b>";
  getBuffer(
    "https://www.eqsl.cc/qslcard/DownloadedFiles/AGMemberList.txt",
    processeqslCallsigns,
    null,
    "https",
    443
  );
}

function processeqslCallsigns(buffer, flag)
{
  var result = String(buffer);
  var lines = Array();
  lines = result.split("\n");
  GT.eqslCallsigns = Object();
  for (x in lines)
  {
    GT.eqslCallsigns[lines[x].trim()] = true;
  }
  GT.callsignLookups.eqslLastUpdate = timeNowSec();

  var now = timeNowSec();
  if (GT.eqslLoadTimer != null) nodeTimers.clearTimeout(GT.eqslLoadTimer);

  var eqslWhenTimer = 86400 * 7 - (now - GT.callsignLookups.eqslLastUpdate);
  GT.eqslWhenDate = now + eqslWhenTimer;
  GT.eqslLoadTimer = nodeTimers.setTimeout(eqslDownload, eqslWhenTimer * 1000);

  if (Object.keys(GT.eqslCallsigns).length > 10000)
  { fs.writeFileSync(GT.eqslFile, JSON.stringify(GT.eqslCallsigns)); }

  eqslSettingsDisplay();
}

function ulsLoadCallsigns()
{
  if (GT.ulsLoadTimer != null)
  {
    nodeTimers.clearTimeout(GT.ulsLoadTimer);
    GT.ulsLoadTimer = null;
  }

  var now = timeNowSec();
  if (now - GT.callsignLookups.ulsLastUpdate > 86400 * 7) ulsDownload();
  else
  {
    var ulsWhenTimer = 86400 * 7 - (now - GT.callsignLookups.ulsLastUpdate);
    GT.ulsWhenDate = now + ulsWhenTimer;
    GT.ulsLoadTimer = nodeTimers.setTimeout(ulsDownload, ulsWhenTimer * 1000);
    updateCallsignCount();
  }
}

function updateQSO()
{
  if (GT.ulsCallsignsCount > 0)
  {
    for (hash in GT.QSOhash)
    {
      var details = GT.QSOhash[hash];
      var lookupCall = false;

      if ((details.cnty == null || details.state == null) && isKnownCallsignDXCC(details.dxcc))
      {
        // Do County Lookup
        lookupCall = true;
      }
      else if (details.cnty != null && isKnownCallsignUSplus(details.dxcc))
      {
        if (!(details.cnty in GT.cntyToCounty))
        {
          if (details.cnty.indexOf(",") == -1)
          {
            if (!(details.state + "," + details.cnty in GT.cntyToCounty))
            {
              lookupCall = true;
            }
          }
          else
          {
            lookupCall = true;
          }
        }
      }
      if (lookupCall)
      {
        if (GT.callsignLookups.ulsUseEnable)
        {
          lookupUsCallsign(details, true);
        }
      }
    }
  }
}

function updateCallsignCount()
{
  GT.ulsDatabase.transaction(function (tx)
  {
    tx.executeSql("SELECT count(*) as cnt FROM calls", [],
      function (tx, results)
      {
        var len = results.rows.length, i;
        if (len == 1)
        {
          GT.ulsCallsignsCount = results.rows[0].cnt;
          ulsCountTd.innerHTML = GT.ulsCallsignsCount;

          updateQSO();
        }
      },
      null
    );
  });
}

function ulsSettingsDisplay()
{
  ulsUseEnable.checked = GT.callsignLookups.ulsUseEnable;

  if (GT.callsignLookups.ulsLastUpdate == 0)
  {
    ulsUpdatedTd.innerHTML = "Never";
  }
  else
  {
    ulsUpdatedTd.innerHTML = userTimeString(GT.callsignLookups.ulsLastUpdate * 1000);
  }

  if (!GT.callsignLookups.ulsUseEnable)
  {
    if (GT.ulsLoadTimer != null) nodeTimers.clearTimeout(GT.ulsLoadTimer);
    GT.ulsLoadTimer = null;
    GT.ulsCallsignsCount = 0;
    ulsCountTd.innerHTML = GT.ulsCallsignsCount;
  }
}

function ulsValuesChanged()
{
  GT.callsignLookups.ulsUseEnable = ulsUseEnable.checked;

  if (GT.callsignLookups.ulsUseEnable == true)
  {
    ulsLoadCallsigns();
  }
  else
  {
    resetULSDatabase();
    ulsCountTd.innerHTML = 0;
  }
  saveCallsignSettings();

  ulsSettingsDisplay();
  goProcessRoster();
  if (GT.rosterInitialized) GT.callRosterWindowHandle.window.resize();
}

function ulsDownload()
{
  ulsUpdatedTd.innerHTML = "<b><i>Downloading...</i></b>";
  ulsCountTd.innerHTML = 0;
  getChunkedBuffer(
    "https://storage.googleapis.com/gt_app/callsigns/callsigns.txt",
    processulsCallsigns,
    null,
    "http",
    80
  );
}

function getChunkedBuffer(file_url, callback, flag, mode, port, cookie, errorHandler)
{
  var url = require("url");
  var http = require(mode);
  var fileBuffer = null;
  var options = null;
  if (cookie != null)
  {
    options = {
      host: url.parse(file_url).host, // eslint-disable-line node/no-deprecated-api
      port: port,
      followAllRedirects: true,
      path: url.parse(file_url).path, // eslint-disable-line node/no-deprecated-api
      headers: {
        Cookie: cookie
      }
    };
  }
  else
  {
    options = {
      host: url.parse(file_url).host, // eslint-disable-line node/no-deprecated-api
      port: port,
      followAllRedirects: true,
      path: url.parse(file_url).path // eslint-disable-line node/no-deprecated-api
    };
  }
  http.get(options, function (res)
  {
    var fsize = res.headers["content-length"];
    var fread = 0;
    var cookies = null;
    if (typeof res.headers["set-cookie"] != "undefined")
    {
      cookies = res.headers["set-cookie"];
    }
    res
      .on("data", function (data)
      {
        var isEnd = false;
        fread += data.length;
        if (fread == fsize) isEnd = true;
        if (fileBuffer == null)
        {
          fileBuffer = callback(data, flag, cookies, true, isEnd);
        }
        else
        {
          fileBuffer = callback(fileBuffer + data, flag, cookies, false, isEnd); // eslint-disable-line node/no-callback-literal
        }
      })
      .on("end", function () {})
      .on("error", function (e)
      {
        ulsUpdatedTd.innerHTML = "<b><i>Error downloading</i></b>";
        console.error("Got error: " + e.message);
      });
  });
}

GT.ulsDatabase = openDatabase(
  "ulsDB",
  "1.0",
  "US Callsigns",
  50 * 1024 * 1024
);

GT.ulsDatabase.transaction(function (tx)
{
  tx.executeSql("CREATE TABLE IF NOT EXISTS calls (callsign TEXT PRIMARY KEY, zip, state)");
});

function resetULSDatabase()
{
  GT.callsignLookups.ulsLastUpdate = 0;
  GT.ulsCallsignsCount = 0;
}

function processulsCallsigns(data, flag, cookies, starting, finished)
{
  var buffer = String(data);
  var returnBuffer = "";

  if (buffer && buffer.length > 0)
  {
    var lines = null;

    if (buffer[buffer.length - 1] == "\n")
    {
      lines = buffer.split("\n");
    }
    else
    {
      var lastIndex = buffer.lastIndexOf("\n");
      returnBuffer = buffer.substring(lastIndex);
      lines = buffer.substring(0, lastIndex).split("\n");
    }

    if (lines.length > 0)
    {
      GT.ulsDatabase.transaction(function (tx)
      {
        if (starting == true)
        {
          if (GT.ulsLoadTimer != null)
          {
            nodeTimers.clearTimeout(GT.ulsLoadTimer);
          }
          GT.ulsLoadTimer = null;
          GT.ulsWhenDate = 0;
          GT.ulsCallsignsCount = 0;
          ulsUpdatedTd.innerHTML = "<b><i>Processing...</i></b>";
          tx.executeSql("delete from calls");
        }
        for (var x in lines)
        {
          if (lines[x].length)
          {
            ++GT.ulsCallsignsCount;
            tx.executeSql("INSERT INTO calls (rowid, callsign, zip, state) VALUES (" + GT.ulsCallsignsCount + ",\"" + lines[x].substr(7) + "\",\"" + lines[x].substr(0, 5) + "\",\"" + lines[x].substr(5, 2) + "\")");
            if (GT.ulsCallsignsCount % 10000 == 0)
            {
              tx.executeSql(
                "SELECT count(*) as cnt FROM calls",
                [],
                function (rx, results)
                {
                  var len = results.rows.length;
                  if (len == 1)
                  {
                    ulsCountTd.innerHTML = results.rows[0].cnt;
                  }
                }
              );
            }
          }
        }
        lines = null;
      });
    }
  }

  if (finished == true)
  {
    var now = timeNowSec();

    if (GT.ulsLoadTimer != null)
    {
      nodeTimers.clearTimeout(GT.ulsLoadTimer);
    }

    var ulsWhenTimer = 86400 * 7;
    GT.ulsWhenDate = ulsWhenTimer + now;
    GT.ulsLoadTimer = nodeTimers.setTimeout(ulsDownload, ulsWhenTimer * 1000);

    GT.ulsDatabase.transaction(function (tx)
    {
      tx.executeSql(
        "SELECT count(*) as cnt FROM calls",
        [],
        function (rx, results)
        {
          var len = results.rows.length,
            i;
          if (len == 1)
          {
            GT.ulsCallsignsCount = results.rows[0].cnt;
            ulsCountTd.innerHTML = GT.ulsCallsignsCount;
            GT.callsignLookups.ulsLastUpdate = timeNowSec();
            saveCallsignSettings();
            ulsSettingsDisplay();
            updateQSO();
          }
        }
      );
    });
  }

  return Buffer(returnBuffer); // eslint-disable-line node/no-deprecated-api
}

function lookupUsCallsign(object, writeState = false)
{
  GT.ulsDatabase.transaction(function (tx)
  {
    let qry = "SELECT * FROM calls where callsign = \"" + object.DEcall + "\"";
    tx.executeSql(
      qry,
      [],
      function (tx, results)
      {
        if (results.rows.length == 1)
        {
          if (object.state == null)
          {
            if (object.dxcc == 1)
            {
              object.state = "CA-" + results.rows[0].state;
            }
            else
            {
              object.state = "US-" + results.rows[0].state;
            }

            if (writeState)
            {
              setState(object);
            }
          }
          object.zipcode = String(results.rows[0].zip);
          if (object.cnty == null)
          {
            let request = GT.Idb.transaction(["lookups"], "readwrite").objectStore("lookups").get(object.DEcall);

            request.onsuccess = function (event)
            {
              if (request.result)
              {
                object.cnty = request.result.cnty;
                object.qual = true;
              }

              if (object.cnty == null && object.zipcode in GT.zipToCounty)
              {
                var counties = GT.zipToCounty[object.zipcode];
                if (counties.length > 1)
                {
                  object.qual = false;
                }
                else
                {
                  object.qual = true;
                }
                object.cnty = counties[0];
              }
              else
              {
                object.qual = false;
              }

              if (writeState)
              {
                setState(object);
              }
            };

            request.onerror = function (event)
            {
              object.qual = false;
              if (writeState)
              {
                setState(object);
              }
            };
          }
          if (writeState)
          {
            setState(object);
          }
        }
      },
      null
    );
  });
}

function downloadCtyDat()
{
  ctyDatStatus.innerHTML = "<b><i>Downloading...</i></b>";
  getBuffer(
    "https://storage.googleapis.com/gt_app/ctydat.json?cb=" + Date.now(),
    processCtyDat,
    null,
    "https",
    443
  );
}

function processCtyDat(buffer)
{
  var data = String(buffer);
  ctyDatStatus.innerHTML = "Update: " + data.length + " bytes read";
  try
  {
    var ctydata = JSON.parse(data);
    var file = "./data/mh-root-prefixed.json";
    if (fs.existsSync(file))
    {
      var fileBuf = fs.readFileSync(file, "UTF-8");
      var dxccInfo = JSON.parse(fileBuf);
      for (const key in dxccInfo)
      {
        dxccInfo[key].ituzone = null;
        dxccInfo[key].cqzone = null;
        dxccInfo[key].prefixITU = {};
        dxccInfo[key].prefixCQ = {};
        dxccInfo[key].directITU = {};
        dxccInfo[key].directCQ = {};

        if (key in ctydata)
        {
          dxccInfo[key].cqzone = padNumber(Number(ctydata[key].cqzone), 2);
          dxccInfo[key].ituzone = padNumber(Number(ctydata[key].ituzone), 2);

          // Skip Guantanamo Bay, hand crafted with love
          if (key != "105")
          {
            dxccInfo[key].prefix = [];
            dxccInfo[key].direct = [];

            var arr = ctydata[key].prefix.substr(0, ctydata[key].prefix.length - 1).split(" ");
            for (const x in arr)
            {
              var test = arr[x];
              var direct = false;
              var cq = null;
              var itu = null;
              
              if (test.charAt(0) == "=")
              {
                direct = true;
                test = test.substr(1);
              }
              var cqTest = test.match(/\((.*)\)/);
              if (cqTest)
              {
                cq = padNumber(Number(cqTest[1]), 2);
              }
              var ituTest = test.match(/\[(.*)\]/);
              if (ituTest)
              {
                itu = padNumber(Number(ituTest[1]), 2);
              }
    
              var i = test.indexOf("(");
              if (i > -1)
              {
                test = test.substr(0, i);
              }
              i = test.indexOf("[");
              if (i > -1)
              {
                test = test.substr(0, i);
              }
              i = test.indexOf("<");
              if (i > -1)
              {
                test = test.substr(0, i);
              }
              i = test.indexOf("{");
              if (i > -1)
              {
                test = test.substr(0, i);
              }
              i = test.indexOf("~");
              if (i > -1)
              {
                test = test.substr(0, i);
              }
              
              if (direct)
              {
                dxccInfo[key].direct.push(test);
                if (cq)
                {
                  dxccInfo[key].directCQ[test] = cq;
                }
                if (itu)
                {
                  dxccInfo[key].directITU[test] = itu;
                }
              }
              else
              {
                dxccInfo[key].prefix.push(test);
                if (cq)
                {
                  dxccInfo[key].prefixCQ[test] = cq;
                }
                if (itu)
                {
                  dxccInfo[key].prefixITU[test] = itu;
                }
              }
            }
            dxccInfo[key].prefix = uniqueArrayFromArray(dxccInfo[key].prefix);
            dxccInfo[key].prefix.sort();
            dxccInfo[key].direct = uniqueArrayFromArray(dxccInfo[key].direct);
            dxccInfo[key].direct.sort();
          }
        }
      }
      fs.writeFileSync(file, JSON.stringify(dxccInfo, null, 2));
      ctyDatFinal.innerHTML = file + " updated!";
    }
  }
  catch (e)
  {
    console.log(e);
  }
}
