/*****************************************************************************/
/*
                                HyperSpi.c

This application generates VMS System Performance Information HTML documents.  
Coupled with 'HyperSpi$agent.c', the data-collection application, it can 
profile, complete with graphics, fundamental system performance indicators as 
CPU usage, memory usage, IO values.

It operates in two distinct modes, text and graphic.  In text mode it returns 
an HTML stream to the browser comprising a hypertext page, with selection 
menu, node performance presentation page, data listing or dump page.  In 
graphic mode it returns a GIF image to the browser, first processing the 
specified data into an in-memory bitmap graph, then sending this image to the 
client via an internal GIF processor. 

A node preformance presentation page may have one or more HTML <IMG...> tags 
within it.  Each of these tags will separately cause the browser to invoke the 
application to generate a graphic from the data specified in the SRC= URL. 

If the /NODES= qualifier specifies a comma-separated list of node names these 
are used in the menus for listing the available nodes.  If this is not 
supplied the data directory is searched for current-day data files, those 
found have the respective node name extacted and these are used to list the 
nodes. 

The /STYLE= qualifier provide for a URL to a site-local style file.  This
allows the internal styles to be over-loaded.

Button labels are customizable (potentially to non-English language). They
comprise a label, equate symbol and URL-style path suitable for creating a
link.  Multiple buttons are separated using the semicolon. Note that any such
button customization must provide escaped HTML-forbidden characters in the
button label and URI-forbidden characters in the path!  See DEFAULT_BUTTONS.

Here is an example of changing the button labels:

  /BUTTON="Selector$Help=/hyperspi/-/hyperspi.html"

Always have the equivalent of "Close" for the first button!  Additional buttons
may be created by adding "label=path;" elements to the button string.  In this
way an additional information page could be referenced as follows:

  /BUTTON="&#8630;Back=javascript:parent.history.go(-1)$" +
          "Selector$^Help=/hyperspi/-/hyperspi.html$^Other VMS=/vms/"

DIFFICULTY FITTING ALL THESE QUALIFIERS INTO A COMMAND LINE OR LOGICAL?
Use an existing, or create a new, DCL wrapper procedure for the script (same
name and directory) and build up a DCL symbol to provide the information. Up
to 1024 characters can be included in this way. For example:

  $ HYPERSPI$PARAM = "/BUTTON=""Select$Help=/hyperspi/-/hyperspihelp.html"""
  $ HYPERSPI$PARAM = HYPERSPI$PARAM + "/STYLE=""/hyperspi/-/local.css"""
  $ RUN HT_EXE:HYPERSPI


OSU ENVIRONMENT
---------------
Script responses are returned in OSU "raw" mode; the script taking care of the
full response header and correctly carriage-controlled data stream, text or
binary!!  Uses the CGILIB.C to engage in the dialog phase generating, storing
and then making available the equivalent of CGI variables.


"VANILLA" CGI ENVIRONMENT
-------------------------
Primarily for the likes of Netscape FastTrack.  This environment can accomodate
CGI variables that are not prefixed with "WWW_" and do not supply "KEY_xxxxx"
or "FORM_xxxxx" (which must be derived from "QUERY_STRING").  Full HTTP stream
(non-parsed header) is assumed as not supported so all output occurs with a
CGI-compliant header line (e.g. "Status: 200 Success") and record-oriented
output.


CGI VARIABLES
-------------
FORM_BUFFERED_IO        if non-null then buffered IO requested
FORM_CPU        if non-null then cpu usage requested
FORM_DO         what to do(!): "DUMP", "GRAPH", "LIST", "PAGE", "MENU"
FORM_DAY        the (first) day of the data file(s)
FORM_DIRECT_IO  if non-null then direct IO requested
FORM_EXTRACT    if non-null provide a link to allow graph extraction
FORM_HOUR       the (first) hour of the data
FORM_INCLUDE    additional category: PEAK, TOTAL (only with "user-mode-cpu"),
                                     HARD-FAULTS (only with "faults")
FORM_LIST_NODE  name of node to process data (see also FORM_NODE)
FORM_MINUTE     the (first) minute of the data
FORM_MONTH      the (first) month of the data file(s)
FORM_MSCP_IO    if non-null then MSCP IO requested
FORM_NET_INT    network interface traffic
FORM_NODE       name of node to process data (used before FORM_LIST_NODE)
FORM_PERIOD     standard period (e.g. "until" now, "business", "today",
                "yesterday", or since a number of days)
FORM_REFRESH    integer number of minutes between summary refreshes
FORM_TODAY      the last day of the data file(s)
FORM_TOMINUTE   the last minute of the data
FORM_TOHOUR     the last hour of the data
FORM_TOMONTH    the last month of the data file(s)
FORM_TOYEAR     the last year of the data file(s)
FORM_USER_MODE_CPU      if non-null then user-mode-cpu usage requested
FORM_WHAT       any data category can be placed in this comma-separated list
FORM_XMAG       number of times X axis should be enlarged
FORM_YEAR       the (first) year of the data file(s)
FORM_YMAG       number of times Y axis should be enlarged


QUALIFIERS
----------
/BUTTONS=       string containing button labels/paths
/CHARSET=       "Content-Type: text/html; charset=...", empty suppresses charset
/DBUG           turns on all "if (Debug)" statements
/DIRECTORY=     directory containing any node description HTML files
/HELP=          help HTML file URL
/NODES=         comma-separated list of node names collecting SPI data
/SHUTDOWN       causes the HYPERSPI$AGENT image/process to exit


LOGICAL NAMES
-------------
HYPERSPI$DATA          locates the data files
HYPERSPI$PARAM         equivalent to (overrides) the command line
                       parameters/qualifiers (define as a system-wide logical)


BUILD DETAILS
-------------
See BUILD_HYPERSPI.COM procedure.


COPYRIGHT
---------
Copyright (C) 1996-2020 Mark G.Daniel
This program, comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it under the
conditions of the GNU GENERAL PUBLIC LICENSE, version 3, or any later version.
http://www.gnu.org/licenses/gpl.txt


VERSION HISTORY (update SOFTWAREVN as well!)
---------------
14-OCT-2014  MGD  v2.1.0, a nod to the twenty-first century
21-MAY-2011  MGD  v2.0.0, add network interface data
                          data format version 3 (shared with HyperSPI++)
                          (There is a lot of work that *could* be done to this
                           older piece of code but I've spent the minimal time
                           necessary just to make it work on modern platforms.)
                          plus a few tweaks (couldn't resist :-)
10-MAY-2005  MGD  v1.8.4, SWS 2.0 ignore query string components supplied as
                          command-line parameters differently to CSWS 1.2/3
23-DEC-2003  MGD  v1.8.3, minor conditional mods to support IA64
12-APR-2003  MGD  v1.8.2, link colour changed to 0000cc
16-AUG-2002  MGD  v1.8.1, some accomodations for CSWS v1.2
09-SEP-2001  MGD  v1.8.0, provide /SHUTDOWN for the agent via $FORCEX
01-JUL-2001  MGD  v1.7.1, add 'SkipParameters' for direct OSU support
28-OCT-2000  MGD  v1.7.0, use CGILIB object module
12-APR-2000  MGD  v1.6.1, minor changes for CGILIB 1.4
07-AUG-1999  MGD  v1.6.0, use more of the CGILIB functionality
24-APR-1999  MGD  v1.5.0, use CGILIB.C,
                          standard CGI environment (Netscape FastTrack),
                          modify to use CgiVar()
02-OCT-1998  MGD  v1.4.0, provide content-type "; charset=..."
13-AUG-1998  MGD  v1.3.0, accomodations for OSU
                          bugfix; IncludeFile() file name length
13-AUG-1998  MGD  NOTE:   this application is not Y2K compliant (in the sense
                          data is stored in files named with a 2 digit year!)
06-MAY-1998  MGD  v1.2.0, general maintenance, cosmetic changes
11-SEP-1997  MGD  v1.1.1, upped MAX_NODE_COUNT_BEFORE_SELECT to 20
01-AUG-1997  MGD  v1.1.0, added /BODY= qualifier,
                          remove extraneous '/' from <IMG SRC=...>,
                          general maintenance
19-SEP-1995  MGD  v1.0.1, replace <CR><LF> carriage-control single newline,
                          still acceptable for HTTP, slightly more efficient
20-JUN-1995  MGD  v1.0.0, initial development
*/
/*****************************************************************************/

#define SOFTWAREVN "2.1.0"
#define SOFTWARENM "HYPERSPI"
#define SOFTWARECR "Copyright (C) 1996-2020 Mark G.Daniel"
#ifdef __ALPHA
#  define SOFTWAREID  SOFTWARENM " AXP-" SOFTWAREVN
#endif
#ifdef __ia64
#  define SOFTWAREID  SOFTWARENM " IA64-" SOFTWAREVN
#endif
#ifdef __VAX
#  define SOFTWAREID  SOFTWARENM " VAX-" SOFTWAREVN
#endif
#ifdef __x86_64
   char SoftwareID [] = SOFTWARENM " X86-" SOFTWAREVN;
#endif

/* standard C header files */
#include <ctype.h>
#include <errno.h>
#include <lnmdef.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unixio.h>

/* VMS related header files */
#include <descrip.h>
#include <libdef.h>
#include <libdtdef.h>
#include <rmsdef.h>
#include <rms.h>
#include <syidef.h>
#include <ssdef.h>
#include <stsdef.h>

/* application header file */
#include "HyperSpi.h"
#include <cgilib.h>

#ifndef __VAX
#   pragma nomember_alignment
#endif

#define boolean int
#define true 1
#define false 0
 
#define VMSok(x) ((x) & STS$M_SUCCESS)
#define VMSnok(x) !(((x) & STS$M_SUCCESS))
 
#define FI_LI __FILE__, __LINE__

/* for use by functions in PlotSpi.c */
#define PLOT_ON 0
#define PLOT_OFF 1
#define PLOT_XOR 2

#define MAX_SAMPLE_PERIOD_DAYS 31
#define MAX_NODE_COUNT_BEFORE_SELECT 20

#define DEFAULT_BUTTONS "\
&#8630;Back=javascript:parent.history.go(-1)$Selector$\
^Help=/hyperspi/-/hyperspi.html\
"

