
// keep these at the top!
#define VERSIONINFO "Version:  0.03"
#define FW_SCRIPT_VERSION 0.03
#define MIN_COM_SCRIPT_SUPPORTED_VERSION 1.82
#define SCRIPTNAME "VerifyDeviceLicense.spt"

#define CREO_FEATURE_LICENSING_REG_KEY "software\\creo\\featurelicensing\\v1\\databasepath"
#define MAGNUS_VLF_LICENSE_DEF_FILE "ctp_magnus_vlf_ver2.cdf.xml"
#define TRENDSETTER_3244_LICENSE_DEF_FILE "ctp_trendsetter_ver2.cdf.xml"
#define TRENDSETTER_3244_NEWS_LICENSE_DEF_FILE "ctp_trendsetter_news_ver1.cdf.xml"
#define LICENSE_FILE "license.xml"

// svsh registry query types
#define REG_STRING "REG_SZ"
#define REG_DWORD "REG_DWORD"


/*                                    
***********************************************************************************************************************************
* VerifyMagnusVLFDeviceLicense.spt
*
* This script verifies a license by comparing it with the device configuration. This script is 
* intended to be run before the license is installed. It will tell you whether installing the
* license will remove or restrict any current machine features.
*
*
* Version    Date        Author      Description                                                                     
*********************************************************************************************************************************
* 0.03      Jul 11 2006  G.Brown     Added support for 3244 News devices
* 0.02      Feb 03 2006  G.Brown     Added support for 3244 devices and changed the name of the script
* 0.01      Dec 4 2005   M.Joy       Pre-release version - subject to change
*
* Copyright:    Copyright (C) 1998-2006 Creo Products Inc. All Rights Reserved.
*               Reproduction or  disclosure of  this file or  its contents
*               without the  prior written  consent of  Creo Products Ltd.
*               is prohibited.
*
************************************************************************************************************************************/

// includes
#include "CommonUtilities.inc"            //common file used by the device scripts
FILE *f1 = NULL;

void main (void)
{
  int nRC = FAILURE;
  int nHeadType = 0;
  int nNoCodeOnBoard = FALSE;
  int nBaseTrendsetterMPE = 0;
  int nDualMCE = FALSE;
  int nPortNum = 0;

  float fFWversion = 0;
  float fUpgradeVersion = 0;
  float fMCEFWVersion = 0;

  char sDeviceType[STR_LEN];
  char sFWType[10];
  char sMCEFWversion[256];
  char sMCE2FWversion[256];
  char sTransmitMessage[STR_LEN];
  char sTransmitline[STR_LEN];
  char sTmp[STR_LEN];
  char sTmp2[STR_LEN];
  char sConnectionType[STR_LEN];
 
  // check supported versions of included files 
  VersionWarning();

  //----------------------------------------------------------------------
  // Initialize etc.

  COM_SignOn();

  COM_GetConnectionType(sConnectionType);


  COM_GetFWType(sFWType);

  if (strcmp(sFWType, "GMCE") != 0)
  {
    COM_GetPort(sFWType, &nPortNum);
  }

  COM_CheckForPrompt(1, nPortNum, sFWType, nDualMCE);
     
  COM_GetDeviceInfo(sDeviceType, 
                    sFWType, 
                    &fUpgradeVersion, 
                    &nBaseTrendsetterMPE, 
                    nDualMCE, 
                    nNoCodeOnBoard, 
                    &fFWversion, 
                    sMCEFWversion, 
                    sMCE2FWversion, 
                    &nHeadType, 
                    &fMCEFWVersion);

  if (strcmp(sDeviceType, MCE_TRENDSETTER_AL) == 0)
  {
    if (CheckIfNewspaperOrAutoloader(sMCEFWversion) == FALSE)
    {
      COM_Output("Not a MCE News 3244 AL with rotator device.", INFORMATIVE, 0, "");       
    } 
    else
    {
      COM_Output("MCE News 3244 AL with rotator device.", INFORMATIVE, 0, "");      
      strcpy(sDeviceType, MCE_NEWS);
    }
  }
  
  if ( COM_IsMCEVLF(sDeviceType) == FAILURE && 
       IsMCENews(sDeviceType) == FAILURE &&
       IsMCE3244(sDeviceType) == FAILURE)
  {
    COM_Output("Incorrect device type. This device type is not supported.", SUSPEND_BOX, 0 ,"");
    ExitInError();
  }

  transmit ("access dev");
  if (!(waitfor("Command Complete", 5) == SUCCESS))
  {
    LocalOutput("Could not set access dev", "");
    ExitInError();
  }
    
  MainMenu();  

  GetLicenseInfo(sFWType, 
                 sDeviceType, 
                 nHeadType,
                 sConnectionType,
                 sMCEFWversion);
    
  COM_Done();
} 

//----------------------------------------------------------------------------------------
void VerifyBinaryOption (char *fmwOptionName, 
                         char *licenseFeatureName, 
                         char *sLicenseFileLocation, 
                         char* resultString)
{
  char sTransmitLine[STR_LEN];
  char sReturnLine[STR_LEN];
  char sSearchStr[STR_LEN];
  char sMatchedLicenseFileLine[STR_LEN];
  char sTmp[STR_LEN];
  int bOptionEnabled=FALSE;
  int bOptionLicensed=FALSE;

  QueryOption (fmwOptionName, &bOptionEnabled);

  SearchForStringInFile (licenseFeatureName, sLicenseFileLocation, &bOptionLicensed, sMatchedLicenseFileLine);
  if ((TRUE == bOptionEnabled) && (TRUE == bOptionLicensed))
  {
    sprintf (sTmp, "OK:         %s option on the device matches the license (enabled).\n\n", fmwOptionName);
    strcat (resultString, sTmp);
  }
  else if ((TRUE == bOptionEnabled) && (FALSE == bOptionLicensed))
  {
    sprintf (sTmp, "ERROR:     %s option is enabled on the device -- but is not enabled in the license. "
                   "INSTALLING THE LICENSE WILL DISABLE THIS FEATURE!\n\n", fmwOptionName);
    strcat (resultString, sTmp);
  }
  else if ((FALSE == bOptionEnabled) && (TRUE == bOptionLicensed))
  {
    sprintf (sTmp, "Warning: %s option is disabled on the device -- but it is enabled in the license.\n\n", fmwOptionName);
    strcat (resultString, sTmp);
  }
  else if ((FALSE == bOptionEnabled) && (FALSE == bOptionLicensed))
  {
    sprintf (sTmp, "OK:         %s option on the device matches the license (disabled).\n\n", fmwOptionName);
    strcat (resultString, sTmp);
  }


}