#define DEFAULT_STYLE "\
body { margin:0.5em; background-color:white; color:black; \
font-family:sans-serif; }\n\
a { text-decoration:none; color:black; \
border:1px solid slategray; border-radius:3px; padding:1px 5px 2px 5px; }\n\
.header { padding:0.5em 0.5em 0.5em 1em; background-color: gainsboro; \
border:1px solid lightslategray; border-radius:1px; \
font-size: 140%; font-weight: bold; word-spacing:0.2em; }\n\
.buttonbar { padding:0.7em 1em 0.7em 1em; \
border:1px solid lightslategray; border-radius:1px; \
background-color: gainsboro; min-height:1.3em; }\n\
.buttonbar a { text-decoration:none; color:inherit; \
border:1px solid slategray; border-radius:3px; padding:1px 5px 2px 5px; }\n\
.hyperSPI { display:table-cell; \
font-family: futura, \"Tw Cen MT\", helvetica, arial, sans; \
font-weight:normal; font-size:125%; letter-spacing:-2px; }\n\
.heading { display:table-cell; width:95%; text-align:center; \
font-size:110%; }\n\
.datetime { display:table-cell; white-space:nowrap; font-size:80%; \
word-spacing:0px; }\n\
.content { margin:1.5em; }\n\
.precis { margin:0.5em 1em 0.5em 2em; }\n\
.precis th { text-align:right; }\n\
.precis td { text-align:left; }\n\
.graph { margin:0.5em; }\n\
.graphtitle { margin:1em 0.5em 0.5em 0.5em; font-size:120%; font-weight:bold; \
text-decoration:underline; }\n\
.graphdata { margin:1em 1em 1em 2em; }\n\
.fileday { margin-bottom:1em; font-size:120%; font-weight:bold; }\n\
.filename { font-family:monospace; font-size:120%; }\n\
.extrbtn { margin-left:2em; background-color:whitesmoke; font-size:80%; }\n\
"

char  Utility [] = "HYPERSPI";

char  *DayName [] =
      { "", "Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday", };

char  *MonthName [] =
      { "", "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December" };

boolean  Debug,
         DoDump,
         DoGraph,
         DoList,
         DoComprehensiveMenu,
         DoShutdownAgent,
         DoSummaryMenu,
         DoPresentSummaryPage,
         ErrorReported,
         ExtractGraph,
         GifTransparentBackground = true,
         HttpHasBeenOutput,
         IncludePeak,
         IncludeTotal,
         ProvidePercentCPU,
         ProvidePercentUserModeCPU,
         ProvideBufferedIO,
         ProvidePeakBufferedIO,
         ProvideDirectIO,
         ProvidePeakDirectIO,
         ProvideMemory,
         ProvideMscpIO,
         ProvidePeakMscpIO,
         ProvideNetInt,
         ProvidePeakNetInt,
         ProvidePageFaults,
         ProvidePeakPageFaults,
         ProvideHardPageFaults,
         ProvidePeakHardPageFaults,
         ProvideProcesses,
         OsuEnvironment,
         StdCgiEnvironment;

int  AvePercentCPU,
     AvePercentUserModeCPU,
     AveBufferedIO,
     AveDirectIO,
     AveLck,
     AveLckIn,
     AveLckOut,
     AveLckLoc,
     AveMscpIO,
     AveNetIntRxTx,
     AveNumberOfCom,
     AvePageFaults,
     AveHardPageFaults,
     AveNumberOfProcesses,
     AveSystemMemoryPercentInUse,
     AvePageSpacePercentInUse,
     CurrentJulianDate,
     CurrentMinuteFromStartOfPeriod,
     DataFileNameLength,
     DataFileSpecLength,
     DataFilesFoundCount,
     DataFilesProcessedCount,
     DataRecordsReadCount,
     DataRecordsProcessedCount,
     DataMinute,
     DataHour,
     DataDay,
     DataMonth,
     DataYear,
     FromJulianDate,
     FromDay,
     FromHour,
     FromMinute,
     FromMonth,
     FromYear,
     HaveDataY,
     MaxAveBufferedIO,
     MaxAveDirectIO,
     MaxAveMscpIO,
     MaxAveNetIntRxTx,
     MaxAvePageFaults,
     MaxAveHardPageFaults,
     MaxNumberOfCom,
     MaxNumberOfProcesses,
     MaxPageSpacePercentInUse,
     MaxSystemMemoryPercentInUse,
     NodeCount,
     NumberOfCPUs,
     NumberOfDays,
     NumberOfDaysIntoData,
     NumberOfHours,
     NumberOfMinutesIntoData,
     NumberOfProcesses,
     PageSpaceMBytes,
     PageSpacePercentInUse,
     PeakPercentUserModeCPU,
     PeakBufferedIO,
     PeakDirectIO,
     PeakMscpIO,
     PeakPageFaults,
     PeakNetIntRxTx,
     PeakPercentCPU,
     PeakHardPageFaults,
     PercentCPU,
     PercentUserModeCPU,
     RecordSampleRate,
     RefreshSeconds = 0,
     SizeOfMarginX = 10,
     SizeOfMarginY = 20,
     SizeOfPlotX,
     SizeOfPlotY,
     StartMinuteOnFirstDay,
     StartMinuteOfData,
     SystemMemoryMBytes,
     SystemMemoryPercentInUse,
     ToJulianDate,
     ToMinute,
     ToHour,
     ToDay,
     ToMonth,
     ToYear,
     XMag,
     YMag;
     
#ifndef __VAX
    unsigned __int64  NetIntRxTx;
#else
    unsigned int  NetIntRxTx;
#endif

unsigned int  AvePercentModeCPU[HYPERSPI_CPU_MODE_COUNT];

float  ScalingFactorY;

char  DataFileName [256],
      DataFileSpec [256],
      DataNode [32],
      DateString [32],
      DefaultButtons [] = DEFAULT_BUTTONS,
      FileSpecification [256],
      HyperSpiUrl [256],
      SoftwareID [48],
      ToDateString [32],
      UnixDateTime [64];

char  *ButtonsPtr = DefaultButtons,
      *CgiEnvironmentPtr,
      *CgiFormDoPtr,
      *CgiFormIncludePtr,
      *CgiFormNodePtr,
      *CgiFormPeriodPtr,
      *CgiFormRefreshPtr,
      *CgiFormWhatPtr,
      *CgiRequestMethodPtr,
      *CgiPathInfoPtr,
      *CgiPathTranslatedPtr,
      *CgiScriptNamePtr,
      *CgiServerNamePtr,
      *CgiServerSoftwarePtr,
      *CliCharsetPtr,
      *DefaultStyle = DEFAULT_STYLE,
      *HyperSpiDirectoryPtr = "HYPERSPI$DATA:",
      *SelectorPtr,
      *SoftwareCopy = SOFTWARECR,
      *StyleSheetPtr = "";

char  SpiNodeNames [16][16] = { "" };

unsigned long  CurrentBinTime [2];
unsigned short  CurrentNumTime [7];

/* this structure is declared in HyperSpi.h */
struct HyperSpiData  SpiRecord;

/* external storage (declared in PlotSpi.c) */
extern boolean  DoPlotDiagnostic;
extern int  PixelPlotOperation,
            PlotScaleY;

/* function prototypes for graphing (from PlotSpi.c) */
int PlotAllocate (int XSize, int YSize);
int PlotAxes (int Operation);
int PlotPixel (int Operation, int AtX, int AtY, int XOrigin, int YOrigin);
int PlotLineX (int Operation, int FromX, int ToX, int AtY,
               int XOrigin, int YOrigin);
int PlotLineY (int Operation, int FromY, int ToY, int AtX,
               int XOrigin, int YOrigin);

/* required function prototypes */
char* ButtonBarButton (char*, char*);
void DumpData();
void DumpRecord();
void ListProcessedRecord();
int GraphImageLink (int, char*, char*, ...);
int GraphRecordCPU();
int GraphRecordMemory();
int GraphRecordProcesses();
int GraphRecordRange();
int ProvideScaling ();
void SetScaling (int);
int SelectNodeNameByDataFileName();
void SummarizeRecord();
char* SystemNodeName ();
char* UniqueNumber();

/*****************************************************************************/
/*
'argc/argv' are only required to support OSU, in particular CgiLibOsuInit().
*/

main
(
int argc,
char *argv[]
)
{
   int  status;
   unsigned long  UnixTime;
   struct tm  *UnixTmPtr;

   /*********/
   /* begin */
   /*********/

   sprintf (SoftwareID, "%s (%s)", SOFTWAREID, CgiLibEnvironmentVersion());

   if (getenv ("HYPERSPI$DBUG") != NULL)
   {
      Debug = true;
      fputs ("Content-Type: text/plain\n\n", stdout);
      CgiLibEnvironmentSetDebug (Debug);
   }

   CgiLibEnvironmentInit (argc, argv, false);
   CgiEnvironmentPtr = CgiLibEnvironmentName ();

   GetParameters ();

   if (DoShutdownAgent) exit (ShutdownAgent());

   CgiLibResponseSetCharset (CliCharsetPtr);
   CgiLibResponseSetSoftwareID (SoftwareID);
   CgiLibResponseSetErrorMessage ("Reported by HyperSPI");

   if (StyleSheetPtr[0])
   {
      char *cptr = calloc (1, 64+strlen(StyleSheetPtr));
      sprintf (cptr, "<link rel=\"stylesheet\" \
type=\"text/css\" href=\"%s\">\n",
               StyleSheetPtr);
      StyleSheetPtr = cptr;
   }

   CgiServerSoftwarePtr = CgiVar ("WWW_SERVER_SOFTWARE");
   CgiRequestMethodPtr = CgiVar ("WWW_REQUEST_METHOD");
   if (strcmp (CgiRequestMethodPtr, "GET"))
   {
      CgiLibResponseHeader (501, "text/html");
      fprintf (stdout, "Not implemented!\n");
      return;
   }

   CgiScriptNamePtr = CgiVar ("WWW_SCRIPT_NAME");
   CgiServerNamePtr = CgiVar ("WWW_SERVER_NAME");

   sys$gettim (&CurrentBinTime);
   sys$numtim (&CurrentNumTime, &CurrentBinTime);

   time (&UnixTime);
   UnixTmPtr = localtime (&UnixTime);
   if (!strftime (UnixDateTime, sizeof(UnixDateTime),
                  "%a, %d %b %Y %T", UnixTmPtr))
      strcpy (UnixDateTime, "[error]");
   if (Debug) fprintf (stdout, "UnixDateTime |%s|\n", UnixDateTime);

   GetRequest ();
   ValidateRequest ();

   if (DoSummaryMenu || DoComprehensiveMenu)
   {
      SummaryMenu ();
      exit (SS$_NORMAL);
   }

   /* create file specification for processing data */
   DataFileSpecLength =
      sprintf (DataFileSpec,
               "%sHYPERSPI_%s_%s_%%%%%%%%%%%%.DAT",
               HYPERSPI_DATA_DIRECTORY, HYPERSPI_DATA_VERSION, CgiFormNodePtr);
   if (Debug) fprintf (stdout, "DataFileSpec |%s|\n", DataFileSpec);

   if (DoPresentSummaryPage)
      PresentSummaryPage ();
   else   
   if (DoDump)
      DumpData ();
   else   
   if (DoGraph)
      GraphData ();
   else   
   if (DoList)
      ListProcessedData ();

   exit (SS$_NORMAL);
}

/*****************************************************************************/
/*
Get "command-line" parameters, whether from the command-line or from a
configuration symbol or logical containing the equivalent.  OSU scripts have
the 'method', 'url' and 'protocol' supplied as P1, P2, P3 (these being detected
and used by CGILIB), and are of no interest to this function.
*/

GetParameters ()

{
   static char  CommandLine [256];
   static unsigned long  Flags = 0;

   int  idx, status,
        SkipParameters;
   unsigned short  Length;
   char  ch;
   char  *aptr, *cptr, *clptr, *sptr;
   $DESCRIPTOR (CommandLineDsc, CommandLine);

   /*********/
   /* begin */
   /*********/

   if ((clptr = getenv ("HYPERSPI$PARAM")) == NULL)
   {
      /* get the entire command line following the verb */
      if (VMSnok (status =
          lib$get_foreign (&CommandLineDsc, 0, &Length, &Flags)))
         exit (status);
      (clptr = CommandLine)[Length] = '\0';
   }

   /* if [C]SWS (VMS Apache) */
   if (CgiLibEnvironmentIsApache())
   {
      /* CSWS 1.2/3 look for something non-space outside of quotes */
      for (cptr = clptr; *cptr; cptr++)
      {
         if (isspace(*cptr)) continue;
         if (*cptr != '\"') break;
         cptr++;
         while (*cptr && *cptr != '\"') cptr++;
         if (*cptr) cptr++;
      }
      /* CSWS 1.2/3 if nothing outside of quotes then ignore command line */
      if (!*cptr) return;
      /* SWS 2.0 doesn't begin with /APACHE from DCL procedure wrapper */
      if (!strsame (cptr, "/APACHE", 7)) return;
   }

   /* if OSU environment then skip P1, P2, P3 */
   if (CgiLibEnvironmentIsOsu())
      SkipParameters = 3;
   else
      SkipParameters = 0;

   aptr = NULL;
   ch = *clptr;
   for (;;)
   {
      if (aptr != NULL) *aptr = '\0';
      if (!ch) break;

      *clptr = ch;
      if (Debug) fprintf (stdout, "clptr |%s|\n", clptr);
      while (*clptr && isspace(*clptr)) *clptr++ = '\0';
      aptr = clptr;
      if (*clptr == '/') clptr++;
      while (*clptr && !isspace (*clptr) && *clptr != '/')
      {
         if (*clptr != '\"')
         {
            clptr++;
            continue;
         }
         cptr = clptr;
         clptr++;
         while (*clptr)
         {
            if (*clptr == '\"')
               if (*(clptr+1) == '\"')
                  clptr++;
               else
                  break;
            *cptr++ = *clptr++;
         }
         *cptr = '\0';
         if (*clptr) clptr++;
      }
      ch = *clptr;
      if (*clptr) *clptr = '\0';
      if (Debug) fprintf (stdout, "aptr |%s|\n", aptr);
      if (!*aptr) continue;

      if (SkipParameters)
      {
         SkipParameters--;
         continue;
      }

      if (strsame (aptr, "/APACHE", 4))
      {
         /* just skip this marker for command-line parameters under SWS 2.0 */
         continue;
      }
      if (strsame (aptr, "/BUTTONS=", 4))
      {
         for (cptr = aptr; *cptr && *cptr != '='; cptr++);
         if (*cptr) cptr++;
         ButtonsPtr = cptr;
         continue;
      }
      if (strsame (aptr, "/CHARSET=", 4))
      {
         for (cptr = aptr; *cptr && *cptr != '='; cptr++);
         if (*cptr) cptr++;
         CliCharsetPtr = cptr;
         continue;
      }
      if (strsame (aptr, "/DBUG", -1))
      {
         Debug = true;
         continue;
      }
      if (strsame (aptr, "/DIRECTORY=", 3))
      {
         for (cptr = aptr; *cptr && *cptr != '='; cptr++);
         if (*cptr) cptr++;
         HyperSpiDirectoryPtr = cptr;
         continue;
      }
      if (strsame (aptr, "/NODES=", 3))
      {
         for (cptr = aptr; *cptr && *cptr != '='; cptr++);
         if (*cptr) cptr++;
         /* quick and nasty, no checks on array bounds (caveat emptor) */
         idx = 0;
         while (*cptr)
         {
            sptr = SpiNodeNames[idx++];
            while (*cptr && *cptr != ',') *sptr++ = toupper(*cptr++);
            *sptr = '\0';
            if (*cptr) cptr++;
         }
         SpiNodeNames[idx][0] = '\0';
         continue;
      }
      if (strsame (aptr, "/SHUTDOWN", 3))
      {
         DoShutdownAgent = true;
         continue;
      }

      if (*aptr != '/')
      {
         fprintf (stdout, "%%%s-E-MAXPARM, too many parameters\n \\%s\\\n",
                  Utility, aptr);
         exit (STS$K_ERROR | STS$M_INHIB_MSG);
      }
      else
      {
         fprintf (stdout, "%%%s-E-IVQUAL, unrecognized qualifier\n \\%s\\\n",
                  Utility, aptr+1);
         exit (STS$K_ERROR | STS$M_INHIB_MSG);
      }
   }
}

/*****************************************************************************/
/*
Create the navigation buttons.
*/ 

ButtonBar (int Top1Bottom2)

{
   int  idx;
   char  *cptr, *sptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ButtonBar()\n");

   fprintf (stdout, "<div class=\"buttonbar%s\">\n",
            Top1Bottom2 == 1 ? " butbartop" : "");

   cptr = ButtonsPtr;

   /* back */
   cptr = ButtonBarButton (cptr, NULL);

   /* calendar request form */
   cptr = ButtonBarButton (cptr, CgiScriptNamePtr);

   /* any further buttons */
   while (*cptr) cptr = ButtonBarButton (cptr, NULL);

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Generate a single "button" inside the context created by ButtonBar().
*/

char* ButtonBarButton
(
char *ButtonLabel,
char *ButtonPath
)
{
   char  *cptr, *sptr, *tptr, *uptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ButtonBarButton() |%s|\n", ButtonLabel);

   if (!*ButtonLabel)
      for (cptr = ButtonLabel = "*ERROR*"; *cptr; cptr++);
   else
      for (cptr = ButtonLabel; *cptr && *cptr != '=' && *cptr != '$'; cptr++);

   if (*ButtonLabel == '^')
   {
      ButtonLabel++;
      tptr = " target=\"_blank\"";
   }
   else
      tptr = "";

   if (*cptr == '=')
      for (sptr = uptr = cptr+1; *sptr && *sptr != '$'; sptr++);
   else
   if (ButtonPath)
      sptr = (uptr = ButtonPath) + strlen(ButtonPath);
   else
      sptr = (uptr = "*ERROR*") + 8;

   if (!memcmp(uptr,"javascript:", 11))
      fprintf (stdout,
"<script type=\"text/javascript\">\
document.write(\'<a%s href=\"%*.*s\">%*.*s</a>\\n\');\
</script>\n",
               tptr, sptr-uptr, sptr-uptr, uptr,
               cptr-ButtonLabel, cptr-ButtonLabel, ButtonLabel);
      else
         fprintf (stdout, "<a%s href=\"%*.*s\">%*.*s</a>\n",
                  tptr, sptr-uptr, sptr-uptr, uptr,
                  cptr-ButtonLabel, cptr-ButtonLabel, ButtonLabel);

   while (*cptr && *cptr != '$') cptr++;
   while (*cptr && *cptr == '$') cptr++;

   return (cptr);
}

/*****************************************************************************/
/*
Get the request CGI variables.
*/

GetRequest ()

{
   char  *cptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GetRequest()\n");

   /* determine what has been requested */

   CgiFormWhatPtr = CgiVar ("WWW_FORM_WHAT");
   for (cptr = CgiFormWhatPtr; *cptr; cptr++) *cptr = toupper(*cptr);

   CgiFormRefreshPtr = CgiVar ("WWW_FORM_REFRESH");
   RefreshSeconds = atoi(CgiFormRefreshPtr) * 60;
   if (RefreshSeconds < 0 || RefreshSeconds > 3600) RefreshSeconds = 0;

   if (strsame (CgiFormWhatPtr, "CPU", -1)) ProvidePercentCPU = true;
   if (strstr (CgiFormWhatPtr, ",CPU") != NULL) ProvidePercentCPU = true;
   cptr = CgiVar ("WWW_FORM_CPU");
   if (cptr[0]) ProvidePercentCPU = true;

   if (strstr (CgiFormWhatPtr, "USER_MODE") != NULL)
      ProvidePercentUserModeCPU= true;
   cptr = CgiVar ("WWW_FORM_USER_MODE_CPU");
   if (cptr[0]) ProvidePercentUserModeCPU = true;

   if (strstr (CgiFormWhatPtr, "BUFFERED") != NULL) ProvideBufferedIO = true;
   cptr = CgiVar ("WWW_FORM_BUFFERED_IO");
   if (cptr[0]) ProvideBufferedIO = true;

   if (strstr (CgiFormWhatPtr, "PEAK_BUFFERED") != NULL)
      ProvidePeakBufferedIO = true;
   cptr = CgiVar ("WWW_FORM_PEAK_BUFFERED_IO");
   if (cptr[0]) ProvidePeakBufferedIO = true;

   if (strstr (CgiFormWhatPtr, "DIRECT") != NULL) ProvideDirectIO = true;
   cptr = CgiVar ("WWW_FORM_DIRECT_IO");
   if (cptr[0]) ProvideDirectIO = true;

   if (strstr (CgiFormWhatPtr, "PEAK_DIRECT") != NULL)
      ProvidePeakDirectIO = true;
   cptr = CgiVar ("WWW_FORM_PEAK_DIRECT_IO");
   if (cptr[0]) ProvidePeakDirectIO = true;

   if (strstr (CgiFormWhatPtr, "MSCP") != NULL) ProvideMscpIO = true;
   cptr = CgiVar ("WWW_FORM_MSCP_IO");
   if (cptr[0]) ProvideMscpIO = true;

   if (strstr (CgiFormWhatPtr, "PEAK_MSCP") != NULL) ProvidePeakMscpIO = true;
   cptr = CgiVar ("WWW_FORM_PEAK_MSCP_IO");
   if (cptr[0]) ProvidePeakMscpIO = true;

   if (strstr (CgiFormWhatPtr, "NET_INT") != NULL) ProvideNetInt = true;
   cptr = CgiVar ("WWW_FORM_NET_INT");
   if (cptr[0]) ProvideNetInt = true;

   if (strstr (CgiFormWhatPtr, "PEAK_NET_INT") != NULL)
      ProvidePeakNetInt = true;
   cptr = CgiVar ("WWW_FORM_PEAK_NET_INT");
   if (cptr[0]) ProvidePeakNetInt = true;

   if (strstr (CgiFormWhatPtr, "FAULTS") != NULL) ProvidePageFaults = true;
   cptr = CgiVar ("WWW_FORM_FAULTS");
   if (cptr[0]) ProvidePageFaults = true;

   if (strstr (CgiFormWhatPtr, "PEAK_FAULTS") != NULL)
      ProvidePeakHardPageFaults = true;
   cptr = CgiVar ("WWW_FORM_PEAK_FAULTS");
   if (cptr[0]) ProvidePeakPageFaults = true;

   if (strstr (CgiFormWhatPtr, "HARD_FAULTS") != NULL)
      ProvideHardPageFaults = true;
   cptr = CgiVar ("WWW_FORM_HARD_FAULTS");
   if (cptr[0]) ProvideHardPageFaults = true;

   if (strstr (CgiFormWhatPtr, "PEAK_HARD_FAULTS") != NULL)
      ProvidePeakHardPageFaults = true;
   cptr = CgiVar ("WWW_FORM_PEAK_HARD_FAULTS");
   if (cptr[0]) ProvidePeakHardPageFaults = true;

   if (strstr (CgiFormWhatPtr, "MEMORY") != NULL) ProvideMemory = true;
   cptr = CgiVar ("WWW_FORM_MEMORY");
   if (cptr[0]) ProvideMemory = true;

   if (strstr (CgiFormWhatPtr, "PROCESSES") != NULL) ProvideProcesses = true;
   cptr = CgiVar ("WWW_FORM_PROCESSES");
   if (cptr[0]) ProvideProcesses = true;

   CgiFormIncludePtr = CgiVar ("WWW_FORM_INCLUDE");
   for (cptr = CgiFormIncludePtr; *cptr; cptr++) *cptr = toupper(*cptr);
   if (strstr (CgiFormIncludePtr, "PEAK") != NULL) IncludePeak = true;
   if (strstr (CgiFormIncludePtr, "TOTAL") != NULL) IncludeTotal = true;

   cptr = CgiVar ("WWW_FORM_FROM");
   sscanf (cptr, "%4d-%2d-%2d %2d:%2d",
           &FromYear, &FromMonth, &FromDay, &FromHour, &FromMinute);

   cptr = CgiVar ("WWW_FORM_TO");
   sscanf (cptr, "%4d-%2d-%2d %2d:%2d",
           &ToYear, &ToMonth, &ToDay, &ToHour, &ToMinute);

   CgiFormDoPtr = CgiVar ("WWW_FORM_DO");

   CgiFormNodePtr = CgiVar ("WWW_FORM_NODE");
   if (!CgiFormNodePtr[0])
      CgiFormNodePtr = CgiVar ("WWW_FORM_LIST_NODE");
   if (!CgiFormNodePtr[0])
      CgiFormNodePtr = SystemNodeName();
   if (CgiFormNodePtr[0])
   {
      /* ensure the node name is in upper case */
      for (cptr = CgiFormNodePtr; *cptr; cptr++) *cptr = toupper(*cptr);
   }

   cptr = CgiVar ("WWW_FORM_EXTRACT");
   if (cptr[0]) ExtractGraph = true;

   CgiFormPeriodPtr = CgiVar ("WWW_FORM_PERIOD");

   cptr = CgiVar ("WWW_FORM_XMAG");
   if (isdigit(cptr[0]))
      XMag = atoi (cptr);
   else
      XMag = 1;
   if (XMag > 4) XMag = 4;
   if (XMag < 1) XMag = 1;

   cptr = CgiVar ("WWW_FORM_YMAG");
   if (isdigit(cptr[0]))
      YMag = atoi (cptr);
   else
      YMag = 1;
   if (YMag > 4) YMag = 4;
   if (YMag < 1) YMag = 1;
}

/*****************************************************************************/
/*
Process the request parameters (e.g. time, node name).  Verify the parameters 
are within constraints, particular time.  Process the time components into 
values the application can use.
*/

ValidateRequest ()

{
   static long  LibJulianDate = LIB$K_JULIAN_DATE;
   static char  *MonthName [] = 
      { "???", "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
        "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };

   int  status;
   unsigned long  BinTime [2],
                  DeltaTime [2];
   unsigned short  NumTime [7];
   char  Scratch [256];
   $DESCRIPTOR (TempDsc, "");

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ValidateRequest()\n");

   if (!CgiFormDoPtr[0])
      DoSummaryMenu = true;
   else
   if (toupper(CgiFormDoPtr[0]) == 'G')
      DoGraph = true;
   else
   if (toupper(CgiFormDoPtr[0]) == 'P')
      DoPresentSummaryPage = true;
   else
   if (toupper(CgiFormDoPtr[0]) == 'C')
      DoComprehensiveMenu = true;
   else
   if (toupper(CgiFormDoPtr[0]) == 'M')
      DoSummaryMenu = true;
   else
   if (toupper(CgiFormDoPtr[0]) == 'D')
      DoDump = true;
   else
   if (toupper(CgiFormDoPtr[0]) == 'L')
      DoList = true;
   else
   {
      sprintf (Scratch, "Cannot do \"%s\"", CgiFormDoPtr);
      CgiLibResponseError (FI_LI, 0, Scratch);
      exit (SS$_NORMAL);
   }

   if ((DoPresentSummaryPage || DoGraph || DoList || DoDump) &&
       !CgiFormNodePtr[0])
   {
      CgiLibResponseError (FI_LI, 0, "Node name not specified.");
      exit (SS$_NORMAL);
   }

   /********************/
   /* standard periods */
   /********************/

   if (CgiFormPeriodPtr[0] && toupper(CgiFormPeriodPtr[0]) != 'O')
   {
      /* a standard time period has been specified, other than "other" */
      FromHour = 0;
      FromMinute = 0;
      ToHour = 23;
      ToMinute = 59;
      FromDay = ToDay =  CurrentNumTime[2];
      FromMonth = ToMonth =  CurrentNumTime[1];
      FromYear = ToYear =  CurrentNumTime[0];

      if (toupper(CgiFormPeriodPtr[0]) == 'U')
      {
         /* "until_now" (7am to this hour) */
         FromHour = 7;
         ToHour = CurrentNumTime[3];
      }
      else
      if (toupper(CgiFormPeriodPtr[0]) == 'B')
      {
         /* "business" hours (7am to 7pm) */
         FromHour = 7;
         ToHour = 18;
      }
      else
      if (toupper(CgiFormPeriodPtr[0]) == 'T')
      {
         /* "today" */
         ToHour = 23;
      }
      else
      if (toupper(CgiFormPeriodPtr[0]) == 'S' ||
          toupper(CgiFormPeriodPtr[0]) == 'Y')
      {
         /* "since_yesterday" until now, or all of "yesterday" */
         TempDsc.dsc$a_pointer = "1 00:00:00.00";
         TempDsc.dsc$w_length = 13;
         if (VMSnok (status = sys$bintim (&TempDsc, &DeltaTime)))
         {
            CgiLibResponseError (FI_LI, status, CgiFormPeriodPtr);
            exit (SS$_NORMAL);
         }
         lib$sub_times (&CurrentBinTime, &DeltaTime, &BinTime);
         sys$numtim (&NumTime, &BinTime);
         FromDay = NumTime[2];
         FromMonth = NumTime[1];
         FromYear = NumTime[0];
         if (toupper(CgiFormPeriodPtr[0]) == 'S')
            ToHour = CurrentNumTime[3];
         else
         {
            ToDay = NumTime[2];
            ToMonth = NumTime[1];
            ToYear = NumTime[0];
         }
      }
      else
      if (isdigit(CgiFormPeriodPtr[0]))
      {
         TempDsc.dsc$a_pointer = Scratch;
         TempDsc.dsc$w_length =
            sprintf (Scratch, "%s 00:00:00.00", CgiFormPeriodPtr);
         if (VMSnok (status = sys$bintim (&TempDsc, &DeltaTime)))
         {
            CgiLibResponseError (FI_LI, status, CgiFormPeriodPtr);
            exit (SS$_NORMAL);
         }
         lib$sub_times (&CurrentBinTime, &DeltaTime, &BinTime);
         sys$numtim (&NumTime, &BinTime);
         FromDay = NumTime[2];
         FromMonth = NumTime[1];
         FromYear = NumTime[0];
      }
      else
      {
         CgiLibResponseError (FI_LI, 0, "Periods are \"until_now\"");
         exit (SS$_NORMAL);
      }
   }

   /*******************/
   /* time components */
   /*******************/

   /* non-specified date components default to those of the current day */
   if (!FromDay) FromDay = CurrentNumTime[2];
   if (!FromMonth) FromMonth = CurrentNumTime[1];
   if (!FromYear) FromYear = CurrentNumTime[0];
   if (!ToDay) ToDay =  CurrentNumTime[2];
   if (!ToMonth) ToMonth =  CurrentNumTime[1];
   if (!ToYear) ToYear =  CurrentNumTime[0];

   /* bit of a sanity check (prevents 'MonthName[x]' access violating, etc.) */
   if (FromMonth < 1 || FromMonth > 12) FromMonth = 0;
   if (ToMonth < 1 || ToMonth > 12) ToMonth = 0;

   /* ensure the commencement date/time is acceptable */
   TempDsc.dsc$a_pointer = DateString;
   TempDsc.dsc$w_length = 
      sprintf (DateString, "%d-%s-%d %02.02d:%02.02d",
               FromDay, MonthName[FromMonth], FromYear, FromHour, FromMinute);
   if (Debug) fprintf (stdout, "DateString |%s|\n", DateString);
   if (VMSnok (status = sys$bintim (&TempDsc, &BinTime)))
   {
      sprintf (Scratch, "%02.02d:%02.02d %02.02d/%02.02d/%02.02d",
               FromHour, FromMinute, FromDay, FromMonth, FromYear);
      CgiLibResponseError (FI_LI, status, Scratch);
      exit (SS$_NORMAL);
   }
   /* get the commencement julian date (number of days in epoch) */
   lib$cvt_from_internal_time (&LibJulianDate, &FromJulianDate, &BinTime);

   /* ensure the conclusion date/time is acceptable */
   TempDsc.dsc$a_pointer = ToDateString;
   TempDsc.dsc$w_length = 
      sprintf (ToDateString, "%d-%s-%d %02.02d:%02.02d",
               ToDay, MonthName[ToMonth], ToYear, ToHour, ToMinute);
   if (Debug) fprintf (stdout, "ToDateString |%s|\n", ToDateString);
   if (VMSnok (status = sys$bintim (&TempDsc, &BinTime)))
   {
      sprintf (Scratch, "%02.02d:%02.02d %02.02d/%02.02d/%02.02d",
               ToHour, ToMinute, ToDay, ToMonth, ToYear);
      CgiLibResponseError (FI_LI, status, Scratch);
      exit (SS$_NORMAL);
   }
   /* get the conclusion julian date (number of days in epoch) */
   lib$cvt_from_internal_time (&LibJulianDate, &ToJulianDate, &BinTime);

   /***************************/
   /* calculate period values */
   /***************************/

   /* using julian dates, get number of days and hours sample period covers */
   NumberOfHours = ((ToJulianDate - FromJulianDate) * 24) + ToHour - FromHour;
   NumberOfDays = (NumberOfHours / 24);

   if (DoPresentSummaryPage || DoGraph || DoList || DoDump)
   {
      if (NumberOfHours < 0 || (NumberOfHours == 0 && ToMinute <= FromMinute))
      {
         sprintf (Scratch,
"Beginning of period (%04.04d-%02.02d-%02.02d %02.02d:%02.02d) \
does not precede end (%04.04d-%02.02d-%02.02d %02.02d:%02.02d)!",
         FromYear, FromMonth, FromDay, FromHour, FromMinute,
         ToYear, ToMonth, ToDay, ToHour, ToMinute);
         CgiLibResponseError (FI_LI, 0, Scratch);
         exit (SS$_NORMAL);
      }
      if (NumberOfHours < 1)
      {
         CgiLibResponseError (FI_LI, 0, "Little point to such a short period!");
         exit (SS$_NORMAL);
      }
      if (NumberOfDays > MAX_SAMPLE_PERIOD_DAYS)
      {
         sprintf (Scratch, "Maximum sample period is %d days.",
                  MAX_SAMPLE_PERIOD_DAYS);
         CgiLibResponseError (FI_LI, 0, Scratch);
         exit (SS$_NORMAL);
      }
   }

   /* rate at which the data (and any graphic) must be X-axis compressed */
   if (NumberOfHours <= 12)
      RecordSampleRate = 1;
   else
   if (NumberOfHours <= 24)
      RecordSampleRate = 2;
   else
      RecordSampleRate = (NumberOfDays + 1) * 2;

   /* add one to number of hours, for graphing purposes, re-calculate days */
   NumberOfHours++;
   NumberOfDays = (NumberOfHours / 24);

   /* the number of minutes from midnight data begins being processed */
   StartMinuteOnFirstDay = (FromHour * 60) + FromMinute;

   /* the current minute from the start of the specified period */
   lib$cvt_from_internal_time (&LibJulianDate, &CurrentJulianDate,
                               &CurrentBinTime);
   CurrentMinuteFromStartOfPeriod =
      ((((CurrentJulianDate - FromJulianDate) * 24) +
        (CurrentNumTime[3] - FromHour)) * 60) +
       CurrentNumTime[4];

   if (Debug)
      fprintf (stdout,
"FromJulianDate: %d ToJulianDate: %d\n\
NumberOfDays: %d NumberOfHours: %d RecordSampleRate: %d\n",
      FromJulianDate, ToJulianDate,
      NumberOfDays, NumberOfHours, RecordSampleRate);
}

/*****************************************************************************/
/*
Provide either a standard or comprehensive menu allowing System Performance 
Information system, category and period to be specified.
*/

SummaryMenu ()

{
   char  *CheckedPtr,
         *TodayCheckedPtr,
         *UntilNowCheckedPtr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "SummaryMenu()\n");

   if (DoComprehensiveMenu)
      CheckedPtr = "";
   else
      CheckedPtr = " checked";

   CgiLibResponseHeader (200, "text/html");

   fprintf (stdout,
"<!DOCTYPE html>\n\
<html>\n\
<head>\n\
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\
<meta name=\"generator\" content=\"%s\">\n\
<meta name=\"copyright\" content=\"%s - GPL licensed\">\n\
<meta name=\"environment\" content=\"%s\">\n\
<meta name=\"date\" content=\"%s\">\n\
<title>HyperSPI, Summary Selector</title>\n\
<style type=\"text/css\">\n\
%s\
</style>\n\
%s\
</head>\n\
<body>\n",
            SoftwareID, SoftwareCopy,
            CgiEnvironmentPtr,
            UnixDateTime,
            DefaultStyle,
            StyleSheetPtr);

   fprintf (stdout,
"<div class=\"header\">\
<div class=\"hyperSPI\">HyperSPI</div>\
<div class=\"heading\">Summary Selector</div>\
<div class=\"datetime\">%d %s %d %0.2d:%0.2d</div>\
</div>\n",
            CurrentNumTime[2], MonthName[CurrentNumTime[1]], CurrentNumTime[0],
            CurrentNumTime[3], CurrentNumTime[4]);

   HttpHasBeenOutput = true;

   fprintf (stdout,
"<div class=\"content\">\n\
<form action=\"%s\">\n",
            CgiScriptNamePtr);

   SelectNodeNames ();

   if (DoComprehensiveMenu)
   {
      fputs (
"&nbsp;&nbsp;or ... node \
<input type=\"text\" name=\"node\" size=\"6\" maxlength=\"6\"><br>",
      stdout);
   }

   if (CurrentNumTime[3] >= 7)
   {
      UntilNowCheckedPtr = " checked";
      TodayCheckedPtr = "";
   }
   else
   {
      UntilNowCheckedPtr = "";
      TodayCheckedPtr = " checked";
   }

   fprintf (stdout,
"<p>\n\
<input type=\"radio\" name=\"period\" value=\"until_now\"%s>\
 since 7am <font size=-1>(until now)</font><br>\
<input type=\"radio\" name=\"period\" value=\"today\"%s> today<br>\n\
<input type=\"radio\" name=\"period\" value=\"since_yesterday\">\
 since yesterday  <font size=-1>(until now)</font><br>\n\
<input type=\"radio\" name=\"period\" value=\"yesterday\"> yesterday<br>\n\
<input type=\"radio\" name=\"period\" value=\"7\"> previous week &nbsp;\n\
<input type=\"radio\" name=\"period\" value=\"14\"> two weeks &nbsp;\n\
<input type=\"radio\" name=\"period\" value=\"28\"> four weeks<br>\n\
<nobr>\n\
<input type=radio name=period value=other>\
 from\n\
<input type=\"text\" size=\"16\" maxlength=\"16\" name=\"from\" \
value=\"%04.04d-%02.02d-%02.02d %02.02d:00\">\
 to\n\
<input type=\"text\" size=\"16\" maxlength=\"16\" name=\"to\" \
value=\"%04.04d-%02.02d-%02.02d 23:59\">\
 &nbsp;<font size=-1>(yyyy-mm-dd hh:mm)</font>\n\
</nobr>\n\
<p>\n\
<input type=\"checkbox\" name=\"cpu\" value=\"yes\" checked> cpu<br>\n\
<input type=\"checkbox\" name=\"memory\" value=\"yes\"%s> memory<br>\n\
<input type=\"checkbox\" name=\"processes\" value=\"yes\"> processes<br>\n",
   UntilNowCheckedPtr, TodayCheckedPtr,
   CurrentNumTime[0], CurrentNumTime[1], CurrentNumTime[2],
   CurrentNumTime[3],
   CurrentNumTime[0], CurrentNumTime[1], CurrentNumTime[2],
   CheckedPtr);

   if (DoComprehensiveMenu)
   {
      fputs (
"<input type=\"checkbox\" name=\"faults\" value=\"yes\"> paging (soft) \
 <input type=\"checkbox\" name=\"peak_faults\" value=\"yes\"> peak<br>\n",
             stdout);
   }

   fprintf (stdout,
"<input type=\"checkbox\" name=\"hard_faults\" value=\"yes\"%s> paging",
            CheckedPtr);
   if (DoComprehensiveMenu)
   {
      fputs (
" (hard)\
 <input type=\"checkbox\" name=\"peak_hard_faults\" value=\"yes\"> peak",
             stdout);
   }
   fputs ("<br>\n", stdout);

   fputs (
"<input type=\"checkbox\" name=\"direct_IO\" value=\"yes\"> disk IO",
          stdout);
   if (DoComprehensiveMenu)
   {
      fputs (
" <input type=\"checkbox\" name=\"peak_direct_IO\" value=\"yes\"> peak",
             stdout);
   }
   fputs ("<br>\n", stdout);

   fputs (
"<input type=\"checkbox\" name=\"buffered_IO\" value=\"yes\"> other IO",
          stdout);
   if (DoComprehensiveMenu)
   {
      fputs (
" <input type=\"checkbox\" name=\"peak_buffered_IO\" value=\"yes\"> peak",
             stdout);
   }
   fputs ("<br>\n", stdout);

   fputs (
"<input type=\"checkbox\" name=\"mscp_IO\" value=\"yes\"> mscp IO",
          stdout);
   if (DoComprehensiveMenu)
   {
      fputs (
" <input type=\"checkbox\" name=\"peak_mscp_IO\" value=\"yes\"> peak",
             stdout);
   }
   fputs ("<br>\n", stdout);

   fputs (
"<input type=\"checkbox\" name=\"net_int\" value=\"yes\"> network",
          stdout);
   if (DoComprehensiveMenu)
   {
      fputs (
" <input type=\"checkbox\" name=\"peak_net_int\" value=\"yes\"> peak",
             stdout);
   }
   fputs ("<br>\n", stdout);

   if (DoComprehensiveMenu)
   {
      fputs (
"<input type=\"checkbox\" name=\"include\" value=\"peak\">\
 <i>include peak plot (where applicable)</i>\n\
<p>\n\
<input type=\"radio\" name=\"do\" value=\"page\" checked>graph&nbsp;...\
&nbsp;X,Y magnification:\
<select name=\"Xmag\" size=\"1\">\n\
<option value=\"1\" selected>1 \n\
<option value=\"2\">2 \n\
<option value=\"4\">4 \n\
</select>,\
<select name=\"Ymag\" size=\"1\">\n\
<option value=\"1\" selected> 1 \n\
<option value=\"2\"> 2 \n\
<option value=\"4\"> 4 \n\
</select><br>\n\
<input type=\"radio\" name=\"do\" value=\"list\"> list<br>\n\
<input type=\"radio\" name=\"do\" value=\"dump\"> dump<br>\n\
<input type=\"hidden\" name=\"extract\" value=\"yes\">\n\
<p>\n",
             stdout);
   }
   else
   {
      fputs (
"<input type=\"hidden\" name=\"do\" value=\"page\">\n",
             stdout);
   }

   fputs (
"<p><select name=\"refresh\" size=\"1\">\n\
<option value=\"0\" selected>no\n\
<option value=\"5\">5\n\
<option value=\"10\">10\n\
<option value=\"15\">15\n\
<option value=\"30\">30\n\
<option value=\"60\">60\n\
</select> &nbsp;refresh (minutes)",
          stdout);

   fputs (
"<p>\n\
<input type=\"submit\" value=\"Process\">\n",
          stdout);

   if (!DoComprehensiveMenu)
   { 
      fputs (
"&nbsp;<input type=\"checkbox\" name=\"ymag\" value=\"2\"> \
double-height graph &nbsp;&nbsp;\n",
             stdout);
   }

   fprintf (stdout,
"<input type=\"reset\" value=\"Reset\">\n\
</form>\n\
</div>\n");

   SelectorPtr = NULL;

   ButtonBar (2);

   fprintf (stdout, "</body>\n</html>\n");
}

/*****************************************************************************/
/*
Output a list of node names that data can be selected from.  Get these either 
from a command-line-supplied list or from data files present for the current 
day.
*/ 

SelectNodeNames ()

{
   int  idx;
   char  *CheckedPtr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "SelectNodeNames()\n");

   if (SpiNodeNames[0][0])
   {
      NodeCount = 0;
      for (idx = 0; SpiNodeNames[idx][0]; idx++) NodeCount++;
      if (NodeCount <= MAX_NODE_COUNT_BEFORE_SELECT)
      {
         CheckedPtr = " checked";
         for (idx = 0; SpiNodeNames[idx][0]; idx++)
         {
            fprintf (stdout,
"<input type=\"radio\" name=\"list_node\" value=\"%s\"%s> %s<br>\n",
                     SpiNodeNames[idx], CheckedPtr, SpiNodeNames[idx]);
            CheckedPtr = "";
         }
      }
      else
      {
         CheckedPtr = " selected";
         fprintf (stdout, "<select name=\"list_node\" size=\"%d\">\n",
                  MAX_NODE_COUNT_BEFORE_SELECT);
         for (idx = 0; SpiNodeNames[idx][0]; idx++)
         {
            fprintf (stdout, "<option value=\"%s\"%s> %s\n",
                     SpiNodeNames[idx], CheckedPtr, SpiNodeNames[idx]);
            CheckedPtr = "";
         }
         fputs ("</SELECT>\n", stdout);
      }
   }
   else
   {
      /* create file specification for getting node names (today's files) */
      DataFileSpecLength =
         sprintf (DataFileSpec,
                  "%sHYPERSPI_%s_*_%02.02d%02.02d%02.02d.DAT",
                  HYPERSPI_DATA_DIRECTORY, HYPERSPI_DATA_VERSION,
                  FromDay, FromMonth, FromYear%100);
      if (Debug) fprintf (stdout, "DataFileSpec |%s|\n", DataFileSpec);

      /* count the number of node data files */
      ProcessDataFiles (NULL, false);
      NodeCount = DataFilesFoundCount;

      if (NodeCount <= MAX_NODE_COUNT_BEFORE_SELECT)
         ProcessDataFiles (&SelectNodeNameByDataFileName, false);
      else
      {
         fprintf (stdout, "<SELECT NAME=list_node SIZE=%d>\n",
                  MAX_NODE_COUNT_BEFORE_SELECT);
         ProcessDataFiles (&SelectNodeNameByDataFileName, false);
         fputs ("</SELECT>\n", stdout);
      }
   }
}

/*****************************************************************************/
/*
Called by pointer to function each time a matching data file is returned by 
sys$search(0 in function FindDataFiles().  Output the node name associated 
with the data file.
*/ 

SelectNodeNameByDataFileName ()

{
   static char  *CheckedPtr = " checked";
   static char  *SelectedPtr = " selected";

   /*********/
   /* begin */
   /*********/

   if (Debug)
      fprintf (stdout, "SelectNodeNameByFileName() |%s|\n", DataFileName);

   if (NodeCount < MAX_NODE_COUNT_BEFORE_SELECT)
   {
      fprintf (stdout,
"<input type=\"radio\" name=\"list_node\" value=\"%s\"%s> %s<br>\n",
               DataNode, CheckedPtr, DataNode);
      CheckedPtr = "";
   }
   else
   {
      fprintf (stdout, "<option value=\"%s\"%s> %s\n",
               DataNode, SelectedPtr, DataNode);
      SelectedPtr = "";
   }
}

/*****************************************************************************/
/*
Generates an HTML page containing information about the selected node, and the 
any additional performance information and graphs.
*/

PresentSummaryPage ()

{
   int  PeriodHours;
   char  MetaRefresh [64];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentSummaryPage()\n");

   if (RefreshSeconds)
      sprintf (MetaRefresh, "<meta http-equiv=\"refresh\" content=\"%d\">\n",
               RefreshSeconds);
   else 
      MetaRefresh[0] = '\0';

   CgiLibResponseHeader (200, "text/html");

   fprintf (stdout,
"<!DOCTYPE html>\n\
<html>\n\
<head>\n\
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\
<meta name=\"generator\" content=\"%s\">\n\
<meta name=\"copyright\" content=\"%s - GPL licensed\">\n\
<meta name=\"environment\" content=\"%s\">\n\
%s\
<title>HyperSPI - Data Summary - %s</title>\n\
<style type=\"text/css\">\n\
%s\
</style>\n\
%s\
</head>\n\
<body>\n",
            SoftwareID, SoftwareCopy,
            CgiEnvironmentPtr,
            MetaRefresh,
            CgiFormNodePtr,
            DefaultStyle,
            StyleSheetPtr);

   fprintf (stdout,
"<div class=\"header\">\
<div class=\"hyperSPI\">HyperSPI</div>\
<div class=\"heading\">Summary for %s</div>\
<div class=\"datetime\">%d %s %d %0.2d:%0.2d</div>\
</div>\n",
            CgiFormNodePtr,
            CurrentNumTime[2], MonthName[CurrentNumTime[1]], CurrentNumTime[0],
            CurrentNumTime[3], CurrentNumTime[4]);

   fprintf (stdout, "<div class=\"content\">\n");

   fflush (stdout);
   HttpHasBeenOutput = true;

   fprintf (stdout, "<table class=\"precis\">\n<tr><th>Period:</th><td>");

   if ((!NumberOfDays && NumberOfHours == 24) || NumberOfDays == 1)
      fputs ("1 day", stdout);
   else
   if (NumberOfDays > 1)
      fprintf (stdout, "%d days", NumberOfDays);

   if ((PeriodHours = (NumberOfHours % 24)) == 1)
      fputs ("1 hour", stdout);
   else
   if (PeriodHours > 1)
      fprintf (stdout, " %d hours", PeriodHours);

   fprintf (stdout,
", from %02.02d %s %d %02.02d:%02.02d to %02.02d %s %d %02.02d:%02.02d\
</td></tr>\n",
   FromDay, MonthName[FromMonth], FromYear, FromHour, FromMinute,
   ToDay, MonthName[ToMonth], ToYear, ToHour, ToMinute);

   /* summarize the data and calculate required averages */
   SummarizeData ();

   if (DataRecordsProcessedCount)
   {
      IncludeFile (CgiFormNodePtr);

      fprintf (stdout,
"<tr><th>CPUs:</th><td>%d</td></tr>\n\
<tr><th>Memory:</th><td>%dMB physical, %dMB page space \
(%dmb total)</td></tr>\n\
<tr><th>Processes:</th><td>%d average, %d peak</td></tr>\n\
<tr><td colspan=\"2\" style=\"font-size:80%%;\">\
(x axes are marked at hour intervals)</td></tr>\n\
</table>\n\
<p>\n",
         NumberOfCPUs,
         SystemMemoryMBytes, PageSpaceMBytes,
         SystemMemoryMBytes+PageSpaceMBytes,
         AveNumberOfProcesses, MaxNumberOfProcesses);

      if (ProvidePercentCPU) PresentCPU ();
      if (ProvideMemory) PresentMemory ();
      if (ProvideProcesses) PresentProcesses ();
      if (ProvidePageFaults) PresentPageFaults ();
      if (ProvidePeakPageFaults) PresentPeakPageFaults ();
      if (ProvideHardPageFaults) PresentHardPageFaults ();
      if (ProvidePeakHardPageFaults) PresentPeakHardPageFaults ();
      if (ProvideBufferedIO) PresentBufferedIO ();
      if (ProvidePeakBufferedIO) PresentPeakBufferedIO ();
      if (ProvideDirectIO) PresentDirectIO ();
      if (ProvidePeakDirectIO) PresentPeakDirectIO ();
      if (ProvideMscpIO) PresentMscpIO ();
      if (ProvidePeakMscpIO) PresentPeakMscpIO ();
      if (ProvideNetInt) PresentNetInt ();
      if (ProvidePeakNetInt) PresentPeakNetInt ();
   }
   else
      fputs ("No data available.\n", stdout);

   fprintf (stdout, "</div>\n");

   ButtonBar (2);

   fprintf (stdout, "</body>\n</html>\n");
}

/*****************************************************************************/
/*
Place an HTML link into the HTTP output stream to get a plot-data, GIF image, 
generated dynamically by this application, embedded in the current HTML 
document.  The 'UniqueNumber()' is used to place a unique component into the 
URL of the graph GIF URL, ensuring a cached version is not retrieved.  The 
'WhatPtr' is the name of the performance count to graph.  The optional 
'IncludePtr' allows selected graphs to contain additional information.
*/ 

GraphImageLink
(
boolean InlineImage,
char *WhatPtr,
char *IncludePtr,
...
)
{
#define LABEL_UNITS 0
#define LABEL_Y1    1
#define LABEL_Y2    2
#define LABEL_X1    3
#define LABEL_X2    4

   int  argcnt, idx;
   char  *Labels[5] = { NULL,NULL,NULL,NULL,NULL };
   va_list  argptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GraphImageLink()\n");

   va_count (argcnt);

   if (argcnt < 3 || argcnt > 8) exit (SS$_BUGCHECK);

   /* labels: Y units, Y axis 1, Y axis 2, X axis 1, X axis 2 */
   idx = 0;
   va_start (argptr, IncludePtr);
   for (argcnt -= 3; argcnt; argcnt--)
      Labels[idx++] = (char*)va_arg (argptr, char*);
   va_end (argptr);
   for (idx = 0; idx < 5; idx++) if (!Labels[idx]) Labels[idx] = "";

   if (InlineImage)
   {
      fprintf (stdout,
"<table class=\"graph\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n\
<tr><td style=\"width:4em;font-size:80%%;\
text-align:right;vertical-align:top;\">%s</td><td rowspan=\"3\">\n\
<img align=\"top\" alt=\"[graph]\" src=\"",
               Labels[LABEL_Y1]);

   }
   else
      fputs ("<a class=\"extrbtn\" href=\"", stdout);

   fprintf (stdout,
"%s?do=graph&unique=%s&%s=yes&include=%s\
&Xmag=%d&Ymag=%d&node=%s\
&from=%04.04d-%02.02d-%02.02d%%20%02.02d:%02.02d\
&to=%04.04d-%02.02d-%02.02d%%20%02.02d:%02.02d",
            CgiScriptNamePtr, UniqueNumber(), WhatPtr, IncludePtr, 
            XMag, YMag, CgiFormNodePtr,
            FromYear, FromMonth, FromDay, FromHour, FromMinute,
            ToYear, ToMonth, ToDay, ToHour, ToMinute);

   if (InlineImage)
   {
      fprintf (stdout,
"\">\n\
</td><td style=\"font-size:80%%;\
text-align:right;vertical-align:top;\">%s</td></tr>\n\
<tr><td style=\"font-size:80%%;padding:5px 15px 0 0;white-space:nowrap;\
text-align:right;vertical-align:middle;\">%s</td></tr>\n\
<tr><td style=\"font-size:80%%;padding-bottom:10px;\
text-align:right;vertical-align:bottom;\">%s</td>\
<td style=\"font-size:80%%;padding-bottom:10px;\
text-align:left;vertical-align:bottom;\">%s</td></tr>\n\
</table>\n",
               Labels[LABEL_Y2],
               Labels[LABEL_UNITS],
               Labels[LABEL_X1],
               Labels[LABEL_X2]);
   }
   else
      fputs ("\">Extract Graph</a>\n", stdout);
}

/*****************************************************************************/
/*
CPU usage.  Place textual information and a graphic GIF image link into the 
current HTML document being generated.
*/ 

PresentCPU ()

{
   char  NumCPU [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentCPU()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">CPU Usage</div>\n\
<div class=\"graphdata\">\n");

   sprintf (NumCPU, "%d CPU%s", NumberOfCPUs, NumberOfCPUs == 1 ? "" : "s");
   GraphImageLink (true, "cpu", "peak", NumCPU, "100%", NULL, "0");
   fprintf (stdout,
"%d%% average, %d%% peak; user-mode %d%% average, %d%% peak.\n",
            AvePercentCPU, PeakPercentCPU,
            AvePercentUserModeCPU, PeakPercentUserModeCPU);
   if (ExtractGraph)
      GraphImageLink (false, "cpu", "peak", NumCPU, "100%", NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Page space and physical memory usage.  Place textual information and a graphic 
GIF image link into the current HTML document being generated.
*/ 

PresentMemory ()

{
   char  Yaxis1 [32],
         Yaxis2 [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentMemory()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Memory Usage</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis1, "%dMB", SystemMemoryMBytes);
   sprintf (Yaxis2, "%dMB<br>(pgfl)", PageSpaceMBytes);
   GraphImageLink (true, "memory", "", NULL, Yaxis1, Yaxis2, "0", "0");
   fprintf (stdout,
"Physical memory %d%% average, %d%% peak;&nbsp; \
page space %d%% average, %d%% peak.\n",
            AveSystemMemoryPercentInUse, MaxSystemMemoryPercentInUse,
            AvePageSpacePercentInUse, MaxPageSpacePercentInUse);
   if (ExtractGraph)
      GraphImageLink (false, "memory", "", NULL, Yaxis1, Yaxis2, 0);

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Number of processes.  Place textual information and a graphic GIF image link 
into the current HTML document being generated.
*/ 

PresentProcesses ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentProcesses()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Number of Processes</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentProcesses));
   GraphImageLink (true, "processes", "", NULL, Yaxis, NULL, "0");
   fprintf (stdout, "%d average, maximum %d.\n",
            AveNumberOfProcesses, MaxNumberOfProcesses);
   if (ExtractGraph)
      GraphImageLink (false, "processes", "", NULL, Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Buffered IO (non-disk, non-tape, i.e. network, terminal).  Place textual 
information and a graphic GIF image link into the current HTML document being 
generated.
*/ 

PresentBufferedIO ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentBufferedIO()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Buffered IO (network, terminal, etc.)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentBufferedIO));
   if (IncludePeak)
      GraphImageLink (true, "buffered_IO", "peak", "IO/S", Yaxis, NULL, "0");
   else
      GraphImageLink (true, "buffered_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "%d average, maximum %d, peak %d.\n",
            AveBufferedIO, MaxAveBufferedIO, PeakBufferedIO);

   if (IncludePeak)
      if (ExtractGraph)
         GraphImageLink (false, "buffered_IO", "peak", "IO/S", Yaxis, NULL, "0");
      else;
   else
      if (ExtractGraph)
         GraphImageLink (false, "buffered_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Peak buffered IO.  Place textual information and a graphic GIF image link 
into the current HTML document being generated.
*/ 

PresentPeakBufferedIO ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentPeakBufferedIO()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Peak Buffered IO (network, terminal, etc.)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentPeakBufferedIO));
   GraphImageLink (true, "peak_buffered_IO", "", "IO/S", Yaxis, NULL, "0");
   fprintf (stdout, "Peak %d per-second.\n", PeakBufferedIO);
   if (ExtractGraph)
      GraphImageLink (false, "peak_buffered_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Direct IO (disk, tape, etc).  Place textual information and a graphic GIF 
image link into the current HTML document being generated.
*/ 

PresentDirectIO ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentDirectIO()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Direct IO (disk, tape, etc.)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentDirectIO));
   if (IncludePeak)
      GraphImageLink (true, "direct_IO", "peak", "IO/S", Yaxis, NULL, "0");
   else
      GraphImageLink (true, "direct_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "%d average, maximum %d, peak %d.\n",
            AveDirectIO, MaxAveDirectIO, PeakDirectIO);

   if (IncludePeak)
      if (ExtractGraph)
         GraphImageLink (false, "direct_IO", "peak", "IO/S", Yaxis, NULL, "0");
      else;
   else
      if (ExtractGraph)
         GraphImageLink (false, "direct_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Peak direct IO.  Place textual information and a graphic GIF image link 
into the current HTML document being generated.
*/ 

PresentPeakDirectIO ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentPeakDirectIO()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Peak Direct IO (disk, tape, etc.)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentPeakDirectIO));
   GraphImageLink (true, "peak_direct_IO", "", "IO/S", Yaxis, NULL, "0");
   fprintf (stdout, "Peak %d per-second.\n", PeakDirectIO);
   if (ExtractGraph)
      GraphImageLink (false, "peak_direct_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
MSCP IO.  Place textual information and a graphic GIF image link into the 
current HTML document being generated.
*/ 

PresentMscpIO ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentMscpIO()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">MSCP IO (served disk and tape)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentMscpIO));
   if (IncludePeak)
      GraphImageLink (true, "mscp_IO", "peak", "IO/S", Yaxis, NULL, "0");
   else
      GraphImageLink (true, "mscp_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "%d average, maximum %d, peak %d.\n",
            AveMscpIO, MaxAveMscpIO, PeakMscpIO);

   if (IncludePeak)
      if (ExtractGraph)
         GraphImageLink (false, "mscp_IO", "peak", "IO/S", Yaxis, NULL, "0");
      else;
   else
      if (ExtractGraph)
         GraphImageLink (false, "mscp_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Peak MSCP IO.  Place textual information and a graphic GIF image link 
into the current HTML document being generated.
*/ 

PresentPeakMscpIO ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentPeakMscpIO()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Peak MSCP IO (served disk and tape)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentPeakMscpIO));
   GraphImageLink (true, "peak_mscp_IO", "", "IO/S", Yaxis, NULL, "0");
   fprintf (stdout, "Peak %d per-second.\n", PeakMscpIO);
   if (ExtractGraph)
      GraphImageLink (false, "peak_mscp_IO", "", "IO/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Network interface traffic.  Place textual information and a graphic GIF image
link into the current HTML document being generated.
*/ 

PresentNetInt ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentNetInt()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Network Interface</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentNetInt));
   if (IncludePeak)
      GraphImageLink (true, "net_int", "peak", "kB/S", Yaxis, NULL, "0");
   else
      GraphImageLink (true, "net_int", "", "kB/S", Yaxis, NULL, "0");

   fprintf (stdout, "%d average, maximum %d, peak %d.\n",
            AveNetIntRxTx, MaxAveNetIntRxTx, PeakNetIntRxTx);

   if (IncludePeak)
      if (ExtractGraph)
         GraphImageLink (false, "net_int", "peak", "kB/S", Yaxis, NULL, "0");
      else;
   else
      if (ExtractGraph)
         GraphImageLink (false, "net_int", "", "kB/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Peak mscp IO.  Place textual information and a graphic GIF image link 
into the current HTML document being generated.
*/ 

PresentPeakNetInt ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentPeakNetInt()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Peak Network Interface</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentPeakNetInt));
   GraphImageLink (true, "peak_net_int", "", "kB/S", Yaxis, NULL, "0");
   fprintf (stdout, "Peak %d per-second.\n", PeakNetIntRxTx);
   if (ExtractGraph)
      GraphImageLink (false, "peak_net_int", "", "kB/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Page faulting IO.  Place textual information and a graphic GIF image link into 
the current HTML document being generated.
*/ 

PresentPageFaults ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentPageFaults()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Paging (Soft)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentPageFaults));
   if (IncludePeak)
      GraphImageLink (true, "faults", "peak", "flt/S", Yaxis, NULL, "0");
   else
      GraphImageLink (true, "faults", "", "flt/S", Yaxis, NULL, "0");

   fprintf (stdout, "%d average, maximum %d, peak %d.\n",
            AvePageFaults, MaxAvePageFaults, PeakPageFaults);

   if (IncludePeak)
      if (ExtractGraph)
         GraphImageLink (false, "faults", "peak", "flt/S", Yaxis, NULL, "0");
      else;
   else
      if (ExtractGraph)
         GraphImageLink (false, "faults", "", "flt/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Peak paging to disk.  Place textual information and a graphic GIF image link 
into the current HTML document being generated.
*/ 

PresentPeakPageFaults ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentPeakPageFaults()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Peak Paging (Soft)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentPeakPageFaults));
   GraphImageLink (true, "peak_faults", "", "flt/S", Yaxis, NULL, "0");
   fprintf (stdout, "BR>Peak %d per-second.\n", PeakPageFaults);
   if (ExtractGraph)
      GraphImageLink (false, "peak_faults", "", "flt/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Page faulting IO.  Place textual information and a graphic GIF image link into 
the current HTML document being generated.
*/ 

PresentHardPageFaults ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentHardPageFaults()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Paging (Hard)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentHardPageFaults));
   if (IncludePeak)
      GraphImageLink (true, "hard_faults", "peak", "flt/S", Yaxis, NULL, "0");
   else
      GraphImageLink (true, "hard_faults", "", "flt/S", Yaxis, NULL, "0");

   fprintf (stdout, "%d average, maximum %d, peak %d.\n",
            AveHardPageFaults, MaxAveHardPageFaults, PeakHardPageFaults);

   if (IncludePeak)
      if (ExtractGraph)
         GraphImageLink (false, "hard_faults", "peak", "flt/S", Yaxis, NULL, "0");
      else;
   else
   if (ExtractGraph)
      GraphImageLink (false, "hard_faults", "", "flt/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Peak paging to disk.  Place textual information and a graphic GIF image link 
into the current HTML document being generated.
*/ 

PresentPeakHardPageFaults ()

{
   char  Yaxis [32];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "PresentPeakHardPageFaults()\n");

   fprintf (stdout,
"<div class=\"graphtitle\">Peak Paging (Hard)</div>\n\
<div class=\"graphdata\">\n");

   sprintf (Yaxis, "%d", ProvideScaling(PresentPeakHardPageFaults));
   GraphImageLink (true, "peak_hard_faults", "", "flt/S", Yaxis, NULL, "0");
   fprintf (stdout, "Y axis is IOs per-second.\n<br>Peak %d per-second.\n",
            PeakHardPageFaults);
   if (ExtractGraph)
      GraphImageLink (false, "peak_hard_faults", "", "flt/S", Yaxis, NULL, "0");

   fprintf (stdout, "</div>\n");
}