//------------------------------------------------------------------------------------------------
void VerifySpeedOption (char* sLicenseFileLocation, 
                        char* resultString,
                        char* sDeviceType,
                        char* sMCEFWversion)
{
  int bLicenseStringFound = FALSE;
  char sMatchedLicenseFileLine[STR_LEN];
  int bLargeDrumEnabled = FALSE;

/*
- need to figure out carriage speed from drum speed, swidth, escan, diameter, resolution
- get max carriage speed over all media
- compare with value parsed from license
*/
  if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
  {
    QueryOption ("largedrum", &bLargeDrumEnabled);
  }

  SearchForStringInFile ("Imaging Speed", sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
  if (FALSE == bLicenseStringFound)
  {
    LocalOutput("Invalid license file -- unable to find Imaging Speed.", "");
    ExitInError();
  }

  int licenseMaxMscanResolution = 1;
  if ( (strstr (sMatchedLicenseFileLine, "value=\"Very Fast Plus\"") != NULL) ||
       (strstr (sMatchedLicenseFileLine, "value=\"X\"") != NULL)   )
  {
    if (TRUE == bLargeDrumEnabled)
    {
      strcat (resultString, "Imaging Speed: X-speed (TH3). Typical maximum speed for large drum: 368 rpm.\n\n");
    }
    else 
    {
      if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
      {
        strcat (resultString, "Imaging Speed: X-speed (TH3). Typical maximum speed for small drum: 448 rpm.\n\n");
      }
      if (IsMCE3244(sDeviceType) == SUCCESS)
      {
        strcat (resultString, "Imaging Speed: X-speed. Typical maximum drum speed: 400 rpm.\n\n");
      }      
    }
  }
  else if (strstr (sMatchedLicenseFileLine, "value=\"Very Fast\"") != NULL)
  {
    if (TRUE == bLargeDrumEnabled)
    {
      strcat (resultString, "Imaging Speed: V-speed (TH2). Typical maximum speed for large drum: 350 rpm.\n\n");
    }
    else
    {
      if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
      {
        strcat (resultString, "Imaging Speed: V-speed (TH2). Typical maximum speed for small drum: 426 rpm.\n\n");
      }      
      if (IsMCE3244(sDeviceType) == SUCCESS)
      {
        strcat (resultString, "Imaging Speed: V-speed. Typical maximum drum speed: 360 rpm.\n\n");      
      }
    }
  }
  else if (strstr (sMatchedLicenseFileLine, "value=\"Fast\"") != NULL)
  {
    if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
    {
      strcat (resultString, "Imaging Speed: F-speed (TH2). Typical maximum drum speed: 236 rpm.\n\n");
    }
    if (IsMCE3244(sDeviceType) == SUCCESS)
    {
      strcat (resultString, "Imaging Speed: F-speed. Typical maximum drum speed: 265 rpm.\n\n");    
    }

  }
  else if (strstr (sMatchedLicenseFileLine, "value=\"Standard\"") != NULL)
  {
    if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
    {
      strcat (resultString, "Imaging Speed: S-speed (TH2). Typical maximum drum speed: 118 rpm.\n\n");
    }
    if (IsMCE3244(sDeviceType) == SUCCESS)
    {
      strcat (resultString, "Imaging Speed: S-speed. Typical maximum drum speed: 165 rpm.\n\n");
    }    
  }
  else 
  {
    LocalOutput("Could not parse licensed Imaging Speed.", "");
    ExitInError();
  }
}

//------------------------------------------------------------------------------------------------
void VerifyQuantumOption (char* sLicenseFileLocation, 
                          char* resultString,
                          char* sFWType,
                          int nHeadType)
{
  int bPremiumHeadOnDevice = TRUE;
  int pPremiumHeadInLicense = TRUE;

  char sLicenseString[STR_LEN];
  int bLicenseStringFound = TRUE;
  char sMatchedLicenseFileLine[STR_LEN];
  char sReturnLine[STR_LEN];
  char sTransmitLine[STR_LEN];

  // Find the value bPremiumHeadOnDevice from the device --------------------

  // Parse the head type from the string
  if (nHeadType == TH17)
  {
    // TH2 - need to check LDD info to determine Premium or Performance
    transmit ("head version");
    if (waitfor("(P33 Imaging)", WAIT_TIME))
    {    
      bPremiumHeadOnDevice = TRUE;
    }
    else 
    {
      bPremiumHeadOnDevice = FALSE;
    }    
  } // if TH2
  else if (nHeadType == TH2)
  {
    // TH2 - need to check LDD info to determine Premium or Performance
    transmit ("th2 \"ldd info");
    if (!(waitreg("Head Model=[ a-zA-Z]*$", sReturnLine, 5) == SUCCESS))
    {
      LocalOutput("Could not determine head model from ldd info.", "");
      ExitInError();
    }
    if (strstr(sReturnLine, "SQUAREspot Imaging") != NULL)
    {
      bPremiumHeadOnDevice = TRUE;
    }
    else if (strstr(sReturnLine, "P33 Imaging") != NULL)
    {
      bPremiumHeadOnDevice = FALSE;
    }
    else
    {
      LocalOutput("Could not parse head model from LDD info.", "");
      ExitInError();
    }
  } // if TH2
  else if (nHeadType == TH3)
  {
     // TH3 - always Premium
     bPremiumHeadOnDevice = TRUE;
  }
  else
  {
    LocalOutput("Could not parse head type.", "");
    ExitInError();
  }

  sprintf(sTransmitLine, "Premium HeadType: '%i'", bPremiumHeadOnDevice);
  COM_Output(sTransmitLine, INFORMATIVE, 0, "");

  // Determine whether the license is Premium or Performance -----------------
  strcpy (sLicenseString, "Head Type\" value=\"Premium\"");
  SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
  if (TRUE == bLicenseStringFound)
  {
     pPremiumHeadInLicense = TRUE;
  }
  else
  {
    strcpy (sLicenseString, "Head Type\" value=\"Performance\"");
    SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
    if (TRUE == bLicenseStringFound)
    {
       pPremiumHeadInLicense = FALSE;
    }
    else
    {
         LocalOutput("Invalid license file -- unable to find Premium/Performance option.", "");
         ExitInError();
    }
  }

  // Compare device setting vs license setting -------------------------------
  if ( (TRUE == bPremiumHeadOnDevice) && (TRUE == pPremiumHeadInLicense) )
  {
     strcat (resultString, "OK:         Quantum head matches Premium option in the license\n\n");
  }
  else if ( (FALSE == bPremiumHeadOnDevice) && (FALSE == pPremiumHeadInLicense) )
  {
     strcat (resultString, "OK:         non-Quantum head matches Performance option in the license\n\n");
  }
  else if ( (TRUE == bPremiumHeadOnDevice) && (FALSE == pPremiumHeadInLicense) )
  {
     strcat (resultString, "ERROR:      Quantum head mis-match with Performance option in the license." 
                           "IF YOU INSTALL THE LICENSE, THE HEAD WILL NOT PLOT.\n\n");
  }
  else if ( (FALSE == bPremiumHeadOnDevice) && (TRUE == pPremiumHeadInLicense) )
  {
     strcat (resultString, "ERROR:      non-Quantum head mis-match with Premium option in the license." 
                           "IF YOU INSTALL THE LICENSE, THE HEAD WILL NOT PLOT.\n\n");
  }
      
}

//------------------------------------------------------------------------------------------------
void VerifyPlateSizes (char *sLicenseFileLocation, 
                       char* resultString,
                       char* sDeviceType)
{
  int bLargeDrumEnabled = FALSE;
  int bLicenseStringFound = FALSE;
  char sMatchedLicenseFileLine[STR_LEN];

  if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
  {
    QueryOption ("largedrum", &bLargeDrumEnabled);

    // Check for 6383
    SearchForStringInFile ("<package name=\"Plate Size\" value=\"6383\"", 
                           sLicenseFileLocation, 
                           &bLicenseStringFound, 
                           sMatchedLicenseFileLine);
     if (TRUE == bLicenseStringFound)
     {
       if (TRUE == bLargeDrumEnabled)
       { 
         strcat (resultString, "OK:         Licensed format size: 6383."
                               "Licensed plate size limits are the same as physical limits for large drum device\n\n");
       }
       else
       {
         strcat (resultString, "Warning: largedrum option disabled on the device conflicts with 6383 format size in device license.\n\n");
       }
     } // if 6383
     else // Check for 5183
     {
       SearchForStringInFile ("<package name=\"Plate Size\" value=\"5183\"", sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
       if (TRUE == bLicenseStringFound) // 5183
       {
         if (FALSE == bLargeDrumEnabled)
         { 
           strcat (resultString, "OK:         Licensed format size: 5183." 
                                 "Licensed plate size limits are the same as physical limits for small drum device.\n\n");
         }
         else
         {
           strcat (resultString, "ERROR:     largedrum option enabled on the device, conflicts with 5183 format size in device license.\n\n");
         }
       } // if 5183
       else // Check for 4570
       {
         SearchForStringInFile ("<package name=\"Plate Size\" value=\"4570\"", sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
         if (TRUE == bLicenseStringFound) // 4570
         {
           if (FALSE == bLargeDrumEnabled)
           { 
             strcat (resultString, "Check Plate Sizes: Licensed format size: 4570. Licensed maximum plate sizes: Mainscan 1169 mm (46 inches)."
                                   "Dual-plate Subscan 889 mm (35 inches). Single-plate Subscan single stack 1804 mm (71 inches).\n\n");
           }
           else
           {
             strcat (resultString, "ERROR:     largedrum option enabled on the device, conflicts with 4570 format size in device license.\n\n");
           }
         } // if 4570
         else // Check for 5570
         {
           SearchForStringInFile ("<package name=\"Plate Size\" value=\"5570\"", sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
           if (TRUE == bLicenseStringFound) // 5570
           {
             if (TRUE == bLargeDrumEnabled)
             { 
               strcat (resultString, "Check Plate Sizes: Licensed format size: 5570. Licensed maximum plate sizes: Mainscan 1423 mm (56 inches);"
                                     " Dual-plate Subscan 889 mm (35 inches); Single-plate Subscan single stack 1804 mm (71 inches).\n\n");
             }
             else
             {
               strcat (resultString, "ERROR:     largedrum option disabled on the device, conflicts with 5570 format size in device license.\n\n");
             }
           } // if 5570
           else
           {
             LocalOutput("Invalid license file -- unable to find valid Plate Size.", "");
             ExitInError();
           }
         } // else -- check for 5570
       } // else -- check for 4570
     } // else -- Check for 5183
  }
}


//------------------------------------------------------------------------------------------------
void VerifyAutomation(char *sLicenseFileLocation, 
                      char* resultString,
                      char *sDeviceType,
                      char *sMCEFWversion)
{
  int bAutoloaderEnabled=FALSE;
  int bContinuousLoadEnabled=FALSE;
  int bMCUEnabled=FALSE;
  char sReturnLine[STR_LEN];
  char sSearchStr[STR_LEN];
  char sTmp[STR_LEN];
  char sLicenseString[STR_LEN];
  int bLicenseStringFound = FALSE;
  char sMatchedLicenseFileLine[STR_LEN];

  // Check autoloader option  -------------------------------
  QueryOption ("autoloader", &bAutoloaderEnabled); 

  if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
  {
    // Check MCU option  -------------------------------
    QueryOption ("mcu", &bMCUEnabled); 

    if (TRUE == bMCUEnabled)
    {
      // Look for MCU license
      strcpy (sLicenseString, "package name=\"Automation\" value=\"MCU\"");
      SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
    }
    else if ( (FALSE == bMCUEnabled) && (TRUE == bAutoloaderEnabled) )
    {
       // Look for CL license
      strcpy (sLicenseString, "package name=\"Automation\" value=\"Continuous Load\"");
      SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
    }
    else if ( (FALSE == bMCUEnabled) && (FALSE == bAutoloaderEnabled) )
    {
      // Look for SA license
      strcpy (sLicenseString, "package name=\"Automation\" value=\"Semi-automatic\"");
      SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
    }
  }  
  if (IsMCE3244(sDeviceType) == SUCCESS)
  {
    QueryOption ("ContinuousLoad", &bContinuousLoadEnabled); 

    if (TRUE == bAutoloaderEnabled) 
    {
       // Look for autoloader license
      strcpy (sLicenseString, "package name=\"Automation\" value=\"Autoloader\"");
      SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
    }
    else if (TRUE == bContinuousLoadEnabled) 
    {
      // Look for continuous license
      strcpy (sLicenseString, "package name=\"Automation\" value=\"Continuous\"");
      SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);
    }
    else
    {
      // Look for base license
      strcpy (sLicenseString, "package name=\"Automation\" value=\"Base\"");
      SearchForStringInFile (sLicenseString, sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);    
    }  
  }
    
  if (TRUE == bLicenseStringFound) 
  {
    strcat (resultString, "OK:         Automation options on the device match the license\n\n");
  }
  else 
  {
    strcat (resultString, "Warning: Automation options on the device do not match the license."
                          "Note: device firmware does not currently check this option.\n\n");
  }
}



//---------------------------------------------------------------------------------------------------
void VerifyResolution(char *sLicenseFileLocation, char* resultString)
{
  char sTmp[STR_LEN];
  char sTmp2[STR_LEN];
  int modeIndex=0;
  int deviceMaxMscanResolution = 1;
  int deviceMaxSscanResolution = 1;
  int bLicenseStringFound = FALSE;
  char sMatchedLicenseFileLine[STR_LEN];
  int tempResolution=0;
  int tempIndex=0;
  int tempJunk=-1;
  char sReturnLine[STR_LEN];

  // Check mainscan resolution ------------------------------------------------
  for (modeIndex = 1; modeIndex <=4; modeIndex++)
  {
    sprintf (sTmp, "set mode %d mscanresolution", modeIndex);
    transmit (sTmp);
    // Looking for a string that looks like this: MscanResolution[1] 2400
    if (!(waitreg("MscanResolution\[[1-4]\] *[0-9]* ", sReturnLine, 5) == SUCCESS))
    {
      LocalOutput("Could not determine mainscan resolution.", "");
      ExitInError();
    }

    // Parse the resolution from the string
    if (sscanf(sReturnLine, "MscanResolution[%d] %d", &tempIndex, &tempResolution) !=2)
    {
      LocalOutput("Could not parse mainscan resolution.", "");
      ExitInError();
    }
    if (tempResolution > deviceMaxMscanResolution)
    {  
      deviceMaxMscanResolution = tempResolution;
    }

  } // for modeIndex

  sprintf (sTmp, "detected max mainscan resolution: %d", deviceMaxMscanResolution);
  COM_Output(sTmp, INFORMATIVE, 0, "");

  // Verify that the licensed mainscan resolution is better than the enabled license  
  SearchForStringInFile ("Mainscan Resolution", sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);

  if (FALSE == bLicenseStringFound)
  {
    LocalOutput("Invalid license file -- unable to find mainscan resolution.", "");
    ExitInError();
  }

  int licenseMaxMscanResolution = 1;
  if (sscanf (sMatchedLicenseFileLine, " <package name=\"Mainscan Resolution\" value=\"%d", &licenseMaxMscanResolution) !=1)
  {
    LocalOutput("Could not parse licensed mainscan resolution.", "");
    ExitInError();
  }

  sprintf (sTmp, "licensed max mainscan resolution: %d", licenseMaxMscanResolution);
  COM_Output(sTmp, INFORMATIVE, 0, "");
  if (deviceMaxMscanResolution > licenseMaxMscanResolution)
  {
    sprintf (sTmp, "ERROR:     Device mainscan resolution %d for one of the configured resolution modes is greater than the max licensed mainscan resolution."
                   "IF YOU INSTALL THE LICENSE, THE DEVICE WILL NOT PLOT AT THIS RESOLUTION!\n\n", deviceMaxMscanResolution);
    strcat (resultString, sTmp);
  }
  else
  {
    strcat (resultString, "OK:         Device mainscan resolution does not exceed licensed max mainscan resolution.\n\n");
  }


  // Check subscan resolution ------------------------------------------------
  for (modeIndex = 1; modeIndex <=4; modeIndex++)
  {
    sprintf (sTmp, "set mode %d sscanresolution", modeIndex);
    transmit (sTmp);
    // Looking for a string that looks like this: SscanResolution[1] 2400
    if (!(waitreg("SscanResolution\[[1-4]\] *[0-9]* ", sReturnLine, 5) == SUCCESS))
    {
      LocalOutput("Could not determine subscan resolution.", "");
      ExitInError();
    }

    // Parse the resolution from the string
    if (sscanf(sReturnLine, "SscanResolution[%d] %d", &tempIndex, &tempResolution) !=2)
    {
      LocalOutput("Could not parse subscan resolution.", "");
      ExitInError();
    }
    if (tempResolution > deviceMaxSscanResolution)
    {  
      deviceMaxSscanResolution = tempResolution;
    }

  } // for modeIndex

  sprintf (sTmp, "detected max subscan resolution: %d", deviceMaxSscanResolution);
  COM_Output(sTmp, INFORMATIVE, 0, "");

  // Verify that the licensed mainscan resolution is better than the enabled license  
  SearchForStringInFile ("Subscan Resolution", sLicenseFileLocation, &bLicenseStringFound, sMatchedLicenseFileLine);

  if (FALSE == bLicenseStringFound)
  {
    LocalOutput("Invalid license file -- unable to find subscan resolution.", "");
    ExitInError();
  }

  int licenseMaxSscanResolution = 1;
  if (sscanf (sMatchedLicenseFileLine, " <package name=\"Subscan Resolution\" value=\"%d", &licenseMaxSscanResolution) !=1)
  {
    LocalOutput("Could not parse licensed subscan resolution.", "");
    ExitInError();
  }

  sprintf (sTmp, "licensed max subscan resolution: %d", licenseMaxSscanResolution);
  COM_Output(sTmp, INFORMATIVE, 0, "");
  if (deviceMaxSscanResolution > licenseMaxSscanResolution)
  {
    sprintf (sTmp, "ERROR:     Device subscan resolution %d for one of the configured resolution modes is greater than the max licensed mainscan resolution." 
                   "IF YOU INSTALL THE LICENSE, THE DEVICE WILL NOT PLOT AT THIS RESOLUTION!\n\n", deviceMaxSscanResolution);
    strcat (resultString, sTmp);
  }
  else
  {
    strcat (resultString, "OK:         Device subscan resolution does not exceed licensed max subscan resolution.\n\n");
  }

}

//----------------------------------------------------------------------------------------
void VerifyDeviceConfig(char *sLicenseFileLocation, char* resultString)
{
  char sMatchedLicenseFileLine[STR_LEN];
  char sReturnLine[STR_LEN];
  char sConfiguredDeviceType[STR_LEN];
  char sTemp[STR_LEN];
  int bModelStringFound = FALSE;
  int bCommercialDevice = FALSE;


  transmit ("config");
  
  if (!(waitreg("\[[A-Za-z0-9_ ]+\]", sReturnLine, WAIT_TIME) == SUCCESS))
  {
    strcat (resultString, "Could not determine device config value, firmware has most likely already been upgraded.\n\n");
  }
  else
  {
     waitfor("Command Complete", 10);
     strcpy(sConfiguredDeviceType, sReturnLine);
     transmit("mode");
     if (waitfor("2400 by 2400 DPI", WAIT_TIME))
     {     
       COM_Output("Not a Commercial News Device", INFORMATIVE, 0, "");
       bCommercialDevice = FALSE;     
     }
     else
     {
       COM_Output("A Commercial News Device", INFORMATIVE, 0, "");
       bCommercialDevice = TRUE;
     }
     if (strcmp(sConfiguredDeviceType, "[NEWS50]") == 0)
     {
       if (bCommercialDevice == TRUE)
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"50C\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
       }       
       else
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"50\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
       }

     }
     else if (strcmp(sConfiguredDeviceType, "[NEWS70]") == 0)
     {
       if (bCommercialDevice == TRUE)
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"70C\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
       }
       else
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"70\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine);        
       }
     }
     else if (strcmp(sConfiguredDeviceType, "[NEWS100]") == 0)
     {
       if (bCommercialDevice == TRUE)
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"100C\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
       }
       else
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"100\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine);        
       }
     }
     else if (strcmp(sConfiguredDeviceType, "[NEWS150]") == 0)
     {
       SearchForStringInFile ("name=\"Model Type\" value=\"150\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
     }
     else if (strcmp(sConfiguredDeviceType, "[NEWS200]") == 0)
     {
       if (bCommercialDevice == TRUE)
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"200C\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
       }
       else
       {
         SearchForStringInFile ("name=\"Model Type\" value=\"200\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
       }
     }
     else if (strcmp(sConfiguredDeviceType, "[NEWS_SA]") == 0)
     {
       SearchForStringInFile ("name=\"Model Type\" value=\"SA\"", sLicenseFileLocation, &bModelStringFound, sMatchedLicenseFileLine); 
     }
     
     if (TRUE == bModelStringFound) 
     {
       sprintf(sTemp, "OK:         The firmware config value '%s' and the device resolutions matches the license.\n\n", sConfiguredDeviceType);
       strcat(resultString, sTemp);
     }
     else 
     {
       sprintf(sTemp, "Warning: The firmware config value '%s' and or the device resolutions does not match the license.\n\n", sConfiguredDeviceType);  
       strcat(resultString, sTemp);
     }
  }
}