/*****************************************************************************/
/*
Read all records for the specified node in the specified time range, 
calculating the average and maximum for each of the data categories.  Assumes 
it is only to be called once as it does not initialize any of the storage.
*/ 

SummarizeData ()

{
   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "SummarizeData()\n");

   ProcessDataFiles (&SummarizeRecord, true);

   /* the averaging must be by the actual sample rate */
   DataRecordsProcessedCount /= RecordSampleRate;

   if (!DataRecordsProcessedCount) return;

   AvePercentCPU /= DataRecordsProcessedCount;
   AvePercentUserModeCPU /= DataRecordsProcessedCount;
   AveSystemMemoryPercentInUse /= DataRecordsProcessedCount;
   AveNumberOfProcesses /= DataRecordsProcessedCount;
   AvePageSpacePercentInUse /= DataRecordsProcessedCount;
   AvePageFaults /= DataRecordsProcessedCount;
   AveHardPageFaults /= DataRecordsProcessedCount;
   AveBufferedIO /= DataRecordsProcessedCount;
   AveDirectIO /= DataRecordsProcessedCount;
   AveMscpIO /= DataRecordsProcessedCount;
   AveNetIntRxTx /= DataRecordsProcessedCount;
}

/*****************************************************************************/
/*
Set the various accumulators according to the data in the current 'SpiRecord'.
*/