//----------------------------------------------------------------------------------------
void QueryOption (char* optionName, int* bOptionEnabled)
{
  char sTmp[STR_LEN];
  char sReturnLine[STR_LEN];
  
  *bOptionEnabled = FALSE;

  sprintf (sTmp, "option %s", optionName);
  transmit (sTmp);
  if (!(waitreg("option is [^\r]+\r", sReturnLine, 5) == SUCCESS))
  {
    sprintf (sTmp, "Could not determine %s option value.", optionName);
    LocalOutput(sTmp, "");
    ExitInError();
  }
  if (strstr(sReturnLine, "enabled") != NULL)
  // record the result and continue
  {
     *bOptionEnabled = TRUE;
     sprintf (sTmp, "%s option is enabled", optionName);      
  }
  else 
    if (strstr(sReturnLine, "disabled") != NULL)
    {
      *bOptionEnabled = FALSE;       
      sprintf (sTmp, "%s option is disabled", optionName);      
    }
    else 
      {
        sprintf (sTmp, "Unable to determine %s option value.", optionName);
        LocalOutput(sTmp, "");
        ExitInError();
      }

  COM_Output(sTmp, INFORMATIVE, 0, "");

}

//---------------------------------------------------------------------------------------------------
void SearchForStringInFile (char* sStringToFind, 
                            char *sFilePath, 
                            int* pbStringFound, 
                            char *sFileLineContainingMatch)
{

  char sLine[512];
  char sTmp[STR_LEN];

  int bDone = FALSE;  

  if (COM_OpenFile(&f1, sFilePath, MODE_READ_ONLY ) == FAILURE)
  {    
    sprintf (sTmp, "Could not open license file %s", sFilePath);
    LocalOutput(sTmp, "");
    ExitInError();
  }

  *pbStringFound = FALSE;
  
  while(FALSE == bDone)
  {
    if (fgets(sLine, 512 /* max characters */, f1) == NULL)
    {
      bDone = TRUE;
    }
    else if (strstr(sLine, sStringToFind) != NULL)
    {     
      bDone = TRUE;
      *pbStringFound = TRUE;
      strcpy (sFileLineContainingMatch, sLine);
    }
  } // while


  fclose(f1);

  return (SUCCESS);

} // SearchInLicenseFile