void SummarizeRecord ()

{
   static unsigned long  RecordCount = 0,
                         NumberOfProcesses = 0,
                         NumberOfCom = 0,
                         SystemMemoryPercentInUse = 0,
                         PageSpacePercentInUse = 0,
                         PercentCPU = 0,
                         PercentModeCPU[HYPERSPI_CPU_MODE_COUNT] =
			    {0, 0, 0, 0, 0, 0},
                         BufferedIO = 0,
                         DirectIO = 0,
                         MscpIO = 0,
                         PageFaults = 0,
                         HardPageFaults = 0;

#ifndef __VAX
   static unsigned __int64  NetRxTx;
#else
   static unsigned long  NetRxTx;
#endif

   int  idx;
   unsigned long  tmp;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "SummarizeRecord()\n");

   /* usually (though not unconditionally) these remain constant! */
   if (SpiRecord.NumberOfCPUs > NumberOfCPUs)
      NumberOfCPUs = SpiRecord.NumberOfCPUs;
   if (SpiRecord.SystemMemoryMBytes > SystemMemoryMBytes)
      SystemMemoryMBytes = SpiRecord.SystemMemoryMBytes;
   if (SpiRecord.PageSpaceMBytes > PageSpaceMBytes)
      PageSpaceMBytes = SpiRecord.PageSpaceMBytes;

   /*
      The percentage CPU values VERY OCCASIONALLY get slightly above
      100%.  I attribute this behaviour to slight inconsistancies
      between obtaining system times and actually obtaining the CPU
      usage data, i.e. to the delta-time used to calculate the percentage.
      I chose to "massage" the data at the display end rather than the
      collection/recording end so that this behaviour could be monitored
      by using the "dump" facility to examine the actual data.
   */
   if (SpiRecord.PercentCPU > 100) SpiRecord.PercentCPU = 100;
   if (SpiRecord.PeakPercentCPU > 100) SpiRecord.PeakPercentCPU = 100;

   for (idx = 0; idx < HYPERSPI_CPU_MODE_COUNT; ++idx)
      if (SpiRecord.PercentModeCPU[idx] > 100)
         SpiRecord.PercentModeCPU[idx] = 100;

   /* peaks are always taken as absolutes! */
   if (SpiRecord.PeakPercentCPU > PeakPercentCPU)
      PeakPercentCPU = SpiRecord.PeakPercentCPU;

   if (SpiRecord.PeakBufferedIO > PeakBufferedIO)
      PeakBufferedIO = SpiRecord.PeakBufferedIO;
   if (SpiRecord.PeakDirectIO > PeakDirectIO)
      PeakDirectIO = SpiRecord.PeakDirectIO;
   if (SpiRecord.PeakMscpIO > PeakMscpIO)
      PeakMscpIO = SpiRecord.PeakMscpIO;
   if (SpiRecord.PeakPageFaults > PeakPageFaults)
      PeakPageFaults = SpiRecord.PeakPageFaults;
   if (SpiRecord.PeakHardPageFaults > PeakHardPageFaults)
      PeakHardPageFaults = SpiRecord.PeakHardPageFaults;

   /* down convert to kB */
#ifndef __VAX
   *(__int64*)SpiRecord.NetIntRx = *(__int64*)SpiRecord.NetIntRx >> 10;
   *(__int64*)SpiRecord.NetIntTx = *(__int64*)SpiRecord.NetIntTx >> 10;
#else
   SpiRecord.NetIntRx[0] = SpiRecord.NetIntRx[0] >> 10;
   SpiRecord.NetIntTx[0] = SpiRecord.NetIntTx[0] >> 10;
#endif
   SpiRecord.PeakNetIntRx = SpiRecord.PeakNetIntRx >> 10;
   SpiRecord.PeakNetIntTx = SpiRecord.PeakNetIntTx >> 10;
   SpiRecord.PeakNetIntRxTx = SpiRecord.PeakNetIntRxTx >> 10;

   if (SpiRecord.PeakNetIntRxTx > PeakNetIntRxTx)
      PeakNetIntRxTx = SpiRecord.PeakNetIntRxTx;

   if (RecordSampleRate > 1)
   {
      /* X axis compression, i.e. less than one record per plot point */
      PercentCPU += SpiRecord.PercentCPU;
      PercentUserModeCPU += SpiRecord.PercentUserModeCPU;
      NumberOfProcesses += SpiRecord.NumberOfProcesses;
      SystemMemoryPercentInUse += SpiRecord.SystemMemoryPercentInUse;
      PageSpacePercentInUse += SpiRecord.PageSpacePercentInUse;
      BufferedIO += SpiRecord.BufferedIO;
      DirectIO += SpiRecord.DirectIO;
      MscpIO += SpiRecord.MscpIO;
      PageFaults += SpiRecord.PageFaults;
      HardPageFaults += SpiRecord.HardPageFaults;

#ifndef __VAX
      NetRxTx += *(__int64*)SpiRecord.NetIntRx + *(__int64*)SpiRecord.NetIntTx;
#else
      NetRxTx += SpiRecord.NetIntRx[0] + SpiRecord.NetIntTx[0];
#endif

      if (++RecordCount < RecordSampleRate) return;

      /* average by dividing the accumlated values by the record sample rate */
      SpiRecord.PercentCPU = PercentCPU / RecordCount;
      SpiRecord.PercentUserModeCPU = PercentUserModeCPU / RecordCount;
      SpiRecord.NumberOfProcesses = NumberOfProcesses / RecordCount;
      SpiRecord.SystemMemoryPercentInUse =
         SystemMemoryPercentInUse / RecordCount;
      SpiRecord.PageSpacePercentInUse = PageSpacePercentInUse / RecordCount;
      SpiRecord.BufferedIO = BufferedIO / RecordCount;
      SpiRecord.DirectIO = DirectIO / RecordCount;
      SpiRecord.MscpIO = MscpIO / RecordCount;
      SpiRecord.PageFaults = PageFaults / RecordCount;
      SpiRecord.HardPageFaults = HardPageFaults / RecordCount;

      NetRxTx /= RecordCount;

      /* reset the accumulators to zero */
      PercentCPU = PercentUserModeCPU = NumberOfProcesses =
      SystemMemoryPercentInUse = PageSpacePercentInUse =
      BufferedIO = DirectIO = MscpIO = NetIntRxTx =
      PageFaults = HardPageFaults = RecordCount = 0;
   }
   else
   {
#ifndef __VAX
      NetRxTx = *(__int64*)SpiRecord.NetIntRx + *(__int64*)SpiRecord.NetIntTx;
#else
      NetRxTx = SpiRecord.NetIntRx[0] + SpiRecord.NetIntTx[0];
#endif
   }

   /* this will need to be divided by the number of records processed */
   AvePercentCPU += SpiRecord.PercentCPU;
   PercentUserModeCPU += SpiRecord.PercentUserModeCPU;
   if (SpiRecord.PeakPercentUserModeCPU > PeakPercentUserModeCPU)
      PeakPercentUserModeCPU = SpiRecord.PeakPercentUserModeCPU;

   /* this will need to be divided by the number of records processed */
   for (idx = 0; idx < HYPERSPI_CPU_MODE_COUNT; ++idx)
      AvePercentModeCPU[idx] += SpiRecord.PercentModeCPU[idx];

   /* this will need to be divided by the number of records processed */
   AveNumberOfProcesses += SpiRecord.NumberOfProcesses;
   if (SpiRecord.NumberOfProcesses > MaxNumberOfProcesses)
      MaxNumberOfProcesses = SpiRecord.NumberOfProcesses;

   /* this will need to be divided by the number of records processed */
   AveNumberOfCom += SpiRecord.Computable;
   if (SpiRecord.Computable > MaxNumberOfCom)
      MaxNumberOfCom = SpiRecord.Computable;

   /* this will need to be divided by the number of records processed */
   AveSystemMemoryPercentInUse += SpiRecord.SystemMemoryPercentInUse;
   if (SpiRecord.SystemMemoryPercentInUse > MaxSystemMemoryPercentInUse)
      MaxSystemMemoryPercentInUse = SpiRecord.SystemMemoryPercentInUse;

   /* this will need to be divided by the number of records processed */
   AvePageSpacePercentInUse += SpiRecord.PageSpacePercentInUse;
   if (SpiRecord.PageSpacePercentInUse > MaxPageSpacePercentInUse)
      MaxPageSpacePercentInUse = SpiRecord.PageSpacePercentInUse;

   AveBufferedIO += (tmp = SpiRecord.BufferedIO / 60);
   if (tmp > MaxAveBufferedIO) MaxAveBufferedIO = tmp;

   AveDirectIO += (tmp = SpiRecord.DirectIO / 60);
   if (tmp > MaxAveDirectIO) MaxAveDirectIO = tmp;

   AveMscpIO += (tmp = SpiRecord.MscpIO / 60);
   if (tmp > MaxAveMscpIO) MaxAveMscpIO = tmp;

   AvePageFaults += (tmp = SpiRecord.PageFaults / 60);
   if (tmp > MaxAvePageFaults) MaxAvePageFaults = tmp;

   AveHardPageFaults += (tmp = SpiRecord.HardPageFaults / 60);
   if (tmp > MaxAveHardPageFaults) MaxAveHardPageFaults = tmp;

   AveLck += ((SpiRecord.LckLoc + SpiRecord.LckIn + SpiRecord.LckOut) / 60);
   AveLckLoc += (SpiRecord.LckLoc / 60);
   AveLckIn += (SpiRecord.LckIn / 60);
   AveLckOut += (SpiRecord.LckOut / 60);

   AveNetIntRxTx += (tmp = (unsigned long)(NetRxTx / 60));
   if (tmp > MaxAveNetIntRxTx) MaxAveNetIntRxTx = tmp;
}