//---------------------------------------------------------------------------------------------------
void GetLicenseFileLocation (char *sLicenseFileLocation)
{
  char sTmp[STR_LEN];
  char sTmp2[STR_LEN];

  int nRC = 0;
  int i = 0;
    while (nRC < 4)
    {
      if (nRC >= 0)
      {
      if (nRC == 3)
      {
        strcpy(sTmp ,"*.*");
        i = access (sTmp, 00);
        if ( i == 0 )
        {
          strcpy (sLicenseFileLocation, sTmp);
        }
      }
      dialog("Please browse to the location of the license file", 1, 3,            
             "License file location (license.xml)", CTEXT | 1, 0, 0, 200, 5,
             sLicenseFileLocation, EDITBOX | 2, 110, 0, 200, 5,
             "Browse...", BUTTON | 3, 320, 0, 100, 7, 
             "Continue", BUTTON | 4, 0, 10, 100, 7,
             "Cancel", BUTTON | 5, 120, 10, 100, 7);
      sleep(100);     // Sleep so we don't hog the CPU while polling the dialog.
      }
      nRC = dialog(sTmp);
    

      if (nRC != -1)
      {
        COM_Output(sTmp2, INFORMATIVE, 0, "");
      }
      if (nRC == -2)   
      {
        // user hit the x button in the corner of the dialog box
        COM_Done();
      }

      if (nRC == 5)   
      {
        // user hit the x button in the corner of the dialog box
        COM_Done();
      }

    }
    // Erase the dialog box.
    dialog("");
    sprintf (sTmp2, "User defined license file location: %s", sLicenseFileLocation);
    COM_Output(sTmp2, INFORMATIVE, 0, "");
}

//----------------------------------------------------------------------------------------
void ExitInError(void)
{
  char sTransmitline[STR_LEN];
  sprintf(sTransmitline,";%s has now ended.", SCRIPTNAME);
  transmit(sTransmitline); 
  exit(0);
} // ExitInError

//----------------------------------------------------------------------------------------
void LocalOutput(char *sOutputMessage, char *sWaitForString)
{

  char sTransmitMessage[STR_LEN];
  char sTmp[STR_LEN];
  int nRC = 0;
  int dialogHeight = 100;

  COM_Output ("Dumping the output message:", INFORMATIVE, 0, "");

  printf("%s", sOutputMessage);
  COM_BreakStringIntoChunksAndTrasmit(sOutputMessage);
  printf("%s", sWaitForString);
  COM_BreakStringIntoChunksAndTrasmit(sWaitForString);

  while (nRC < 1)
  {
    if (nRC >= 0)
    {
      dialog("Attention!", 1, 1,
             sOutputMessage, CTEXT | 5, -1, -1, 400, dialogHeight,
             "Quit", BUTTON | 1, 0, (dialogHeight-10), 100, 7);
    }
    sleep(100);     // Sleep so we don't hog the CPU while polling the dialog.
    nRC = dialog(sTmp);
    if (nRC == DIALOG_CLOSE) 
    {
      // user hit the x button in the corner of the dialog box
      ExitInError();
    }
  }
  // Erase the dialog box.
  dialog("");

} // LocalOutput