/*****************************************************************************/
/*
Set the global values for the Y axis scaling factor and maximum value
represented on the X axis according to the specified value (maximum out of the
to-be plotted data).
*/

void SetScaling (int Maximum)

{
   if (Debug) fprintf (stdout, "SetScaling() %d\n", Maximum);

   if (Maximum <= 10)
   {
      ScalingFactorY = 10.0;
      PlotScaleY = 10;
   }
   else
   if (Maximum <= 25)
   {
      ScalingFactorY = 4.0;
      PlotScaleY = 25;
   }
   else
   if (Maximum <= 50)
   {
      ScalingFactorY = 2.0;
      PlotScaleY = 50;
   }
   else
   if (Maximum <= 100)
   {
      ScalingFactorY = 1.0;
      PlotScaleY = 100;
   }
   else
   if (Maximum <= 250)
   {
      ScalingFactorY = 0.4;
      PlotScaleY = 250;
   }
   else
   if (Maximum <= 500)
   {
      ScalingFactorY = 0.2;
      PlotScaleY = 500;
   }
   else
   if (Maximum <= 1000)
   {
      ScalingFactorY = 0.1;
      PlotScaleY = 1000;
   }
   else
   if (Maximum <= 2500)
   {
      ScalingFactorY = 0.04;
      PlotScaleY = 2500;
   }
   else
   if (Maximum <= 5000)
   {
      ScalingFactorY = 0.02;
      PlotScaleY = 5000;
   }
   else
   if (Maximum <= 10000)
   {
      ScalingFactorY = 0.01;
      PlotScaleY = 10000;
   }
   else
   if (Maximum <= 25000)
   {
      ScalingFactorY = 0.004;
      PlotScaleY = 25000;
   }
   else
   if (Maximum <= 50000)
   {
      ScalingFactorY = 0.002;
      PlotScaleY = 50000;
   }
   else
   if (Maximum <= 100000)
   {
      ScalingFactorY = 0.001;
      PlotScaleY = 100000;
   }
   else
   {
      ScalingFactorY = 0.0001;
      PlotScaleY = 1000000;
   }

   if (Debug)
      fprintf (stdout, "ScalingFactorY: %f PlotScaleY: %d\n",
               ScalingFactorY, PlotScaleY);
}

/*****************************************************************************/
/*
Set the global values for scaling factor for the Y axis based on the provided
report/graph.  If a call function is provided then ignore the (multiply set)
global Provide.. booleans and use the indicated function to decide.  Return the
value of PlotScaleY (as a convenience only).
*/

int ProvideScaling (void *CallFunc)

{
   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProvideScaling()\n");

   if ((!CallFunc && ProvideBufferedIO) ||
       (CallFunc == PresentBufferedIO))
      if (IncludePeak)
         SetScaling (PeakBufferedIO);
      else
         SetScaling (MaxAveBufferedIO);
   else 
   if ((!CallFunc && ProvidePeakBufferedIO) ||
       (CallFunc == PresentPeakBufferedIO))
      SetScaling (PeakBufferedIO);
   else 
   if ((!CallFunc && ProvideDirectIO) ||
       (CallFunc == PresentDirectIO))
      if (IncludePeak)
         SetScaling (PeakDirectIO);
      else
         SetScaling (MaxAveDirectIO);
   else 
   if ((!CallFunc && ProvidePeakDirectIO) ||
       (CallFunc == PresentPeakDirectIO))
      SetScaling (PeakDirectIO);
   else 
   if ((!CallFunc && ProvideMscpIO) ||
       (CallFunc == PresentMscpIO))
      if (IncludePeak)
         SetScaling (PeakMscpIO);
      else
         SetScaling (MaxAveMscpIO);
   else 
   if ((!CallFunc && ProvidePeakMscpIO) ||
       (CallFunc == PresentPeakMscpIO))
      SetScaling (PeakMscpIO);
   else 
   if ((!CallFunc && ProvideNetInt) ||
       (CallFunc == PresentNetInt))
      if (IncludePeak)
         SetScaling (PeakNetIntRxTx);
      else
         SetScaling (MaxAveNetIntRxTx);
   else 
   if ((!CallFunc && ProvidePeakNetInt) ||
       (CallFunc == PresentPeakNetInt))
      SetScaling (PeakNetIntRxTx);
   else
   if ((!CallFunc && ProvidePageFaults) ||
       (CallFunc == PresentPageFaults))
      if (IncludePeak)
         SetScaling (PeakPageFaults);
      else
         SetScaling (MaxAvePageFaults);
   else 
   if ((!CallFunc && ProvidePeakPageFaults) ||
       (CallFunc == PresentPeakPageFaults))
      SetScaling (PeakPageFaults);
   else 
   if ((!CallFunc && ProvideHardPageFaults) ||
       (CallFunc == PresentHardPageFaults))
      if (IncludePeak)
         SetScaling (PeakHardPageFaults);
      else
         SetScaling (MaxAveHardPageFaults);
   else 
   if ((!CallFunc && ProvidePeakHardPageFaults) ||
       (CallFunc == PresentPeakHardPageFaults))
      SetScaling (PeakHardPageFaults);
   else 
   if ((!CallFunc && ProvideProcesses) ||
       (CallFunc == PresentProcesses))
      SetScaling (MaxNumberOfProcesses);
   else
      exit (SS$_BUGCHECK);

   return (PlotScaleY);
}

/*****************************************************************************/
/*
The application is being called to plot a graph of the data of the specified 
node in the specified time range, and generate a GIF image of that graph and 
return it to the browser.
*/

GraphData ()

{
   int  Xcnt, Ycnt, AtX, AtY;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GraphData()\n");

#ifdef GIF_EXPIRED

   CgiLibResponseHeader (200, "image/gif",
                         "Expires: Fri, 13 Jan 1978 14:30:00 GMT\n");

#else

   CgiLibResponseHeader (200, "image/gif");

#endif
   fflush (stdout);

   SizeOfPlotX = NumberOfHours * 60 * XMag / RecordSampleRate;
   SizeOfPlotY = 100 * YMag;
   if (Debug) fprintf (stdout, "size %d,%d\n", SizeOfPlotX, SizeOfPlotY);

   HaveDataY = SizeOfMarginY / 6;

   PlotAllocate (SizeOfPlotX + SizeOfMarginX*2,
                 SizeOfPlotY + SizeOfMarginY + SizeOfMarginY/2);

   if (ProvidePercentCPU || ProvidePercentUserModeCPU)
   {
      /* no scaling to be done for the X axis so plot it now */
      PlotAxes (0);
      /* process specified data calling 'GraphRecordCPU()' for each record */
      ProcessDataFiles (&GraphRecordCPU, true);
   }
   else
   if (ProvideMemory)
   {
      /* no scaling to be done for the X axis so plot it now */
      PlotAxes (0);
      /* process specified data calling 'GraphRecordMemory()' for each record */
      ProcessDataFiles (&GraphRecordMemory, true);
   }
   else
   if (ProvideBufferedIO || ProvidePeakBufferedIO ||
       ProvideDirectIO ||  ProvidePeakDirectIO ||
       ProvideMscpIO || ProvidePeakMscpIO ||
       ProvideNetInt || ProvidePeakNetInt ||
       ProvidePageFaults || ProvidePeakPageFaults  ||
       ProvideHardPageFaults || ProvidePeakHardPageFaults ||
       ProvideProcesses)
   {
      /* plot the X and Y axes after summarizing the data and setting scaling */
      SummarizeData ();
      ProvideScaling (NULL);
      PlotAxes (0);

      if (ProvideProcesses)
      {
         /* process data calling 'GraphRecordProcesses()' for each record */
         ProcessDataFiles (&GraphRecordProcesses, true);
      }
      else
      {
         /* process data calling 'GraphRecordRange()' for each record */
         ProcessDataFiles (&GraphRecordRange, true);
      }
   }
   else
   {
      CgiLibResponseError (FI_LI, 0, "Internal error.");
      exit (SS$_NORMAL);
   }

   /* if the current time is within the graphed X axis timescale */
   if (CurrentMinuteFromStartOfPeriod < NumberOfHours * 60)
   {
      /* place a horizontal mark at the end of the data available line */
      AtX = (CurrentMinuteFromStartOfPeriod / RecordSampleRate) * XMag;
      AtY = SizeOfMarginY / 4;
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = -3; Ycnt < 3 + YMag; Ycnt++)
            PlotPixel (0, AtX+Xcnt, HaveDataY+Ycnt, SizeOfMarginX, 0);
   }

   /* generate and return the GIF image to the browser */
   GifImage ("");
}

/*****************************************************************************/
/*
Plot a CPU record.  Either total or user-mode usage, as a line from zero to 
the percentage value uasage.  Optionally and additionally, plot peak total or 
user-mode usage, or total usage (for use with the user-mode line plot) as a 
single point.  Plot has a Y axis fixed to representPeak 100 percent.
*/ 

GraphRecordCPU ()

{
   static int  RecordCount = 0;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GraphRecordCPU()\n");

   /*
      The percentage CPU values VERY OCCASIONALLY get slightly above
      100%.  I attribute this behaviour to slight inconsistancies
      between obtaining system times and actually obtaining the CPU
      usage data, i.e. to the delta-time used to calculate the percentage.
      I chose to "massage" the data at the display end rather than the
      collection/recording end so that this behaviour could be monitored
      by using the "dump" facility to examine the actual data.
   */
   if (SpiRecord.PercentCPU > 100) SpiRecord.PercentCPU = 100;
   if (SpiRecord.PeakPercentCPU > 100) SpiRecord.PeakPercentCPU = 100;
   if (SpiRecord.PercentUserModeCPU > 100) SpiRecord.PercentUserModeCPU = 100;
   if (SpiRecord.PeakPercentUserModeCPU > 100)
      SpiRecord.PeakPercentUserModeCPU = 100;

   if (RecordSampleRate > 1)
   {
      /* X axis compression, i.e. less than one record per plot point */
      PercentCPU += SpiRecord.PercentCPU;
      PercentUserModeCPU += SpiRecord.PercentUserModeCPU;
      /* get the maximum of the peak values read */
      if (SpiRecord.PeakPercentCPU > PeakPercentCPU)
          PeakPercentCPU = SpiRecord.PeakPercentCPU;
      if (SpiRecord.PeakPercentUserModeCPU > PeakPercentUserModeCPU)
          PeakPercentUserModeCPU = SpiRecord.PeakPercentUserModeCPU;

      if (++RecordCount < RecordSampleRate) return;

      /* get the average of the values read */
      SpiRecord.PercentCPU = PercentCPU / RecordCount;
      SpiRecord.PercentUserModeCPU = PercentUserModeCPU / RecordCount;
      /* maximum of the peak values read */
      SpiRecord.PeakPercentCPU = PeakPercentCPU;
      SpiRecord.PeakPercentUserModeCPU = PeakPercentUserModeCPU;

      PercentCPU = PercentUserModeCPU = PeakPercentCPU =
         PeakPercentUserModeCPU = RecordCount = 0;
   }

   /*********************/
   /* plot the value(s) */
   /*********************/

   {
      int  Xcnt, Ycnt, ToY, AtX, AtY;

      AtX = (NumberOfMinutesIntoData / RecordSampleRate) * XMag;

      /* plot the fact we have data for this minute */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (0, AtX+Xcnt, HaveDataY+Ycnt, SizeOfMarginX, 0);

      if (ProvidePercentCPU)
         ToY = SpiRecord.PercentCPU * YMag;
      else
      if (ProvidePercentUserModeCPU)
         ToY = SpiRecord.PercentUserModeCPU * YMag;

      /* plot as line from zero to whatever the value is */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         PlotLineY (0, 0, ToY, AtX+Xcnt, SizeOfMarginX, SizeOfMarginY);

      /* any extra data to plot? (is plotted in single pixels) */

      if (IncludePeak)
      {
         /* CPU peak usage has been requested to be included */
         if (ProvidePercentCPU)
            AtY = SpiRecord.PeakPercentCPU * YMag;
         else
         if (ProvidePercentUserModeCPU)
            AtY = SpiRecord.PeakPercentUserModeCPU * YMag;
         else;
      }
      else
      if (IncludeTotal)
      {
         /* CPU total usage has been requested to be included */
         AtY = SpiRecord.PercentCPU * YMag;
      }
      else
      {
         /* no, nothing extra to plot! */
         return;
      }

      /* plot the extra value as a point */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (PLOT_XOR, AtX+Xcnt, AtY+Ycnt,
                       SizeOfMarginX, SizeOfMarginY);
   }
}