//------------------------------------------------------------------------------------------------------------------------------------------------------------
//Description:
//     This function checks for the proper CommonUtilities.inc file
//
//  Input:
//       None
//  Output:
//       None
//              
//
//  Return:
//       Nothing
//       
//------------------------------------------------------------------------------------------------------------------------------------------------------------
void VersionWarning(void)
{
  char sTransmitline[STR_LEN];

  if (COM_SCRIPT_VERSION  < MIN_COM_SCRIPT_SUPPORTED_VERSION)
  {
    sprintf(sTransmitline, "Upgrade CommonUtilities.inc to version %3.2f or higher!", MIN_COM_SCRIPT_SUPPORTED_VERSION);
    msgbox(sTransmitline, "Error");
    transmit(sTransmitline);
    printf(sTransmitline);
    ExitInError();
  }
}   

//------------------------------------------------------------------------------------------------------------------------------------------------------------
//Description:
//     This function preforms the majority of the functions in this script
//
//  Input:
//       None
//  Output:
//       None
//              
//
//  Return:
//       Nothing
//       
//------------------------------------------------------------------------------------------------------------------------------------------------------------
void GetLicenseInfo(char* sFWType, 
                    char* sDeviceType, 
                    int nHeadType,
                    char* sConnectionType,
                    char* sMCEFWversion)
{
  char sResultString[8*STR_LEN];
  char sReturnValue[STR_LEN];
  char sLicenseFileLocation[STR_LEN];

  strcpy (sResultString, "");

  // if connected remotely get the file from the user don't try to find it automatically
  if (strcmp(sConnectionType, LOCAL_CONNECTION) != 0)
  {
    GetLicenseFileLocation (sLicenseFileLocation);   
  }
  else
  {
    // try to see if we can get access to the feature licensing file if not get it from the user
    if (GetRegistryValue(sFWType, CREO_FEATURE_LICENSING_REG_KEY, REG_STRING, sReturnValue) == FAILURE)
    {
      GetLicenseFileLocation (sLicenseFileLocation);
    }
    else
    {
      sprintf(sLicenseFileLocation, "%s\\%s", sReturnValue, LICENSE_FILE);
  
      // try to see if we have access to the file if not get it from the user
      if (access(sLicenseFileLocation, 0))
      {
         GetLicenseFileLocation (sLicenseFileLocation);
      }
    }
  }

  dialog("Checking Parameters", 1, 1,
         "Checking Device Parameters...",CTEXT | 1);


  //-------------------------------------------------------------------
  // verify all the options
  if (COM_IsMCEVLF(sDeviceType) == SUCCESS)
  {
    VerifyBinaryOption("processorinterface", "Processor Interface", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("portrait",           "Portrait Loading", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("dual-plate",         "Dual Plate Loader", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("rotator",            "Rotator", sLicenseFileLocation, sResultString);
    
    VerifySpeedOption(sLicenseFileLocation, sResultString, sDeviceType, sMCEFWversion);
    VerifyAutomation(sLicenseFileLocation, sResultString, sDeviceType, sMCEFWversion);
    VerifyPlateSizes(sLicenseFileLocation, sResultString, sDeviceType);
    VerifyResolution(sLicenseFileLocation, sResultString);
    VerifyQuantumOption(sLicenseFileLocation, sResultString, sFWType, nHeadType);
  }

  if (IsMCENews(sDeviceType) == SUCCESS)
  {
    VerifyBinaryOption("processorinterface", "\"Processor Interface\" value=\"1\"", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("rotator",            "\"Rotator\" value=\"1\"", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("dual-head",          "name=\"Model Type\" value=\"200", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("preloader",          "\"Preloader\" value=\"1\"", sLicenseFileLocation, sResultString);    
    VerifyQuantumOption(sLicenseFileLocation, sResultString, sFWType, nHeadType);  
    VerifyDeviceConfig(sLicenseFileLocation, sResultString);
  }

  if (IsMCE3244(sDeviceType) == SUCCESS)
  {
    VerifyBinaryOption("processorinterface", "Processor Interface", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("rotator",            "Rotator", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("spectrum",           "<option name=\"Proofing\" value=\"1\" \/>", sLicenseFileLocation, sResultString);
    VerifyBinaryOption("VMR",                "Variable Mainscan Resolution", sLicenseFileLocation, sResultString); 
    VerifySpeedOption(sLicenseFileLocation, sResultString, sDeviceType, sMCEFWversion);
    VerifyAutomation(sLicenseFileLocation, sResultString, sDeviceType, sMCEFWversion);
    VerifyResolution(sLicenseFileLocation, sResultString);
    VerifyQuantumOption(sLicenseFileLocation, sResultString, sFWType, nHeadType);
  }
  
  LocalOutput(sResultString, "");
}

//------------------------------------------------------------------------------------------------------------------------------------------------------------
//This function gives the user for script details
//------------------------------------------------------------------------------------------------------------------------------------------------------------
void MainMenu(void)
{
  int rc = 0;
  char tmp[256];

  while (rc < 10)              // while a button is not pressed loop exit loop once the continue or cancel buttons pressed
  {
    if (rc >= 0)
    {
      dialog("Carrier hole setup.", 
             "This script will determine whether the options in your firmware and the license you currently have match.\n"
             "This script will check the current device configuration against a license file.\n"
             "It is intended to be run before you upgrade the controlled release or install the license,"
             " to ensure that the license will not disable any features which are currently operating on the device.\nThis script simply reports information. "
             "It will not modify the device configuration or license.\n", CTEXT | 5, 0, 0, 350, 25,
             "Continue", BUTTON | 10, 0, 30, 100, 7,             
             "Cancel", BUTTON | 11, 110, 30, 100, 7);
    }
    sleep(100);     // Sleep so we don't hog the CPU while polling the dialog.
    rc = dialog(tmp);
    if (rc == -2)
    { 
      // user hit the x button in the corner of the dialog box
      COM_Done();
    }
  }        
  dialog("");
  if (rc == 11)
  {
    COM_Done();
  }
  return(rc);
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------
//  This function queries the host for registy information.
//
//  type should be either 'REG_SZ' or 'REG_DWORD'
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
int GetRegistryValue(char *device, 
                         char *sQueryReg,
                         char *sType,                          
                         char *sReturnValue)
{
  int nRC = SUCCESS; 
  char sTransmitline[STR_LEN];
  char sCaptureString[STR_LEN];
  char sParseString[STR_LEN];

  sprintf(sTransmitline, "talkto %s", SSDIAG);
  transmit(sTransmitline);

  sprintf(sTransmitline,"svsh registry query %s %s", sQueryReg, sType);
  
  transmit(sTransmitline);

  if (waitreg("VALUE=\"[^\"]*\"", sCaptureString, WAIT_TIME))
  {            
    sprintf(sTransmitline, "talkto %s", device);
    transmit(sTransmitline);
    COM_Output("Registry value not found.", INFORMATIVE, 0, "");
    nRC = FAILURE; 
  }
  else
  {
    sprintf(sTransmitline, "talkto %s", device);
    transmit(sTransmitline);
    strcpy(sParseString, sCaptureString + strlen("VALUE=\""));
    sParseString[strlen(sParseString) - 1] = '\0';
    sprintf(sTransmitline, "Registry value found \"%s\"", sParseString);
    COM_Output(sTransmitline, INFORMATIVE, 0, "");
    strcpy(sReturnValue, sParseString);
  }

  return nRC;
}

//------------------------------------------------------------------------------------------------------------------------------------------------------------
// This functions returns if the device is a MCE 3244 device or not
//
//------------------------------------------------------------------------------------------------------------------------------------------------------------/
int IsMCE3244(char *sDeviceType)
{
  if (strcmp(sDeviceType, MCE_TRENDSETTER_SP) == 0 ||
      strcmp(sDeviceType, MCE_TRENDSETTER_CL_SP) == 0 ||
      strcmp(sDeviceType, MCE_TRENDSETTER_AL_SP) == 0 ||
      strcmp(sDeviceType, MCE_TRENDSETTER) == 0 || 
      strcmp(sDeviceType, MCE_TRENDSETTER_AL) == 0 ||
      strcmp(sDeviceType, MCE_TRENDSETTER_CL) == 0)
  {
    COM_Output("MCE 3244 device.", INFORMATIVE, 0, "");
    return(SUCCESS);
  }
  else
  {
    COM_Output("Not a MCE 3244 device.", INFORMATIVE, 0, "");
    return(FAILURE);
  }
}

//------------------------------------------------------------------------------------------------------------------------------------------------------------
// This functions returns if the device is a MCE 3244 device or not
//
//------------------------------------------------------------------------------------------------------------------------------------------------------------/
int IsMCENews(char *sDeviceType)
{
  if (strcmp(sDeviceType, MCE_NEWS) == 0)
  {
    COM_Output("MCE News 3244 device.", INFORMATIVE, 0, "");
    return(SUCCESS);
  }
  else
  {      
    COM_Output("Not a MCE News 3244 device.", INFORMATIVE, 0, "");
    return(FAILURE);
  }
}

//------------------------------------------------------------------------------------------------------------------------------------------------------------
//This function asks the user if the system is a newspaper or autoloader.
//------------------------------------------------------------------------------------------------------------------------------------------------------------
int CheckIfNewspaperOrAutoloader(char *sMCEFWversion)
{
  int nNewspaper = FALSE;
  int rc = 0;
  int nHeadType = 0;

  char tmp[STR_LEN];
  char sFWType[STR_LEN];

  float fFWversion = 0;

  strcpy(sFWType, MCENAME);
  COM_GetHeadType(sFWType, &nHeadType);

  dialog("Device Type", 1, 1,
         "Checking if device is an 3244 Autoloader or a Newspaper device...",CTEXT | 1);

  COM_ConvertFWVersionToFloat(sMCEFWversion, &fFWversion);

  if (fFWversion < 136) 
  {
    if (nHeadType != TH2)
    {
      Output("access dev", TERMINAL, WAIT_TIME, "Command Complete");
 
      transmit("config");

      if (!waitfor("[NEWS", WAIT_TIME))
      {
        nNewspaper = TRUE;   
      }
      waitfor("Command Complete", 10);
    }
    else
    {
      nNewspaper = TRUE;   
    }
  }
  else
  {
     Output("access dev", TERMINAL, WAIT_TIME, "Command Complete");
 
     transmit("license");

     if (waitfor("Trendsetter", WAIT_TIME))
     {
       nNewspaper = TRUE;   
     }
     waitfor("Command Complete", WAIT_TIME);       
  }
  
  
  if (nNewspaper == TRUE)
  {
    COM_Output("Newspaper Device", INFORMATIVE, 0, "");
  }
  else
  {
    COM_Output("Not a Newspaper Device", INFORMATIVE, 0, "");
  }

  // Erase the dialog box.
  dialog("");

  return(nNewspaper);
}