/*****************************************************************************/
/*
Plot page space usage as a line from zero to percentage used.  Plot physical 
memory as a point at the percentage used.  Plot has a Y axis fixed to 
represent 100 percent.
*/ 

GraphRecordMemory ()

{
   static int  RecordCount = 0;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GraphRecordMemory()\n");

   if (RecordSampleRate > 1)
   {
      /* X axis compression, i.e. less than one record per plot point */
      SystemMemoryPercentInUse += SpiRecord.SystemMemoryPercentInUse;
      PageSpacePercentInUse += SpiRecord.PageSpacePercentInUse;

      if (++RecordCount < RecordSampleRate) return;

      /* get the average of the values read */
      SpiRecord.SystemMemoryPercentInUse =
         SystemMemoryPercentInUse / RecordCount;
      SpiRecord.PageSpacePercentInUse =
         PageSpacePercentInUse / RecordCount;

      SystemMemoryPercentInUse = PageSpacePercentInUse = RecordCount = 0;
   }

   /*******************/
   /* plot the values */
   /*******************/

   {
      int  Xcnt, Ycnt, ToY, AtX, AtY;

      AtX = (NumberOfMinutesIntoData / RecordSampleRate) * XMag;

      /* plot the fact we have data for this minute */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (0, AtX+Xcnt, HaveDataY+Ycnt, SizeOfMarginX, 0);

      ToY = SpiRecord.PageSpacePercentInUse * YMag;
      /* plot as line from zero to whatever the value is */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         PlotLineY (0, 0, ToY, AtX+Xcnt, SizeOfMarginX, SizeOfMarginY);

      AtY = SpiRecord.SystemMemoryPercentInUse * YMag;
      /* plot a point */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (PLOT_XOR, AtX+Xcnt, AtY+Ycnt,
                       SizeOfMarginX, SizeOfMarginY);
   }
}

/*****************************************************************************/
/*
Plot the number of processes on the system as plot-points (forming a
semi-continuous line).  Requires a variable range for the Y axis.  That is data
that  can vary considerably in the maximum value represented on the Y axis. 
Employs  a previously set variable 'ScalingFactorY' to adjust the plot values
to fall  within the Y axis.  'ScalingFactorY' must be set after scanning all of
the  specified data to determine the maximum value.
*/ 

GraphRecordProcesses ()

{
   static int  RecordCount = 0;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GraphRecordProcesses()\n");

   if (RecordSampleRate > 1)
   {
      /* X axis compression, i.e. less than one record per plot point */
      NumberOfProcesses += SpiRecord.NumberOfProcesses;
      /* return if still averaging according to sample rate */
      if (++RecordCount < RecordSampleRate) return;
      /* get the average of the values read */
      SpiRecord.NumberOfProcesses = NumberOfProcesses / RecordCount;
      /* reset the accumulator */
      NumberOfProcesses = RecordCount = 0;
   }

   /*******************/
   /* plot the value */
   /*******************/

   {
      int  Xcnt, Ycnt, AtX, AtY;

      AtX = (NumberOfMinutesIntoData / RecordSampleRate) * XMag;

      /* plot the fact we have data for this minute */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (0, AtX+Xcnt, HaveDataY+Ycnt, SizeOfMarginX, 0);

      AtY = SpiRecord.NumberOfProcesses * ScalingFactorY * YMag;
      /* plot a point */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (PLOT_XOR, AtX+Xcnt, AtY+Ycnt,
                       SizeOfMarginX, SizeOfMarginY);
   }
}

/*****************************************************************************/
/*
Plot values that require a variable range for the Y axis.  That is data that 
can vary considerably in the maximum value represented on the Y axis.  Employs 
a previously set variable 'ScalingFactorY' to adjust the plot values to fall 
within the Y axis.  'ScalingFactorY' must be set after scanning all of the 
specified data to determine the maximum value.
*/

GraphRecordRange ()

{
   static int  RecordCount = 0;
   static unsigned long  StaticPeakValue = 0,
                         StaticValue = 0;

    unsigned long  PeakValue,
                   Value;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GraphRecordRange()\n");

   if (ProvideBufferedIO)
   {
      Value = SpiRecord.BufferedIO;
      PeakValue = SpiRecord.PeakBufferedIO;
   }
   else
   if (ProvidePeakBufferedIO)
      Value = PeakValue = SpiRecord.PeakBufferedIO;
   else
   if (ProvideDirectIO)
   {
      Value = SpiRecord.DirectIO;
      PeakValue = SpiRecord.PeakDirectIO;
   }
   else
   if (ProvidePeakDirectIO)
      Value = PeakValue = SpiRecord.PeakDirectIO;
   else
   if (ProvideMscpIO)
   {
      Value = SpiRecord.MscpIO;
      PeakValue = SpiRecord.PeakMscpIO;
   }
   else
   if (ProvidePeakMscpIO)
      Value = PeakValue = SpiRecord.PeakMscpIO;
   else
   if (ProvideNetInt)
   {
#ifndef __VAX
      Value = (unsigned long)(((*(__int64*)SpiRecord.NetIntRx +
                                *(__int64*)SpiRecord.NetIntTx)) >> 10);
#else
      Value = (SpiRecord.NetIntRx[0] + SpiRecord.NetIntTx[0]) >> 10;
#endif
      PeakValue = SpiRecord.PeakNetIntRxTx;
   }
   else
   if (ProvidePeakNetInt)
      Value = PeakValue = SpiRecord.PeakNetIntRxTx;
   else
   if (ProvidePageFaults)
   {
      Value = SpiRecord.PageFaults;
      PeakValue = SpiRecord.PeakPageFaults;
   }
   else
   if (ProvidePeakPageFaults)
      Value = PeakValue = SpiRecord.PeakPageFaults;
   else
   if (ProvideHardPageFaults)
   {
      Value = SpiRecord.HardPageFaults;
      PeakValue = SpiRecord.PeakHardPageFaults;
   }
   else
   if (ProvidePeakHardPageFaults)
      Value = PeakValue = SpiRecord.PeakHardPageFaults;

   if (RecordSampleRate > 1)
   {
      /* X axis compression, i.e. less than one record per plot point */
      StaticValue += Value; 
      /* get the maximum of the peak values read */
      if (PeakValue > StaticPeakValue) StaticPeakValue = PeakValue; 

      if (++RecordCount < RecordSampleRate) return;

      /* get the average of the values read */
      Value = StaticValue / RecordCount;
      /* maximum of the peak values read */
      PeakValue = StaticPeakValue;

      StaticValue = StaticPeakValue = RecordCount = 0;
   }
   if (Debug) fprintf (stdout, "Value: %d PeakValue: %d\n", Value, PeakValue);

   /*********************/
   /* plot the value(s) */
   /*********************/

   {
      int  Xcnt, Ycnt, ToY, AtX, AtY;

      AtX = (NumberOfMinutesIntoData / RecordSampleRate) * XMag;

      /* plot the fact we have data for this minute */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (0, AtX+Xcnt, HaveDataY+Ycnt, SizeOfMarginX, 0);

      if (ProvideBufferedIO ||
          ProvideDirectIO ||
          ProvideMscpIO ||
          ProvideNetInt ||
          ProvidePageFaults ||
          ProvideHardPageFaults)
         ToY = (int)((float)(Value / 60) * ScalingFactorY) * YMag;
      else
         ToY = (int)((float)PeakValue * ScalingFactorY) * YMag;

      /* plot as line from zero to whatever the value is */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         PlotLineY (0, 0, ToY, AtX+Xcnt, SizeOfMarginX, SizeOfMarginY);

      if (IncludePeak)
         AtY = (int)((float)PeakValue * ScalingFactorY) * YMag;
      else
      {
         /* no, nothing extra to plot! */
         return;
      }

      /* plot peak value as a point */
      for (Xcnt = 0; Xcnt < XMag; Xcnt++)
         for (Ycnt = 0; Ycnt < YMag; Ycnt++)
            PlotPixel (PLOT_XOR, AtX+Xcnt, AtY+Ycnt,
                       SizeOfMarginX, SizeOfMarginY);
   }
}

/*****************************************************************************/
/*
*/

ListProcessedData ()

{
   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ListProcessedData()\n");

   CgiLibResponseHeader (200, "text/html");

   fprintf (stdout,
"<!DOCTYPE html>\n\
<html>\n\
<head>\n\
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\
<meta name=\"generator\" content=\"%s\">\n\
<meta name=\"copyright\" content=\"%s - GPL licensed\">\n\
<meta name=\"environment\" content=\"%s\">\n\
<title>HyperSPI - Processed Data - %s</title>\n\
<style type=\"text/css\">\n\
%s\
</style>\n\
%s\
</head>\n\
<body>\n",
            SoftwareID, SoftwareCopy,
            CgiEnvironmentPtr,
            CgiFormNodePtr,
            DefaultStyle,
            StyleSheetPtr);

   fprintf (stdout,
"<div class=\"header\">\
<div class=\"hyperSPI\">HyperSPI</div>\
<div class=\"heading\">Processed Data for %s</div>\
<div class=\"datetime\">%d %s %d %0.2d:%0.2d</div>\
</div>\n",
            CgiFormNodePtr,
            CurrentNumTime[2], MonthName[CurrentNumTime[1]], CurrentNumTime[0],
            CurrentNumTime[3], CurrentNumTime[4]);

   fprintf (stdout, "<div class=\"content\">\n");

   HttpHasBeenOutput = true;

   ProcessDataFiles (&ListProcessedRecord, true);

   if (DataFilesProcessedCount)
      fputs ("</pre>\n</div>\n", stdout);
   else
      fputs ("<p>No matching data files.\n</div>\n", stdout);

   ButtonBar (2);

   fprintf (stdout, "</body>\n</html>\n");
}

/*****************************************************************************/
/*
*/

void ListProcessedRecord ()

{
   static int  PrevDay = -1,
               PrevHour = -1;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ListProcessedRecord()\n");

   if (DataDay != PrevDay)
   {
      if (PrevDay != -1) fputs ("</pre>\n", stdout);
      PrevDay = DataDay;
      fprintf (stdout, 
"<div class=\"fileday\">%s &nbsp;%02.02d %s %d</div>\n\
<div class=\"filename\">%s</div>\n\
<pre>",
      CgiFormNodePtr, DataDay, MonthName[DataMonth], DataYear,
      DataFileName);
   }

   if (SpiRecord.Hour != PrevHour)
   {
      if (PrevHour != -1) fputs ("\n", stdout);
      PrevHour = SpiRecord.Hour;
      fprintf (stdout,
"hh:mm  CPU usr  mem pge  b-IO peak  d-IO peak  mscp peak   flts  peak  \
hard peak  \
       NI rx         peak        NI tx         peak   rx+tx peak\n\
-----  --- ---  --- ---  ---- ----  ---- ----  ---- ----  ----- -----  \
---- ----  \
------------ ------------ ------------ ------------ ------------\n");
   }

   fprintf (stdout,
"%02.02d:%02.02d  %3d %3d  %3d %3d  \
%4d %4d  %4d %4d  %4d %4d  %5d %5d  %4d %4d  ",
   SpiRecord.Hour, SpiRecord.Minute,
   SpiRecord.PercentCPU, SpiRecord.PercentUserModeCPU,
   SpiRecord.SystemMemoryPercentInUse,
   SpiRecord.PageSpacePercentInUse,
   SpiRecord.BufferedIO / 60, SpiRecord.PeakBufferedIO,
   SpiRecord.DirectIO / 60, SpiRecord.PeakDirectIO,
   SpiRecord.MscpIO / 60, SpiRecord.PeakMscpIO,
   SpiRecord.PageFaults / 60, SpiRecord.PeakPageFaults,
   SpiRecord.HardPageFaults / 60, SpiRecord.PeakHardPageFaults);

#ifndef __VAX
   fprintf (stdout,
"%12Lu %12u %12Lu %12u %12u\n",
            *(__int64*)&SpiRecord.NetIntRx,
            SpiRecord.PeakNetIntRx,
            *(__int64*)&SpiRecord.NetIntTx,
            SpiRecord.PeakNetIntTx,
            SpiRecord.PeakNetIntRxTx);
#else
   fprintf (stdout,
"%12u %12u %12u %12u %12u\n",
            SpiRecord.NetIntRx[0],
            SpiRecord.PeakNetIntRx,
            SpiRecord.NetIntTx[0],
            SpiRecord.PeakNetIntTx,
            SpiRecord.PeakNetIntRxTx);
#endif
}

/*****************************************************************************/
/*
*/

void DumpData ()

{
   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "DumpData()\n");

   CgiLibResponseHeader (200, "text/html");

   fprintf (stdout,
"<!DOCTYPE html>\n\
<html>\n\
<head>\n\
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\
<meta name=\"generator\" content=\"%s\">\n\
<meta name=\"copyright\" content=\"%s - GPL licensed\">\n\
<meta name=\"environment\" content=\"%s\">\n\
<title>HyperSPI - Data Dump - %s</title>\n\
<style type=\"text/css\">\n\
%s\
</style>\n\
%s\
</head>\n\
<body>\n",
            SoftwareID, SoftwareCopy,
            CgiEnvironmentPtr,
            CgiFormNodePtr,
            DefaultStyle,
            StyleSheetPtr);

   fprintf (stdout,
"<div class=\"header\">\
<div class=\"hyperSPI\">HyperSPI</div>\
<div class=\"heading\">Data Dump for %s</div>\
<div class=\"datetime\">%d %s %d %0.2d:%0.2d</div>\
</div>\n",
            CgiFormNodePtr,
            CurrentNumTime[2], MonthName[CurrentNumTime[1]], CurrentNumTime[0],
            CurrentNumTime[3], CurrentNumTime[4]);

   fprintf (stdout, "<div class=\"content\">\n");

   HttpHasBeenOutput = true;

   ProcessDataFiles (&DumpRecord, true);

   if (DataFilesProcessedCount)
      fputs ("</pre>\n</div>\n", stdout);
   else
      fputs ("<p>No matching data files.\n</div>\n", stdout);

   ButtonBar (2);

   fprintf (stdout, "</body>\n</html>\n");
}

/*****************************************************************************/
/*
*/

void DumpRecord()

{
   static int  PrevDay = -1,
               PrevHour = -1;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "DumpRecord()\n");

   if (DataDay != PrevDay)
   {
      if (PrevDay != -1) fputs ("</pre>\n", stdout);
      PrevDay = DataDay;
      fprintf (stdout, 
"<div class=\"fileday\">%s &nbsp;%02.02d %s %d</div>\n\
<div class=\"filename\">%s</div>\n\
<pre>",
      CgiFormNodePtr, DataDay, MonthName[DataMonth], DataYear,
      DataFileName);
   }

   if (SpiRecord.Hour != PrevHour)
   {
      fputs ("\n", stdout);
      PrevHour = SpiRecord.Hour;
      fprintf (stdout,
"hh:mm  prc  CPU  pk  usr  pk  mem pge   buf-IO    peak  \
 dir-IO    peak  mscp-IO    peak   faults    peak   hard  peak Com \
int mps krn exe sup usr Lck-Loc Lck-In  Lck-Out  \
          rx         peak           tx         peak   rx+tx peak\n\
-----  ---  --- ---  --- ---  --- ---  ------- -------  \
------- -------  ------- -------  ------- -------  ----- ----- --- \
--- --- --- --- --- --- ------- ------- -------  \
------------ ------------ ------------ ------------ ------------\n");
   }

   fprintf (stdout,
"%02.02d:%02.02d  %3d  %3d %3d  %3d %3d  %3d %3d  \
%7d %7d  %7d %7d  %7d %7d  %7d %7d  %5d %5d %3d \
%3d %3d %3d %3d %3d %3d %7d %7d %7d  ",
   SpiRecord.Hour, SpiRecord.Minute,
   SpiRecord.NumberOfProcesses,
   SpiRecord.PercentCPU, SpiRecord.PeakPercentCPU,
   SpiRecord.PercentUserModeCPU, SpiRecord.PeakPercentUserModeCPU,
   SpiRecord.SystemMemoryPercentInUse,
   SpiRecord.PageSpacePercentInUse,
   SpiRecord.BufferedIO, SpiRecord.PeakBufferedIO,
   SpiRecord.DirectIO, SpiRecord.PeakDirectIO,
   SpiRecord.MscpIO, SpiRecord.PeakMscpIO,
   SpiRecord.PageFaults, SpiRecord.PeakPageFaults,
   SpiRecord.HardPageFaults, SpiRecord.PeakHardPageFaults,
   SpiRecord.Computable,
   SpiRecord.PercentModeCPU[HYPERSPI_MODE_INTERRUPT],
   SpiRecord.PercentModeCPU[HYPERSPI_MODE_MULTIPROC],
   SpiRecord.PercentModeCPU[HYPERSPI_MODE_KERNEL],
   SpiRecord.PercentModeCPU[HYPERSPI_MODE_EXECUTIVE],
   SpiRecord.PercentModeCPU[HYPERSPI_MODE_SUPERVISOR],
   SpiRecord.PercentModeCPU[HYPERSPI_MODE_USER],
   SpiRecord.LckLoc,
   SpiRecord.LckIn,
   SpiRecord.LckOut);

#ifndef __VAX
   fprintf (stdout,
"%12Lu %12u %12Lu %12u %12u\n",
            *(__int64*)&SpiRecord.NetIntRx,
            SpiRecord.PeakNetIntRx,
            *(__int64*)&SpiRecord.NetIntTx,
            SpiRecord.PeakNetIntTx,
            SpiRecord.PeakNetIntRxTx);
#else
   fprintf (stdout,
"%12u %12u %12u %12u %12u\n",
            SpiRecord.NetIntRx[0],
            SpiRecord.PeakNetIntRx,
            SpiRecord.NetIntTx[0],
            SpiRecord.PeakNetIntTx,
            SpiRecord.PeakNetIntRxTx);
#endif
}

/*****************************************************************************/
/*
The first parameter to this function is the address (a pointer to) the 
function used to process each file name found.
*/ 
 
int ProcessDataFiles
(
int (*ProcessFileFunction)(),
boolean OpenDataFile
)
{
   char  *cptr, *sptr;

   int  status;
   char  ExpandedFileName [256],
         Scratch [256];
   struct FAB  SearchFab;
   struct RAB  SearchRab;
   struct NAM  SearchNam;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessDataFiles() |%s|\n", DataFileSpec);

   DataFilesFoundCount = DataFilesProcessedCount =
      DataRecordsReadCount = DataRecordsProcessedCount = 0;

   SearchFab = cc$rms_fab;
   SearchFab.fab$l_fna = DataFileSpec;
   SearchFab.fab$b_fns = DataFileSpecLength;
   SearchFab.fab$l_fop = FAB$M_NAM;
   SearchFab.fab$l_nam = &SearchNam;

   SearchNam = cc$rms_nam;
   SearchNam.nam$l_esa = ExpandedFileName;
   SearchNam.nam$b_ess = sizeof(ExpandedFileName)-1;
   SearchNam.nam$l_rsa = DataFileName;
   SearchNam.nam$b_rss = sizeof(DataFileName)-1;

   if (VMSnok (status = sys$parse (&SearchFab, 0, 0)))
   {
      if (Debug) fprintf (stdout, "sys$parse() %%X%08.08X\n", status);
      CgiLibResponseError (FI_LI, status, DataFileSpec);
      exit (SS$_NORMAL);
   }

   while (VMSok (status = sys$search (&SearchFab, 0, 0)))
   {
      DataFilesFoundCount++;

      SearchNam.nam$l_ver[SearchNam.nam$b_ver] = '\0';
      DataFileNameLength = SearchNam.nam$b_rsl;
      if (Debug) fprintf (stdout, "DataFileName |%s|\n", DataFileName);

      /*
         Pull the node name and time components from the data file name.
         Format: "HYPERSPI_v_node_ddmmyy.DAT"
         ("v" represents the data file version, a single digit number)
      */
      cptr = SearchNam.nam$l_name;
      /* skip "HYPERSPI_version_" */
      while (*cptr && *cptr != '_') cptr++;
      if (*cptr) cptr++;
      while (*cptr && *cptr != '_') cptr++;
      if (*cptr) cptr++;
      /* get the node name this data represents */
      sptr = DataNode;
      while (*cptr && *cptr != '_') *sptr++ = *cptr++;
      *sptr = '\0';
      if (*cptr) cptr++;
      /* get the day, month and year */
      sptr = Scratch;
      if (*cptr) *sptr++ = *cptr++;
      if (*cptr) *sptr++ = *cptr++;
      *sptr = '\0';
      DataDay = atoi (Scratch);
      sptr = Scratch;
      if (*cptr) *sptr++ = *cptr++;
      if (*cptr) *sptr++ = *cptr++;
      *sptr = '\0';
      DataMonth = atoi (Scratch);
      sptr = Scratch;
      if (*cptr) *sptr++ = *cptr++;
      if (*cptr) *sptr++ = *cptr++;
      *sptr = '\0';
      DataYear = atoi (Scratch);
      if (Debug)
         fprintf (stdout, "data-file-name |%s|%d|%d|%d|\n",
                  DataNode, DataDay, DataMonth, DataYear);

      /* filter on year, month and day */
      if (DataYear <= 90)
         DataYear += 2000;
      else
         DataYear += 1900;
      if (DataYear < FromYear || DataYear > ToYear) continue;
      if (DataYear == FromYear)
      {
         if (DataMonth < FromMonth) continue;
         if (DataMonth == FromMonth && DataDay < FromDay) continue;
      }
      if (DataYear == ToYear)
      {
         if (DataMonth > ToMonth) continue;
         if (DataMonth == ToMonth && DataDay > ToDay) continue;
      }

      DataFilesProcessedCount++;

      /* can be used to just count the number of matching files! */
      if (ProcessFileFunction == NULL) continue;

      if (OpenDataFile)
         ProcessDataFileRecords (ProcessFileFunction);
      else
         /* by pointer, call the function to process this file name */
         (*ProcessFileFunction) ();
   }
   if (Debug) fprintf (stdout, "sys$search() %%X%08.08X\n", status);

   if (SearchFab.fab$l_sts == RMS$_FNF || SearchFab.fab$l_sts == RMS$_NMF)
      return (SS$_NORMAL);

   CgiLibResponseError (FI_LI, status, DataFileSpec);
   exit (SS$_NORMAL);
}

/*****************************************************************************/
/*
Open the 'DataFileName', read each record and call a specified function to 
process it, then close the file.  The first parameter to this function is the 
address (a pointer to) the function used to process the SPI data record.
*/ 

ProcessDataFileRecords (int (*ProcessDataFunction)(struct HyperSpiData*))

{
   static long  LibJulianDate = LIB$K_JULIAN_DATE;
   static unsigned short  PrevNumTime [7] = {0,0,0,0,0,0,0};

   int  status;
   unsigned long  JulDate,
                  BinTime [2];
   struct FAB  DataFileFab;
   struct RAB  DataFileRab;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessDataFileRecords() |%s|\n", DataFileName);

   DataFileFab = cc$rms_fab;
   DataFileFab.fab$b_fac = FAB$M_GET;
   DataFileFab.fab$l_fna = DataFileName;  
   DataFileFab.fab$b_fns = DataFileNameLength;
   DataFileFab.fab$b_shr = FAB$M_SHRGET | FAB$M_SHRPUT;

   if (VMSnok (status = sys$open (&DataFileFab, 0, 0)))
   {
      if (Debug) fprintf (stdout, "sys$open() %%X%08.08X\n", status);
      if (status == RMS$_FNF)
      {
         CgiLibResponseError (FI_LI, status, DataNode);
         exit (SS$_NORMAL);
      }
      CgiLibResponseError (FI_LI, status, DataNode);
      exit (SS$_NORMAL);
   }

   DataFileRab = cc$rms_rab;
   DataFileRab.rab$l_fab = &DataFileFab;
   /* 2 buffers and read ahead performance option */
   DataFileRab.rab$b_mbf = 2;
   DataFileRab.rab$l_rop = RAB$M_RAH;
   DataFileRab.rab$l_ubf = (char*)&SpiRecord;
   DataFileRab.rab$w_usz = sizeof(SpiRecord);

   if (VMSnok (status = sys$connect (&DataFileRab, 0, 0)))
   {
      if (Debug) fprintf (stdout, "sys$connect() %%X%08.08X\n", status);
      sys$close (&DataFileFab, 0, 0);
      CgiLibResponseError (FI_LI, status, DataNode);
      exit (SS$_NORMAL);
   }

   while (VMSok (status = sys$get (&DataFileRab, 0, 0)))
   {
      DataRecordsReadCount++;

      /* filter on hour and minute */
      if (SpiRecord.Day == FromDay)
      {
         if (SpiRecord.Hour < FromHour) continue;
         if (SpiRecord.Hour == FromHour && SpiRecord.Minute < FromMinute)
            continue;
      }
      if (SpiRecord.Day == ToDay)
      {
         if (SpiRecord.Hour > ToHour) continue;
         if (SpiRecord.Hour == ToHour && SpiRecord.Minute > ToMinute) continue;
      }

      if (SpiRecord.Hour != PrevNumTime[3] ||
          SpiRecord.Day != PrevNumTime[2] ||
          SpiRecord.Month != PrevNumTime[1] ||
          SpiRecord.Year != PrevNumTime[0])
      {
         PrevNumTime[3] = SpiRecord.Hour;
         PrevNumTime[2] = SpiRecord.Day;
         PrevNumTime[1] = SpiRecord.Month;
         PrevNumTime[0] = SpiRecord.Year;

         lib$cvt_vectim (&PrevNumTime, &BinTime);
         lib$cvt_from_internal_time (&LibJulianDate, &JulDate, &BinTime);
         NumberOfDaysIntoData = JulDate - FromJulianDate;
         StartMinuteOfData = NumberOfDaysIntoData * 1440;
         if (Debug)
            fprintf (stdout,
               "NumberOfDaysIntoData: %d StartMinuteOfData: %d\n",
               NumberOfDaysIntoData, StartMinuteOfData);
      }
      NumberOfMinutesIntoData = StartMinuteOfData +
                                ((SpiRecord.Hour * 60) + SpiRecord.Minute) -
                                StartMinuteOnFirstDay;

      DataRecordsProcessedCount++;

      /* by pointer, call the function to process this SPI data record */
      (*ProcessDataFunction) (&SpiRecord);
   }

   sys$close (&DataFileFab, 0, 0);

   if (status == RMS$_EOF) status = SS$_NORMAL;
   if (VMSnok (status))
   {
      CgiLibResponseError (FI_LI, status, DataNode);
      exit (SS$_NORMAL);
   }
}

/*****************************************************************************/
/*
The specified parameter is the name of the file, excluding directory and file 
type, just the name.  Construct a full HTML file name and open it, read each 
record just passing the contents into the HTTP output stream, the close the 
file.  If the file cannot be found the status RMS$_FNF is returned, all other 
errors are reported and the image exits.
*/ 

IncludeFile (char *Name)

{
   int  status;
   char  FileName [256],
         Line [256],
         Scratch [256];
   struct FAB  FileFab;
   struct RAB  FileRab;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "IncludeFile() |%s|\n", Name);

   sprintf (FileName, "%s%s.HTML", HyperSpiDirectoryPtr, Name);
   if (Debug) fprintf (stdout, "FileName |%s|\n", FileName);

   FileFab = cc$rms_fab;
   FileFab.fab$b_fac = FAB$M_GET;
   FileFab.fab$l_fna = FileName;  
   FileFab.fab$b_fns = strlen(FileName);  
   FileFab.fab$b_shr = FAB$M_SHRGET;

   if (VMSnok (status = sys$open (&FileFab, 0, 0)))
   {
      if (Debug) fprintf (stdout, "sys$open() %%X%08.08X\n", status);
      if (status == RMS$_FNF || status == RMS$_DNF) return (status);
      CgiLibResponseError (FI_LI, status, Name);
      exit (SS$_NORMAL);
   }

   FileRab = cc$rms_rab;
   FileRab.rab$l_fab = &FileFab;
   /* 2 buffers and read ahead performance option */
   FileRab.rab$b_mbf = 2;
   FileRab.rab$l_rop = RAB$M_RAH;
   FileRab.rab$l_ubf = Line;
   FileRab.rab$w_usz = sizeof(Line)-1;

   if (VMSnok (status = sys$connect (&FileRab, 0, 0)))
   {
      if (Debug) fprintf (stdout, "sys$connect() %%X%08.08X\n", status);
      sys$close (&FileFab, 0, 0);
      CgiLibResponseError (FI_LI, status, Name);
      exit (SS$_NORMAL);
   }

   while (VMSok (status = sys$get (&FileRab, 0, 0)))
   {
      Line[FileRab.rab$w_rsz++] = '\r';
      Line[FileRab.rab$w_rsz++] = '\n';
      Line[FileRab.rab$w_rsz] = '\0';
      if (Debug) fprintf (stdout, "Line |%s|\n", Line);
      fputs (Line, stdout);
   }

   sys$close (&FileFab, 0, 0);

   if (status == RMS$_EOF) return (status);

   CgiLibResponseError (FI_LI, status, Name);
   exit (SS$_NORMAL);
}

/*****************************************************************************/
/*
Return a pointer to a unique number built up of time components.  Used to 
place a unique component into the URL of a graph GIF, ensuring a cached 
version is not retrieved.
*/

char* UniqueNumber ()

{
   static char  String [16];

   unsigned long  BinTime [2];
   unsigned short  NumTime [7];

   sys$gettim (&BinTime);
   sys$numtim (&NumTime, &BinTime);

   sprintf (String, "%d%d%d%d%d%d%d",
            NumTime[0] % 10, NumTime[1], NumTime[2], NumTime[3],
            NumTime[4], NumTime[5], NumTime[6]);
   return (String);
}

/*****************************************************************************/
/*
Translate the logical name HYPERSPI_AGENT_PID containing the agent process ID
(binary) and issue a $FORCEX against the image.
*/

int ShutdownAgent ()

{
   static $DESCRIPTOR (LnmSystemDsc, "LNM$SYSTEM");
   static $DESCRIPTOR (PidLogNameDsc, "HYPERSPI_AGENT_PID");

   static unsigned long  Pid;
   static struct
   {
      unsigned short  buf_len;
      unsigned short  item;
      void   *buf_addr;
      unsigned short  *short_ret_len;
   }
   LnmPidItem [] =
   {
      { sizeof(Pid), LNM$_STRING, &Pid, 0 },
      { 0,0,0,0 }
   };

   int  status;

   /*********/
   /* begin */
   /*********/

   status = sys$trnlnm (0, &LnmSystemDsc, &PidLogNameDsc, 0, &LnmPidItem);
   if (VMSok (status)) status = sys$forcex (&Pid, 0, SS$_NORMAL);
   return (status);
}

/****************************************************************************/
/*
*/

char* SystemNodeName ()

{
   static char  SyiNodeName [15+1];
   static unsigned short  SyiNodeNameLength;
   static struct {
      short BufferLength;
      short ItemCode;
      void  *BufferPtr;
      void  *LengthPtr;
   }
   SyiItems [] =
   {
      { 15, SYI$_NODENAME, &SyiNodeName, &SyiNodeNameLength },
      { 0,0,0,0 }
   };
   struct {
      unsigned long  Status;
      unsigned long  Reserved;
   } IOsb;

   int  status;

   /*********/
   /* begin */
   /*********/

   status = sys$getsyiw (0, 0, 0, &SyiItems, &IOsb, 0, 0);

   if (Debug)
      fprintf (stdout, "sys$getsyiw() %%X%08.08X IOsb: %%X%08.08X\n",
               status, IOsb.Status);

   if (VMSok (IOsb.Status))
      SyiNodeName[SyiNodeNameLength] = '\0';
   else
      sprintf(SyiNodeName, "%%X%08.08X", IOsb.Status);

   if (Debug) fprintf (stdout, "SyiNodeName |%s|\n", SyiNodeName);

   return (SyiNodeName);
}

/****************************************************************************/
/*
Does a case-insensitive, character-by-character string compare and returns 
true if two strings are the same, or false if not.  If a maximum number of 
characters are specified only those will be compared, if the entire strings 
should be compared then specify the number of characters as 0.
*/ 

boolean strsame
(
char *sptr1,
char *sptr2,
int  count
)
{
   while (*sptr1 && *sptr2)
   {
      if (toupper (*sptr1++) != toupper (*sptr2++)) return (false);
      if (count)
         if (!--count) return (true);
   }
   if (*sptr1 || *sptr2)
      return (false);
   else
      return (true);
}

/*****************************************************************************/

