×UTF-8ý}ì‘Î/*
** 21aalertname.p
**
** This program will adjust the alert name for 2.0A sample records accordingly
** to make the alert name match the 2.1A format. 
**
*/

DEFINE VARIABLE txn-loop AS INTEGER NO-UNDO INITIAL 1000.
DEFINE VARIABLE update-cnt AS INTEGER NO-UNDO INITIAL 0.
DEFINE VARIABLE rec-cnt AS INTEGER NO-UNDO INITIAL 0.
DEFINE VARIABLE Update-Location AS INTEGER NO-UNDO INITIAL 0.
DEFINE VARIABLE i AS INTEGER NO-UNDO INITIAL 0.
DEFINE VARIABLE NewList AS CHARACTER FORMAT "x(28)" NO-UNDO 
                           INITIAL "DB_AutoStartFail,DB_RecordWaitsHigh,DB_BuffersFlushedatCheckpointHigh,DB_CheckpointLengthShort,DB_VariableAreaExtentGrow,DB_PhysicalReadHigh,DB_BIWWritePercentLow,DB_EmptyAIBufferWaitsHigh,DB_EmptyBiBufferWaitsHigh,DB_BIPartialWritesHigh,DB_AreaSpaceUtilizationHigh,DB_AbnormalShutdown,DB_TrendingStopped,DB_BusyBIBufferWaitsHigh,DB_AIWWritePercentLow,DB_ReadstoRequestsHigh,DB_DatabaseCommitsLow,DB_BusyAIBufferWaitsHigh,DB_PartialAIBufferWritesHigh,DB_AgentReadError,DB_AgentStartup,DB_Startup,DB_NormalShutdown,DB_BufferIOHigh,DB_DatabaseLicenseConflict,DB_FathomTrendDatabase,DB_ResourceNameConflict,DB_DatabaseDown,DB_AgentIdle,DB_AgentCrash,DB_AgentDown,DB_UserCountHigh,DB_ResourceEnabled,DB_ResourceAdded,DB_ResourceDisabled,DB_BrokerReconnectFail,DB_DatabaseCrash, , , ".

DEFINE VARIABLE OldList AS CHARACTER FORMAT "x(25)" NO-UNDO 
			   INITIAL "AutoStartFail,RecordWaitsHigh,BuffersFlushedatCheckpointHigh,CheckpointLengthShort,VariableAreaExtentGrow,PhysicalReadHigh,BIWWritePercentLow,EmptyAIBufferWaitsHigh,EmptyBiBufferWaitsHigh,BIPartialWritesHigh,AreaSpaceUtilizationHigh,AbnormalShutdown,TrendingStopped,BusyBIBufferWaitsHigh,AIWWritePercentLow,ReadstoRequestsHigh,DatabaseCommitsLow,BusyAIBufferWaitsHigh,PartialAIBufferWritesHigh,AgentReadError,AgentStartup,Startup,NormalShutdown,BufferIOHigh,DatabaseLicenseConflict,FathomTrendDatabase,ResourceNameConflict,DatabaseDown,AgentIdle,AgentCrash,AgentDown,UserCountHigh,ResourceEnabled,ResourceAdded,ResourceDisabled,BrokerReconnectFail,DatabaseCrash, , , ".

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Starting migration of Alert Names..." SKIP.

repeat-loop:
REPEAT:
   DO TRANSACTION:
      DO i = 1 to txn-loop:
         IF rec-cnt = 0 THEN
         DO:
             FIND FIRST Cf_Alert_Detail EXCLUSIVE-LOCK NO-ERROR.
         END.
         ELSE
         DO:
             FIND NEXT Cf_Alert_Detail EXCLUSIVE-LOCK NO-ERROR.
         END.

         rec-cnt = rec-cnt + 1.

         IF NOT AVAILABLE Cf_Alert_Detail THEN
         DO:
            PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Ending migration of Alert Names..." SKIP.
            PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Total Records Searched: " rec-cnt.
            PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Total Records Updated: " update-cnt.
            LEAVE repeat-loop.
         END.

	 /*
	 ** Find the alert name in the index.  If it exists then update it, if it doesn't then skip it
	 */

	 Update-Location = LOOKUP(Cf_Alert_Detail.Alert_Name, OldList).

	 IF Update-Location NE 0 THEN 
	 DO:
             Cf_Alert_Detail.Alert_Name = ENTRY( Update-Location, NewList).
             update-cnt = update-cnt + 1.
         END.

         RELEASE Cf_Alert_Detail.
      END. /* OF txn counter */
      PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records Updated: " update-cnt.
   END. /* OF DO TRANSACTION */
END. /* OF REPEAT LOOP */

/* 
** Procedure to load Fathom Version 2.1A schema into a Fathom Version 2.0A 
** database
**
**  FATHOMINSTALLDIR must exist and point to the Fathom 2.0A Fathom 
**  Installation directory where
**  the version 2.0A FathomTrendDatabase resides in the db subdirectory.
*/

FIND FIRST Cf_Control WHERE Cf_Control.ID = "version" EXCLUSIVE-LOCK NO-ERROR.

IF AVAILABLE Cf_Control THEN
DO:
   Cf_Control.c1 = "2.1A".
END.
ELSE 
DO:
   PUT SKIP "Updating Definitions - ERROR! Could not find Cf_Control Table entry!!!" SKIP.

   QUIT.
END.

PUT SKIP "Updating Control Table - Update Complete!!!" SKIP.
/*
** migration code fix for 2.1A migrations from 2.0A.
** NOTE:  This is only for migrations from 2.0A to 2.1A.  Migrations from
** 1.0A are not supported.
*/
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Migrating database".

DEF VAR install-dir AS CHARACTER FORMAT "x(96)" INITIAL "".
DEF VAR run-pgm AS CHARACTER FORMAT "x(24)" INITIAL "".

install-dir = OS-GETENV("fathomInstallDir"). 
IF install-dir = "" OR install-dir = ? THEN  
DO:
   PUT SKIP "ERROR! FathomInstallDir not set! Aborting" SKIP.
   QUIT.
END. 
 

run-pgm = install-dir + "/src/21acontrol.p".

RUN VALUE(run-pgm).

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Updating Sample Records ...".

run-pgm = install-dir + "/src/21asampledate.p".

RUN VALUE(run-pgm).

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Updating Resource Table with new resourc names..." SKIP.

run-pgm = install-dir + "/src/21aresourceupdate.p".

RUN VALUE(run-pgm).

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Updating Alert Table with new alert names..." SKIP.

run-pgm = install-dir + "/src/21aalertname.p".

RUN VALUE(run-pgm).
/*
** 21aupdateresource.p
**
** This program will adjust the resource name accordingly adding the resource
** containier name to the front of the resource name.  All of the container
** names in a migration are the host name of the local resource.  
**
*/

DEFINE VARIABLE t-site-id AS CHARACTER NO-UNDO FORMAT "x(24)".
DEFINE VARIABLE t-container-name AS CHARACTER NO-UNDO FORMAT "x(24)".
DEFINE VARIABLE i AS INTEGER NO-UNDO INITIAL 0.

t-site-id = OS-GETENV( "UpgradeSiteID" ) NO-ERROR.
t-container-name = OS-GETENV( "UpgradeContainerName" ) NO-ERROR.

If t-site-id EQ ? or t-site-id = "" THEN
DO:
   PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Site ID ENV VAR UpgradeSiteID not set - aborting upgrade..." SKIP.
   RETURN.
END.
IF t-container-name = ? or t-container-name = "" THEN
DO:
   PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Container name ENV VAR UpgradeContainerName not set - aborting upgrade..." SKIP.
   RETURN.
END.

FOR EACH Cf_Resrc WHERE 
   Cf_Resrc.Site_ID = t-site-id:
   Cf_Resrc.Resrc_Name = t-container-name + "." + Cf_Resrc.Resrc_Name.
   i = i + 1.
END.

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Resource name update complete. Update count: " i SKIP.
/*
** 20sampledate.p
**
** This program will adjust the sample date for 2.0A sample records accordingly
** to make the sample date the beginning of the period and not the end of the
** period.
**
*/

DEFINE VARIABLE txn-loop AS INTEGER NO-UNDO INITIAL 1000.
DEFINE VARIABLE update-cnt AS INTEGER NO-UNDO INITIAL 0.
DEFINE VARIABLE i AS INTEGER NO-UNDO INITIAL 0.

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Starting migration of Sample Data..." SKIP.

repeat-loop:
REPEAT:
   DO TRANSACTION:
      DO i = 1 to txn-loop:
         IF update-cnt = 0 THEN
         DO:
             FIND FIRST Cf_Sample EXCLUSIVE-LOCK NO-ERROR.
         END.
         ELSE
         DO:
             FIND NEXT Cf_Sample EXCLUSIVE-LOCK NO-ERROR.
         END.

         IF NOT AVAILABLE Cf_Sample THEN
         DO:
            PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Ending migration of Sample Data..." SKIP.
            PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Total Records Updated: " update-cnt.
            LEAVE repeat-loop.
         END.
         update-cnt = update-cnt + 1.
         IF (Cf_Sample.Sample_time - Cf_Sample.Sample_Len) LT 0 THEN
         DO:
            Cf_Sample.Sample_Date = Cf_Sample.Sample_Date - 1.
            Cf_Sample.Sample_Time = 86400 - (Cf_Sample.Sample_Len - Cf_Sample.Sample_time).
         END.
         ELSE
         DO:
            Cf_Sample.Sample_Time = Cf_Sample.Sample_Time - Cf_Sample.Sample_Len.
         END.

         RELEASE Cf_Sample.
      END. /* OF txn counter */
      PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records Updated: " update-cnt.
   END. /* OF DO TRANSACTION */
END. /* OF REPEAT LOOP */

/* 
** Procedure to correct Db_TabAnalysis.TAB_Bytes. Run after 30anewfield.p has
** run.
**
** FATHOMINSTALLDIR must exist and point to the Fathom 3.0A Fathom 
** Installation directory.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".
DEF VAR fathom-dir AS CHARACTER INITIAL "".
DEF VAR db-dir AS CHARACTER INITIAL "".
DEF VAR src-dir AS CHARACTER INITIAL "".
DEF VAR df-delete-field AS CHARACTER INITIAL "".
DEF VAR df-rename-field AS CHARACTER INITIAL "".

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Updating Definitions - ERROR! DLC not set! Aborting".
    QUIT.
END.

fathom-dir = OS-GETENV("fathomInstallDir"). 
IF fathom-dir = "" OR fathom-dir = ? THEN  
DO:
   PUT SKIP "Updating Defintions - ERROR! FathomInstallDir not set! Aborting".
   QUIT.
END. 
db-dir = fathom-dir + "/db".
src-dir = fathom-dir + "/src".
df-delete-field = fathom-dir + "/src/fathom30a_delete.df".
df-rename-field = fathom-dir + "/src/fathom30a_rename.df".

FIND FIRST Cf_Control WHERE Cf_Control.ID = "version" EXCLUSIVE-LOCK NO-ERROR.
IF AVAILABLE Cf_Control THEN
DO:
    IF Cf_Control.C1 NE "2.1A" THEN
    DO:
        PUT SKIP "Updating Definitions - The existing Fathom Database does not have a version number of 2.1A".
        PUT SKIP "Database version " + Cf_Control.C1 + ", change not applicable.".
        QUIT.
    END.

/*
 * For all records in Db_TabAnalysis save integer value from TAB_Bytes
 * in the temp decimal field TAB_BytesUsed. If it is a negative value, 
 * zero it out.
 */
    PUT SKIP " ".
    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Moving data ...".
    FOR EACH Db_TabAnalysis:
        IF Db_TabAnalysis.TAB_Bytes GE 0 THEN
        DO:
            Db_TabAnalysis.TAB_BytesUsed = Db_TabAnalysis.TAB_Bytes.
        END.
        ELSE
        DO:
            Db_TabAnalysis.TAB_BytesUsed = 0.
        END.
    END.

/*
 * Delete the original TAB_Bytes field
 */
    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Delete original Db_TabAnalysis.TAB_Bytes integer field".
    RUN prodict/load_df.p (df-delete-field).

/*
 * Rename TAB_BytesUsed to TAB_Bytes
 */
    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Rename Db_TabAnalysis_TAB_BytesUsed to Db_TabAnalysis_TAB_Bytes".
    RUN prodict/load_df.p (df-rename-field).

    Cf_Control.c1 = "3.0A".

END.
ELSE
DO:
    PUT SKIP "Updating Definitions - ERROR! Unable to find Control Table".
    QUIT.
END.













/* 
** Procedure to add indexes to improve archiving performance.
**
** FATHOMINSTALLDIR must exist and point to the Fathom 3.0A Fathom 
** Installation directory.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".
DEF VAR fathom-dir AS CHARACTER INITIAL "".
DEF VAR db-dir AS CHARACTER INITIAL "".
DEF VAR src-dir AS CHARACTER INITIAL "".
DEF VAR df-index-fields AS CHARACTER INITIAL "".

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Updating Definitions - ERROR! DLC not set! Aborting".
    QUIT.
END.

fathom-dir = OS-GETENV("fathomInstallDir"). 
IF fathom-dir = "" OR fathom-dir = ? THEN  
DO:
   PUT SKIP "Updating Defintions - ERROR! FathomInstallDir not set! Aborting".
   QUIT.
END. 
db-dir = fathom-dir + "/db".
src-dir = fathom-dir + "/src".

df-index-fields = src-dir + "/fathom30a_index.df".

FIND FIRST Cf_Control WHERE Cf_Control.ID = "version" EXCLUSIVE-LOCK NO-ERROR.
IF AVAILABLE Cf_Control THEN
DO:
    IF Cf_Control.C1 NE "2.1A" THEN
    DO:
        PUT SKIP "Updating Definitions - The existing Fathom Database does not have a version number of 2.1A".
        PUT SKIP "Database version " + Cf_Control.C1 + ", change not applicable.".
        QUIT.
    END.

/*
 * Add the indexes
 */
    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Adding inactive index fields.".
    RUN prodict/load_df.p (df-index-fields).
END.

ELSE
DO:
    PUT SKIP "Updating Definitions - ERROR! Unable to find Control Table".
    QUIT.
END.













/* 
** Procedure to correct a Fathom Version 3.0A schema which is the same as a 
** Fathom Version 2.1A database. Fathom 3.0a and 2.1a have the same database 
** schema. 
** A fix is needed to change Db_TabAnalysis.TAB_Bytes from integer to decimal.
** When done change the version id in Cf_Control from 2.1a to 3.0a.
**
** This procedure is run first and then the database is reconnected to run
** 30achangedfield.p so it can then refer to the field TAB_BytesUsed created
** in this procedure. 
**
** FATHOMINSTALLDIR must exist and point to the Fathom 3.0A Fathom 
** Installation directory where the FathomTrendDatabase resides in the 
** db subdirectory. If it is unmodified the db will have a version id of 2.1a.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".
DEF VAR fathom-dir AS CHARACTER INITIAL "".
DEF VAR db-dir AS CHARACTER INITIAL "".
DEF VAR src-dir AS CHARACTER INITIAL "".
DEF VAR df-new-field AS CHARACTER INITIAL "".

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Updating Definitions - ERROR! DLC not set! Aborting".
    QUIT.
END.

fathom-dir = OS-GETENV("fathomInstallDir"). 
IF fathom-dir = "" OR fathom-dir = ? THEN  
DO:
   PUT SKIP "Updating Defintions - ERROR! FathomInstallDir not set! Aborting".
   QUIT.
END. 
db-dir = fathom-dir + "/db".
src-dir = fathom-dir + "/src".

FIND FIRST Cf_Control WHERE Cf_Control.ID = "version" EXCLUSIVE-LOCK NO-ERROR.
IF AVAILABLE Cf_Control THEN
DO:
    IF Cf_Control.C1 NE "2.1A" THEN
    DO:
        PUT SKIP "Updating Definitions - The existing Fathom Database does not have a version number of 2.1A".
        PUT SKIP "Database version " + Cf_Control.C1 + ", change not applicable.".
        PUT SKIP "".
        QUIT.
    END.

/*
 * Db_TabAnalysis.TAB_Bytes field is an integer and it needs to be a decimal.
 * Add 'Db_TabAnalysis.Tab_BytesUsed decimal' field to hold
 * the values from 'Db_TabAnalysis.Tab_Bytes' fields.
 */
    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Create new Db_TabAnalysis.TAB_BytesUsed decimal field".
    df-new-field = src-dir + "/fathom30a_new.df".
    RUN prodict/load_df.p(df-new-field).
END.
ELSE
DO:
    PUT SKIP "Updating Definitions - ERROR! Unable to find Control Table".
    QUIT.
END.


/* 
** Procedure to run .p file making changes to the Fathom Trend Database during upgrade
** to Fathom 3.1A.
** FATHOMINSTALLDIR must exist and point to the existing Fathom installation directory.
*/
  
DEF VAR fathom-dir AS CHARACTER INITIAL "".
DEF VAR src-dir AS CHARACTER INITIAL "".
DEF VAR progProcIndex AS CHARACTER INITIAL "".
DEF VAR progProcChange AS CHARACTER INITIAL "".

fathom-dir = OS-GETENV("fathomInstallDir"). 
IF fathom-dir = "" OR fathom-dir = ? THEN  
DO:
   PUT SKIP "Updating Defintions - ERROR! FathomInstallDir not set! Aborting".
   QUIT.
END. 
src-dir = fathom-dir + "/src".

progProcIndex = src-dir + "/30aindex.p".
RUN value(progProcIndex).

progProcChange = src-dir + "/30achangefield.p".
RUN value(progProcChange).













/*
** Alertgeneral.p
** This program will present a trend report based on the dates provided to
** the report for a site. 
** The only information that needs to be provided to the report is
** the Report Definition Number, Resource ID, Site ID, and Report Type. For this report
** the report type is general.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Define local variables 
*/

DEF NEW SHARED TEMP-TABLE data_store NO-UNDO
   FIELD h-resrc-name AS CHARACTER
   FIELD h-Site_ID AS CHARACTER
   FIELD h-Resrc_ID AS INTEGER 
   FIELD h-samples AS INT EXTENT 366
   FIELD h-alert1 AS INT EXTENT 366
   FIELD h-alert2 AS INT EXTENT 366
   FIELD h-alert3 AS INT EXTENT 366
   FIELD h-alert4 AS INT EXTENT 366
   INDEX three h-resrc-name.

/* DEF VAR h-samples AS INT NO-UNDO EXTENT 366.
DEF VAR h-resrc-name AS CHAR NO-UNDO.
DEF VAR h-alert1 AS INT NO-UNDO EXTENT 366.
DEF VAR h-alert2 AS INT NO-UNDO EXTENT 366.
DEF VAR h-alert3 AS INT NO-UNDO EXTENT 366.
DEF VAR h-alert4 AS INT NO-UNDO EXTENT 366. */
DEF VAR save-total AS INT NO-UNDO.

/* 
**
** Begin Main Processing
**
*/

/* 
** Set up the date arrays
*/

{ include/trenddates.i }
/* 
** Begin Main Processing.
*/

sec-name = "Processing alert details".
pgm-name = "alertgeneral.p".
{include/debug.i "pgm-name" "sec-name"}

FOR EACH cf_alert_detail 
    WHERE
    Cf_Alert_Detail.Site_ID = Fathom-i-site_ID AND
    Cf_Alert_Detail.Alert_Date GE Fathom-t-beg-date[1] AND
    Cf_Alert_Detail.Alert_Date LE Fathom-t-end-date[Fathom-i-periods] AND
    Cf_Alert_Detail.Alert_Time GE Fathom-t-beg-time[1] AND
    Cf_Alert_Detail.Alert_Time LE Fathom-t-end-time[Fathom-i-periods]:

    FIND FIRST Cf_Resrc WHERE 
        Cf_Resrc.Resrc_ID = Cf_Alert_Detail.Resrc_ID NO-LOCK NO-ERROR.
    IF AVAILABLE Cf_Resrc THEN 
    DO:
        If Cf_Resrc.Resrc_Type NE "GROUP" AND 
	   Cf_Resrc.resrc_type NE "REPORT" AND
	   Cf_Resrc.Resrc_Type NE "JOB" 
	THEN
	DO:
            Fathom-i = 0.
            REPEAT:
       	         Fathom-i = Fathom-i + 1.
                IF Cf_Alert_Detail.Alert_Date GE Fathom-t-beg-date[Fathom-i] AND
                   Cf_Alert_Detail.Alert_Date LE Fathom-t-end-date[Fathom-i] THEN
                DO:
                   IF Cf_Alert_Detail.Alert_Time GE Fathom-t-beg-Time[Fathom-i] AND
                      Cf_Alert_Detail.Alert_Time LE Fathom-t-end-Time[Fathom-i] THEN
                      LEAVE.
                END.
                IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
            END.
	    FIND FIRST data_store WHERE
                data_store.h-resrc-name = Cf_Resrc.Resrc_Name AND
		data_store.h-site_id = cf_resrc.Site_ID AND
		data_store.h-resrc_id = Cf_Resrc.Resrc_ID
		NO-ERROR.
	    
	    IF NOT AVAILABLE data_store THEN
	    DO:
	        Create data_store.
		ASSIGN
		    data_store.h-resrc-name = Cf_Resrc.Resrc_Name
		    data_store.h-site_id = Cf_Resrc.Site_ID
		    data_store.h-resrc_id = Cf_Resrc.Resrc_ID.
	    END.
        
            CASE Cf_Alert_Detail.Alert_Severity:
                WHEN 1 THEN h-alert1[Fathom-i] = h-alert1[Fathom-i] + 1.
                WHEN 2 THEN h-alert2[Fathom-i] = h-alert2[Fathom-i] + 1.
                WHEN 3 THEN h-alert3[Fathom-i] = h-alert3[Fathom-i] + 1.
                WHEN 4 THEN h-alert4[Fathom-i] = h-alert4[Fathom-i] + 1.
            END CASE.
        END. /* of assignment of for each */
    END.
END. 
sec-name = "Processing Samples".
pgm-name = "alertgeneral.p".
{include/debug.i "pgm-name" "sec-name"}

FOR EACH cf_sample  
    WHERE 
    Cf_Sample.Site_ID = Fathom-i-site_ID AND
    Cf_Sample.Sample_Date GE Fathom-t-beg-date[1] AND      
    Cf_Sample.Sample_Date LE Fathom-t-end-date[Fathom-i-periods] AND  
    Cf_Sample.Sample_Time GE Fathom-t-beg-time[1] AND      
    Cf_Sample.Sample_Time LE Fathom-t-end-time[Fathom-i-periods]:
    Fathom-k = 0.

    FIND FIRST Cf_Resrc WHERE 
        Cf_Resrc.Resrc_ID = Cf_Alert_Detail.Resrc_ID NO-LOCK NO-ERROR.
    IF AVAILABLE Cf_Resrc THEN 
    DO:
	FIND FIRST data_store WHERE
            data_store.h-resrc-name = Cf_Resrc.Resrc_Name AND
	    data_store.h-site_id = cf_resrc.Site_ID AND
	    data_store.h-resrc_id = Cf_Resrc.Resrc_ID
            NO-ERROR.
	    
	IF NOT AVAILABLE data_store THEN NEXT.
	    
        REPEAT:
           Fathom-k = Fathom-k + 1.
           IF cf_sample.sample_date GE Fathom-t-beg-date[Fathom-k] AND
              cf_sample.sample_date LE Fathom-t-end-date[Fathom-k] THEN 
           DO:
              IF cf_sample.sample_time GE Fathom-t-beg-time[Fathom-k] AND
                 cf_sample.sample_time LE Fathom-t-end-time[Fathom-k] THEN 
                 LEAVE.
           END.
           IF Fathom-k EQ Fathom-i-periods THEN LEAVE.
        END.

        h-samples[Fathom-k] = h-samples[Fathom-k] + 1.
    END.
END.

/*
** Print Section.
*/
sec-name = "Printing Output".
pgm-name = "alertgeneral.p".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }.

RUN xml-alertgeneral.p.

sec-name = "Exiting Program".
pgm-name = "alertgeneral.p".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** Trendalert.p
** This program will present a trend report based on the dates provided to
** the report.  The dates will be defined in the Trend database in the table
** Cf_Rep_Def.  The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Set up local definitions.
*/
DEF NEW SHARED TEMP-TABLE data_store NO-UNDO
   FIELD h-resrc-name AS CHARACTER
   FIELD h-Site_ID AS CHARACTER
   FIELD h-Resrc_ID AS INTEGER 
   FIELD h-samples AS INT EXTENT 366
   FIELD h-alert1 AS INT EXTENT 366
   FIELD h-alert2 AS INT EXTENT 366
   FIELD h-alert3 AS INT EXTENT 366
   FIELD h-alert4 AS INT EXTENT 366
   INDEX three h-resrc-name.

/* DEF VAR h-samples AS INT NO-UNDO EXTENT 366.
DEF VAR h-alert1 AS INT NO-UNDO EXTENT 366.
DEF VAR h-alert2 AS INT NO-UNDO EXTENT 366.
DEF VAR h-alert3 AS INT NO-UNDO EXTENT 366.
DEF VAR h-alert4 AS INT NO-UNDO EXTENT 366. */

DEF VAR save-total AS INT NO-UNDO.

/* 
**
** Begin Main Processing
**
*/

/* 
** Set up the date arrays
*/

{ include/trenddates.i }

/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }
/* 
** Begin Main Processing.
*/
pgm-name = "trendalert.p".
sec-name = "Process Alert Details".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "periods: " + STRING(fathom-i-periods).
{include/debug.i "pgm-name" "sec-name"}

FOR EACH cf_alert_detail 
    WHERE
    Cf_Alert_Detail.Resrc_ID = Fathom-i-Resrc_ID AND
    Cf_Alert_Detail.Site_ID = Fathom-i-site_ID AND
    Cf_Alert_Detail.Alert_Date GE Fathom-t-beg-date[1] AND
    Cf_Alert_Detail.Alert_Date LE Fathom-t-end-date[Fathom-i-periods] AND
    Cf_Alert_Detail.Alert_Time GE Fathom-t-beg-time[1] AND
    Cf_Alert_Detail.Alert_Time LE Fathom-t-end-time[Fathom-i-periods]:
    Fathom-i = 0.

    REPEAT:
       Fathom-i = Fathom-i + 1.
        IF Cf_Alert_Detail.Alert_Date GE Fathom-t-beg-date[Fathom-i] AND
           Cf_Alert_Detail.Alert_Date LE Fathom-t-end-date[Fathom-i] THEN
        DO:
           IF Cf_Alert_Detail.Alert_time GE Fathom-t-beg-time[Fathom-i] AND
              Cf_Alert_Detail.Alert_time LE Fathom-t-end-time[Fathom-i] THEN
              LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    FIND FIRST data_store WHERE
        data_store.h-site_ID = Fathom-i-Site_ID AND
        data_store.h-Resrc_ID = Fathom-i-Resrc_ID NO-ERROR.

    IF NOT AVAILABLE data_store THEN
    DO:
        CREATE data_store.
	ASSIGN
	    h-site_id = Cf_Resrc.Site_ID
	    h-Resrc_id = Cf_Resrc.Resrc_ID
	    h-resrc-name = Cf_Resrc.Resrc_Name.
    END.

    CASE Cf_Alert_Detail.Alert_Severity:
        WHEN 1 THEN 
        DO:
           h-alert1[Fathom-i] = h-alert1[Fathom-i] + 1.
           h-samples[Fathom-i] = h-samples[Fathom-i] + 1.
           fathom-rec-count = fathom-rec-count + 1.
        END.
        WHEN 2 THEN 
        DO:
           h-alert2[Fathom-i] = h-alert2[Fathom-i] + 1.
           h-samples[Fathom-i] = h-samples[Fathom-i] + 1.
           fathom-rec-count = fathom-rec-count + 1.
        END.
        WHEN 3 THEN 
        DO:
           h-alert3[Fathom-i] = h-alert3[Fathom-i] + 1.
           h-samples[Fathom-i] = h-samples[Fathom-i] + 1.
           fathom-rec-count = fathom-rec-count + 1.
        END.
        WHEN 4 THEN 
        DO:
           h-alert4[Fathom-i] = h-alert4[Fathom-i] + 1.
           h-samples[Fathom-i] = h-samples[Fathom-i] + 1.
           fathom-rec-count = fathom-rec-count + 1.
        END.
    END CASE.
END. /* of assignment of for each */

pgm-name = "trendalert.p".
sec-name = "Process Samples".
{include/debug.i "pgm-name" "sec-name"}
/* 
FOR EACH cf_sample  
   WHERE 
   Cf_Sample.Resrc_ID = Fathom-i-Resrc_ID AND
   Cf_Sample.Site_ID = Fathom-i-site_ID AND
   Cf_Sample.Sample_Date GE Fathom-t-beg-date[1] AND      
   Cf_Sample.Sample_Date LE Fathom-t-end-date[Fathom-i-periods] AND  
   Cf_Sample.Sample_Time GE Fathom-t-beg-time[1] AND      
   Cf_Sample.Sample_Time LE Fathom-t-end-time[Fathom-i-periods]
   BY sample_date BY sample_time:

   Fathom-k = 0.
   REPEAT:
       Fathom-k = Fathom-k + 1.
       IF cf_sample.sample_date GE Fathom-t-beg-date[Fathom-k] AND
          cf_sample.sample_date LE Fathom-t-end-date[Fathom-k] THEN 
       DO:
          IF cf_sample.sample_time GE Fathom-t-beg-time[Fathom-k] AND
             cf_sample.sample_time LE Fathom-t-end-time[Fathom-k] THEN 
             LEAVE.
       END.
       IF Fathom-k EQ Fathom-i-periods THEN LEAVE.
   END.
   FIND FIRST data_store WHERE
       data_store.h-site_ID = Fathom-i-Site_ID AND
       data_store.h-Resrc_ID = Fathom-i-Resrc_ID NO-ERROR.

   IF AVAILABLE data_store THEN
   DO:
       h-samples[Fathom-k] = h-samples[Fathom-k] + 1.
   END.
END. */

/*
** Print Section
**
*/

pgm-name = "trendalert.p".
sec-name = "Print Section".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }

RUN xml-alertindividual.p.

pgm-name = "trendalert.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/* 
** ar_actapw.p
**
** This include will archive the ar_actapw rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
**    Create the hourly records
**    Create the daily records
**    Create the weekly records
*/

/*
llaubach 10/2005
 - tt-ar-ActAPW temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActAPW table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActAPW WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-ActAPW NO-UNDO LIKE ar_ActAPW
    INDEX myindex1 Site_Id resrc_id actapw_archiveType actapw_startDate.

/* 
** CREATE THE HOURLY RECORDS
*/

RUN archive/ar-h-actapw.p.

/* 
** SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK
*/

FOR EACH Ar_ActAPW
    WHERE Ar_ActAPW.ActAPW_ArchiveType = "H"
      AND Ar_ActAPW.ActAPW_StartDate LT Fathom-i-Date NO-LOCK:
    
    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actapw
        WHERE tt-ar-actapw.Site_Id = ar_actapw.site_id
          AND tt-ar-actapw.Resrc_Id = ar_actapw.Resrc_id
          AND tt-ar-actapw.actapw_archiveType = "D"
          AND tt-ar-actapw.actapw_startDate = ar_actapw.Actapw_startdate:
        RUN add-actapw.
    END.

    IF NOT AVAILABLE tt-ar-actapw
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actapw.ActAPW_StartDate = Ar_ActAPW.ActAPW_StartDate
            tt-ar-actapw.ActAPW_EndDate = Ar_ActAPW.ActAPW_EndDate
            tt-ar-actapw.ActAPW_archiveType = "D".
     END.
    RELEASE tt-ar-actapw.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actapw
        WHERE tt-ar-actapw.Site_Id = ar_actapw.site_id
          AND tt-ar-actapw.Resrc_Id = ar_actapw.Resrc_id
          AND tt-ar-actapw.actapw_archiveType = "W"
          AND ar_actapw.Actapw_startdate GE tt-ar-actapw.actapw_startDate
          AND ar_actapw.Actapw_startdate LE tt-ar-actapw.actapw_EndDate:
        RUN add-actapw.
    END.
    
    IF NOT AVAILABLE tt-ar-actapw
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actapw.ActAPW_StartDate = Ar_ActAPW.ActAPW_StartDate - (WEEKDAY(Ar_ActAPW.ActAPW_StartDate) - 1)
            tt-ar-actapw.ActAPW_EndDate = tt-ar-actapw.ActAPW_StartDate + 6
            tt-ar-actapw.ActAPW_archiveType = "W".
      END.
    RELEASE tt-ar-actapw.
END. /*  Of for each Ar_ActAPW */

    /*  This will write out the temp tables to the appropriate files. */
    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}
    
     /* Write out db_actapw */
     FOR EACH tt-ar-actapw
         WHERE tt-ar-actapw.actapw_archiveType = "D":
         FOR FIRST ar_actapw
             WHERE ar_actapw.actapw_archiveType = "D"
               AND tt-ar-actapw.Site_Id = ar_actapw.site_id
               AND tt-ar-actapw.Resrc_Id = ar_actapw.Resrc_id
               AND tt-ar-actapw.actapw_startDate = ar_actapw.Actapw_startdate NO-LOCK: END.
          IF NOT AVAILABLE ar_actapw
           THEN DO TRANSACTION:
                   CREATE Ar_ActAPW.
                   BUFFER-COPY tt-ar-ActAPW TO Ar_ActAPW.
                   RELEASE Ar_ActAPW.
            END.
    END.
    /* Write out db_actapw */
    FOR EACH tt-ar-actapw
        WHERE tt-ar-actapw.actapw_archiveType = "W":
        FOR FIRST ar_actapw
            WHERE ar_actapw.actapw_archiveType = "W"
              AND tt-ar-actapw.Site_Id = ar_actapw.site_id
              AND tt-ar-actapw.Resrc_Id = ar_actapw.Resrc_id
              AND ar_actapw.Actapw_startdate GE tt-ar-actapw.actapw_startDate
              AND ar_actapw.Actapw_startdate LE tt-ar-actapw.actapw_EndDate NO-LOCK: END.
         IF NOT AVAILABLE ar_actapw
          THEN DO TRANSACTION:
                  CREATE Ar_ActAPW.
                  BUFFER-COPY tt-ar-ActAPW TO Ar_ActAPW.
                  RELEASE Ar_ActAPW.
          END.
    END.
    
    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actapw.
    BUFFER-COPY ar_actapw TO tt-ar-actapw.
    ASSIGN
      tt-ar-actapw.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actapw.ActAPW_EndTime = {&DAY_END_TIME}
      tt-ar-actapw.ActAPW_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actapw.
    ASSIGN
      tt-ar-ActAPW.ActAPW_RecordCount  = tt-ar-ActAPW.ActAPW_RecordCount + Ar_ActAPW.ActAPW_RecordCount 
      tt-ar-ActAPW.ActAPW_transactions = tt-ar-ActAPW.ActAPW_transactions + Ar_ActAPW.ActAPW_transactions 
      tt-ar-ActAPW.ActAPW_APWEnq       = tt-ar-ActAPW.ActAPW_APWEnq      + Ar_ActAPW.ActAPW_APWEnq      
      tt-ar-ActAPW.ActAPW_APWQWrites   = tt-ar-ActAPW.ActAPW_APWQWrites  + Ar_ActAPW.ActAPW_APWQWrites  
      tt-ar-ActAPW.ActAPW_BufsCkpt     = tt-ar-ActAPW.ActAPW_BufsCkpt    + Ar_ActAPW.ActAPW_BufsCkpt    
      tt-ar-ActAPW.ActAPW_BufsScanned  = tt-ar-ActAPW.ActAPW_BufsScanned + Ar_ActAPW.ActAPW_BufsScanned 
      tt-ar-ActAPW.ActAPW_CkptQWrites  = tt-ar-ActAPW.ActAPW_CkptQWrites + Ar_ActAPW.ActAPW_CkptQWrites 
      tt-ar-ActAPW.ActAPW_Ckpts        = tt-ar-ActAPW.ActAPW_Ckpts       + Ar_ActAPW.ActAPW_Ckpts       
      tt-ar-ActAPW.ActAPW_DBWrites     = tt-ar-ActAPW.ActAPW_DBWrites    + Ar_ActAPW.ActAPW_DBWrites    
      tt-ar-ActAPW.ActAPW_Flushed      = tt-ar-ActAPW.ActAPW_Flushed     + Ar_ActAPW.ActAPW_Flushed     
      tt-ar-ActAPW.ActAPW_Marked       = tt-ar-ActAPW.ActAPW_Marked      + Ar_ActAPW.ActAPW_Marked      
      tt-ar-ActAPW.ActAPW_ScanCycles   = tt-ar-ActAPW.ActAPW_ScanCycles  + Ar_ActAPW.ActAPW_ScanCycles  
      tt-ar-ActAPW.ActAPW_ScanWrites   = tt-ar-ActAPW.ActAPW_ScanWrites  + Ar_ActAPW.ActAPW_ScanWrites  
      tt-ar-ActAPW.ActAPW_Length       = tt-ar-ActAPW.ActAPW_Length      + Ar_ActAPW.ActAPW_Length  
      tt-ar-ActAPW.ActAPW_TotDBWrites  = tt-ar-ActAPW.ActAPW_TotDBWrites + Ar_ActAPW.ActAPW_TotDBWrites .
END PROCEDURE.
/* 
** ar_actbuf.p
**
** This include will archive the ar_actbuf rows that are designated "H" to Day and Weekly.
*/

/*
llaubach 10/2005
 - tt-ar-ActBuf temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActBuf table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActBug WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-ActBuf NO-UNDO LIKE ar_ActBuf
    INDEX myindex1 site_id resrc_id actbuf_archiveType actbuf_startDate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actbuf.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_ActBuf
    WHERE Ar_ActBuf.ActBuf_ArchiveType = "H"
      AND Ar_ActBuf.ActBuf_StartDate LT Fathom-i-Date NO-LOCK:
    
    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actbuf
        WHERE tt-ar-actbuf.Site_Id = ar_actbuf.site_id
          AND tt-ar-actbuf.Resrc_Id = ar_actbuf.Resrc_id
          AND tt-ar-actbuf.actbuf_archiveType = "D"
          AND tt-ar-actbuf.actbuf_startDate = ar_actbuf.Actbuf_startdate:
        RUN add-actbuf.
    END.
    
    IF NOT AVAILABLE tt-ar-actbuf 
     THEN DO:
          RUN create-record.       
          ASSIGN
            tt-ar-actbuf.Actbuf_StartDate = Ar_Actbuf.Actbuf_StartDate
            tt-ar-actbuf.Actbuf_EndDate = Ar_Actbuf.Actbuf_EndDate
            tt-ar-actbuf.Actbuf_archiveType = "D".
     END.
    RELEASE tt-ar-actbuf.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actbuf
        WHERE tt-ar-actbuf.Site_Id = ar_actbuf.site_id
          AND tt-ar-actbuf.Resrc_Id = ar_actbuf.Resrc_id
          AND tt-ar-actbuf.actbuf_archiveType = "W"
          AND ar_actbuf.Actbuf_startdate GE tt-ar-actbuf.actbuf_startDate
          AND ar_actbuf.Actbuf_startdate LE tt-ar-actbuf.actbuf_endDate:
        RUN add-actbuf.
    END.
    
    IF NOT AVAILABLE tt-ar-actbuf
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actbuf.ActBuf_StartDate = ar_actbuf.actbuf_startdate - (WEEKDAY(ar_actbuf.actbuf_startdate) - 1)
            tt-ar-actbuf.ActBuf_EndDate = tt-ar-actbuf.ActBuf_StartDate + 6
            tt-ar-actbuf.actbuf_archiveType = "W".
     END.
    RELEASE tt-ar-actbuf.
END. /*  Of for each Ar_ActBuf */

   /* This will write out the temp tables to the appropriate files. */
   sec-name = "Writing Data to disk ".
   {include/ar-debug.i "sec-name"}
    
   FOR EACH tt-ar-actbuf
       WHERE tt-ar-actbuf.actbuf_archiveType = "D":
       FOR FIRST ar_actbuf
           WHERE ar_actbuf.actbuf_archiveType = "D"
             AND tt-ar-actbuf.Site_Id = ar_actbuf.site_id
             AND tt-ar-actbuf.Resrc_Id = ar_actbuf.Resrc_id
             AND tt-ar-actbuf.actbuf_startDate = ar_actbuf.Actbuf_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_actbuf
         THEN DO TRANSACTION:
                 CREATE Ar_ActBuf.
                 BUFFER-COPY tt-ar-ActBuf TO Ar_ActBuf.
                 RELEASE Ar_ActBuf.
         END.
   END.
   FOR EACH tt-ar-actbuf
       WHERE tt-ar-actbuf.actbuf_archiveType = "W":
       FOR FIRST ar_actbuf
           WHERE ar_actbuf.actbuf_archiveType = "W"
             AND tt-ar-actbuf.Site_Id = ar_actbuf.site_id
             AND tt-ar-actbuf.Resrc_Id = ar_actbuf.Resrc_id
             AND ar_actbuf.Actbuf_startdate GE tt-ar-actbuf.actbuf_startDate
             AND ar_actbuf.Actbuf_startdate LE tt-ar-actbuf.actbuf_endDate NO-LOCK: END.
       IF NOT AVAILABLE ar_actbuf
        THEN DO TRANSACTION:
                CREATE Ar_ActBuf.
                BUFFER-COPY tt-ar-ActBuf TO Ar_ActBuf.
                RELEASE Ar_ActBuf.
        END.
   END.

   sec-name = "Ending Writing Data to disk".
   {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actbuf.
    BUFFER-COPY ar_actbuf TO tt-ar-actbuf.
    ASSIGN
      tt-ar-actbuf.sample_id = NEXT-VALUE(ar_sample-seq).
      tt-ar-actbuf.ActBuf_EndTime = {&DAY_END_TIME}.
      tt-ar-actbuf.ActBuf_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actbuf.
    ASSIGN
       tt-ar-Actbuf.actbuf_RecordCount  = tt-ar-actbuf.actbuf_RecordCount + Ar_actbuf.actbuf_RecordCount 
       tt-ar-Actbuf.actbuf_transactions = tt-ar-actbuf.actbuf_transactions + Ar_actbuf.actbuf_transactions 
       tt-ar-Actbuf.actbuf_length = tt-ar-actbuf.actbuf_length + Ar_actbuf.actbuf_length 
       tt-ar-ActBuf.ActBuf_Deferred = tt-ar-ActBuf.ActBuf_Deferred + Ar_ActBuf.ActBuf_Deferred
       tt-ar-ActBuf.ActBuf_Flushed = tt-ar-ActBuf.ActBuf_Flushed + Ar_ActBuf.ActBuf_Flushed
       tt-ar-ActBuf.ActBuf_LogicReads = tt-ar-ActBuf.ActBuf_LogicReads + Ar_ActBuf.ActBuf_LogicReads
       tt-ar-ActBuf.ActBuf_LogicWrites = tt-ar-ActBuf.ActBuf_LogicWrites + Ar_ActBuf.ActBuf_LogicWrites
       tt-ar-ActBuf.ActBuf_OSReads = tt-ar-ActBuf.ActBuf_OSReads + Ar_ActBuf.ActBuf_OSReads
       tt-ar-ActBuf.ActBuf_OSWrites = tt-ar-ActBuf.ActBuf_OSWrites + Ar_ActBuf.ActBuf_OSWrites.
END PROCEDURE.
/* 
** ar_actidx.p
**
** This include will archive the ar_actidx rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-ActIdx temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActIdx table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActIdx WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-Actidx NO-UNDO LIKE ar_Actidx
    INDEX myindex1 site_id resrc_id actidx_archivetype actidx_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actidx.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_Actidx
    WHERE Ar_Actidx.Actidx_ArchiveType = "H"
      AND Ar_Actidx.Actidx_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actidx
        WHERE tt-ar-actidx.Site_Id = ar_actidx.site_id
          AND tt-ar-actidx.Resrc_Id = ar_actidx.Resrc_id
          AND tt-ar-actidx.actidx_archiveType = "D"
          AND tt-ar-actidx.actidx_startDate = ar_actidx.Actidx_startdate:
        RUN add-actidx.
    END.
    
    IF NOT AVAILABLE tt-ar-actidx
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actidx.actidx_startDate = ar_actidx.Actidx_startdate
            tt-ar-actidx.actidx_endDate = ar_actidx.Actidx_enddate
            tt-ar-actidx.actidx_archiveType = "D".
     END.
    RELEASE tt-ar-actidx.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actidx
        WHERE tt-ar-actidx.Site_Id = ar_actidx.site_id
          AND tt-ar-actidx.Resrc_Id = ar_actidx.Resrc_id
          AND tt-ar-actidx.actidx_archiveType = "W"
          AND ar_actidx.Actidx_startdate GE tt-ar-actidx.actidx_startDate
          AND ar_actidx.Actidx_startdate LE tt-ar-actidx.actidx_enddate:
        RUN add-actidx.
    END.
    
    IF NOT AVAILABLE tt-ar-actidx
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actidx.Actidx_StartDate = Ar_Actidx.Actidx_StartDate - (WEEKDAY(Ar_Actidx.Actidx_StartDate) - 1)
            tt-ar-actidx.Actidx_EndDate = tt-ar-actidx.Actidx_StartDate + 6
            tt-ar-actidx.actidx_archiveType = "W".
     END.
    RELEASE tt-ar-actidx.
END. /*  Of for each Ar_Actidx */


    /* This will write out the temp tables to the appropriate files. */
    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}
    
    /* Write out db_actidx */
    FOR EACH tt-ar-actidx
        WHERE tt-ar-actidx.actidx_archiveType = "W":
        FOR FIRST ar_actidx
            WHERE ar_actidx.actidx_archiveType = "W"
              AND tt-ar-actidx.Site_Id = ar_actidx.site_id
              AND tt-ar-actidx.Resrc_Id = ar_actidx.Resrc_id
              AND ar_actidx.Actidx_startdate GE tt-ar-actidx.actidx_startDate
              AND ar_actidx.Actidx_startdate LE tt-ar-actidx.actidx_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_actidx
         THEN DO TRANSACTION:
                 CREATE Ar_Actidx.
                 BUFFER-COPY tt-ar-Actidx TO Ar_Actidx.
                 RELEASE Ar_Actidx.
         END.
    END.
    
    /* Write out db_actidx */
    FOR EACH tt-ar-actidx
        WHERE tt-ar-actidx.actidx_archiveType = "D":
        FOR FIRST ar_actidx
            WHERE ar_actidx.actidx_archiveType = "D"
              AND tt-ar-actidx.Site_Id = ar_actidx.site_id
              AND tt-ar-actidx.Resrc_Id = ar_actidx.Resrc_id
              AND tt-ar-actidx.actidx_startDate = ar_actidx.Actidx_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_actidx
         THEN DO TRANSACTION:
                 CREATE Ar_Actidx.
                 BUFFER-COPY tt-ar-Actidx TO Ar_Actidx.
                 RELEASE Ar_Actidx.
         END.
    END.
        
    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actidx.
    BUFFER-COPY ar_actidx TO tt-ar-actidx.
    ASSIGN
      tt-ar-actidx.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actidx.Actidx_EndTime = {&DAY_END_TIME}
      tt-ar-actidx.Actidx_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actidx.
    ASSIGN
        tt-ar-ActIdx.actidx_RecordCount  = tt-ar-actidx.actidx_RecordCount + Ar_actidx.actidx_RecordCount 
        tt-ar-ActIdx.actidx_transactions = tt-ar-actidx.actidx_transactions + Ar_actidx.actidx_transactions 
        tt-ar-ActIdx.actidx_Length = tt-ar-actidx.actidx_Length + Ar_actidx.actidx_Length 
        tt-ar-ActIdx.ActIdx_Create = tt-ar-ActIdx.ActIdx_Create + Ar_ActIdx.ActIdx_Create
        tt-ar-ActIdx.ActIdx_Delete = tt-ar-ActIdx.ActIdx_Delete + Ar_ActIdx.ActIdx_Delete
        tt-ar-ActIdx.ActIdx_Find = tt-ar-ActIdx.ActIdx_Find + Ar_ActIdx.ActIdx_Find
        tt-ar-ActIdx.ActIdx_Free = tt-ar-ActIdx.ActIdx_Free + Ar_ActIdx.ActIdx_Free
        tt-ar-ActIdx.ActIdx_Remove = tt-ar-ActIdx.ActIdx_Remove + Ar_ActIdx.ActIdx_Remove
        tt-ar-ActIdx.ActIdx_Splits = tt-ar-ActIdx.ActIdx_Splits + Ar_ActIdx.ActIdx_Splits.
END PROCEDURE.
/* 
** ar_actiofile.p
**
** This include will archive the ar_actiofile rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-ActIOFile temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActIOFile table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActIOFile WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-ar-Actiofile NO-UNDO LIKE ar_Actiofile
    INDEX myindex1 site_id resrc_id actiofile_archivetype actiofile_filename actiofile_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actiofile.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_Actiofile
    WHERE Ar_Actiofile.Actiofile_ArchiveType = "H"
      AND Ar_Actiofile.Actiofile_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actiofile
        WHERE tt-ar-actiofile.Site_Id = ar_actiofile.site_id
          AND tt-ar-actiofile.Resrc_Id = ar_actiofile.Resrc_id
          AND tt-ar-actiofile.actiofile_archiveType = "D"
          AND tt-ar-actiofile.actiofile_filename = ar_actiofile.actiofile_filename
          AND tt-ar-actiofile.actiofile_startDate = ar_actiofile.Actiofile_startdate:
        RUN add-actiofile.
    END.
    
    IF NOT AVAILABLE tt-ar-actiofile
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actiofile.actiofile_StartDate = Ar_actiofile.actiofile_StartDate
            tt-ar-actiofile.actiofile_EndDate = Ar_actiofile.actiofile_EndDate
            tt-ar-actiofile.actiofile_archiveType = "D".
     END.
    RELEASE tt-ar-actiofile.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actiofile
        WHERE tt-ar-actiofile.Site_Id = ar_actiofile.site_id
          AND tt-ar-actiofile.Resrc_Id = ar_actiofile.Resrc_id
          AND tt-ar-actiofile.actiofile_archiveType = "W"
          AND tt-ar-actiofile.actiofile_filename = ar_actiofile.actiofile_filename
          AND ar_actiofile.Actiofile_startdate GE tt-ar-actiofile.actiofile_startDate
          AND ar_actiofile.Actiofile_startdate LE tt-ar-actiofile.actiofile_enddate:
        RUN add-actiofile.
    END.
    
    IF AVAILABLE tt-ar-actiofile
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actiofile.actiofile_StartDate   = Ar_actiofile.actiofile_StartDate - (WEEKDAY(Ar_actiofile.actiofile_StartDate) - 1)
            tt-ar-actiofile.actiofile_EndDate     = tt-ar-actiofile.actiofile_StartDate + 6
            tt-ar-actiofile.actiofile_archiveType = "W".
     END.
    RELEASE tt-ar-actiofile.
END. /*  Of for each Ar_Actiofile */


    /* This will write out the temp tables to the appropriate files. */
    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}
    
    /* Write out db_actiofile */
    FOR EACH tt-ar-actiofile
        WHERE tt-ar-actiofile.actiofile_archiveType = "W":
        FOR FIRST ar_actiofile
            WHERE ar_actiofile.actiofile_archiveType = "W"
              AND tt-ar-actiofile.Site_Id = ar_actiofile.site_id
              AND tt-ar-actiofile.Resrc_Id = ar_actiofile.Resrc_id
              AND tt-ar-actiofile.actiofile_filename = ar_actiofile.actiofile_filename
              AND ar_actiofile.Actiofile_startdate GE tt-ar-actiofile.actiofile_startDate
              AND ar_actiofile.Actiofile_startdate LE tt-ar-actiofile.actiofile_enddate NO-LOCK: END.
	    IF NOT AVAILABLE ar_actiofile THEN
            DO TRANSACTION:
                CREATE Ar_Actiofile.
                BUFFER-COPY tt-ar-Actiofile TO Ar_Actiofile.
                RELEASE Ar_Actiofile.
            END.
    END.

    /* Write out db_actiofile */
    FOR EACH tt-ar-actiofile
        WHERE tt-ar-actiofile.actiofile_archiveType = "D":
        FOR FIRST ar_actiofile
            WHERE ar_actiofile.actiofile_archiveType = "D" 
              AND tt-ar-actiofile.Site_Id = ar_actiofile.site_id
              AND tt-ar-actiofile.Resrc_Id = ar_actiofile.Resrc_id
              AND tt-ar-actiofile.actiofile_filename = ar_actiofile.actiofile_filename
              AND tt-ar-actiofile.actiofile_startDate = ar_actiofile.Actiofile_startdate NO-LOCK: END.
	    IF NOT AVAILABLE ar_actiofile THEN
            DO TRANSACTION:
                CREATE Ar_Actiofile.
                BUFFER-COPY tt-ar-Actiofile TO Ar_Actiofile.
                RELEASE Ar_Actiofile.
            END.
    END.
        
    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actiofile.
    BUFFER-COPY ar_actiofile TO tt-ar-actiofile.
    ASSIGN
      tt-ar-actiofile.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actiofile.Actiofile_EndTime = {&DAY_END_TIME}
      tt-ar-actiofile.Actiofile_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actiofile.
    ASSIGN
        tt-ar-ActIOFile.actiofile_RecordCount  = tt-ar-actiofile.actiofile_RecordCount + Ar_actiofile.actiofile_RecordCount 
        tt-ar-ActIOFile.actiofile_transactions = tt-ar-actiofile.actiofile_transactions + Ar_actiofile.actiofile_transactions 
        tt-ar-ActIOFile.actiofile_length       = tt-ar-actiofile.actiofile_length + Ar_actiofile.actiofile_length 
        tt-ar-ActIOFile.ActIOFile_BufReads     = tt-ar-ActIOFile.ActIOFile_BufReads + Ar_ActIOFile.ActIOFile_BufReads
        tt-ar-ActIOFile.ActIOFile_BufWrites    = tt-ar-ActIOFile.ActIOFile_BufWrites + Ar_ActIOFile.ActIOFile_BufWrites
        tt-ar-ActIOFile.ActIOFile_Extends      = tt-ar-ActIOFile.ActIOFile_Extends + Ar_ActIOFile.ActIOFile_Extends
        tt-ar-ActIOFile.ActIOFile_Reads        =   tt-ar-ActIOFile.ActIOFile_Reads + Ar_ActIOFile.ActIOFile_Reads
        tt-ar-ActIOFile.ActIOFile_UnbufReads   = tt-ar-ActIOFile.ActIOFile_UnbufReads + Ar_ActIOFile.ActIOFile_UnbufReads
        tt-ar-ActIOFile.ActIOFile_UnbufWrites  = tt-ar-ActIOFile.ActIOFile_UnbufWrites + Ar_ActIOFile.ActIOFile_UnbufWrites
        tt-ar-ActIOFile.ActIOFile_Writes       = tt-ar-ActIOFile.ActIOFile_Writes + Ar_ActIOFile.ActIOFile_Writes.       
END PROCEDURE.
/* 
** ar_actiotype.p
**
** This include will archive the ar_actiotype rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-ActIOType temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActIOType table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActIOType WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-Actiotype NO-UNDO LIKE ar_Actiotype
    INDEX site_id resrc_id actiotype_archivetype actiotype_startDate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actiotype.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

FOR EACH Ar_Actiotype
    WHERE Ar_Actiotype.Actiotype_ArchiveType = "H"
      AND Ar_Actiotype.Actiotype_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actiotype
        WHERE tt-ar-actiotype.Site_Id = ar_actiotype.site_id
          AND tt-ar-actiotype.Resrc_Id = ar_actiotype.Resrc_id
          AND tt-ar-actiotype.actiotype_archiveType = "D"
          AND tt-ar-actiotype.actiotype_startDate = ar_actiotype.Actiotype_startdate:
        RUN add-actiotype.
    END.
    
    IF NOT AVAILABLE tt-ar-actiotype
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actiotype.actiotype_StartDate = Ar_actiotype.actiotype_StartDate
            tt-ar-actiotype.actiotype_EndDate = Ar_actiotype.actiotype_EndDate
            tt-ar-actiotype.actiotype_archiveType = "D".
     END.
    RELEASE tt-ar-actiotype.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actiotype
        WHERE tt-ar-actiotype.Site_Id = ar_actiotype.site_id
          AND tt-ar-actiotype.Resrc_Id = ar_actiotype.Resrc_id
          AND tt-ar-actiotype.actiotype_archiveType = "W"
          AND ar_actiotype.Actiotype_startdate GE tt-ar-actiotype.actiotype_startDate
          AND ar_actiotype.Actiotype_startdate LE tt-ar-actiotype.actiotype_enddate:
        RUN add-actiotype.
    END.
    
    IF NOT AVAILABLE tt-ar-actiotype
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actiotype.actiotype_StartDate   = Ar_actiotype.actiotype_StartDate - (WEEKDAY(Ar_actiotype.actiotype_StartDate) - 1)
            tt-ar-actiotype.actiotype_EndDate     = tt-ar-actiotype.actiotype_StartDate + 6
            tt-ar-actiotype.actiotype_archiveType = "W".
     END.
    RELEASE tt-ar-actiotype.
END. /*  Of for each Ar_Actiotype */


    /* This will write out the temp tables to the appropriate files. */
    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}
    
    /* Write out db_actiotype */
    FOR EACH tt-ar-actiotype
        WHERE tt-ar-actiotype.actiotype_archiveType = "W":
        FOR FIRST ar_actiotype
            WHERE ar_actiotype.actiotype_archiveType = "W"
              AND tt-ar-actiotype.Site_Id = ar_actiotype.site_id
              AND tt-ar-actiotype.Resrc_Id = ar_actiotype.Resrc_id
              AND ar_actiotype.Actiotype_startdate GE tt-ar-actiotype.actiotype_startDate
              AND ar_actiotype.Actiotype_startdate LE tt-ar-actiotype.actiotype_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_actiotype
         THEN DO TRANSACTION:
                 CREATE Ar_Actiotype.
                 BUFFER-COPY tt-ar-Actiotype TO Ar_Actiotype.
                 RELEASE Ar_Actiotype.
         END.
    END.

    /* Write out db_actiotype */
    FOR EACH tt-ar-actiotype
        WHERE tt-ar-actiotype.actiotype_archiveType = "D":
        FOR FIRST ar_actiotype
            WHERE ar_actiotype.actiotype_archiveType = "D"
              AND tt-ar-actiotype.Site_Id = ar_actiotype.site_id
              AND tt-ar-actiotype.Resrc_Id = ar_actiotype.Resrc_id
              AND tt-ar-actiotype.actiotype_startDate = ar_actiotype.Actiotype_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_actiotype
         THEN DO TRANSACTION:
                 CREATE Ar_Actiotype.
                 BUFFER-COPY tt-ar-Actiotype TO Ar_Actiotype.
                 RELEASE Ar_Actiotype.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actiotype.
    BUFFER-COPY ar_actiotype TO tt-ar-actiotype.
    ASSIGN
      tt-ar-actiotype.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actiotype.Actiotype_EndTime = {&DAY_END_TIME}
      tt-ar-actiotype.Actiotype_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actiotype.
    ASSIGN
        tt-ar-ActIOType.actIOType_RecordCount  = tt-ar-actIOType.actIOType_RecordCount + Ar_actIOType.actIOType_RecordCount 
        tt-ar-ActIOType.actIOType_transactions = tt-ar-actIOType.actIOType_transactions + Ar_actIOType.actIOType_transactions 
        tt-ar-ActIOType.actIOType_Length       = tt-ar-actIOType.actIOType_Length + Ar_actIOType.actIOType_Length 
        tt-ar-ActIOType.ActIOType_AiReads      = tt-ar-ActIOType.ActIOType_AiReads + Ar_ActIOType.ActIOType_AiReads
        tt-ar-ActIOType.ActIOType_AiWrites     = tt-ar-ActIOType.ActIOType_AiWrites + Ar_ActIOType.ActIOType_AiWrites
        tt-ar-ActIOType.ActIOType_BiReads      =  tt-ar-ActIOType.ActIOType_BiReads + Ar_ActIOType.ActIOType_BiReads
        tt-ar-ActIOType.ActIOType_BiWrites     = tt-ar-ActIOType.ActIOType_BiWrites + Ar_ActIOType.ActIOType_BiWrites
        tt-ar-ActIOType.ActIOType_DataReads    = tt-ar-ActIOType.ActIOType_DataReads + Ar_ActIOType.ActIOType_DataReads
        tt-ar-ActIOType.ActIOType_DataWrites   = tt-ar-ActIOType.ActIOType_DataWrites + Ar_ActIOType.ActIOType_DataWrites
        tt-ar-ActIOType.ActIOType_IdxReads     = tt-ar-ActIOType.ActIOType_IdxReads + Ar_ActIOType.ActIOType_IdxReads
        tt-ar-ActIOType.ActIOType_IdxWrites   = tt-ar-ActIOType.ActIOType_IdxWrites + Ar_ActIOType.ActIOType_IdxWrites.  
END PROCEDURE.
/* 
** ar_actlock.p
**
** This include will archive the ar_actlock rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-ActLock temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActLock table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActLock WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-Actlock NO-UNDO LIKE ar_Actlock
    INDEX myindex1 actlock_archivetype site_id resrc_id actlock_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actlock.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_Actlock
    WHERE Ar_Actlock.Actlock_ArchiveType = "H" 
      AND Ar_Actlock.Actlock_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actlock
        WHERE tt-ar-actlock.actlock_archiveType = "D"
          AND tt-ar-actlock.Site_Id = ar_actlock.site_id 
          AND tt-ar-actlock.Resrc_Id = ar_actlock.Resrc_id
          AND tt-ar-actlock.actlock_startDate = ar_actlock.Actlock_startdate:
        RUN add-actlock.
    END.
    
    IF NOT AVAILABLE tt-ar-actlock
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actlock.actlock_StartDate = Ar_actlock.actlock_StartDate
            tt-ar-actlock.actlock_EndDate = Ar_actlock.actlock_EndDate
            tt-ar-actlock.actlock_archiveType = "D".
     END.
    RELEASE tt-ar-actlock.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actlock
        WHERE tt-ar-actlock.actlock_archiveType = "W"
          AND tt-ar-actlock.Site_Id = ar_actlock.site_id 
          AND tt-ar-actlock.Resrc_Id = ar_actlock.Resrc_id
          AND ar_actlock.Actlock_startdate GE tt-ar-actlock.actlock_startDate
          AND ar_actlock.Actlock_startdate LE tt-ar-actlock.actlock_enddate:
        RUN add-actlock.
    END.

    IF NOT AVAILABLE tt-ar-actlock
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actlock.actlock_StartDate   = Ar_actlock.actlock_StartDate - (WEEKDAY(Ar_actlock.actlock_StartDate) - 1)
            tt-ar-actlock.actlock_EndDate     = tt-ar-actlock.actlock_StartDate + 6
            tt-ar-actlock.actlock_archiveType = "W".
      END.
    RELEASE tt-ar-actlock.
END. /*  Of for each Ar_Actlock */

    /* Write out db_actlock */
    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    FOR EACH tt-ar-actlock
        WHERE tt-ar-actlock.actlock_archiveType = "W":
        FOR FIRST ar_actlock
            WHERE ar_actlock.actlock_archiveType = "W"
              AND tt-ar-actlock.Site_Id = ar_actlock.site_id
              AND tt-ar-actlock.Resrc_Id = ar_actlock.Resrc_id
              AND ar_actlock.Actlock_startdate GE tt-ar-actlock.actlock_startDate
              AND ar_actlock.Actlock_startdate LE tt-ar-actlock.actlock_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_actlock
         THEN DO TRANSACTION:
                 CREATE Ar_Actlock.
                 BUFFER-COPY tt-ar-Actlock TO Ar_Actlock.
                 RELEASE Ar_Actlock.
         END.
    END.
        
    FOR EACH tt-ar-actlock
        WHERE tt-ar-actlock.actlock_archiveType = "D":
        FOR FIRST ar_actlock
            WHERE ar_actlock.actlock_archiveType = "D"
              AND tt-ar-actlock.Site_Id = ar_actlock.site_id
              AND tt-ar-actlock.Resrc_Id = ar_actlock.Resrc_id
              AND tt-ar-actlock.actlock_startDate = ar_actlock.Actlock_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_actlock
         THEN DO TRANSACTION:
                 CREATE Ar_Actlock.
                 BUFFER-COPY tt-ar-Actlock TO Ar_Actlock.
                 RELEASE Ar_Actlock.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actlock.
    BUFFER-COPY ar_actlock TO tt-ar-actlock.
    ASSIGN
      tt-ar-actlock.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actlock.Actlock_EndTime = {&DAY_END_TIME}
      tt-ar-actlock.Actlock_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actlock.
    ASSIGN
        tt-ar-ActLock.ActLock_RecordCount  = tt-ar-actLock.actLock_RecordCount + Ar_actLock.actLock_RecordCount 
        tt-ar-ActLock.ActLock_transactions = tt-ar-actLock.actLock_transactions + Ar_actLock.actLock_transactions 
        tt-ar-ActLock.ActLock_Length = tt-ar-actLock.actLock_Length + Ar_actLock.actLock_Length 
        tt-ar-ActLock.ActLock_CanclReq = tt-ar-ActLock.ActLock_CanclReq + Ar_ActLock.ActLock_CanclReq
        tt-ar-ActLock.ActLock_Downgrade = tt-ar-ActLock.ActLock_Downgrade + Ar_ActLock.ActLock_Downgrade
        tt-ar-ActLock.ActLock_ExclFind = tt-ar-ActLock.ActLock_ExclFind + Ar_ActLock.ActLock_ExclFind
        tt-ar-ActLock.ActLock_ExclLock = tt-ar-ActLock.ActLock_ExclLock + Ar_ActLock.ActLock_ExclLock
        tt-ar-ActLock.ActLock_ExclReq = tt-ar-ActLock.ActLock_ExclReq + Ar_ActLock.ActLock_ExclReq
        tt-ar-ActLock.ActLock_ExclWait = tt-ar-ActLock.ActLock_ExclWait + Ar_ActLock.ActLock_ExclWait
        tt-ar-ActLock.ActLock_RecGetLock = tt-ar-ActLock.ActLock_RecGetLock + Ar_ActLock.ActLock_RecGetLock
        tt-ar-ActLock.ActLock_RecGetReq = tt-ar-ActLock.ActLock_RecGetReq + Ar_ActLock.ActLock_RecGetReq
        tt-ar-ActLock.ActLock_RecGetWait = tt-ar-ActLock.ActLock_RecGetWait + Ar_ActLock.ActLock_RecGetWait
        tt-ar-ActLock.ActLock_ShrFind = tt-ar-ActLock.ActLock_ShrFind + Ar_ActLock.ActLock_ShrFind
        tt-ar-ActLock.ActLock_ShrLock = tt-ar-ActLock.ActLock_ShrLock + Ar_ActLock.ActLock_ShrLock
        tt-ar-ActLock.ActLock_ShrReq = tt-ar-ActLock.ActLock_ShrReq + Ar_ActLock.ActLock_ShrReq
        tt-ar-ActLock.ActLock_ShrWait = tt-ar-ActLock.ActLock_ShrWait + Ar_ActLock.ActLock_ShrWait
        tt-ar-ActLock.ActLock_UpgLock = tt-ar-ActLock.ActLock_UpgLock + Ar_ActLock.ActLock_UpgLock
        tt-ar-ActLock.ActLock_UpgReq = tt-ar-ActLock.ActLock_UpgReq + Ar_ActLock.ActLock_UpgReq
        tt-ar-ActLock.ActLock_UpgWait = tt-ar-ActLock.ActLock_UpgWait + Ar_ActLock.ActLock_UpgWait.
END PROCEDURE.
/* 
** ar_actlog.p
**
** This include will archive the ar_actlog rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-ActLog temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActLog table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActLog WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-Actlog NO-UNDO LIKE ar_Actlog
    INDEX myindex1 site_id resrc_id actlog_archivetype actlog_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actlog.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

FOR EACH Ar_Actlog
    WHERE Ar_Actlog.Actlog_ArchiveType = "H"
      AND Ar_Actlog.Actlog_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actlog
        WHERE tt-ar-actlog.Site_Id = ar_actlog.site_id
          AND tt-ar-actlog.Resrc_Id = ar_actlog.Resrc_id
          AND tt-ar-actlog.actlog_archiveType = "D"
          AND tt-ar-actlog.actlog_startDate = ar_actlog.Actlog_startdate:
        RUN add-actlog.
    END.
    
    IF NOT AVAILABLE tt-ar-actlog
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actlog.actlog_StartDate = Ar_actlog.actlog_StartDate
            tt-ar-actlog.actlog_EndDate = Ar_actlog.actlog_EndDate
            tt-ar-actlog.actlog_archiveType = "D".
     END.
    RELEASE tt-ar-actlog.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actlog
        WHERE tt-ar-actlog.Site_Id = ar_actlog.site_id
          AND tt-ar-actlog.Resrc_Id = ar_actlog.Resrc_id
          AND tt-ar-actlog.actlog_archiveType = "W"
          AND ar_actlog.Actlog_startdate GE tt-ar-actlog.actlog_startDate
          AND ar_actlog.Actlog_startdate LE tt-ar-actlog.actlog_enddate:
        RUN add-actlog.
    END.

    IF NOT AVAILABLE tt-ar-actlog
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actlog.actlog_StartDate = Ar_actlog.actlog_StartDate - (WEEKDAY(Ar_actlog.actlog_StartDate) - 1)
            tt-ar-actlog.actlog_EndDate = tt-ar-actlog.actlog_StartDate + 6
            tt-ar-actlog.actlog_archiveType = "W".
     END.
    RELEASE tt-ar-actlog.
END. /*  Of for each Ar_Actlog */

    /* This will write out the temp tables to the appropriate files. */
    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_actlog */
    FOR EACH tt-ar-actlog
        WHERE tt-ar-actlog.actlog_archiveType = "D":
        FOR FIRST ar_actlog
            WHERE ar_actlog.actlog_archiveType = "D"
              AND tt-ar-actlog.Site_Id = ar_actlog.site_id
              AND tt-ar-actlog.Resrc_Id = ar_actlog.Resrc_id
              AND tt-ar-actlog.actlog_startDate = ar_actlog.Actlog_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_actlog
         THEN DO TRANSACTION:
                 CREATE Ar_Actlog.
                 BUFFER-COPY tt-ar-Actlog TO Ar_Actlog.
                 RELEASE Ar_Actlog.
         END.
    END.

    FOR EACH tt-ar-actlog
        WHERE tt-ar-actlog.actlog_archiveType = "W":
        FOR FIRST ar_actlog
            WHERE ar_actlog.actlog_archiveType = "W"
              AND tt-ar-actlog.Site_Id = ar_actlog.site_id
              AND tt-ar-actlog.Resrc_Id = ar_actlog.Resrc_id
              AND ar_actlog.Actlog_startdate GE tt-ar-actlog.actlog_startDate
              AND ar_actlog.Actlog_startdate LE tt-ar-actlog.actlog_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_actlog
         THEN DO TRANSACTION:
                 CREATE Ar_Actlog.
                 BUFFER-COPY tt-ar-Actlog TO Ar_Actlog.
                 RELEASE Ar_Actlog.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actlog.
    BUFFER-COPY ar_actlog TO tt-ar-actlog.
    ASSIGN
      tt-ar-actlog.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actlog.Actlog_EndTime = {&DAY_END_TIME}
      tt-ar-actlog.Actlog_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actlog.
    ASSIGN
        tt-ar-ActLog.actLog_RecordCount  = tt-ar-actLog.actLog_RecordCount + Ar_actLog.actLog_RecordCount 
        tt-ar-ActLog.actLog_transactions = tt-ar-actLog.actLog_transactions + Ar_actLog.actLog_transactions 
        tt-ar-ActLog.actLog_length = tt-ar-actLog.actLog_length + Ar_actLog.actLog_length 
        tt-ar-ActLog.ActLog_AIBBufWaits = tt-ar-ActLog.ActLog_AIBBufWaits + Ar_ActLog.ActLog_AIBBufWaits
        tt-ar-ActLog.ActLog_AIByteWrites = tt-ar-ActLog.ActLog_AIByteWrites + Ar_ActLog.ActLog_AIByteWrites
        tt-ar-ActLog.ActLog_AINoBufAvail = tt-ar-ActLog.ActLog_AINoBufAvail + Ar_ActLog.ActLog_AINoBufAvail
        tt-ar-ActLog.ActLog_AIPartialWrites = tt-ar-ActLog.ActLog_AIPartialWrites + Ar_ActLog.ActLog_AIPartialWrites
        tt-ar-ActLog.ActLog_AIRecWrites = tt-ar-ActLog.ActLog_AIRecWrites + Ar_ActLog.ActLog_AIRecWrites
        tt-ar-ActLog.ActLog_AITotWrites = tt-ar-ActLog.ActLog_AITotWrites + Ar_ActLog.ActLog_AITotWrites
        tt-ar-ActLog.ActLog_AIWWrites = tt-ar-ActLog.ActLog_AIWWrites + Ar_ActLog.ActLog_AIWWrites
        tt-ar-ActLog.ActLog_BIBBufWaits = tt-ar-ActLog.ActLog_BIBBufWaits + Ar_ActLog.ActLog_BIBBufWaits
        tt-ar-ActLog.ActLog_BIByteReads = tt-ar-ActLog.ActLog_BIByteReads + Ar_ActLog.ActLog_BIByteReads
        tt-ar-ActLog.ActLog_BIByteWrites = tt-ar-ActLog.ActLog_BIByteWrites + Ar_ActLog.ActLog_BIByteWrites
        tt-ar-ActLog.ActLog_BIEBufWaits = tt-ar-ActLog.ActLog_BIEBufWaits + Ar_ActLog.ActLog_BIEBufWaits
        tt-ar-ActLog.ActLog_BIPartialWrites = tt-ar-ActLog.ActLog_BIPartialWrites + Ar_ActLog.ActLog_BIPartialWrites
        tt-ar-ActLog.ActLog_BIRecReads = tt-ar-ActLog.ActLog_BIRecReads + Ar_ActLog.ActLog_BIRecReads
        tt-ar-ActLog.ActLog_BIRecWrites = tt-ar-ActLog.ActLog_BIRecWrites + Ar_ActLog.ActLog_BIRecWrites
        tt-ar-ActLog.ActLog_BITotReads = tt-ar-ActLog.ActLog_BITotReads + Ar_ActLog.ActLog_BITotReads
        tt-ar-ActLog.ActLog_BITotWrites = tt-ar-ActLog.ActLog_BITotWrites + Ar_ActLog.ActLog_BITotWrites
        tt-ar-ActLog.ActLog_BIWWrites = tt-ar-ActLog.ActLog_BIWWrites + Ar_ActLog.ActLog_BIWWrites.
END PROCEDURE.
/* 
** ar_actrec.p
**
** This include will archive the ar_actrec rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-ActRec temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActRec table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActRec WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-Actrec NO-UNDO LIKE ar_Actrec
    INDEX myindex site_id resrc_id actrec_archivetype actrec_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actrec.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_Actrec
    WHERE Ar_Actrec.Actrec_ArchiveType = "H"
      AND Ar_Actrec.Actrec_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actrec
        WHERE tt-ar-actrec.Site_Id = ar_actrec.site_id
          AND tt-ar-actrec.Resrc_Id = ar_actrec.Resrc_id
          AND tt-ar-actrec.actrec_archiveType = "D"
          AND tt-ar-actrec.actrec_startDate = ar_actrec.Actrec_startdate:
        RUN add-actrec.
    END.
    
    IF NOT AVAILABLE tt-ar-actrec
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actrec.actrec_StartDate = Ar_actrec.actrec_StartDate
            tt-ar-actrec.actrec_EndDate = Ar_actrec.actrec_EndDate
            tt-ar-actrec.actrec_archiveType = "D".
     END.
    RELEASE tt-ar-actrec.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actrec
        WHERE tt-ar-actrec.Site_Id = ar_actrec.site_id
          AND tt-ar-actrec.Resrc_Id = ar_actrec.Resrc_id
          AND tt-ar-actrec.actrec_archiveType = "W"
          AND ar_actrec.Actrec_startdate GE tt-ar-actrec.actrec_startDate
          AND ar_actrec.Actrec_startdate LE tt-ar-actrec.actrec_enddate:
        RUN add-actrec.
    END.

    IF NOT AVAILABLE tt-ar-actrec
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actrec.actrec_StartDate = Ar_actrec.actrec_StartDate - (WEEKDAY(Ar_actrec.actrec_StartDate) - 1)
            tt-ar-actrec.actrec_EndDate = tt-ar-actrec.actrec_StartDate + 6
            tt-ar-actrec.actrec_archiveType = "W".
     END.
    RELEASE tt-ar-actrec.
END. /*  Of for each Ar_Actrec */

    /* This will write out the temp tables to the appropriate files. */
    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_actrec */
    FOR EACH tt-ar-actrec
        WHERE tt-ar-actrec.actrec_archiveType = "D":
        FOR FIRST ar_actrec
            WHERE ar_actrec.actrec_archiveType = "D"
              AND tt-ar-actrec.Site_Id = ar_actrec.site_id 
              AND tt-ar-actrec.Resrc_Id = ar_actrec.Resrc_id
              AND tt-ar-actrec.actrec_startDate = ar_actrec.Actrec_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_actrec
         THEN DO TRANSACTION:
                 CREATE Ar_Actrec.
                 BUFFER-COPY tt-ar-Actrec TO Ar_Actrec.
                 RELEASE Ar_Actrec.
         END.
    END.
        
    /* Write out db_actrec */
    FOR EACH tt-ar-actrec
        WHERE tt-ar-actrec.actrec_archiveType = "W":
        FOR FIRST ar_actrec
            WHERE ar_actrec.actrec_archiveType = "W"
              AND tt-ar-actrec.Site_Id = ar_actrec.site_id
              AND tt-ar-actrec.Resrc_Id = ar_actrec.Resrc_id
              AND ar_actrec.Actrec_startdate GE tt-ar-actrec.actrec_startDate
              AND ar_actrec.Actrec_startdate LE tt-ar-actrec.actrec_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_actrec
         THEN DO TRANSACTION:
                 CREATE Ar_Actrec.
                 BUFFER-COPY tt-ar-Actrec TO Ar_Actrec.
                 RELEASE Ar_Actrec.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actrec.
    BUFFER-COPY ar_actrec TO tt-ar-actrec.
    ASSIGN
      tt-ar-actrec.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actrec.Actrec_EndTime = {&DAY_END_TIME}
      tt-ar-actrec.Actrec_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actrec.
    ASSIGN
        tt-ar-ActRec.actRec_RecordCount  = tt-ar-actRec.actRec_RecordCount + Ar_actRec.actRec_RecordCount 
        tt-ar-ActRec.actRec_transactions = tt-ar-actRec.actRec_transactions + Ar_actRec.actRec_transactions 
        tt-ar-ActRec.actRec_length = tt-ar-actRec.actRec_length + Ar_actRec.actRec_length 
        tt-ar-ActRec.ActRec_ByteCreate = tt-ar-ActRec.ActRec_ByteCreate + Ar_ActRec.ActRec_ByteCreate
        tt-ar-ActRec.ActRec_ByteDel = tt-ar-ActRec.ActRec_ByteDel + Ar_ActRec.ActRec_ByteDel
        tt-ar-ActRec.ActRec_ByteRead = tt-ar-ActRec.ActRec_ByteRead + Ar_ActRec.ActRec_ByteRead
        tt-ar-ActRec.ActRec_ByteUpd = tt-ar-ActRec.ActRec_ByteUpd + Ar_ActRec.ActRec_ByteUpd
        tt-ar-ActRec.ActRec_FragCreate = tt-ar-ActRec.ActRec_FragCreate + Ar_ActRec.ActRec_FragCreate 
        tt-ar-ActRec.ActRec_FragDel = tt-ar-ActRec.ActRec_FragDel + Ar_ActRec.ActRec_FragDel
        tt-ar-ActRec.ActRec_FragRead = tt-ar-ActRec.ActRec_FragRead + Ar_ActRec.ActRec_FragRead
        tt-ar-ActRec.ActRec_FragUpd = tt-ar-ActRec.ActRec_FragUpd + Ar_ActRec.ActRec_FragUpd
        tt-ar-ActRec.ActRec_RecCreate = tt-ar-ActRec.ActRec_RecCreate + Ar_ActRec.ActRec_RecCreate
        tt-ar-ActRec.ActRec_RecDel = tt-ar-ActRec.ActRec_RecDel + Ar_ActRec.ActRec_RecDel
        tt-ar-ActRec.ActRec_RecLock = tt-ar-ActRec.ActRec_RecLock + Ar_ActRec.ActRec_RecLock
        tt-ar-ActRec.ActRec_RecRead = tt-ar-ActRec.ActRec_RecRead + Ar_ActRec.ActRec_RecRead
        tt-ar-ActRec.ActRec_RecUpd = tt-ar-ActRec.ActRec_RecUpd + Ar_ActRec.ActRec_RecUpd
        tt-ar-ActRec.ActRec_RecWait = tt-ar-ActRec.ActRec_RecWait + Ar_ActRec.ActRec_RecWait.
END PROCEDURE.
/* 
** ar_actserv.p
**
** This include will archive the ar_actserv rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
*/

/*
llaubach 10/2005
 - tt-ar-ActServ temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActServ table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActServ WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-Actserv NO-UNDO LIKE ar_Actserv
    INDEX myindex1 site_id resrc_id actserv_archivetype actserv_num actserv_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actserv.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_Actserv
    WHERE Ar_Actserv.Actserv_ArchiveType = "H"
      AND Ar_Actserv.Actserv_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actserv
        WHERE tt-ar-actserv.Site_Id = ar_actserv.site_id
          AND tt-ar-actserv.Resrc_Id = ar_actserv.Resrc_id
          AND tt-ar-actserv.actserv_archiveType = "D"
          AND tt-ar-actserv.actserv_num = ar_actserv.actserv_num
          AND tt-ar-actserv.actserv_startDate = ar_actserv.Actserv_startdate:
        RUN add-actserv.
    END.

    IF NOT AVAILABLE tt-ar-actserv
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actserv.actserv_StartDate = Ar_actserv.actserv_StartDate
            tt-ar-actserv.actserv_EndDate = Ar_actserv.actserv_EndDate
            tt-ar-actserv.actserv_archiveType = "D".
     END.
    RELEASE tt-ar-actserv.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actserv
        WHERE tt-ar-actserv.Site_Id = ar_actserv.site_id
          AND tt-ar-actserv.Resrc_Id = ar_actserv.Resrc_id
          AND tt-ar-actserv.actserv_archiveType = "W"
          AND tt-ar-actserv.actserv_num = ar_actserv.actserv_num
          AND ar_actserv.Actserv_startdate GE tt-ar-actserv.actserv_startDate
          AND ar_actserv.Actserv_startdate LE tt-ar-actserv.actserv_enddate:
        RUN add-actserv.
    END.
       
    IF NOT AVAILABLE tt-ar-actserv
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actserv.actserv_StartDate = Ar_actserv.actserv_StartDate - (WEEKDAY(Ar_actserv.actserv_StartDate) - 1)
            tt-ar-actserv.actserv_EndDate = tt-ar-actserv.actserv_StartDate + 6
            tt-ar-actserv.actserv_archiveType = "W".
     END.
    RELEASE tt-ar-actserv.
END. /*  Of for each Ar_Actserv */

/* modify average lines... */
RUN modify-actserv.

/* This will write out the temp tables to the appropriate files. */
sec-name = "Writing Data to disk ".
{include/ar-debug.i "sec-name"}

/* Write out db_actserv */
FOR EACH tt-ar-actserv:
    FOR FIRST ar_actserv WHERE tt-ar-actserv.sample_id = ar_actserv.sample_id NO-LOCK: END.
    IF NOT AVAILABLE ar_actserv
     THEN DO TRANSACTION:
             CREATE Ar_Actserv.
             BUFFER-COPY tt-ar-Actserv TO Ar_Actserv.
             RELEASE Ar_Actserv.
      END.
END.
        
sec-name = "Ending Writing Data to disk".
{include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-actserv.
    BUFFER-COPY ar_actserv TO tt-ar-actserv.
    ASSIGN
        tt-ar-actserv.actserv_currusers = (Ar_ActServ.ActServ_Length * Ar_ActServ.actserv_currusers) 
        tt-ar-actserv.actserv_logins = (Ar_ActServ.ActServ_Length * Ar_ActServ.actserv_Logins) 
        tt-ar-actserv.sample_id = NEXT-VALUE(ar_sample-seq)
        tt-ar-actserv.Actserv_EndTime = {&DAY_END_TIME}
        tt-ar-actserv.Actserv_StartTime = 0.
END PROCEDURE.

/* This procedure will modify the existing records */
PROCEDURE modify-actserv.
  FOR EACH tt-ar-actserv:
      ASSIGN
	      tt-ar-actserv.actserv_currusers = tt-ar-actserv.actserv_currusers / tt-ar-actserv.actserv_Length
          tt-ar-actserv.actserv_logins    = tt-ar-actserv.actserv_logins / tt-ar-actserv.actserv_Length
          tt-ar-actserv.actserv_PID       = 0
          tt-ar-actserv.actserv_portnum   = 0.
  END.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actserv.
    ASSIGN
        tt-ar-ActServ.actServ_RecordCount  = tt-ar-actServ.actServ_RecordCount + Ar_actServ.actServ_RecordCount 
        tt-ar-ActServ.actServ_transactions = tt-ar-actServ.actServ_transactions + Ar_actServ.actServ_transactions 
        tt-ar-ActServ.actServ_Length    = tt-ar-actServ.actServ_Length + Ar_actServ.actServ_Length 
        tt-ar-ActServ.ActServ_ByteRec   = tt-ar-ActServ.ActServ_ByteRec   + Ar_ActServ.ActServ_ByteRec
        tt-ar-ActServ.ActServ_ByteSent  = tt-ar-ActServ.ActServ_ByteSent  + Ar_ActServ.ActServ_ByteSent
        tt-ar-ActServ.ActServ_MsgRec    = tt-ar-ActServ.ActServ_MsgRec    + Ar_ActServ.ActServ_MsgRec
        tt-ar-ActServ.ActServ_MsgSent   = tt-ar-ActServ.ActServ_MsgSent   + Ar_ActServ.ActServ_MsgSent
        tt-ar-ActServ.ActServ_QryRec    = tt-ar-ActServ.ActServ_QryRec    + Ar_ActServ.ActServ_QryRec
        tt-ar-ActServ.ActServ_RecRec    = tt-ar-ActServ.ActServ_RecRec    + Ar_ActServ.ActServ_RecRec
        tt-ar-ActServ.ActServ_RecSent   = tt-ar-ActServ.ActServ_RecSent   + Ar_ActServ.ActServ_RecSent
        tt-ar-ActServ.ActServ_TimeSlice = tt-ar-ActServ.ActServ_TimeSlice + Ar_ActServ.ActServ_TimeSlice
        tt-ar-ActServ.ActServ_Num       = Ar_ActServ.ActServ_Num
        tt-ar-ActServ.ActServ_Type      = Ar_ActServ.ActServ_Type
        tt-ar-actserv.actserv_currusers = tt-ar-actserv.actserv_currusers + (Ar_ActServ.ActServ_Length * Ar_ActServ.actserv_currusers) 
        tt-ar-actserv.actserv_logins    = tt-ar-actserv.actserv_logins + (Ar_ActServ.ActServ_Length * Ar_ActServ.actserv_Logins). 
     IF tt-ar-ActServ.ActServ_MaxUsers LT Ar_ActServ.ActServ_MaxUsers
      THEN tt-ar-ActServ.ActServ_MaxUsers = Ar_ActServ.ActServ_MaxUsers.
END PROCEDURE.
/* 
** ar_actsum.p
**
** This include will archive the ar_actsum rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
*/

/*
llaubach 10/2005
 - tt-ar-ActSum temp-table now defined with NO-UNDO
 - defined an index on tt-ar-ActSum table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_ActSum WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-Actsum NO-UNDO LIKE ar_Actsum
    INDEX myindex1 site_id resrc_id actsum_archivetype actsum_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-actsum.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_Actsum
    WHERE Ar_Actsum.Actsum_ArchiveType = "H"
      AND Ar_Actsum.Actsum_StartDate LT Fathom-i-Date NO-LOCK:
    
    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-actsum
        WHERE tt-ar-actsum.Site_Id = ar_actsum.site_id
          AND tt-ar-actsum.Resrc_Id = ar_actsum.Resrc_id
          AND tt-ar-actsum.actsum_archiveType = "D"
          AND tt-ar-actsum.actsum_startDate = ar_actsum.Actsum_startdate:
        RUN add-actsum.
    END.

    IF NOT AVAILABLE tt-ar-actsum
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actsum.actsum_StartDate = Ar_actsum.actsum_StartDate
            tt-ar-actsum.actsum_EndDate = Ar_actsum.actsum_EndDate
            tt-ar-actsum.actsum_archiveType = "D".
     END.
    RELEASE tt-ar-actsum.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-actsum
        WHERE tt-ar-actsum.Site_Id = ar_actsum.site_id
          AND tt-ar-actsum.Resrc_Id = ar_actsum.Resrc_id
          AND tt-ar-actsum.actsum_archiveType = "W"
          AND ar_actsum.Actsum_startdate GE tt-ar-actsum.actsum_startDate
          AND ar_actsum.Actsum_startdate LE tt-ar-actsum.actsum_enddate:
        RUN add-actsum.
    END.
    IF NOT AVAILABLE tt-ar-actsum
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-actsum.actsum_StartDate = Ar_actsum.actsum_StartDate - (WEEKDAY(Ar_actsum.actsum_StartDate) - 1)
            tt-ar-actsum.actsum_EndDate = tt-ar-actsum.actsum_StartDate + 6
            tt-ar-actsum.actsum_archiveType = "W".
     END.
    RELEASE tt-ar-actsum.
END. /*  Of for each Ar_Actsum */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_actsum */
    FOR EACH tt-ar-actsum
        WHERE tt-ar-actsum.actsum_archiveType = "D":
        FOR FIRST ar_actsum
            WHERE ar_actsum.actsum_archiveType = "D"
              AND tt-ar-actsum.Site_Id = ar_actsum.site_id
              AND tt-ar-actsum.Resrc_Id = ar_actsum.Resrc_id
              AND tt-ar-actsum.actsum_startDate = ar_actsum.Actsum_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_actsum
         THEN DO TRANSACTION:
                 CREATE Ar_Actsum.
                 BUFFER-COPY tt-ar-Actsum TO Ar_Actsum.
                 RELEASE Ar_Actsum.
         END.
    END.
        
    /* Write out db_actsum */
    FOR EACH tt-ar-actsum
        WHERE tt-ar-actsum.actsum_archiveType = "W":
        FOR FIRST ar_actsum
            WHERE ar_actsum.actsum_archiveType = "W"
              AND tt-ar-actsum.Site_Id = ar_actsum.site_id
              AND tt-ar-actsum.Resrc_Id = ar_actsum.Resrc_id
              AND ar_actsum.Actsum_startdate GE tt-ar-actsum.actsum_startDate
              AND ar_actsum.Actsum_startdate LE tt-ar-actsum.actsum_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_actsum
         THEN DO TRANSACTION:
                 CREATE Ar_Actsum.
                 BUFFER-COPY tt-ar-Actsum TO Ar_Actsum.
                 RELEASE Ar_Actsum.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */

PROCEDURE create-record.
    CREATE tt-ar-actsum.
    BUFFER-COPY ar_actsum TO tt-ar-actsum.
    ASSIGN
      tt-ar-actsum.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-actsum.Actsum_EndTime = {&DAY_END_TIME}
      tt-ar-actsum.Actsum_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-actsum.
    ASSIGN
        tt-ar-ActSum.actSum_RecordCount    = tt-ar-actSum.actSum_RecordCount + Ar_actSum.actSum_RecordCount 
        tt-ar-ActSum.actSum_transactions   = tt-ar-actSum.actSum_transactions + Ar_actSum.actSum_transactions 
        tt-ar-ActSum.actSum_Length         = tt-ar-actSum.actSum_Length      + Ar_actSum.actSum_Length 
        tt-ar-ActSum.ActSum_AiWrites       = tt-ar-ActSum.ActSum_AiWrites    + Ar_ActSum.ActSum_AiWrites   
        tt-ar-ActSum.ActSum_AllocNewRm     = tt-ar-ActSum.ActSum_AllocNewRm  + Ar_ActSum.ActSum_AllocNewRm 
        tt-ar-ActSum.ActSum_BiReads        = tt-ar-ActSum.ActSum_BiReads     + Ar_ActSum.ActSum_BiReads
        tt-ar-ActSum.ActSum_BiWrites       = tt-ar-ActSum.ActSum_BiWrites    + Ar_ActSum.ActSum_BiWrites
        tt-ar-ActSum.ActSum_BytesAlloc     = tt-ar-ActSum.ActSum_BytesAlloc  + Ar_ActSum.ActSum_BytesAlloc
        tt-ar-ActSum.ActSum_Commits        = tt-ar-ActSum.ActSum_Commits     + Ar_ActSum.ActSum_Commits
        tt-ar-ActSum.ActSum_DbAccesses     = tt-ar-ActSum.ActSum_DbAccesses  + Ar_ActSum.ActSum_DbAccesses 
        tt-ar-ActSum.ActSum_DbExtend       = tt-ar-ActSum.ActSum_DbExtend    + Ar_ActSum.ActSum_DbExtend   
        tt-ar-ActSum.ActSum_DbReads        = tt-ar-ActSum.ActSum_DbReads     + Ar_ActSum.ActSum_DbReads    
        tt-ar-ActSum.ActSum_DbWrites       = tt-ar-ActSum.ActSum_DbWrites    + Ar_ActSum.ActSum_DbWrites   
        tt-ar-ActSum.ActSum_Examined       = tt-ar-ActSum.ActSum_Examined    + Ar_ActSum.ActSum_Examined   
        tt-ar-ActSum.ActSum_FromFree       = tt-ar-ActSum.ActSum_FromFree    + Ar_ActSum.ActSum_FromFree   
        tt-ar-ActSum.ActSum_FromRm         = tt-ar-ActSum.ActSum_FromRm      + Ar_ActSum.ActSum_FromRm     
        tt-ar-ActSum.ActSum_Removed        = tt-ar-ActSum.ActSum_Removed     + Ar_ActSum.ActSum_Removed    
        tt-ar-ActSum.ActSum_RetFree        = tt-ar-ActSum.ActSum_RetFree     + Ar_ActSum.ActSum_RetFree    
        tt-ar-ActSum.ActSum_TakeFree       = tt-ar-ActSum.ActSum_TakeFree    + Ar_ActSum.ActSum_TakeFree   
        tt-ar-ActSum.ActSum_Undos          = tt-ar-ActSum.ActSum_Undos       + Ar_ActSum.ActSum_Undos      .
END PROCEDURE.
/* 
** ar_areastatus.p
**
** This include will archive the ar_areastatus rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-AreaStatus temp-table now defined with NO-UNDO
 - defined an index on tt-ar-AreaStatus table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_AreaStatus WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-areastatus NO-UNDO LIKE ar_areastatus
    INDEX myindex1 site_id resrc_id areastatus_archivetype areastatus_areanum areastatus_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-areastatus.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

FOR EACH Ar_areastatus
    WHERE Ar_areastatus.areastatus_ArchiveType = "H"
      AND Ar_areastatus.areastatus_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */

    FOR FIRST tt-ar-areastatus
        WHERE tt-ar-areastatus.Site_Id = ar_areastatus.site_id
          AND tt-ar-areastatus.Resrc_Id = ar_areastatus.Resrc_id
          AND tt-ar-areastatus.areastatus_archiveType = "D"
          AND tt-ar-areastatus.areastatus_areanum = ar_areastatus.areastatus_areanum
          AND tt-ar-areastatus.areastatus_startDate = ar_areastatus.areastatus_startdate:
        RUN add-areastatus.
    END.
      
    IF NOT AVAILABLE tt-ar-areastatus
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-areastatus.areastatus_StartDate = Ar_areastatus.areastatus_StartDate
            tt-ar-areastatus.areastatus_EndDate = Ar_areastatus.areastatus_EndDate
            tt-ar-areastatus.areastatus_archiveType = "D".
     END.
    RELEASE tt-ar-areastatus.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-areastatus
        WHERE tt-ar-areastatus.Site_Id = ar_areastatus.site_id
          AND tt-ar-areastatus.Resrc_Id = ar_areastatus.Resrc_id
          AND tt-ar-areastatus.areastatus_archiveType = "W"
          AND tt-ar-areastatus.areastatus_areanum = ar_areastatus.areastatus_areanum
          AND ar_areastatus.areastatus_startdate GE tt-ar-areastatus.areastatus_startDate
          AND ar_areastatus.areastatus_startdate LE tt-ar-areastatus.areastatus_enddate:
        RUN add-areastatus.
    END.    

    IF NOT AVAILABLE tt-ar-areastatus
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-areastatus.areastatus_StartDate = Ar_areastatus.areastatus_StartDate - (WEEKDAY(Ar_areastatus.areastatus_StartDate) - 1)
            tt-ar-areastatus.areastatus_EndDate = tt-ar-areastatus.areastatus_StartDate + 6
            tt-ar-areastatus.areastatus_archiveType = "W".
     END.
    RELEASE tt-ar-areastatus.
END. /*  Of for each Ar_areastatus */

/* modify average lines... */
RUN modify-areastatus.

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Begin writing data to disk ".
    {include/ar-debug.i "sec-name"}
 
    /* Write out db_areastatus */
    FOR EACH tt-ar-areastatus
        WHERE tt-ar-areastatus.areastatus_archiveType = "D":
        FOR FIRST ar_areastatus
            WHERE ar_areastatus.areastatus_archiveType = "D"
              AND tt-ar-areastatus.Site_Id = ar_areastatus.site_id
              AND tt-ar-areastatus.Resrc_Id = ar_areastatus.Resrc_id
              AND tt-ar-areastatus.areastatus_areanum = ar_areastatus.areastatus_areanum
              AND tt-ar-areastatus.areastatus_startDate = ar_areastatus.areastatus_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_areastatus
         THEN DO TRANSACTION:
              CREATE Ar_areastatus.
              BUFFER-COPY tt-ar-areastatus TO Ar_areastatus.
              RELEASE Ar_areastatus.
         END.
    END.
    
    /* Write out db_areastatus */
    FOR EACH tt-ar-areastatus
        WHERE tt-ar-areastatus.areastatus_archiveType = "W":
        FOR FIRST ar_areastatus
            WHERE ar_areastatus.areastatus_archiveType = "W"
              AND tt-ar-areastatus.Site_Id = ar_areastatus.site_id
              AND tt-ar-areastatus.Resrc_Id = ar_areastatus.Resrc_id
              AND tt-ar-areastatus.areastatus_areanum = ar_areastatus.areastatus_areanum
              AND ar_areastatus.areastatus_startdate GE tt-ar-areastatus.areastatus_startDate
              AND ar_areastatus.areastatus_startdate LE tt-ar-areastatus.areastatus_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_areastatus
         THEN DO TRANSACTION:
              CREATE Ar_areastatus.
              BUFFER-COPY tt-ar-areastatus TO Ar_areastatus.
              RELEASE Ar_areastatus.
         END.
    END.

    sec-name = "Ending writing data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */

PROCEDURE create-record.
    CREATE tt-ar-areastatus.
    BUFFER-COPY ar_areastatus TO tt-ar-areastatus.
    ASSIGN
        tt-ar-AreaStatus.AreaStatus_Freenum    = (Ar_AreaStatus.AreaStatus_Length * Ar_AreaStatus.AreaStatus_Freenum)
        tt-ar-AreaStatus.AreaStatus_Rmnum      = (Ar_AreaStatus.AreaStatus_Length * Ar_AreaStatus.AreaStatus_Rmnum)
        tt-ar-areastatus.sample_id             = NEXT-VALUE(ar_sample-seq)
        tt-ar-areastatus.areastatus_EndTime    = {&DAY_END_TIME}
        tt-ar-areastatus.areastatus_StartTime  = 0.
END PROCEDURE.

/* This procedure will modify the existing records */

PROCEDURE modify-areastatus.
  FOR EACH tt-ar-areastatus:
      ASSIGN
        tt-ar-areastatus.areastatus_freenum = INT64 (tt-ar-areastatus.areastatus_freenum / tt-ar-areastatus.areastatus_Length)
        tt-ar-areastatus.areastatus_rmnum   = INT64 (tt-ar-areastatus.areastatus_rmnum / tt-ar-areastatus.areastatus_Length).
  END.
END PROCEDURE.

/* This procedure will add to an existing record */

PROCEDURE add-areastatus.
    ASSIGN
        tt-ar-AreaStatus.AreaStatus_RecordCount  = tt-ar-AreaStatus.AreaStatus_RecordCount + Ar_AreaStatus.AreaStatus_RecordCount 
        tt-ar-AreaStatus.AreaStatus_transactions = tt-ar-AreaStatus.AreaStatus_transactions + Ar_AreaStatus.AreaStatus_transactions 
        tt-ar-AreaStatus.AreaStatus_length       = tt-ar-AreaStatus.AreaStatus_length + Ar_AreaStatus.AreaStatus_length 
        tt-ar-AreaStatus.AreaStatus_Areaname     = Ar_AreaStatus.AreaStatus_Areaname
        tt-ar-AreaStatus.AreaStatus_Areanum      = Ar_AreaStatus.AreaStatus_Areanum
        tt-ar-AreaStatus.AreaStatus_Extents      = Ar_AreaStatus.AreaStatus_Extents
        tt-ar-AreaStatus.AreaStatus_Freenum      = tt-ar-AreaStatus.AreaStatus_Freenum + (Ar_AreaStatus.AreaStatus_Length * Ar_AreaStatus.AreaStatus_Freenum)
        tt-ar-AreaStatus.AreaStatus_Rmnum        = tt-ar-AreaStatus.AreaStatus_Rmnum   + (Ar_AreaStatus.AreaStatus_Length * Ar_AreaStatus.AreaStatus_Rmnum).
    IF tt-ar-AreaStatus.AreaStatus_Hiwater < Ar_AreaStatus.AreaStatus_Hiwater
     THEN tt-ar-AreaStatus.AreaStatus_Hiwater = Ar_AreaStatus.AreaStatus_Hiwater.
	IF tt-ar-AreaStatus.AreaStatus_TotBlocks  < Ar_AreaStatus.AreaStatus_TotBlocks
     THEN tt-ar-AreaStatus.AreaStatus_TotBlocks = Ar_AreaStatus.AreaStatus_TotBlocks .
END PROCEDURE.
/* 
** ar_checkpoint.p
**
** This include will archive the ar_checkpoint rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-CheckPoint temp-table now defined with NO-UNDO
 - defined an index on tt-ar-CheckPoint table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_CheckPoint WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-checkpoint NO-UNDO LIKE ar_checkpoint
    INDEX myindex1 site_id resrc_id checkpoint_archivetype checkpoint_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-checkpoint.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_checkpoint 
    WHERE Ar_checkpoint.checkpoint_ArchiveType = "H"
      AND Ar_checkpoint.checkpoint_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-checkpoint
        WHERE tt-ar-checkpoint.Site_Id = ar_checkpoint.site_id
          AND tt-ar-checkpoint.Resrc_Id = ar_checkpoint.Resrc_id
          AND tt-ar-checkpoint.checkpoint_archiveType = "D"
          AND tt-ar-checkpoint.checkpoint_startDate = ar_checkpoint.checkpoint_startdate:
        RUN add-checkpoint.
    END.
    
    IF NOT AVAILABLE tt-ar-checkpoint
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-checkpoint.checkpoint_StartDate = Ar_checkpoint.checkpoint_StartDate
            tt-ar-checkpoint.checkpoint_EndDate = Ar_checkpoint.checkpoint_EndDate
            tt-ar-checkpoint.checkpoint_archiveType = "D".
     END.
    RELEASE tt-ar-checkpoint.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-checkpoint
        WHERE tt-ar-checkpoint.Site_Id = ar_checkpoint.site_id
          AND tt-ar-checkpoint.Resrc_Id = ar_checkpoint.Resrc_id
          AND tt-ar-checkpoint.checkpoint_archiveType = "W"
          AND ar_checkpoint.checkpoint_startdate GE tt-ar-checkpoint.checkpoint_startDate
          AND ar_checkpoint.checkpoint_startdate LE tt-ar-checkpoint.checkpoint_enddate:
        RUN add-checkpoint.
    END.

    IF NOT AVAILABLE tt-ar-checkpoint
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-checkpoint.checkpoint_StartDate = Ar_checkpoint.checkpoint_StartDate - (WEEKDAY(Ar_checkpoint.checkpoint_StartDate) - 1)
            tt-ar-checkpoint.checkpoint_EndDate = tt-ar-checkpoint.checkpoint_StartDate + 6
            tt-ar-checkpoint.checkpoint_archiveType = "W".
    END.
    RELEASE tt-ar-checkpoint.
END. /*  Of for each Ar_checkpoint */

/* Modify average columns */
RUN modify-checkpoint.

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out ar-checkpoint */
    FOR EACH tt-ar-checkpoint
        WHERE tt-ar-checkpoint.checkpoint_archiveType = "D":
        FOR FIRST ar_checkpoint
            WHERE Ar_Checkpoint.checkpoint_archiveType = "D"
              AND tt-ar-checkpoint.Site_Id = ar_checkpoint.site_id
              AND tt-ar-checkpoint.Resrc_Id = ar_checkpoint.Resrc_id
              AND tt-ar-checkpoint.checkpoint_startDate = ar_checkpoint.checkpoint_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_checkpoint
         THEN DO TRANSACTION:
                 CREATE Ar_checkpoint.
                 BUFFER-COPY tt-ar-checkpoint TO Ar_checkpoint.
                 RELEASE Ar_checkpoint.
              END.
    END.
        
    /* Write out ar-checkpoint */
    FOR EACH tt-ar-checkpoint
        WHERE tt-ar-checkpoint.checkpoint_archiveType = "W":
        FOR FIRST ar_checkpoint
            WHERE Ar_Checkpoint.checkpoint_archiveType = "W" 
              AND tt-ar-checkpoint.Site_Id = ar_checkpoint.site_id
              AND tt-ar-checkpoint.Resrc_Id = ar_checkpoint.Resrc_id
              AND ar_checkpoint.checkpoint_startdate GE tt-ar-checkpoint.checkpoint_startDate
              AND ar_checkpoint.checkpoint_startdate LE tt-ar-checkpoint.checkpoint_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_checkpoint
         THEN DO TRANSACTION:
                 CREATE Ar_checkpoint.
                 BUFFER-COPY tt-ar-checkpoint TO Ar_checkpoint.
                 RELEASE Ar_checkpoint.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-checkpoint.
    BUFFER-COPY ar_checkpoint TO tt-ar-checkpoint.
    ASSIGN
        /* tt-ar-Checkpoint.Checkpoint_ApwQ   = 
	   (Ar_Checkpoint.Checkpoint_Length * Ar_Checkpoint.Checkpoint_ApwQ)
        tt-ar-Checkpoint.Checkpoint_CkptQ  = 
	   (Ar_Checkpoint.Checkpoint_Length * Ar_Checkpoint.Checkpoint_CkptQ)
        tt-ar-Checkpoint.Checkpoint_Dirty  = 
	   (Ar_Checkpoint.Checkpoint_Length * Ar_Checkpoint.Checkpoint_Dirty)
        tt-ar-Checkpoint.Checkpoint_Flush  = 
	   (Ar_Checkpoint.Checkpoint_Length * Ar_Checkpoint.Checkpoint_Flush)
        tt-ar-Checkpoint.Checkpoint_Scan   = 
	   (Ar_Checkpoint.Checkpoint_Length * Ar_Checkpoint.Checkpoint_Scan) */
        tt-ar-checkpoint.sample_id = NEXT-VALUE(ar_sample-seq)
        tt-ar-checkpoint.checkpoint_EndTime = {&DAY_END_TIME}
        tt-ar-checkpoint.checkpoint_StartTime = 0.
END PROCEDURE.

/* This procedure will modify the existing records */
PROCEDURE modify-checkpoint.
  FOR EACH tt-ar-checkpoint:
        /* tt-ar-checkpoint.checkpoint_apwq = 
            INTEGER (tt-ar-checkpoint.checkpoint_apwq / 
            tt-ar-checkpoint.checkpoint_Length).
    
        tt-ar-checkpoint.checkpoint_ckptq = 
            INTEGER (tt-ar-checkpoint.checkpoint_ckptq / 
            tt-ar-checkpoint.checkpoint_Length).
    
        tt-ar-checkpoint.checkpoint_dirty = 
            INTEGER (tt-ar-checkpoint.checkpoint_dirty / 
            tt-ar-checkpoint.checkpoint_Length).
    
        tt-ar-checkpoint.checkpoint_flush = 
            INTEGER (tt-ar-checkpoint.checkpoint_flush / 
            tt-ar-checkpoint.checkpoint_Length).
    
        tt-ar-checkpoint.checkpoint_length = 
            INTEGER (tt-ar-checkpoint.checkpoint_length / 
        tt-ar-checkpoint.checkpoint_Length).

        tt-ar-checkpoint.checkpoint_scan = 
            INTEGER (tt-ar-checkpoint.checkpoint_scan / 
        tt-ar-checkpoint.checkpoint_Length).    */
       ASSIGN
          tt-ar-checkpoint.checkpoint_time = ""
          tt-ar-checkpoint.checkpoint_num = 0.
  END.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-checkpoint.
    ASSIGN
        tt-ar-Checkpoint.Checkpoint_RecordCount  = tt-ar-Checkpoint.Checkpoint_RecordCount + Ar_Checkpoint.Checkpoint_RecordCount 
        tt-ar-Checkpoint.Checkpoint_transactions = tt-ar-Checkpoint.Checkpoint_transactions + Ar_Checkpoint.Checkpoint_transactions 
        tt-ar-Checkpoint.Checkpoint_Length = tt-ar-Checkpoint.Checkpoint_Length + Ar_Checkpoint.Checkpoint_Length
        tt-ar-Checkpoint.Checkpoint_Time   = tt-ar-Checkpoint.Checkpoint_Time + Ar_Checkpoint.Checkpoint_Time
        tt-ar-Checkpoint.Checkpoint_ApwQ   = tt-ar-Checkpoint.Checkpoint_ApwQ + Ar_Checkpoint.Checkpoint_ApwQ
        tt-ar-Checkpoint.Checkpoint_CkptQ  = tt-ar-Checkpoint.Checkpoint_CkptQ  + Ar_Checkpoint.Checkpoint_CkptQ
        tt-ar-Checkpoint.Checkpoint_Dirty  = tt-ar-Checkpoint.Checkpoint_Dirty  + Ar_Checkpoint.Checkpoint_Dirty
        tt-ar-Checkpoint.Checkpoint_Flush  = tt-ar-Checkpoint.Checkpoint_Flush  + Ar_Checkpoint.Checkpoint_Flush
        tt-ar-Checkpoint.Checkpoint_Scan   = tt-ar-Checkpoint.Checkpoint_Scan   + Ar_Checkpoint.Checkpoint_Scan.
END PROCEDURE.
/* 
** ar_cpu.p
**
** This include will archive the ar_cpu rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-cpu temp-table now defined with NO-UNDO
 - defined an index on tt-ar-cpu table to match WHERE clause
 - db Ar_cpu should have better index to avoid client sorting (it has only ArchiveType
 - added NO-LOCK to FOR EACH Ar_cpu WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-cpu NO-UNDO LIKE ar_cpu 
   INDEX myindex1 Site_Id Resrc_Id CPU_archivetype CPU_startdate.
   
/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-cpu.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

FOR EACH Ar_cpu
    WHERE Ar_cpu.cpu_ArchiveType = "H"
      AND Ar_cpu.cpu_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-cpu
        WHERE tt-ar-cpu.Site_Id = ar_cpu.site_id
          AND tt-ar-cpu.Resrc_Id = ar_cpu.Resrc_id
          AND tt-ar-cpu.cpu_archiveType = "D"
          AND tt-ar-cpu.cpu_startDate = ar_cpu.cpu_startdate:
        RUN add-cpu.
    END.
    
    IF NOT AVAILABLE tt-ar-cpu
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-cpu.cpu_StartDate = Ar_cpu.cpu_StartDate
            tt-ar-cpu.cpu_EndDate = Ar_cpu.cpu_EndDate
            tt-ar-cpu.cpu_archiveType = "D".
     END.
    RELEASE tt-ar-cpu.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-cpu
        WHERE tt-ar-cpu.Site_Id = ar_cpu.site_id
          AND tt-ar-cpu.Resrc_Id = ar_cpu.Resrc_id
          AND tt-ar-cpu.cpu_archiveType = "W"
          AND ar_cpu.cpu_startdate GE tt-ar-cpu.cpu_startDate
          AND ar_cpu.cpu_startdate LE tt-ar-cpu.cpu_enddate:
        RUN add-cpu.
    END.
    
    IF NOT AVAILABLE tt-ar-cpu
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-cpu.cpu_StartDate = Ar_cpu.cpu_StartDate - (WEEKDAY(Ar_cpu.cpu_StartDate) - 1)
            tt-ar-cpu.cpu_EndDate = tt-ar-cpu.cpu_StartDate + 6
            tt-ar-cpu.cpu_archiveType = "W".
     END.
    RELEASE tt-ar-cpu.
END. /*  Of for each Ar_cpu */

/* This will bring the numbers back to averages... */
RUN modify-cpu.

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_cpu */
    FOR EACH tt-ar-cpu:
        FOR FIRST ar_cpu
            WHERE Ar_CPU.cpu_archiveType = "W"
              AND tt-ar-cpu.Site_Id = ar_cpu.site_id
              AND tt-ar-cpu.Resrc_Id = ar_cpu.Resrc_id
              AND ar_cpu.cpu_startdate GE tt-ar-cpu.cpu_startDate
              AND ar_cpu.cpu_startdate LE tt-ar-cpu.cpu_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_cpu
         THEN DO TRANSACTION:
                 CREATE Ar_cpu.
                 BUFFER-COPY tt-ar-cpu TO Ar_cpu.
                 RELEASE Ar_cpu.
         END.
    END.
        
    /* Write out db_cpu */
    FOR EACH tt-ar-cpu
        WHERE tt-ar-cpu.cpu_archiveType = "D":
        FOR FIRST ar_cpu
            WHERE Ar_CPU.cpu_archiveType = "D"
              AND tt-ar-cpu.Site_Id = ar_cpu.site_id 
              AND tt-ar-cpu.Resrc_Id = ar_cpu.Resrc_id
              AND tt-ar-cpu.cpu_startDate = ar_cpu.cpu_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_cpu
         THEN DO TRANSACTION:
                 CREATE Ar_cpu.
                 BUFFER-COPY tt-ar-cpu TO Ar_cpu.
                 RELEASE Ar_cpu.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-cpu.
    BUFFER-COPY ar_cpu TO tt-ar-cpu.
    ASSIGN
      tt-ar-cpu.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-cpu.cpu_EndTime = {&DAY_END_TIME}
      tt-ar-cpu.cpu_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-cpu.
    ASSIGN
        tt-ar-CPU.CPU_RecordCount  = tt-ar-CPU.CPU_RecordCount  + ar_CPU.CPU_RecordCount 
        tt-ar-CPU.CPU_Transactions = tt-ar-CPU.CPU_Transactions + ar_CPU.CPU_Transactions 
        tt-ar-CPU.CPU_Length       = tt-ar-CPU.CPU_Length       + ar_CPU.CPU_Length 
        /* tt-ar-CPU.CPU_Idle         = tt-ar-CPU.CPU_Idle         + (ar_CPU.CPU_Length * ar_CPU.CPU_Idle) */
        tt-ar-CPU.CPU_System       = tt-ar-CPU.CPU_System       + (ar_CPU.CPU_Length * ar_CPU.CPU_System)
        tt-ar-CPU.CPU_Usr          = tt-ar-CPU.CPU_Usr          + (ar_CPU.CPU_Length * ar_CPU.CPU_Usr)
        tt-ar-CPU.CPU_Wait         = tt-ar-CPU.CPU_Wait         + (ar_CPU.CPU_Length * ar_CPU.CPU_Wait).
END PROCEDURE.

/* This procedure will modify the existing records accordingly */
PROCEDURE modify-cpu.
  /* Changed to use Number of samples rather than the number of records */   
  FOR EACH tt-ar-cpu:
      ASSIGN
         tt-ar-CPU.CPU_System = tt-ar-CPU.CPU_System / tt-ar-CPU.CPU_Length
         tt-ar-CPU.CPU_Usr    = tt-ar-CPU.CPU_Usr / tt-ar-CPU.CPU_Length         
         tt-ar-CPU.CPU_Wait   = tt-ar-CPU.CPU_Wait / tt-ar-CPU.CPU_Length.
      ASSIGN         
         tt-ar-CPU.CPU_Idle   = TRUNCATE(100.0 - (tt-ar-CPU.CPU_Usr + tt-ar-CPU.CPU_System + tt-ar-CPU.CPU_Wait), 0).
      IF tt-ar-CPU.CPU_Idle < 0 THEN
          ASSIGN tt-ar-CPU.CPU_Idle = 0.          
  END.  
END PROCEDURE.
/* 
** ar_dev.p
**
** This include will archive the ar_dev rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-dev temp-table now defined with NO-UNDO
 - defined an index on tt-ar-dev table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_dev WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-dev NO-UNDO LIKE ar_dev
    INDEX myindex1 Site_Id Resrc_id dev_archiveType dev_name dev_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-dev.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_dev
    WHERE Ar_dev.dev_ArchiveType = "H"
      AND Ar_dev.dev_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-dev
        WHERE tt-ar-dev.Site_Id = ar_dev.site_id
          AND tt-ar-dev.Resrc_Id = ar_dev.Resrc_id
          AND tt-ar-dev.dev_archiveType = "D"
          AND tt-ar-dev.dev_name = ar_dev.dev_name
          AND tt-ar-dev.dev_startDate = ar_dev.dev_startdate:
        RUN add-dev.
    END.
    
    IF NOT AVAILABLE tt-ar-dev
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-dev.dev_StartDate = Ar_dev.dev_StartDate
            tt-ar-dev.dev_EndDate = Ar_dev.dev_EndDate
            tt-ar-dev.dev_archiveType = "D".
     END.
    RELEASE tt-ar-dev.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-dev
        WHERE tt-ar-dev.Site_Id = ar_dev.site_id
          AND tt-ar-dev.Resrc_Id = ar_dev.Resrc_id
          AND tt-ar-dev.dev_archiveType = "W"
          AND tt-ar-dev.dev_name = ar_dev.dev_name
          AND ar_dev.dev_startdate GE tt-ar-dev.dev_startDate
          AND ar_dev.dev_startdate LE tt-ar-dev.dev_enddate:
        RUN add-dev.
    END.
    
    IF NOT AVAILABLE tt-ar-dev
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-dev.dev_StartDate = Ar_dev.dev_StartDate - (WEEKDAY(Ar_dev.dev_StartDate) - 1)
            tt-ar-dev.dev_EndDate = tt-ar-dev.dev_StartDate + 6
            tt-ar-dev.dev_archiveType = "W".
     END.
    RELEASE tt-ar-dev.
END. /*  Of for each Ar_dev */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    FOR EACH tt-ar-dev
        WHERE tt-ar-dev.dev_archiveType = "D":
        FOR FIRST ar_dev
            WHERE ar_dev.dev_archiveType = "D"
              AND tt-ar-dev.Site_Id = ar_dev.site_id
              AND tt-ar-dev.Resrc_Id = ar_dev.Resrc_id
              AND tt-ar-dev.dev_name = ar_dev.dev_name
              AND tt-ar-dev.dev_startDate = ar_dev.dev_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_dev
         THEN DO TRANSACTION:
                 ASSIGN
                    tt-ar-Dev.Dev_AvgQue = tt-ar-Dev.Dev_AvgQue / tt-ar-Dev.Dev_Length
                    tt-ar-Dev.Dev_AvgServ = tt-ar-Dev.Dev_AvgServ / tt-ar-Dev.Dev_Length
                    tt-ar-Dev.Dev_AvgWait = tt-ar-Dev.Dev_AvgWait / tt-ar-Dev.Dev_Length
                    tt-ar-Dev.Dev_Pct_Busy = tt-ar-Dev.Dev_Pct_Busy / tt-ar-Dev.Dev_Length.
                 CREATE Ar_dev.
                 BUFFER-COPY tt-ar-dev TO Ar_dev.
                 RELEASE Ar_dev.
         END.
    END.

    FOR EACH tt-ar-dev
        WHERE tt-ar-dev.dev_archiveType = "W":
        FOR FIRST ar_dev
            WHERE ar_dev.dev_archiveType = "W"
              AND tt-ar-dev.Site_Id = ar_dev.site_id
              AND tt-ar-dev.Resrc_Id = ar_dev.Resrc_id
              AND tt-ar-dev.dev_name = ar_dev.dev_name
              AND ar_dev.dev_startdate GE tt-ar-dev.dev_startDate
              AND ar_dev.dev_startdate LE tt-ar-dev.dev_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_dev
         THEN DO TRANSACTION:
                 ASSIGN
                    tt-ar-Dev.Dev_AvgQue = tt-ar-Dev.Dev_AvgQue / tt-ar-Dev.Dev_Length
                    tt-ar-Dev.Dev_AvgServ = tt-ar-Dev.Dev_AvgServ / tt-ar-Dev.Dev_Length
                    tt-ar-Dev.Dev_AvgWait = tt-ar-Dev.Dev_AvgWait / tt-ar-Dev.Dev_Length
                    tt-ar-Dev.Dev_Pct_Busy = tt-ar-Dev.Dev_Pct_Busy / tt-ar-Dev.Dev_Length.
                 CREATE Ar_dev.
                 BUFFER-COPY tt-ar-dev TO Ar_dev.
                 RELEASE Ar_dev.
         END.
    END.
    
    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-dev.
    BUFFER-COPY ar_dev TO tt-ar-dev.
    ASSIGN
        tt-ar-Dev.Dev_AvgQue = (Ar_Dev.Dev_Length * ar_Dev.Dev_AvgQue)
        tt-ar-Dev.Dev_AvgServ = (Ar_Dev.Dev_Length * ar_Dev.Dev_AvgServ)
        tt-ar-Dev.Dev_AvgWait = (Ar_Dev.Dev_Length * ar_Dev.Dev_AvgWait)
        tt-ar-Dev.Dev_Pct_Busy = (Ar_Dev.Dev_Length * ar_Dev.Dev_Pct_Busy)
        tt-ar-dev.sample_id = NEXT-VALUE(ar_sample-seq)
        tt-ar-dev.dev_EndTime = {&DAY_END_TIME}
        tt-ar-dev.dev_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-dev.
    ASSIGN
        tt-ar-Dev.Dev_RecordCount  = tt-ar-Dev.Dev_RecordCount + ar_Dev.Dev_RecordCount
        tt-ar-Dev.Dev_Transactions = tt-ar-Dev.Dev_Transactions + ar_Dev.Dev_Transactions
        tt-ar-Dev.Dev_Length   = tt-ar-Dev.Dev_Length + ar_Dev.Dev_Length
        tt-ar-Dev.Dev_Name     = ar_Dev.Dev_Name
        tt-ar-Dev.Dev_AvgQue   = tt-ar-Dev.Dev_AvgQue + (Ar_Dev.Dev_Length * ar_Dev.Dev_AvgQue)
        tt-ar-Dev.Dev_AvgServ  = tt-ar-Dev.Dev_AvgServ + (Ar_Dev.Dev_Length * ar_Dev.Dev_AvgServ)
        tt-ar-Dev.Dev_AvgWait  = tt-ar-Dev.Dev_AvgWait + (Ar_Dev.Dev_Length * ar_Dev.Dev_AvgWait)
        tt-ar-Dev.Dev_Pct_Busy = tt-ar-Dev.Dev_Pct_Busy + (Ar_Dev.Dev_Length * ar_Dev.Dev_Pct_Busy).
END PROCEDURE.    
/* 
** ar_FileSize.p
**
** This include will archive the ar_FileSize rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-FileSize temp-table now defined with NO-UNDO
 - defined an index on tt-ar-FileSize table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_FileSize WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-FileSize NO-UNDO LIKE ar_FileSize
     INDEX myindex1 site_id resrc_id filesize_archivetype filesize_name filesize_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-filesize.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_FileSize
    WHERE Ar_FileSize.FileSize_ArchiveType = "H"
      AND Ar_FileSize.FileSize_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-FileSize
        WHERE tt-ar-filesize.Site_Id = ar_filesize.site_id
          AND tt-ar-filesize.Resrc_Id = ar_filesize.Resrc_id
          AND tt-ar-FileSize.FileSize_archiveType = "D"
          AND tt-ar-filesize.filesize_name = ar_filesize.filesize_name
          AND tt-ar-FileSize.FileSize_startDate = ar_FileSize.FileSize_startdate:
        RUN add-filesize.
    END.
    
    IF NOT AVAILABLE tt-ar-FileSize
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-filesize.filesize_StartDate = Ar_filesize.filesize_StartDate
            tt-ar-filesize.filesize_EndDate = Ar_filesize.filesize_EndDate
            tt-ar-filesize.filesize_archiveType = "D".
     END.
    RELEASE tt-ar-FileSize.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-FileSize
        WHERE tt-ar-filesize.Site_Id = ar_filesize.site_id
          AND tt-ar-filesize.Resrc_Id = ar_filesize.Resrc_id
          AND tt-ar-FileSize.FileSize_archiveType = "W"
          AND tt-ar-filesize.filesize_name = ar_filesize.filesize_name
          AND ar_FileSize.FileSize_startdate GE tt-ar-FileSize.FileSize_startDate
          AND ar_FileSize.FileSize_startdate LE tt-ar-FileSize.FileSize_enddate:
        RUN add-filesize.
    END.

    IF NOT AVAILABLE tt-ar-FileSize
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-filesize.filesize_StartDate = Ar_filesize.filesize_StartDate - (WEEKDAY(Ar_filesize.filesize_StartDate) - 1)
            tt-ar-filesize.filesize_EndDate = tt-ar-filesize.filesize_StartDate + 6
            tt-ar-filesize.filesize_archiveType = "W".
     END.
    RELEASE tt-ar-FileSize.
END. /*  Of for each Ar_FileSize */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_FileSize */
    FOR EACH tt-ar-FileSize
        WHERE tt-ar-FileSize.FileSize_archiveType = "D":
        FOR FIRST ar_FileSize
            WHERE Ar_Filesize.FileSize_archiveType = "D"
              AND tt-ar-filesize.Site_Id = ar_filesize.site_id
              AND tt-ar-filesize.Resrc_Id = ar_filesize.Resrc_id
              AND tt-ar-filesize.filesize_name = ar_filesize.filesize_name
              AND tt-ar-FileSize.FileSize_startDate = ar_FileSize.FileSize_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_FileSize
         THEN DO TRANSACTION:
                 tt-ar-filesize.filesize_size = tt-ar-filesize.filesize_size / tt-ar-filesize.filesize_RecordCount.
                 CREATE Ar_FileSize.
                 BUFFER-COPY tt-ar-FileSize TO Ar_FileSize.
                 RELEASE Ar_FileSize.
         END.
    END.
        
    /* Write out db_FileSize */
    FOR EACH tt-ar-FileSize
        WHERE tt-ar-FileSize.FileSize_archiveType = "W":
        FOR FIRST ar_FileSize
            WHERE Ar_Filesize.FileSize_archiveType = "W"
              AND tt-ar-filesize.Site_Id = ar_filesize.site_id
              AND tt-ar-filesize.Resrc_Id = ar_filesize.Resrc_id
              AND tt-ar-filesize.filesize_name = ar_filesize.filesize_name
              AND ar_FileSize.FileSize_startdate GE tt-ar-FileSize.FileSize_startDate
              AND ar_FileSize.FileSize_startdate LE tt-ar-FileSize.FileSize_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_FileSize
         THEN DO TRANSACTION:
                 tt-ar-filesize.filesize_size = tt-ar-filesize.filesize_size / tt-ar-filesize.filesize_RecordCount.
                 CREATE Ar_FileSize.
                 BUFFER-COPY tt-ar-FileSize TO Ar_FileSize.
                 RELEASE Ar_FileSize.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-FileSize.
    BUFFER-COPY ar_FileSize TO tt-ar-FileSize.
    ASSIGN
      tt-ar-FileSize.FileSize_Size = Ar_FileSize.FileSize_Size * Ar_FileSize.FileSize_RecordCount
      tt-ar-FileSize.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-FileSize.FileSize_EndTime = {&DAY_END_TIME}
      tt-ar-FileSize.FileSize_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-FileSize.
    ASSIGN
        tt-ar-FileSize.FileSize_Name = ar_FileSize.FileSize_Name
        tt-ar-FileSize.FileSize_Size = tt-ar-FileSize.FileSize_Size + (Ar_FileSize.FileSize_Size * Ar_FileSize.FileSize_RecordCount)
        tt-ar-FileSize.FileSize_Length = tt-ar-FileSize.FileSize_Length + ar_FileSize.FileSize_Length
        tt-ar-FileSize.FileSize_RecordCount = tt-ar-FileSize.FileSize_RecordCount + ar_FileSize.FileSize_RecordCount
        tt-ar-FileSize.FileSize_Transactions = tt-ar-FileSize.FileSize_Transactions + ar_FileSize.FileSize_Transactions.
    IF tt-ar-FileSize.Filesize_Max LT ar_FileSize.FileSize_Max
     THEN tt-ar-FileSize.Filesize_Max = ar_FileSize.FileSize_Size.
    IF tt-ar-FileSize.Filesize_Min = 0
     THEN tt-ar-FileSize.Filesize_Min = ar_FileSize.FileSize_Size.
    IF tt-ar-FileSize.Filesize_Min GT ar_FileSize.FileSize_Min
     THEN tt-ar-FileSize.Filesize_Min = ar_FileSize.FileSize_Size.
END PROCEDURE.
/* 
** ar_FileSys.p
**
** This include will archive the ar_FileSys rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-FileSys temp-table now defined with NO-UNDO
 - defined an index on tt-ar-FileSys table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_FileSys WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-FileSys NO-UNDO LIKE ar_FileSys
    INDEX myindex1 site_id resrc_id filesys_archivetype filesys_mount filesys_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-filesys.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

FOR EACH Ar_FileSys
    WHERE Ar_FileSys.FileSys_ArchiveType = "H"
      AND Ar_FileSys.FileSys_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-FileSys
        WHERE tt-ar-filesys.Site_Id = ar_filesys.site_id
          AND tt-ar-filesys.Resrc_Id = ar_filesys.Resrc_id
          AND tt-ar-FileSys.FileSys_archiveType = "D"
          AND tt-ar-FileSys.FileSys_Mount   = ar_FileSys.FileSys_Mount
          AND tt-ar-FileSys.FileSys_startDate = ar_FileSys.FileSys_startdate:
        RUN add-filesys.
    END.
    
    IF NOT AVAILABLE tt-ar-FileSys
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-filesys.filesys_StartDate = Ar_filesys.filesys_StartDate
            tt-ar-filesys.filesys_EndDate = Ar_filesys.filesys_EndDate
            tt-ar-filesys.filesys_archiveType = "D".
     END.
    RELEASE tt-ar-FileSys.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-FileSys
        WHERE tt-ar-filesys.Site_Id = ar_filesys.site_id
          AND tt-ar-filesys.Resrc_Id = ar_filesys.Resrc_id
          AND tt-ar-FileSys.FileSys_archiveType = "W"
          AND tt-ar-FileSys.FileSys_Mount   = ar_FileSys.FileSys_Mount
          AND ar_FileSys.FileSys_startdate GE tt-ar-FileSys.FileSys_startDate
          AND ar_FileSys.FileSys_startdate LE tt-ar-FileSys.FileSys_enddate:
        RUN add-filesys.
    END.
    
    IF NOT AVAILABLE tt-ar-FileSys
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-filesys.filesys_StartDate = Ar_filesys.filesys_StartDate - (WEEKDAY(Ar_filesys.filesys_StartDate) - 1)
            tt-ar-filesys.filesys_EndDate = tt-ar-filesys.filesys_StartDate + 6
            tt-ar-filesys.filesys_archiveType = "W".
     END.
    RELEASE tt-ar-FileSys.
END. /*  Of for each Ar_FileSys */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_FileSys */
    FOR EACH tt-ar-FileSys
        WHERE tt-ar-FileSys.FileSys_archiveType = "D":
        FOR FIRST ar_FileSys
            WHERE Ar_FileSys.FileSys_archiveType = "D"
              AND tt-ar-filesys.Site_Id = ar_filesys.site_id
              AND tt-ar-filesys.Resrc_Id = ar_filesys.Resrc_id
              AND tt-ar-FileSys.FileSys_Mount   = ar_FileSys.FileSys_Mount
              AND tt-ar-FileSys.FileSys_startDate = ar_FileSys.FileSys_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_FileSys
         THEN DO TRANSACTION:
                 CREATE Ar_FileSys.
                 ASSIGN
                    tt-Ar-FileSys.FileSys_UsedPct = tt-Ar-FileSys.FileSys_UsedPct / tt-Ar-FileSys.FileSys_Length
                    tt-Ar-FileSys.FileSys_Avail   = tt-Ar-FileSys.FileSys_Avail / tt-Ar-FileSys.FileSys_RecordCount.
                 BUFFER-COPY tt-ar-FileSys TO Ar_FileSys.
                 RELEASE Ar_FileSys.
         END.
    END.
        
    /* Write out db_FileSys */
    FOR EACH tt-ar-FileSys
        WHERE tt-ar-FileSys.FileSys_archiveType = "W":
        FOR FIRST ar_FileSys
            WHERE Ar_FileSys.FileSys_archiveType = "W" 
              AND tt-ar-filesys.Site_Id = ar_filesys.site_id
              AND tt-ar-filesys.Resrc_Id = ar_filesys.Resrc_id
              AND tt-ar-FileSys.FileSys_Mount   = ar_FileSys.FileSys_Mount
              AND ar_FileSys.FileSys_startdate GE tt-ar-FileSys.FileSys_startDate
              AND ar_FileSys.FileSys_startdate LE tt-ar-FileSys.FileSys_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_FileSys
         THEN DO TRANSACTION:
                 CREATE Ar_FileSys.
                 ASSIGN
                    tt-Ar-FileSys.FileSys_UsedPct = tt-Ar-FileSys.FileSys_UsedPct /
                                                    tt-Ar-FileSys.FileSys_Length
                    tt-Ar-FileSys.FileSys_Avail   = tt-Ar-FileSys.FileSys_Avail /
                                                    tt-Ar-FileSys.FileSys_RecordCount.
                 BUFFER-COPY tt-ar-FileSys TO Ar_FileSys.
                 RELEASE Ar_FileSys.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-FileSys.
    BUFFER-COPY ar_FileSys TO tt-ar-FileSys.
    ASSIGN
        tt-ar-FileSys.FileSys_Avail   = Ar_FileSys.FileSys_Avail * Ar_FileSys.FileSys_RecordCount
        tt-ar-FileSys.FileSys_UsedPct = Ar_FileSys.FileSys_Length * Ar_FileSys.FileSys_UsedPct
        tt-ar-FileSys.sample_id = NEXT-VALUE(ar_sample-seq)
        tt-ar-FileSys.FileSys_EndTime = {&DAY_END_TIME}
        tt-ar-FileSys.FileSys_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-FileSys.
    IF tt-ar-FileSys.FileSys_Capacity = 0
     THEN tt-ar-FileSys.FileSys_Capacity = ar_FileSys.FileSys_Capacity.
    IF tt-ar-FileSys.FileSys_Capacity LT ar_FileSys.FileSys_Capacity
     THEN tt-ar-FileSys.FileSys_Capacity = ar_FileSys.FileSys_Capacity.
    ASSIGN
        tt-ar-FileSys.FileSys_Avail   = tt-ar-FileSys.FileSys_Avail + (Ar_FileSys.FileSys_Avail * Ar_FileSys.FileSys_RecordCount)
        tt-ar-FileSys.FileSys_Mount   = ar_FileSys.FileSys_Mount
        tt-ar-FileSys.FileSys_Name    = ar_FileSys.FileSys_Name
        tt-ar-FileSys.FileSys_UsedPct = tt-ar-FileSys.FileSys_UsedPct + (Ar_FileSys.FileSys_Length * Ar_FileSys.FileSys_UsedPct)
        tt-ar-FileSys.FileSys_Length = tt-ar-FileSys.FileSys_Length + ar_FileSys.FileSys_Length
        tt-ar-FileSys.FileSys_RecordCount = tt-ar-FileSys.FileSys_RecordCount + ar_FileSys.FileSys_RecordCount
        tt-ar-FileSys.FileSys_Transactions = tt-ar-FileSys.FileSys_Transactions + ar_FileSys.FileSys_Transactions.
END PROCEDURE.
/* 
** Ar-new-actapw.p
** This include will archive the db_actapw rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActAPW definition
 - added an index on tt-DB_ActAPW table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - fixed WHERE clause for AR_ActAPW query to refer to AR_ActAPW not to temp-table
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_ActAPW
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_ActAPW NO-UNDO LIKE Ar_ActAPW
    INDEX myindex1 actapw_archivetype Site_Id resrc_id actapw_startDate actapw_starttime actapw_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_ActAPW WHERE Db_ActAPW.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    IF AVAILABLE Db_ActAPW
     THEN DO:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actapw"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-dB_Actapw
             WHERE tt-Db_ActAPW.ActAPW_archiveType = "H"
               AND tt-Db_ActAPW.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_ActAPW.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_ActAPW.ActAPW_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_ActAPW.ActAPW_StartTime = s-beg-time
               AND tt-Db_ActAPW.ActAPW_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_ActAPW
         THEN ASSIGN
                tt-Db_ActAPW.ActAPW_APWEnq       = tt-Db_ActAPW.ActAPW_APWEnq      + Db_ActAPW.ActAPW_APWEnq      
                tt-Db_ActAPW.ActAPW_APWQWrites   = tt-Db_ActAPW.ActAPW_APWQWrites  + Db_ActAPW.ActAPW_APWQWrites 
                tt-Db_ActAPW.ActAPW_BufsCkpt     = tt-Db_ActAPW.ActAPW_BufsCkpt    + Db_ActAPW.ActAPW_BufsCkpt    
                tt-Db_ActAPW.ActAPW_BufsScanned  = tt-Db_ActAPW.ActAPW_BufsScanned + Db_ActAPW.ActAPW_BufsScanned
                tt-Db_ActAPW.ActAPW_CkptQWrites  = tt-Db_ActAPW.ActAPW_CkptQWrites + Db_ActAPW.ActAPW_CkptQWrites 
                tt-Db_ActAPW.ActAPW_Ckpts        = tt-Db_ActAPW.ActAPW_Ckpts       + Db_ActAPW.ActAPW_Ckpts       
                tt-Db_ActAPW.ActAPW_DBWrites     = tt-Db_ActAPW.ActAPW_DBWrites    + Db_ActAPW.ActAPW_DBWrites    
                tt-Db_ActAPW.ActAPW_Flushed      = tt-Db_ActAPW.ActAPW_Flushed     + Db_ActAPW.ActAPW_Flushed     
                tt-Db_ActAPW.ActAPW_Marked       = tt-Db_ActAPW.ActAPW_Marked      + Db_ActAPW.ActAPW_Marked      
                tt-Db_ActAPW.ActAPW_ScanCycles   = tt-Db_ActAPW.ActAPW_ScanCycles  + Db_ActAPW.ActAPW_ScanCycles  
                tt-Db_ActAPW.ActAPW_ScanWrites   = tt-Db_ActAPW.ActAPW_ScanWrites  + Db_ActAPW.ActAPW_ScanWrites  
                tt-Db_ActAPW.ActAPW_TotDBWrites  = tt-Db_ActAPW.ActAPW_TotDBWrites + Db_ActAPW.ActAPW_TotDBWrites
                tt-Db_ActAPW.ActAPW_RecordCount  = tt-Db_ActAPW.ActAPW_RecordCount + 1
                tt-db_ActAPW.actapw_length       = tt-db_ActAPW.actapw_Length + Cf_Sample.Sample_len
                tt-Db_ActAPW.ActAPW_Transactions = tt-Db_ActAPW.ActAPW_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
            CREATE tt-Db_actapw.
            BUFFER-COPY Db_ActAPW EXCEPT Db_ActAPW.Sample_ID TO tt-db_actapw.
            ASSIGN
                tt-Db_actapw.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_ActAPW.ActAPW_archiveType  = "H" 
                tt-Db_ActAPW.ActAPW_EndDate      = Cf_Sample.Sample_Date
                tt-Db_ActAPW.ActAPW_StartDate    = Cf_Sample.Sample_Date
                tt-Db_ActAPW.Site_ID             = Cf_Sample.Site_ID
                tt-Db_ActAPW.Resrc_ID            = Cf_Sample.Resrc_ID
                tt-Db_ActAPW.ActAPW_EndTime      = s-end-time
                tt-Db_ActAPW.ActAPW_StartTime    = s-beg-time 
                tt-Db_ActAPW.ActAPW_RecordCount  = tt-Db_ActAPW.ActAPW_RecordCount + 1
                tt-db_ActAPW.actapw_length       = tt-db_ActAPW.actapw_Length + Cf_Sample.Sample_len
                tt-Db_ActAPW.ActAPW_Transactions = tt-Db_ActAPW.ActAPW_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_ActAPW THEN */
END. /* FOE EACH W-Table BY w-time BY w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actapw
    WHERE tt-db_actapw.actapw_archiveType = "H":
   
       IF NOT CAN-FIND (FIRST Ar_ActAPW WHERE 
           Ar_ActAPW.ActAPW_archiveType  = "H" AND
           Ar_ActAPW.Site_ID          = tt-Db_ActAPW.Site_ID AND
           Ar_ActAPW.Resrc_ID         = tt-Db_ActAPW.Resrc_ID AND
           Ar_ActAPW.ActAPW_StartDate = tt-Db_ActAPW.ActAPW_StartDate AND 
           Ar_ActAPW.ActAPW_StartTime = tt-Db_ActAPW.ActAPW_StartTime AND 
           Ar_ActAPW.ActAPW_EndTime   = tt-Db_ActAPW.ActAPW_EndTime)
         THEN DO:
                CREATE Ar_ActAPW.
                BUFFER-COPY tt-db_ActAPW TO Ar_ActAPW.
                RELEASE AR_ActAPW.
                write-count = write-count + 1.
         END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActAPW table : " write-count.

RUN delete-Db_ActAPW.
/* 
** Ar-h-actbuf.p
**
** This include will archive the db_actbuf rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActBuf definition
 - added an index on tt-DB_ActBuf table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActBuf
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actbuf NO-UNDO LIKE Ar_actbuf
    INDEX myindex1 actbuf_archiveType site_id resrc_id actbuf_StartDate actbuf_StartTime actbuf_EndTime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_actbuf WHERE Db_actbuf.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    IF AVAILABLE Db_actbuf
     THEN DO:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actbuf"}
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */

        FIND FIRST tt-dB_actbuf
             WHERE tt-Db_actbuf.actbuf_archiveType = "H"
               AND tt-Db_actbuf.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_actbuf.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_actbuf.actbuf_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_actbuf.actbuf_StartTime = s-beg-time
               AND tt-Db_actbuf.actbuf_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_actbuf
         THEN ASSIGN
                tt-Db_ActBuf.ActBuf_Deferred = tt-Db_ActBuf.ActBuf_Deferred + Db_ActBuf.ActBuf_Deferred                      
                tt-Db_ActBuf.ActBuf_Flushed = tt-Db_ActBuf.ActBuf_Flushed + Db_ActBuf.ActBuf_Flushed
                tt-Db_ActBuf.ActBuf_LogicReads = tt-Db_ActBuf.ActBuf_LogicReads + Db_ActBuf.ActBuf_LogicReads
                tt-Db_ActBuf.ActBuf_LogicWrites = tt-Db_ActBuf.ActBuf_LogicWrites + Db_ActBuf.ActBuf_LogicWrites
                tt-Db_ActBuf.ActBuf_OSReads = tt-Db_ActBuf.ActBuf_OSReads + Db_ActBuf.ActBuf_OSReads
                tt-Db_ActBuf.ActBuf_OSWrites = tt-Db_ActBuf.ActBuf_OSWrites + Db_ActBuf.ActBuf_OSWrites
                tt-Db_actbuf.actbuf_RecordCount = tt-Db_actbuf.actbuf_RecordCount + 1
                tt-db_actbuf.actbuf_length = tt-db_actbuf.actbuf_Length + Cf_Sample.Sample_len
                tt-Db_actbuf.actbuf_Transactions = tt-Db_actbuf.actbuf_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_actbuf.
              BUFFER-COPY Db_actbuf EXCEPT Db_actbuf.Sample_ID TO tt-db_actbuf.
              ASSIGN
                tt-Db_actbuf.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_actbuf.actbuf_archiveType = "H" 
                tt-Db_actbuf.actbuf_EndDate = Cf_Sample.Sample_Date
                tt-Db_actbuf.actbuf_StartDate = Cf_Sample.Sample_Date
                tt-Db_actbuf.Site_ID = Cf_Sample.Site_ID
                tt-Db_actbuf.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_actbuf.actbuf_EndTime = s-end-time
                tt-Db_actbuf.actbuf_StartTime = s-beg-time 
                tt-Db_actbuf.actbuf_RecordCount = tt-Db_actbuf.actbuf_RecordCount + 1
                tt-db_actbuf.actbuf_length = tt-db_actbuf.actbuf_Length + Cf_Sample.Sample_len
                tt-Db_actbuf.actbuf_Transactions = tt-Db_actbuf.actbuf_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_actbuf THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actbuf
    WHERE tt-db_actbuf.actbuf_archiveType = "H":

       IF NOT CAN-FIND(FIRST Ar_actbuf WHERE
           Ar_actbuf.actbuf_archiveType = "H" AND
           Ar_actbuf.Site_ID            = tt-Db_ActBuf.Site_ID AND
           Ar_actbuf.Resrc_ID           = tt-Db_ActBuf.Resrc_ID AND
           Ar_actbuf.actbuf_StartDate   = tt-Db_ActBuf.actbuf_StartDate AND
           Ar_actbuf.actbuf_StartTime   = tt-Db_ActBuf.actbuf_StartTime AND
           Ar_actbuf.actbuf_EndTime     = tt-Db_ActBuf.actbuf_EndTime)
        THEN DO:
               CREATE Ar_actbuf.
               BUFFER-COPY tt-db_actbuf TO Ar_actbuf.
               RELEASE AR_actbuf.
               write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActBuf table : " write-count.

RUN delete-Db_ActBuf.
/* 
** Ar-h-actidx.p
**
** This include will archive the db_actidx rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActIdx definition
 - added an index on tt-DB_ActIdx table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActIdx
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actidx NO-UNDO LIKE Ar_actidx
    INDEX myindex actidx_archivetype site_id resrc_id actidx_enddate actidx_starttime actidx_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_actidx WHERE Db_actidx.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    
    IF AVAILABLE Db_actidx 
     THEN DO:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actidx"}       
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */

        FIND FIRST tt-dB_Actidx
             WHERE tt-Db_actidx.actidx_archiveType = "H"
               AND tt-Db_actidx.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_actidx.Resrc_ID = Cf_Sample.Resrc_ID 
               AND tt-Db_actidx.actidx_EndDate = Cf_Sample.Sample_Date
               AND tt-Db_actidx.actidx_StartTime = s-beg-time
               AND tt-Db_actidx.actidx_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_actidx
         THEN ASSIGN
                tt-Db_ActIdx.ActIdx_Create = tt-Db_ActIdx.ActIdx_Create + Db_ActIdx.ActIdx_Create                            
                tt-Db_ActIdx.ActIdx_Delete = tt-Db_ActIdx.ActIdx_Delete + Db_ActIdx.ActIdx_Delete
                tt-Db_ActIdx.ActIdx_Find = tt-Db_ActIdx.ActIdx_Find + Db_ActIdx.ActIdx_Find
                tt-Db_ActIdx.ActIdx_Free = tt-Db_ActIdx.ActIdx_Free + Db_ActIdx.ActIdx_Free
                tt-Db_ActIdx.ActIdx_Remove = tt-Db_ActIdx.ActIdx_Remove + Db_ActIdx.ActIdx_Remove
                tt-Db_ActIdx.ActIdx_Splits = tt-Db_ActIdx.ActIdx_Splits + Db_ActIdx.ActIdx_Splits
                tt-Db_actidx.actidx_RecordCount = tt-Db_actidx.actidx_RecordCount + 1
                tt-db_actidx.actidx_length = tt-db_actidx.actidx_Length + Cf_Sample.Sample_len
                tt-Db_actidx.actidx_Transactions = tt-Db_actidx.actidx_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_actidx.
              BUFFER-COPY Db_actidx EXCEPT Db_actidx.Sample_ID TO tt-db_actidx.
              ASSIGN
                tt-Db_actidx.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_actidx.actidx_archiveType = "H" 
                tt-Db_actidx.actidx_EndDate = Cf_Sample.Sample_Date
                tt-Db_actidx.actidx_StartDate = Cf_Sample.Sample_Date
                tt-Db_actidx.Site_ID = Cf_Sample.Site_ID
                tt-Db_actidx.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_actidx.actidx_EndTime = s-end-time
                tt-Db_actidx.actidx_StartTime = s-beg-time 
                tt-Db_actidx.actidx_RecordCount = tt-Db_actidx.actidx_RecordCount + 1
                tt-db_actidx.actidx_length = tt-db_actidx.actidx_Length + Cf_Sample.Sample_len
                tt-Db_actidx.actidx_Transactions = tt-Db_actidx.actidx_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_actidx THEN */
END. /* FOR EACH W-Table BY w-time BY w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actidx 
    WHERE tt-db_actidx.actidx_archiveType = "H":

        IF NOT CAN-FIND (FIRST Ar_actidx WHERE
            Ar_actidx.actidx_archiveType = "H" AND
	        Ar_actidx.Site_ID            = tt-Db_ActIdx.Site_ID AND
            Ar_actidx.Resrc_ID           = tt-Db_ActIdx.Resrc_ID AND
            Ar_actidx.actidx_StartDate   = tt-Db_actidx.actidx_StartDate AND
            Ar_actidx.actidx_StartTime   = tt-Db_actidx.actidx_StartTime AND
            Ar_actidx.actidx_EndTime     = tt-Db_actidx.actidx_EndTime)
        THEN DO:
             CREATE Ar_actidx.
             BUFFER-COPY tt-db_actidx TO Ar_actidx.
             RELEASE AR_actidx.
             write-count = write-count + 1.
        END.
END.
IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Compaction Records Written for Db_ActIdx table : " write-count.

RUN delete-Db_Actidx.
/* 
** Ar-h-actiofile.p
**
actiofile = all lower case
actiofile = upper and lower
zzz = Db_
**
** This include will archive the db_actiofile rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActIOFile definition
 - added an index on tt-DB_ActIOFile table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - grouped the FOR EACH, FIND FIRST & FOR EACH, into FOR EACH, FIRST, EACH loop
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - fixed WHERE clause for AR_ActIOFile query to refer to AR_ActIOFile not to temp-table 
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActIOFile
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actiofile NO-UNDO LIKE Ar_actiofile
    INDEX myindex1 actiofile_archivetype site_id resrc_id actiofile_filename actiofile_startdate actiofile_starttime actiofile_endtime.

FOR EACH W-Table NO-LOCK,
    FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK,
    EACH Db_ActIOFile WHERE Db_actiofile.Sample_ID = Cf_Sample.Sample_ID NO-LOCK
    BY w-time BY w-date:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actiofile"}       
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.
           If it doesn't exist then create a new one. */

        FIND FIRST tt-dB_actiofile
             WHERE tt-Db_actiofile.actiofile_archiveType = "H"
               AND tt-Db_actiofile.Site_ID               = Cf_Sample.Site_ID
               AND tt-Db_actiofile.Resrc_ID              = Cf_Sample.Resrc_ID
               AND tt-Db_actiofile.actiofile_filename    = db_actiofile.actiofile_filename
               AND tt-Db_actiofile.actiofile_StartDate   = Cf_Sample.Sample_Date 
               AND tt-Db_actiofile.actiofile_StartTime   = s-beg-time
               AND tt-Db_actiofile.actiofile_EndTime     = s-end-time
         NO-LOCK NO-ERROR.

        IF AVAILABLE tt-Db_ActIOFile
         THEN ASSIGN
              tt-Db_ActIOFile.ActIOFile_BufReads     = tt-Db_ActIOFile.ActIOFile_BufReads + Db_ActIOFile.ActIOFile_BufReads
              tt-Db_ActIOFile.ActIOFile_BufWrites    = tt-Db_ActIOFile.ActIOFile_BufWrites + Db_ActIOFile.ActIOFile_BufWrites
              tt-Db_ActIOFile.ActIOFile_Extends      = tt-Db_ActIOFile.ActIOFile_Extends + Db_ActIOFile.ActIOFile_Extends
              tt-Db_ActIOFile.ActIOFile_Reads        = tt-Db_ActIOFile.ActIOFile_Reads + Db_ActIOFile.ActIOFile_Reads
              tt-Db_ActIOFile.ActIOFile_UnbufReads   = tt-Db_ActIOFile.ActIOFile_UnbufReads + Db_ActIOFile.ActIOFile_UnbufReads
              tt-Db_ActIOFile.ActIOFile_UnbufWrites  = tt-Db_ActIOFile.ActIOFile_UnbufWrites + Db_ActIOFile.ActIOFile_UnbufWrites
              tt-Db_ActIOFile.ActIOFile_Writes       = tt-Db_ActIOFile.ActIOFile_Writes + Db_ActIOFile.ActIOFile_Writes
              tt-Db_actiofile.actiofile_RecordCount  = tt-Db_actiofile.actiofile_RecordCount + 1
              tt-db_actiofile.actiofile_length       = tt-db_actiofile.actiofile_Length + Cf_Sample.Sample_len
              tt-Db_actiofile.actiofile_Transactions = tt-Db_actiofile.actiofile_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
                CREATE tt-Db_actiofile.
                BUFFER-COPY Db_actiofile EXCEPT Db_actiofile.Sample_ID TO tt-db_actiofile.
                ASSIGN
                  tt-Db_actiofile.sample_id              = NEXT-VALUE (ar_sample-seq)
                  tt-Db_actiofile.actiofile_archiveType  = "H" 
                  tt-Db_actiofile.actiofile_EndDate      = Cf_Sample.Sample_Date
                  tt-Db_actiofile.actiofile_StartDate    = Cf_Sample.Sample_Date
                  tt-Db_actiofile.Site_ID                = Cf_Sample.Site_ID
                  tt-Db_actiofile.Resrc_ID               = Cf_Sample.Resrc_ID
                  tt-Db_actiofile.actiofile_EndTime      = s-end-time
                  tt-Db_actiofile.actiofile_StartTime    = s-beg-time 
                  tt-Db_actiofile.actiofile_RecordCount  = tt-Db_actiofile.actiofile_RecordCount + 1
                  tt-db_actiofile.actiofile_length       = tt-db_actiofile.actiofile_Length + Cf_Sample.Sample_len
                  tt-Db_actiofile.actiofile_Transactions = tt-Db_actiofile.actiofile_Transactions + Cf_Sample.Sample_Trans
                                                new-recs = new-recs + 1.
         END. /* IF AVAIL */

END. /* FOR EACH */

/*  Write out the records */
write-count = 0.
FOR EACH tt-db_actiofile WHERE tt-db_actiofile.actiofile_archiveType = "H" NO-LOCK:

    IF NOT CAN-FIND(FIRST Ar_actiofile
        WHERE Ar_actiofile.actiofile_archiveType = "H"
          AND Ar_actiofile.Site_ID               = tt-Db_ActIOFile.Site_ID
          AND Ar_actiofile.Resrc_ID              = tt-Db_ActIOFile.Resrc_ID
          AND Ar_actiofile.actiofile_filename    = tt-Db_ActIOFile.actiofile_filename
          AND Ar_actiofile.actiofile_StartDate   = tt-Db_ActIOFile.actiofile_StartDate
          AND Ar_actiofile.actiofile_StartTime   = tt-Db_ActIOFile.actiofile_StartTime
          AND Ar_actiofile.actiofile_EndTime     = tt-Db_ActIOFile.actiofile_EndTime)
      THEN DO:
              CREATE Ar_actiofile.
              BUFFER-COPY tt-db_actiofile TO Ar_actiofile.
              RELEASE AR_actiofile.
              write-count = write-count + 1.
       END. /* IF NOT CAN-FIND */

END. /* FOR EACH */
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActIOFile table : " write-count.

RUN delete-Db_ActIOFile.
/* 
** Ar-new-actiotype.p
** This include will archive the db_actiotype rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActIOType definition
 - added an index on tt-DB_ActIOType to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - fixed WHERE clause for AR_ActIOFile query to refer to AR_ActIOFile not to temp-table  
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActIOType
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_Actiotype NO-UNDO LIKE Ar_Actiotype
    INDEX myindex1 actiotype_archivetype site_id resrc_id actiotype_startdate actiotype_starttime actiotype_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_Actiotype WHERE Db_Actiotype.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    
    IF AVAILABLE Db_Actiotype
     THEN DO:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actiotype"}       
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */

        FIND FIRST tt-dB_Actiotype
             WHERE tt-Db_Actiotype.Actiotype_archiveType = "H"
               AND tt-Db_Actiotype.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_Actiotype.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_Actiotype.Actiotype_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_Actiotype.Actiotype_StartTime = s-beg-time
               AND tt-Db_Actiotype.Actiotype_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_Actiotype
         THEN ASSIGN
                tt-Db_ActIOType.ActIOType_AiReads = tt-Db_ActIOType.ActIOType_AiReads + Db_ActIOType.ActIOType_AiReads
                tt-Db_ActIOType.ActIOType_AiWrites = tt-Db_ActIOType.ActIOType_AiWrites + Db_ActIOType.ActIOType_AiWrites
                tt-Db_ActIOType.ActIOType_BiReads = tt-Db_ActIOType.ActIOType_BiReads + Db_ActIOType.ActIOType_BiReads
                tt-Db_ActIOType.ActIOType_BiWrites = tt-Db_ActIOType.ActIOType_BiWrites + Db_ActIOType.ActIOType_BiWrites 
                tt-Db_ActIOType.ActIOType_DataReads = tt-Db_ActIOType.ActIOType_DataReads + Db_ActIOType.ActIOType_DataReads
                tt-Db_ActIOType.ActIOType_DataWrites = tt-Db_ActIOType.ActIOType_DataWrites + Db_ActIOType.ActIOType_DataWrites
                tt-Db_ActIOType.ActIOType_IdxReads = tt-Db_ActIOType.ActIOType_IdxReads + Db_ActIOType.ActIOType_IdxReads
                tt-Db_ActIOType.ActIOType_IdxWrites = tt-Db_ActIOType.ActIOType_IdxWrites + Db_ActIOType.ActIOType_IdxWrites
                tt-Db_Actiotype.Actiotype_RecordCount = tt-Db_Actiotype.Actiotype_RecordCount + 1
                tt-db_Actiotype.actiotype_length = tt-db_Actiotype.actiotype_Length + Cf_Sample.Sample_len
                tt-Db_Actiotype.Actiotype_Transactions = tt-Db_Actiotype.Actiotype_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_actiotype.
              BUFFER-COPY Db_Actiotype EXCEPT Db_Actiotype.Sample_ID TO tt-db_actiotype.
              ASSIGN
                tt-Db_actiotype.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_Actiotype.Actiotype_archiveType = "H" 
                tt-Db_Actiotype.Actiotype_EndDate = Cf_Sample.Sample_Date
                tt-Db_Actiotype.Actiotype_StartDate = Cf_Sample.Sample_Date
                tt-Db_Actiotype.Site_ID = Cf_Sample.Site_ID
                tt-Db_Actiotype.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_Actiotype.Actiotype_EndTime = s-end-time
                tt-Db_Actiotype.Actiotype_StartTime = s-beg-time 
                tt-Db_Actiotype.Actiotype_RecordCount = tt-Db_Actiotype.Actiotype_RecordCount + 1
                tt-db_Actiotype.actiotype_length = tt-db_Actiotype.actiotype_Length + Cf_Sample.Sample_len
                tt-Db_Actiotype.Actiotype_Transactions = tt-Db_Actiotype.Actiotype_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_Actiotype THEN */
END. /* FOR EACH W-Table BY w-time BY w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actiotype 
    WHERE tt-db_actiotype.actiotype_archiveType = "H":
    
       IF NOT CAN-FIND (FIRST Ar_Actiotype WHERE 
            Ar_Actiotype.Actiotype_archiveType  = "H" AND
            Ar_Actiotype.Site_ID                = tt-Db_ActIOType.Site_ID AND
            Ar_Actiotype.Resrc_ID               = tt-Db_ActIOType.Resrc_ID AND
            Ar_Actiotype.Actiotype_StartDate    = tt-Db_ActIOType.Actiotype_StartDate AND
            Ar_Actiotype.Actiotype_StartTime    = tt-Db_ActIOType.Actiotype_StartTime AND
            Ar_Actiotype.Actiotype_EndTime      = tt-Db_ActIOType.Actiotype_EndTime)
       THEN DO:
            CREATE Ar_Actiotype.
            BUFFER-COPY tt-db_Actiotype TO Ar_Actiotype.
            RELEASE AR_Actiotype.
            write-count = write-count + 1.
       END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActIOType table : " write-count.

RUN delete-Db_ActIOType.
/* 
** Ar-h-actlock.p
** This include will archive the db_actlock rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActLock definition
 - added an index on tt-DB_ActLock table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing 
 - fixed WHERE clause for AR_ActLock query to refer to AR_ActLock not to temp-table  
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActLock
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actlock NO-UNDO LIKE Ar_actlock
    INDEX myindex1 actlock_archivetype site_id resrc_id actlock_enddate actlock_starttime actlock_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_actlock WHERE Db_actlock.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    
    IF AVAILABLE Db_actlock
     THEN DO:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actlock"}       
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */

        FIND FIRST tt-Db_actlock
             WHERE tt-Db_actlock.actlock_archiveType = "H"
               AND tt-Db_actlock.Site_ID  = Cf_Sample.Site_ID 
               AND tt-Db_actlock.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_actlock.actlock_EndDate   = Cf_Sample.Sample_Date
               AND tt-Db_actlock.actlock_StartTime = s-beg-time 
               AND tt-Db_actlock.actlock_EndTime   = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_actlock
         THEN ASSIGN
                tt-Db_ActLock.ActLock_CanclReq = tt-Db_ActLock.ActLock_CanclReq + Db_ActLock.ActLock_CanclReq
                tt-Db_ActLock.ActLock_Downgrade = tt-Db_ActLock.ActLock_Downgrade + Db_ActLock.ActLock_Downgrade
                tt-Db_ActLock.ActLock_ExclFind = tt-Db_ActLock.ActLock_ExclFind + Db_ActLock.ActLock_ExclFind
                tt-Db_ActLock.ActLock_ExclLock = tt-Db_ActLock.ActLock_ExclLock + Db_ActLock.ActLock_ExclLock
                tt-Db_ActLock.ActLock_ExclReq = tt-Db_ActLock.ActLock_ExclReq + Db_ActLock.ActLock_ExclReq
                tt-Db_ActLock.ActLock_ExclWait = tt-Db_ActLock.ActLock_ExclWait + Db_ActLock.ActLock_ExclWait
                tt-Db_ActLock.ActLock_RecGetLock = tt-Db_ActLock.ActLock_RecGetLock + Db_ActLock.ActLock_RecGetLock
                tt-Db_ActLock.ActLock_RecGetReq = tt-Db_ActLock.ActLock_RecGetReq + Db_ActLock.ActLock_RecGetReq
                tt-Db_ActLock.ActLock_RecGetWait = tt-Db_ActLock.ActLock_RecGetWait + Db_ActLock.ActLock_RecGetWait
                tt-Db_ActLock.ActLock_ShrFind = tt-Db_ActLock.ActLock_ShrFind + Db_ActLock.ActLock_ShrFind
                tt-Db_ActLock.ActLock_ShrLock = tt-Db_ActLock.ActLock_ShrLock + Db_ActLock.ActLock_ShrLock
                tt-Db_ActLock.ActLock_ShrReq = tt-Db_ActLock.ActLock_ShrReq + Db_ActLock.ActLock_ShrReq
                tt-Db_ActLock.ActLock_ShrWait = tt-Db_ActLock.ActLock_ShrWait + Db_ActLock.ActLock_ShrWait
                tt-Db_ActLock.ActLock_UpgLock = tt-Db_ActLock.ActLock_UpgLock + Db_ActLock.ActLock_UpgLock
                tt-Db_ActLock.ActLock_UpgReq = tt-Db_ActLock.ActLock_UpgReq + Db_ActLock.ActLock_UpgReq
                tt-Db_ActLock.ActLock_UpgWait = tt-Db_ActLock.ActLock_UpgWait + Db_ActLock.ActLock_UpgWait
                tt-Db_actlock.actlock_RecordCount = tt-Db_actlock.actlock_RecordCount + 1
                tt-db_actlock.actlock_length = tt-db_actlock.actlock_Length + Cf_Sample.Sample_len
                tt-Db_actlock.actlock_Transactions = tt-Db_actlock.actlock_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_actlock.
              BUFFER-COPY Db_actlock EXCEPT Db_actlock.Sample_ID TO tt-db_actlock.
              ASSIGN
                tt-Db_actlock.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_actlock.actlock_archiveType = "H" 
                tt-Db_actlock.actlock_EndDate = Cf_Sample.Sample_Date
                tt-Db_actlock.actlock_StartDate = Cf_Sample.Sample_Date
                tt-Db_actlock.Site_ID = Cf_Sample.Site_ID
                tt-Db_actlock.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_actlock.actlock_EndTime = s-end-time
                tt-Db_actlock.actlock_StartTime = s-beg-time 
                tt-Db_actlock.actlock_RecordCount = tt-Db_actlock.actlock_RecordCount + 1
                tt-db_actlock.actlock_length = tt-db_actlock.actlock_Length + Cf_Sample.Sample_len
                tt-Db_actlock.actlock_Transactions = tt-Db_actlock.actlock_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /*  IF AVAILABLE Db_actlock THEN */
END. /* FOR EACH W-Table BY w-time BY w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actlock 
    WHERE tt-db_actlock.actlock_archiveType = "H":
       
      IF NOT CAN-FIND (FIRST Ar_actlock
           WHERE Ar_actlock.actlock_archiveType  = "H"
             AND Ar_actlock.Site_ID              = tt-Db_ActLock.Site_ID
             AND Ar_actlock.Resrc_ID             = tt-Db_ActLock.Resrc_ID
             AND Ar_actlock.actlock_StartDate    = tt-Db_actlock.actlock_StartDate
             AND Ar_actlock.actlock_StartTime    = tt-Db_actlock.actlock_StartTime
             AND Ar_actlock.actlock_EndTime      = tt-Db_actlock.actlock_EndTime)
       THEN DO:
            CREATE Ar_actlock.
            BUFFER-COPY tt-db_actlock TO Ar_actlock.
            RELEASE AR_actlock.
            write-count = write-count + 1.
       END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActLock table : " write-count.
  
RUN delete-Db_ActLock.
/* 
** Ar-h-actlog.p
**
** This include will archive the db_actlog rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActLog definition
 - added an index on tt-DB_ActLog table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_ActLog query to refer to AR_ActLog not to temp-table  
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActLog
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actlog NO-UNDO LIKE Ar_actlog
    INDEX myindex1 actlog_archivetype site_id resrc_id actlog_enddate actlog_starttime actlog_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_actlog WHERE Db_actlog.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.

    IF AVAILABLE Db_actlog
     THEN DO:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actlog"}       
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */

        FIND FIRST tt-dB_actlog
             WHERE tt-Db_actlog.actlog_archiveType = "H"
               AND tt-Db_actlog.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_actlog.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_actlog.actlog_EndDate = Cf_Sample.Sample_Date
               AND tt-Db_actlog.actlog_StartTime = s-beg-time
               AND tt-Db_actlog.actlog_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_actlog
         THEN ASSIGN
                tt-Db_ActLog.ActLog_AIBBufWaits = tt-Db_ActLog.ActLog_AIBBufWaits + Db_ActLog.ActLog_AIBBufWaits
                tt-Db_ActLog.ActLog_AIByteWrites = tt-Db_ActLog.ActLog_AIByteWrites + Db_ActLog.ActLog_AIByteWrites
                tt-Db_ActLog.ActLog_AINoBufAvail = tt-Db_ActLog.ActLog_AINoBufAvail + Db_ActLog.ActLog_AINoBufAvail
                tt-Db_ActLog.ActLog_AIPartialWrites = tt-Db_ActLog.ActLog_AIPartialWrites + Db_ActLog.ActLog_AIPartialWrites
                tt-Db_ActLog.ActLog_AIRecWrites = tt-Db_ActLog.ActLog_AIRecWrites + Db_ActLog.ActLog_AIRecWrites
                tt-Db_ActLog.ActLog_AITotWrites = tt-Db_ActLog.ActLog_AITotWrites + Db_ActLog.ActLog_AITotWrites
                tt-Db_ActLog.ActLog_AIWWrites = tt-Db_ActLog.ActLog_AIWWrites + Db_ActLog.ActLog_AIWWrites
                tt-Db_ActLog.ActLog_BIBBufWaits = tt-Db_ActLog.ActLog_BIBBufWaits + Db_ActLog.ActLog_BIBBufWaits
                tt-Db_ActLog.ActLog_BIByteReads = tt-Db_ActLog.ActLog_BIByteReads + Db_ActLog.ActLog_BIByteReads
                tt-Db_ActLog.ActLog_BIByteWrites = tt-Db_ActLog.ActLog_BIByteWrites + Db_ActLog.ActLog_BIByteWrites
                tt-Db_ActLog.ActLog_BIEBufWaits = tt-Db_ActLog.ActLog_BIEBufWaits + Db_ActLog.ActLog_BIEBufWaits
                tt-Db_ActLog.ActLog_BIPartialWrites = tt-Db_ActLog.ActLog_BIPartialWrites + Db_ActLog.ActLog_BIPartialWrites
                tt-Db_ActLog.ActLog_BIRecReads = tt-Db_ActLog.ActLog_BIRecReads + Db_ActLog.ActLog_BIRecReads
                tt-Db_ActLog.ActLog_BIRecWrites = tt-Db_ActLog.ActLog_BIRecWrites + Db_ActLog.ActLog_BIRecWrites
                tt-Db_ActLog.ActLog_BITotReads = tt-Db_ActLog.ActLog_BITotReads + Db_ActLog.ActLog_BITotReads
                tt-Db_ActLog.ActLog_BITotWrites = tt-Db_ActLog.ActLog_BITotWrites + Db_ActLog.ActLog_BITotWrites
                tt-Db_ActLog.ActLog_BIWWrites = tt-Db_ActLog.ActLog_BIWWrites + Db_ActLog.ActLog_BIWWrites
                tt-Db_actlog.actlog_RecordCount = tt-Db_actlog.actlog_RecordCount + 1
                tt-db_actlog.actlog_length = tt-db_actlog.actlog_Length + Cf_Sample.Sample_len
                tt-Db_actlog.actlog_Transactions = tt-Db_actlog.actlog_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_actlog.
              BUFFER-COPY Db_actlog EXCEPT Db_actlog.Sample_ID TO tt-db_actlog.
              ASSIGN
                tt-Db_actlog.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_actlog.actlog_archiveType = "H" 
                tt-Db_actlog.actlog_EndDate = Cf_Sample.Sample_Date
                tt-Db_actlog.actlog_StartDate = Cf_Sample.Sample_Date
                tt-Db_actlog.Site_ID = Cf_Sample.Site_ID
                tt-Db_actlog.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_actlog.actlog_EndTime = s-end-time
                tt-Db_actlog.actlog_StartTime = s-beg-time 
                tt-Db_actlog.actlog_RecordCount = tt-Db_actlog.actlog_RecordCount + 1
                tt-db_actlog.actlog_length = tt-db_actlog.actlog_Length + Cf_Sample.Sample_len
                tt-Db_actlog.actlog_Transactions = tt-Db_actlog.actlog_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_actlog THEN */
END. /* FOR EACH W-Table BY w-time BY w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actlog 
    WHERE tt-db_actlog.actlog_archiveType = "H":
       
    IF NOT CAN-FIND (FIRST Ar_actlog
           WHERE Ar_actlog.actlog_archiveType  = "H"
             AND Ar_actlog.Site_ID             = tt-Db_ActLog.Site_ID
             AND Ar_actlog.Resrc_ID            = tt-Db_ActLog.Resrc_ID
             AND Ar_actlog.actlog_StartDate    = tt-Db_ActLog.actlog_StartDate
             AND Ar_actlog.actlog_StartTime    = tt-Db_ActLog.actlog_StartTime
             AND Ar_actlog.actlog_EndTime      = tt-Db_ActLog.actlog_EndTime)
       THEN DO:
             CREATE Ar_actlog.
             BUFFER-COPY tt-db_actlog TO Ar_actlog.
             RELEASE Ar_actlog.
             write-count = write-count + 1.
       END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActLog table : " write-count.

RUN delete-Db_ActLog.
/* 
** Ar-h-actrec.p
** This include will archive the db_actrec rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActRec definition
 - added an index on tt-DB_ActRec table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - fixed WHERE clause for AR_ActRec query to refer to AR_ActRec not to temp-table  
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActRec
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actrec NO-UNDO LIKE Ar_actrec
    INDEX myindex1 actrec_archivetype site_id resrc_id actrec_startdate actrec_starttime actrec_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_actrec WHERE Db_actrec.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    
    IF AVAILABLE Db_actrec
     THEN DO:
  
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actrec"}       
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-dB_actrec
             WHERE tt-Db_actrec.actrec_archiveType = "H"
               AND tt-Db_actrec.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_actrec.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_actrec.actrec_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_actrec.actrec_StartTime = s-beg-time
               AND tt-Db_actrec.actrec_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_actrec
         THEN ASSIGN
                tt-Db_ActRec.ActRec_ByteCreate = tt-Db_ActRec.ActRec_ByteCreate + Db_ActRec.ActRec_ByteCreate
                tt-Db_ActRec.ActRec_ByteDel = tt-Db_ActRec.ActRec_ByteDel + Db_ActRec.ActRec_ByteDel
                tt-Db_ActRec.ActRec_ByteRead = tt-Db_ActRec.ActRec_ByteRead + Db_ActRec.ActRec_ByteRead
                tt-Db_ActRec.ActRec_ByteUpd = tt-Db_ActRec.ActRec_ByteUpd + Db_ActRec.ActRec_ByteUpd
                tt-Db_ActRec.ActRec_FragCreate = tt-Db_ActRec.ActRec_FragCreate + Db_ActRec.ActRec_FragCreate
                tt-Db_ActRec.ActRec_FragDel = tt-Db_ActRec.ActRec_FragDel + Db_ActRec.ActRec_FragDel
                tt-Db_ActRec.ActRec_FragRead = tt-Db_ActRec.ActRec_FragRead + Db_ActRec.ActRec_FragRead
                tt-Db_ActRec.ActRec_FragUpd = tt-Db_ActRec.ActRec_FragUpd + Db_ActRec.ActRec_FragUpd
                tt-Db_ActRec.ActRec_RecCreate = tt-Db_ActRec.ActRec_RecCreate + Db_ActRec.ActRec_RecCreate
                tt-Db_ActRec.ActRec_RecDel = tt-Db_ActRec.ActRec_RecDel + Db_ActRec.ActRec_RecDel
                tt-Db_ActRec.ActRec_RecLock = tt-Db_ActRec.ActRec_RecLock + Db_ActRec.ActRec_RecLock 
                tt-Db_ActRec.ActRec_RecRead = tt-Db_ActRec.ActRec_RecRead + Db_ActRec.ActRec_RecRead
                tt-Db_ActRec.ActRec_RecUpd = tt-Db_ActRec.ActRec_RecUpd + Db_ActRec.ActRec_RecUpd
                tt-Db_ActRec.ActRec_RecWait = tt-Db_ActRec.ActRec_RecWait + Db_ActRec.ActRec_RecWait
                tt-Db_actrec.actrec_RecordCount = tt-Db_actrec.actrec_RecordCount + 1
                tt-Db_actrec.actrec_length = tt-db_actrec.actrec_Length + Cf_Sample.Sample_len
                tt-Db_actrec.actrec_Transactions = tt-Db_actrec.actrec_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_actrec.
              BUFFER-COPY Db_actrec EXCEPT Db_actrec.Sample_ID TO tt-db_actrec.
              ASSIGN
                tt-Db_actrec.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_actrec.actrec_archiveType = "H" 
                tt-Db_actrec.actrec_EndDate = Cf_Sample.Sample_Date
                tt-Db_actrec.actrec_StartDate = Cf_Sample.Sample_Date
                tt-Db_actrec.Site_ID = Cf_Sample.Site_ID
                tt-Db_actrec.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_actrec.actrec_EndTime = s-end-time
                tt-Db_actrec.actrec_StartTime = s-beg-time 
                tt-Db_actrec.actrec_RecordCount = tt-Db_actrec.actrec_RecordCount + 1
                tt-db_actrec.actrec_length = tt-db_actrec.actrec_Length + Cf_Sample.Sample_len
                tt-Db_actrec.actrec_Transactions = tt-Db_actrec.actrec_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_actrec THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actrec 
    WHERE tt-db_actrec.actrec_archiveType = "H":

      IF NOT CAN-FIND (FIRST Ar_actrec
           WHERE Ar_actrec.actrec_archiveType  = "H"
             AND tt-Db_actrec.Site_ID          = Cf_Sample.Site_ID
             AND tt-Db_actrec.Resrc_ID         = Cf_Sample.Resrc_ID
             AND tt-Db_actrec.actrec_StartDate = Ar_ActRec.actrec_StartDate
             AND tt-Db_actrec.actrec_StartTime = Ar_ActRec.actrec_StartTime
             AND tt-Db_actrec.actrec_EndTime   = Ar_ActRec.actrec_EndTime)
        THEN DO:
             CREATE Ar_actrec.
             BUFFER-COPY tt-db_actrec TO Ar_actrec.
             RELEASE AR_actrec.
             write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActRec table : " write-count.

RUN delete-Db_ActRec.
/* 
** Ar-h-actserv.p
** This include will archive the db_actserv rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActServ definition
 - added an index on tt-DB_ActServ table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_ActServ query to refer to AR_ActServ not to temp-table  
 
llaubach 08/2006
 - resrc_id was missing from TT myindex1 definition
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActServ
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actserv NO-UNDO LIKE Ar_actserv
    INDEX myindex1 actserv_archivetype site_id resrc_id actserv_num actserv_startdate actserv_starttime actserv_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH Db_actserv WHERE 
        Db_actserv.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actserv"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */

        FIND FIRST tt-dB_Actserv
             WHERE tt-Db_actserv.actserv_archiveType = "H"
               AND tt-Db_actserv.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_actserv.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_actserv.actserv_num = db_actserv.actserv_num
               AND tt-Db_actserv.actserv_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_actserv.actserv_StartTime = s-beg-time
               AND tt-Db_actserv.actserv_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_actserv 
         THEN DO:
              ASSIGN
                tt-Db_ActServ.ActServ_CurrUsers     = tt-Db_ActServ.ActServ_CurrUsers     + (Db_ActServ.ActServ_CurrUsers * Cf_Sample.Sample_Len)
                tt-Db_ActServ.ActServ_Logins        = tt-Db_ActServ.ActServ_Logins        + (Db_ActServ.ActServ_Logins * Cf_Sample.Sample_Len)
                tt-Db_ActServ.ActServ_ByteRec       = tt-Db_ActServ.ActServ_ByteRec       + Db_ActServ.ActServ_ByteRec
                tt-Db_ActServ.ActServ_ByteSent      = tt-Db_ActServ.ActServ_ByteSent      + Db_ActServ.ActServ_ByteSent
                tt-Db_ActServ.ActServ_MsgRec        = tt-Db_ActServ.ActServ_MsgRec        + Db_ActServ.ActServ_MsgRec
                tt-Db_ActServ.ActServ_MsgSent       = tt-Db_ActServ.ActServ_MsgSent       + Db_ActServ.ActServ_MsgSent
                tt-Db_ActServ.ActServ_QryRec        = tt-Db_ActServ.ActServ_QryRec        + Db_ActServ.ActServ_QryRec
                tt-Db_ActServ.ActServ_RecRec        = tt-Db_ActServ.ActServ_RecRec        + Db_ActServ.ActServ_RecRec
                tt-Db_ActServ.ActServ_RecSent       = tt-Db_ActServ.ActServ_RecSent       + Db_ActServ.ActServ_RecSent
                tt-Db_ActServ.ActServ_TimeSlice     = tt-Db_ActServ.ActServ_TimeSlice     + Db_ActServ.ActServ_TimeSlice
                tt-Db_ActServ.ActServ_Num           = Db_ActServ.ActServ_Num
                tt-Db_ActServ.ActServ_Type          = Db_ActServ.ActServ_Type
                tt-Db_actserv.actserv_RecordCount   = tt-Db_actserv.actserv_RecordCount   + 1
                tt-db_actserv.actserv_length        = tt-db_actserv.actserv_Length        + Cf_Sample.Sample_len
                tt-Db_actserv.actserv_Transactions  = tt-Db_actserv.actserv_Transactions  + Cf_Sample.Sample_Trans.

            /* Special processing not to just sum the fields */
            IF tt-Db_ActServ.ActServ_MaxUsers = 0 THEN 
                tt-Db_ActServ.ActServ_MaxUsers = Db_ActServ.ActServ_MaxUsers.
            IF tt-Db_ActServ.ActServ_MaxUsers LT Db_ActServ.ActServ_MaxUsers THEN 
                tt-Db_ActServ.ActServ_MaxUsers = Db_ActServ.ActServ_MaxUsers.

        END.
        ELSE
        DO:
            CREATE tt-Db_actserv.
            BUFFER-COPY Db_actserv EXCEPT Db_actserv.Sample_ID TO tt-db_actserv.
            ASSIGN
                tt-Db_actserv.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-db_actserv.actserv_currusers = (Db_ActServ.ActServ_CurrUsers * Cf_Sample.Sample_Len)
                tt-db_actserv.actserv_logins = (Db_ActServ.ActServ_Logins * Cf_Sample.Sample_Len)
                tt-Db_actserv.actserv_archiveType = "H" 
                tt-Db_actserv.actserv_EndDate = Cf_Sample.Sample_Date
                tt-Db_actserv.actserv_StartDate = Cf_Sample.Sample_Date
                tt-Db_actserv.Site_ID = Cf_Sample.Site_ID
                tt-Db_actserv.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_actserv.actserv_EndTime = s-end-time
                tt-Db_actserv.actserv_StartTime = s-beg-time 
                tt-Db_actserv.actserv_RecordCount = tt-Db_actserv.actserv_RecordCount + 1
                tt-db_actserv.actserv_length = tt-db_actserv.actserv_Length + Cf_Sample.Sample_len
                tt-Db_actserv.actserv_Transactions = tt-Db_actserv.actserv_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
        END.
    END. /* IF AVAILABLE Db_actserv THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

write-count = 0.
FOR EACH tt-db_actserv 
    WHERE tt-db_actserv.actserv_archiveType = "H":

        IF NOT CAN-FIND (FIRST Ar_actserv
            WHERE Ar_actserv.actserv_archiveType = "H"
              AND Ar_actserv.Site_ID             = tt-Db_ActServ.Site_ID
              AND Ar_actserv.Resrc_ID            = tt-Db_ActServ.Resrc_ID
              AND Ar_actserv.actserv_num         = tt-Db_ActServ.actserv_num
              AND Ar_actserv.actserv_StartDate   = tt-Db_ActServ.actserv_StartDate
              AND Ar_actserv.actserv_StartTime   = tt-Db_ActServ.actserv_StartTime
              AND Ar_actserv.actserv_EndTime     = tt-Db_ActServ.actserv_EndTime)
        THEN DO:
             ASSIGN
                tt-db_actserv.actserv_currusers = INTEGER (tt-db_actserv.actserv_currusers / tt-db_actserv.actserv_Length)
                tt-db_actserv.actserv_logins    = INT64 (tt-db_actserv.actserv_logins / tt-db_actserv.actserv_Length)
                tt-db_actserv.actserv_PID       = 0
                tt-db_actserv.actserv_Portnum   = 0.
              CREATE Ar_actserv.
              BUFFER-COPY tt-db_actserv TO Ar_actserv.
              RELEASE Ar_actserv.
              write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActServ table : " write-count.

RUN delete-DB_ActServ.
/* 
** Ar-h-sum.p
** This include will archive the db_sum rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_ActSum definition
 - added an index on tt-DB_ActSum table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing 
 - fixed WHERE clause for AR_ActSum query to refer to AR_ActSum not to temp-table  
 
llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ActSum
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_actsum NO-UNDO LIKE Ar_actsum
    INDEX myindex1 actsum_archivetype site_id resrc_id actsum_startdate actsum_starttime actsum_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Db_actsum WHERE Db_actsum.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    
    IF AVAILABLE Db_actsum
     THEN DO:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_actsum"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-dB_Actsum
             WHERE tt-Db_actsum.actsum_archiveType = "H"
               AND tt-Db_actsum.Site_ID = Cf_Sample.Site_ID 
               AND tt-Db_actsum.Resrc_ID = Cf_Sample.Resrc_ID 
               AND tt-Db_actsum.actsum_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_actsum.actsum_StartTime = s-beg-time
               AND tt-Db_actsum.actsum_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_actsum
         THEN ASSIGN
                tt-Db_ActSum.ActSum_AiWrites       = tt-Db_ActSum.ActSum_AiWrites    + Db_ActSum.ActSum_AiWrites   
                tt-Db_ActSum.ActSum_AllocNewRm     = tt-Db_ActSum.ActSum_AllocNewRm  + Db_ActSum.ActSum_AllocNewRm
                tt-Db_ActSum.ActSum_BiReads        = tt-Db_ActSum.ActSum_BiReads     + Db_ActSum.ActSum_BiReads
                tt-Db_ActSum.ActSum_BiWrites       = tt-Db_ActSum.ActSum_BiWrites    + Db_ActSum.ActSum_BiWrites
                tt-Db_ActSum.ActSum_BytesAlloc     = tt-Db_ActSum.ActSum_BytesAlloc  + Db_ActSum.ActSum_BytesAlloc
                tt-Db_ActSum.ActSum_Commits        = tt-Db_ActSum.ActSum_Commits     + Db_ActSum.ActSum_Commits
                tt-Db_ActSum.ActSum_DbAccesses     = tt-Db_ActSum.ActSum_DbAccesses  + Db_ActSum.ActSum_DbAccesses
                tt-Db_ActSum.ActSum_DbExtend       = tt-Db_ActSum.ActSum_DbExtend    + Db_ActSum.ActSum_DbExtend
                tt-Db_ActSum.ActSum_DbReads        = tt-Db_ActSum.ActSum_DbReads     + Db_ActSum.ActSum_DbReads
                tt-Db_ActSum.ActSum_DbWrites       = tt-Db_ActSum.ActSum_DbWrites    + Db_ActSum.ActSum_DbWrites
                tt-Db_ActSum.ActSum_Examined       = tt-Db_ActSum.ActSum_Examined    + Db_ActSum.ActSum_Examined
                tt-Db_ActSum.ActSum_FromFree       = tt-Db_ActSum.ActSum_FromFree    + Db_ActSum.ActSum_FromFree
                tt-Db_ActSum.ActSum_FromRm         = tt-Db_ActSum.ActSum_FromRm      + Db_ActSum.ActSum_FromRm
                tt-Db_ActSum.ActSum_Removed        = tt-Db_ActSum.ActSum_Removed     + Db_ActSum.ActSum_Removed
                tt-Db_ActSum.ActSum_RetFree        = tt-Db_ActSum.ActSum_RetFree     + Db_ActSum.ActSum_RetFree
                tt-Db_ActSum.ActSum_TakeFree       = tt-Db_ActSum.ActSum_TakeFree    + Db_ActSum.ActSum_TakeFree
                tt-Db_ActSum.ActSum_Undos          = tt-Db_ActSum.ActSum_Undos       + Db_ActSum.ActSum_Undos
                tt-Db_actsum.actsum_RecordCount    = tt-Db_actsum.actsum_RecordCount + 1
                tt-db_actsum.actsum_length         = tt-db_actsum.actsum_Length      + Cf_Sample.Sample_len
                tt-Db_actsum.actsum_Transactions   = tt-Db_actsum.actsum_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_actsum.
              BUFFER-COPY Db_actsum EXCEPT Db_actsum.Sample_ID TO tt-db_actsum.
              ASSIGN
                tt-Db_actsum.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_actsum.actsum_archiveType = "H" 
                tt-Db_actsum.actsum_EndDate = Cf_Sample.Sample_Date
                tt-Db_actsum.actsum_StartDate = Cf_Sample.Sample_Date
                tt-Db_actsum.Site_ID = Cf_Sample.Site_ID
                tt-Db_actsum.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_actsum.actsum_EndTime = s-end-time
                tt-Db_actsum.actsum_StartTime = s-beg-time 
                tt-Db_actsum.actsum_RecordCount = tt-Db_actsum.actsum_RecordCount + 1
                tt-db_actsum.actsum_length = tt-db_actsum.actsum_Length + Cf_Sample.Sample_len
                tt-Db_actsum.actsum_Transactions = tt-Db_actsum.actsum_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_actsum THEN */
END. /* FOR EAC W-Table by w-time by w-date: */

/* Write out the records */

write-count = 0.
FOR EACH tt-db_actsum
    WHERE tt-db_actsum.actsum_archiveType = "H":

       IF NOT CAN-FIND (FIRST Ar_actsum
           WHERE Ar_actsum.actsum_archiveType = "H"
             AND Ar_actsum.Site_ID            = tt-Db_ActSum.Site_ID
             AND Ar_actsum.Resrc_ID           = tt-Db_ActSum.Resrc_ID 
             AND Ar_actsum.actsum_StartDate   = tt-Db_ActSum.ActSum_StartDate
             AND Ar_actsum.actsum_StartTime   = tt-Db_ActSum.ActSum_StartTime
             AND Ar_actsum.actsum_EndTime     = tt-Db_ActSum.ActSum_EndTime)
        THEN DO:
             CREATE Ar_actsum.
             BUFFER-COPY tt-db_actsum TO Ar_actsum.
             RELEASE AR_actsum.
             write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_ActSum table : " write-count.

RUN delete-Db_ActSum.
/* 
** Ar-h-areastatus.p
** This include will archive the db_areastatus rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_AreaStatus definition
 - added an index on tt-DB_AreaStatus table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_AreaStatus query to refer to AR_AreaStatus not to temp-table  

llaubach 08/2006
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-AreaStatus
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_areastatus NO-UNDO LIKE Ar_areastatus
    INDEX myindex1 areastatus_archivetype site_id resrc_id areastatus_areanum areastatus_startdate areastatus_starttime areastatus_endtime.

FOR EACH W-Table by w-time by w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH Db_areastatus WHERE 
        Db_areastatus.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_areastatus"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */

        FIND FIRST tt-dB_areastatus
             WHERE tt-Db_areastatus.areastatus_archiveType = "H" 
               AND tt-Db_areastatus.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_areastatus.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_areastatus.areastatus_areanum = Db_areastatus.areastatus_areanum
               AND tt-Db_areastatus.areastatus_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_areastatus.areastatus_StartTime = s-beg-time
               AND tt-Db_areastatus.areastatus_EndTime = s-end-time
        NO-LOCK NO-ERROR
            .
        IF AVAILABLE tt-db_areastatus
         THEN DO:
            ASSIGN
                tt-Db_AreaStatus.AreaStatus_Areaname = Db_AreaStatus.AreaStatus_Areaname
                tt-Db_AreaStatus.AreaStatus_Areanum = Db_AreaStatus.AreaStatus_Areanum
                tt-Db_AreaStatus.AreaStatus_Extents = Db_AreaStatus.AreaStatus_Extents
                tt-Db_AreaStatus.AreaStatus_Freenum = tt-Db_AreaStatus.AreaStatus_Freenum + (Cf_Sample.Sample_Len * Db_AreaStatus.AreaStatus_Freenum)
                tt-Db_AreaStatus.AreaStatus_Rmnum   = tt-Db_AreaStatus.AreaStatus_Rmnum   + (Cf_Sample.Sample_Len * Db_AreaStatus.AreaStatus_Rmnum)
                tt-Db_areastatus.areastatus_RecordCount = tt-Db_areastatus.areastatus_RecordCount + 1
                tt-db_areastatus.areastatus_length = tt-db_areastatus.areastatus_Length + Cf_Sample.Sample_len
                tt-Db_areastatus.areastatus_Transactions = tt-Db_areastatus.areastatus_Transactions + Cf_Sample.Sample_Trans.

                IF tt-Db_AreaStatus.AreaStatus_TotBloc LT Db_AreaStatus.AreaStatus_TotBlocks THEN
	           tt-Db_AreaStatus.AreaStatus_TotBloc = Db_AreaStatus.AreaStatus_TotBlocks.
                IF tt-Db_AreaStatus.AreaStatus_Hiwater LT Db_AreaStatus.AreaStatus_Hiwater THEN
		   tt-Db_AreaStatus.AreaStatus_Hiwater = Db_AreaStatus.AreaStatus_Hiwater.
        END.
        ELSE
        DO:
            CREATE tt-Db_areastatus.
            BUFFER-COPY Db_areastatus EXCEPT Db_areastatus.Sample_ID TO tt-db_areastatus.
            ASSIGN
                tt-Db_areastatus.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_areastatus.areastatus_archiveType = "H" 
                tt-Db_areastatus.areastatus_EndDate = Cf_Sample.Sample_Date
                tt-Db_areastatus.areastatus_StartDate = Cf_Sample.Sample_Date
                tt-Db_areastatus.Site_ID = Cf_Sample.Site_ID
                tt-Db_areastatus.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_areastatus.areastatus_EndTime = s-end-time
                tt-Db_areastatus.areastatus_StartTime = s-beg-time 
                tt-Db_areastatus.areastatus_RecordCount = tt-Db_areastatus.areastatus_RecordCount + 1
                tt-db_areastatus.areastatus_length = tt-db_areastatus.areastatus_Length + Cf_Sample.Sample_len
                tt-Db_areastatus.areastatus_Transactions = tt-Db_areastatus.areastatus_Transactions + Cf_Sample.Sample_Trans
                tt-Db_AreaStatus.AreaStatus_Freenum = Cf_Sample.Sample_Len * Db_AreaStatus.AreaStatus_Freenum
                tt-Db_AreaStatus.AreaStatus_Rmnum   = Cf_Sample.Sample_Len * Db_AreaStatus.AreaStatus_Rmnum.
                new-recs = new-recs + 1.
        END.
    END. /* IF AVAILABLE Db_areastatus THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

write-count = 0.
FOR EACH tt-db_areastatus
    WHERE tt-db_areastatus.areastatus_archiveType = "H":
        
      IF NOT CAN-FIND (FIRST Ar_areastatus
            WHERE Ar_areastatus.areastatus_archiveType = "H"
              AND Ar_areastatus.Site_ID                = tt-Db_AreaStatus.Site_ID
              AND Ar_areastatus.Resrc_ID               = tt-Db_AreaStatus.Resrc_ID
              AND Ar_areastatus.areastatus_areanum     = tt-Db_AreaStatus.areastatus_areanum
              AND Ar_areastatus.areastatus_StartDate   = tt-Db_AreaStatus.areastatus_StartDate
              AND Ar_areastatus.areastatus_StartTime   = tt-Db_AreaStatus.areastatus_StartTime
              AND Ar_areastatus.areastatus_EndTime     = tt-Db_AreaStatus.areastatus_EndTime)
        THEN DO:
              ASSIGN tt-db_areastatus.areastatus_freenum = INT64 (tt-db_areastatus.areastatus_freenum / tt-db_areastatus.areastatus_Length)
                     tt-db_areastatus.areastatus_rmnum   = INT64 (tt-db_areastatus.areastatus_rmnum / tt-db_areastatus.areastatus_Length).
              CREATE Ar_areastatus.
              BUFFER-COPY tt-db_areastatus TO Ar_areastatus.
              RELEASE Ar_areastatus.
              write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_AreaStatus table : " write-count.

RUN delete-DB_AreaStatus.
/* 
** Ar-h-checkpoint.p
** This include will archive the db_checkpoint rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_Checkpoint definition
 - added an index on tt-DB_Checkpoint table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_Checkpoint query to refer to AR_Checkpoint not to temp-table  
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - write-count initialization was missing before the REPEAT
 - moved FIND FIRST tt-DB_Checkpoint outside the REPEAT & WHILE loops and added dedicated counter,
   as we could end up in neverending loop
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_Checkpoint
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_checkpoint NO-UNDO LIKE Ar_checkpoint
    INDEX myindex1 checkpoint_archivetype site_id resrc_id checkpoint_startdate checkpoint_starttime checkpoint_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH Db_checkpoint WHERE 
        Db_checkpoint.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_checkpoint"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-db_checkpoint
             WHERE tt-Db_checkpoint.checkpoint_archiveType = "H"
               AND tt-Db_checkpoint.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_checkpoint.Resrc_ID = Cf_Sample.Resrc_ID 
               AND tt-Db_checkpoint.checkpoint_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_checkpoint.checkpoint_StartTime = s-beg-time 
               AND tt-Db_checkpoint.checkpoint_EndTime = s-end-time
        NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_checkpoint
         THEN ASSIGN
                tt-Db_Checkpoint.Checkpoint_ApwQ   = tt-Db_Checkpoint.Checkpoint_ApwQ   + Db_Checkpoint.Checkpoint_ApwQ
                tt-Db_Checkpoint.Checkpoint_CkptQ  = tt-Db_Checkpoint.Checkpoint_CkptQ  + Db_Checkpoint.Checkpoint_CkptQ
                tt-Db_Checkpoint.Checkpoint_Dirty  = tt-Db_Checkpoint.Checkpoint_Dirty  + Db_Checkpoint.Checkpoint_Dirty
                tt-Db_Checkpoint.Checkpoint_Flush  = tt-Db_Checkpoint.Checkpoint_Flush  + Db_Checkpoint.Checkpoint_Flush
                tt-Db_Checkpoint.Checkpoint_Length = tt-Db_Checkpoint.Checkpoint_Length + Db_Checkpoint.Checkpoint_Length
                tt-Db_Checkpoint.Checkpoint_Scan   =  tt-Db_Checkpoint.Checkpoint_Scan  + Db_Checkpoint.Checkpoint_Scan
                tt-Db_Checkpoint.Checkpoint_Time   = tt-Db_Checkpoint.Checkpoint_Time   + Db_Checkpoint.Checkpoint_Time
                tt-Db_checkpoint.checkpoint_RecordCount  = tt-Db_checkpoint.checkpoint_RecordCount + 1
                tt-Db_checkpoint.checkpoint_Transactions = tt-Db_checkpoint.checkpoint_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_checkpoint.
              BUFFER-COPY Db_checkpoint EXCEPT Db_checkpoint.Sample_ID TO tt-db_checkpoint.
              ASSIGN
                tt-Db_checkpoint.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_checkpoint.checkpoint_archiveType = "H" 
                tt-Db_checkpoint.checkpoint_EndDate = Cf_Sample.Sample_Date
                tt-Db_checkpoint.checkpoint_StartDate = Cf_Sample.Sample_Date
                tt-Db_checkpoint.Site_ID = Cf_Sample.Site_ID
                tt-Db_checkpoint.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_checkpoint.checkpoint_EndTime = s-end-time
                tt-Db_checkpoint.checkpoint_StartTime = s-beg-time 
                tt-Db_checkpoint.checkpoint_RecordCount = tt-Db_checkpoint.checkpoint_RecordCount + 1
                tt-Db_checkpoint.checkpoint_Transactions = tt-Db_checkpoint.checkpoint_Transactions + Cf_Sample.Sample_Trans
                tt-Db_Checkpoint.Checkpoint_ApwQ = Db_Checkpoint.Checkpoint_ApwQ
                tt-Db_Checkpoint.Checkpoint_CkptQ = Db_Checkpoint.Checkpoint_CkptQ
                tt-Db_Checkpoint.Checkpoint_Dirty = Db_Checkpoint.Checkpoint_Dirty
                tt-Db_Checkpoint.Checkpoint_Flush = Db_Checkpoint.Checkpoint_Flush
                tt-Db_Checkpoint.Checkpoint_Length = Db_Checkpoint.Checkpoint_Length
                tt-Db_Checkpoint.Checkpoint_Scan =  Db_Checkpoint.Checkpoint_Scan
               new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE Db_checkpoint THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

DEF VAR write-i AS INTEGER NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-db_checkpoint WHERE tt-db_checkpoint.checkpoint_archiveType = "H" NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
        IF write-count <> 0 THEN FIND NEXT tt-db_checkpoint WHERE tt-db_checkpoint.checkpoint_archiveType = "H" NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_checkpoint 
         THEN DO:

           IF NOT CAN-FIND (FIRST Ar_checkpoint
               WHERE Ar_checkpoint.checkpoint_archiveType = "H"
                 AND Ar_checkpoint.Site_ID                = tt-Db_Checkpoint.Site_ID
                 AND Ar_checkpoint.Resrc_ID               = tt-Db_Checkpoint.Resrc_ID
                 AND Ar_checkpoint.checkpoint_StartDate   = tt-Db_Checkpoint.checkpoint_StartDate
                 AND Ar_checkpoint.checkpoint_StartTime   = tt-Db_Checkpoint.checkpoint_StartTime
                 AND Ar_checkpoint.checkpoint_EndTime     = tt-Db_Checkpoint.checkpoint_EndTime)
            THEN DO:
                 ASSIGN tt-db_checkpoint.checkpoint_time = ""
                        tt-db_checkpoint.checkpoint_num = 0.
                 CREATE Ar_checkpoint.
                 BUFFER-COPY tt-db_checkpoint TO Ar_checkpoint.
                 RELEASE AR_checkpoint.
                 write-count = write-count + 1.
            END.
        END. /* IF AVAIL */

        ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_Checkpoint table : " write-count.
               write-i = 99999.
               LEAVE.
        END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-DB_Checkpoint.

/* 
** Ar-h-cpu.p
** This include will archive the db_cpu rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_cpu definition
 - added an index on tt-DB_cpu table to match the WHERE clause
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement  
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replaced FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - reordered AR_CPU query to match the order of a newly added index
 
llaubach 08/2006
 - cpu_starttime was missing from tt-DB_CPU myindex1 definition
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - write-count initialization was missing before the REPEAT
 - moved FIND FIRST tt-DB_CPU outside the REPEAT & WHILE loops and added dedicated counter,
   as we could end up in neverending loop
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_Cpu
 - do commit after 500, not 100 records
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_cpu NO-UNDO LIKE Ar_cpu
    INDEX myindex1 cpu_archivetype site_id resrc_id cpu_startdate cpu_starttime cpu_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST sys_cpu WHERE sys_cpu.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.

    IF AVAILABLE sys_cpu
     THEN DO:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "sys_cpu"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-Db_cpu 
             WHERE tt-Db_cpu.cpu_archiveType = "H"
               AND tt-Db_cpu.Site_ID         = Cf_Sample.Site_ID
               AND tt-Db_cpu.Resrc_ID        = Cf_Sample.Resrc_ID
               AND tt-Db_cpu.cpu_StartDate   = Cf_Sample.Sample_Date
               AND tt-Db_cpu.cpu_StartTime   = s-beg-time
               AND tt-Db_cpu.cpu_EndTime     = s-end-time
         NO-LOCK NO-ERROR.
        
        IF AVAILABLE tt-db_cpu 
         THEN ASSIGN
                /* tt-db_CPU.CPU_Idle   = tt-db_CPU.CPU_Idle   + ( Sys_CPU.CPU_Idle * Cf_Sample.Sample_len) */ 
                tt-db_CPU.CPU_System = tt-db_CPU.CPU_System + ( Sys_CPU.CPU_System * Cf_Sample.Sample_len) 
                tt-db_CPU.CPU_Usr    = tt-db_CPU.CPU_Usr    + ( Sys_CPU.CPU_Usr * Cf_Sample.Sample_len) 
                tt-db_CPU.CPU_Wait   = tt-db_CPU.CPU_Wait   + ( Sys_CPU.CPU_Wait * Cf_Sample.Sample_len) 
                tt-Db_cpu.cpu_RecordCount  = tt-Db_cpu.cpu_RecordCount + 1
                tt-db_cpu.cpu_length       = tt-db_cpu.cpu_Length + Cf_Sample.Sample_len
                tt-Db_cpu.cpu_Transactions = tt-Db_cpu.cpu_Transactions + Cf_Sample.Sample_Trans.
          ELSE DO:
               CREATE tt-Db_cpu.
               ASSIGN
                 tt-Db_cpu.sample_id = NEXT-VALUE (ar_sample-seq)
                 tt-Db_cpu.cpu_archiveType = "H" 
                 tt-Db_cpu.cpu_EndDate = Cf_Sample.Sample_Date
                 tt-Db_cpu.cpu_StartDate = Cf_Sample.Sample_Date
                 tt-Db_cpu.Site_ID = Cf_Sample.Site_ID
                 tt-Db_cpu.Resrc_ID = Cf_Sample.Resrc_ID
                 tt-Db_cpu.cpu_EndTime = s-end-time
                 tt-Db_cpu.cpu_StartTime = s-beg-time 
                 tt-Db_cpu.cpu_RecordCount = 1
                 tt-db_cpu.cpu_length = Cf_Sample.Sample_len
                 tt-Db_cpu.cpu_Transactions = Cf_Sample.Sample_Trans
                 /* tt-Db_CPU.CPU_Idle = ( Sys_CPU.CPU_Idle * Cf_Sample.Sample_len) */
                 tt-Db_CPU.CPU_System = ( Sys_CPU.CPU_System * Cf_Sample.Sample_len) 
                 tt-Db_CPU.CPU_Usr = ( Sys_CPU.CPU_Usr * Cf_Sample.Sample_len) 
                 tt-Db_CPU.CPU_Wait = ( Sys_CPU.CPU_Wait * Cf_Sample.Sample_len) 
                 new-recs = new-recs + 1.
          END.
      END. /* IF AVAILABLE sys_cpu THEN */
END. /* FOR EACH W-Table BY w-time BY w-date: */

/* Modify & Write out the records  */
DEF VAR write-i AS INT NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-db_cpu NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
         IF count-i <> 0 THEN FIND NEXT tt-db_cpu NO-LOCK NO-ERROR.
         IF AVAILABLE tt-db_cpu
          THEN DO:
               count-i = count-i + 1.
               IF NOT CAN-FIND(FIRST Ar_cpu
                   WHERE Ar_CPU.CPU_ArchiveType = tt-db_cpu.CPU_archivetype 
                     AND ar_cpu.site_id         = tt-db_cpu.site_id
                     AND ar_cpu.resrc_id        = tt-db_cpu.resrc_id
                     AND Ar_CPU.CPU_StartDate   = tt-db_cpu.cpu_startdate
                     AND Ar_CPU.CPU_StartTime   = tt-db_cpu.cpu_starttime
                     AND Ar_CPU.CPU_EndDate     = tt-db_cpu.cpu_enddate
                     AND Ar_CPU.CPU_EndTime     = tt-db_cpu.cpu_endtime)
                  THEN DO:
                       ASSIGN
                         tt-db_cpu.CPU_System = tt-db_cpu.CPU_System / tt-db_cpu.cpu_Length
                         tt-db_cpu.CPU_usr    = tt-db_cpu.CPU_usr / tt-db_cpu.cpu_Length                         
                         tt-db_cpu.CPU_Wait   = tt-db_cpu.CPU_Wait / tt-db_cpu.cpu_Length.
                       ASSIGN 
                         tt-db_cpu.CPU_Idle   = TRUNCATE(100.0 - (tt-db_cpu.CPU_usr + tt-db_cpu.CPU_System + tt-db_cpu.CPU_Wait), 0).
                       IF tt-db_cpu.CPU_Idle < 0 THEN
                           ASSIGN tt-db_cpu.CPU_Idle = 0.                                                 
                       CREATE Ar_cpu.
                       BUFFER-COPY tt-db_cpu TO Ar_cpu.
                       RELEASE AR_cpu.
                       write-count = write-count + 1.
                  END.
          END.
          ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Sys_CPU table : " write-count.
               write-i = 99999.
               LEAVE.
          END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-Sys_CPU.
/* 
** Ar-h-dev.p
** This include will archive the db_dev rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_dev definition
 - added an index on tt-DB_dev table to match the WHERE clause
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement  
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_Dev query to refer to AR_Dev not to temp-table  
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_Dev
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_dev NO-UNDO LIKE Ar_dev
    INDEX my_index dev_archiveType Site_ID Resrc_ID dev_name dev_StartDate dev_StartTime dev_EndTime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH sys_dev WHERE 
        sys_dev.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "sys_dev"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-dB_dev
             WHERE tt-Db_dev.dev_archiveType = "H"
               AND tt-Db_dev.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_dev.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_Dev.dev_name = Sys_Dev.dev_name
               AND tt-Db_dev.dev_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_dev.dev_StartTime = s-beg-time 
               AND tt-Db_dev.dev_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_dev
         THEN ASSIGN 
                tt-db_Dev.Dev_Name         = Sys_Dev.Dev_Name
                tt-db_Dev.Dev_AvgQue       = tt-db_Dev.Dev_AvgQue       + (Cf_Sample.Sample_Len * Sys_Dev.Dev_AvgQue)
                tt-db_Dev.Dev_AvgServ      = tt-db_Dev.Dev_AvgServ      + (Cf_Sample.Sample_Len * Sys_Dev.Dev_AvgServ)
                tt-db_Dev.Dev_AvgWait      = tt-db_Dev.Dev_AvgWait      + (Cf_Sample.Sample_Len * Sys_Dev.Dev_AvgWait)
                tt-db_Dev.Dev_Pct_Busy     = tt-db_Dev.Dev_Pct_Busy     + (Cf_Sample.Sample_Len * Sys_Dev.Dev_Pct_Busy)
                tt-Db_dev.dev_RecordCount  = tt-Db_dev.dev_RecordCount  + 1
                tt-db_dev.dev_length       = tt-db_dev.dev_Length       + Cf_Sample.Sample_len
                tt-Db_dev.dev_Transactions = tt-Db_dev.dev_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_dev.
              BUFFER-COPY sys_dev EXCEPT sys_dev.Sample_ID TO tt-db_dev.
              ASSIGN
                tt-Db_dev.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_dev.dev_archiveType = "H" 
                tt-Db_dev.dev_EndDate = Cf_Sample.Sample_Date
                tt-Db_dev.dev_StartDate = Cf_Sample.Sample_Date
                tt-Db_dev.Site_ID = Cf_Sample.Site_ID
                tt-Db_dev.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_dev.dev_EndTime = s-end-time
                tt-Db_dev.dev_StartTime = s-beg-time 
                tt-Db_dev.dev_RecordCount = tt-Db_dev.dev_RecordCount + 1
                tt-db_dev.dev_length = tt-db_dev.dev_Length + Cf_Sample.Sample_len
                tt-Db_dev.dev_Transactions = tt-Db_dev.dev_Transactions + Cf_Sample.Sample_Trans
                tt-db_Dev.Dev_AvgQue = Cf_Sample.Sample_Len * Sys_Dev.Dev_AvgQue
                tt-db_Dev.Dev_AvgServ = Cf_Sample.Sample_Len * Sys_Dev.Dev_AvgServ
                tt-db_Dev.Dev_AvgWait = Cf_Sample.Sample_Len * Sys_Dev.Dev_AvgWait
                tt-db_Dev.Dev_Pct_Busy = Cf_Sample.Sample_Len * Sys_Dev.Dev_Pct_Busy.
               new-recs = new-recs + 1.
         END.
    END. /* IF AVAILABLE sys_dev THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

write-count = 0.
FOR EACH tt-db_dev
    WHERE tt-db_dev.dev_archiveType = "H":
        
       IF NOT CAN-FIND (FIRST Ar_dev
            WHERE Ar_dev.dev_archiveType = "H"
              AND Ar_dev.Site_ID         = tt-Db_Dev.Site_ID
              AND Ar_dev.Resrc_ID        = tt-Db_Dev.Resrc_ID
              AND Ar_Dev.dev_name        = tt-Db_Dev.dev_name
              AND Ar_dev.dev_StartDate   = tt-Db_Dev.dev_StartDate
              AND Ar_dev.dev_StartTime   = tt-Db_Dev.dev_StartTime
              AND Ar_dev.dev_EndTime     = tt-Db_Dev.dev_EndTime)
         THEN DO:
              /* Modify this percentage line for output */
              ASSIGN 
                tt-db_Dev.Dev_AvgQue   = tt-db_Dev.Dev_AvgQue / tt-db_Dev.Dev_Length
                tt-db_Dev.Dev_AvgServ  = tt-db_Dev.Dev_AvgServ / tt-db_Dev.Dev_Length
                tt-db_Dev.Dev_AvgWait  = tt-db_Dev.Dev_AvgWait / tt-db_Dev.Dev_Length
                tt-db_dev.Dev_Pct_Busy = tt-db_dev.Dev_Pct_Busy / tt-db_dev.dev_Length.
              CREATE Ar_dev.
              BUFFER-COPY tt-db_dev TO Ar_dev.
              RELEASE AR_dev.
              write-count = write-count + 1.
         END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Sys_Dev table : " write-count.

RUN delete-Sys_Dev.
/* 
** Ar-h-filesize.p
** This include will archive the sys_filesize rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_filesize definition
 - added an index on tt-DB_filesize table to match the WHERE clause
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement  
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_FileSize query to refer to AR_FileSize not to temp-table   
 - added filesize_name to the archiving as it was missing
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_FileSize
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_filesize NO-UNDO LIKE Ar_filesize
    INDEX myindex1 filesize_archiveType site_id resrc_id filesize_startdate filesize_starttime filesize_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST sys_filesize WHERE sys_filesize.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    
    IF AVAILABLE sys_filesize
     THEN DO:
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "sys_filesize"} 
        {include/ar-setuptimes.i}
  
        /* Search for the temp record.  If it exist then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-dB_filesize
             WHERE tt-Db_filesize.filesize_archiveType = "H" 
               AND tt-Db_filesize.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_filesize.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_filesize.filesize_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_filesize.filesize_StartTime = s-beg-time
               AND tt-Db_filesize.filesize_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_filesize
         THEN DO:
            ASSIGN
                tt-db_FileSize.FileSize_Name = Sys_FileSize.FileSize_Name
                tt-db_FileSize.FileSize_Size = tt-db_FileSize.FileSize_Size + Sys_FileSize.FileSize_Size
                tt-Db_filesize.filesize_RecordCount = tt-Db_filesize.filesize_RecordCount + 1
                tt-db_filesize.filesize_length = tt-db_filesize.filesize_Length + Cf_Sample.Sample_len
                tt-Db_filesize.filesize_Transactions = tt-Db_filesize.filesize_Transactions + Cf_Sample.Sample_Trans.
            IF tt-db_FileSize.Filesize_Max LT Sys_FileSize.FileSize_Size THEN 
                tt-db_FileSize.Filesize_Max = Sys_FileSize.FileSize_Size.
            IF tt-db_FileSize.Filesize_Min = 0 THEN 
                tt-db_FileSize.Filesize_Min = Sys_FileSize.FileSize_Size.
            IF tt-db_FileSize.Filesize_Min GT Sys_FileSize.FileSize_Size THEN 
                tt-db_FileSize.Filesize_Min = Sys_FileSize.FileSize_Size.
         END.
        ELSE DO:
            CREATE tt-Db_filesize.
            BUFFER-COPY sys_filesize EXCEPT sys_filesize.Sample_ID TO tt-db_filesize.
            ASSIGN
                tt-Db_filesize.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_filesize.filesize_archiveType = "H" 
                tt-Db_filesize.filesize_EndDate = Cf_Sample.Sample_Date
                tt-Db_filesize.filesize_StartDate = Cf_Sample.Sample_Date
                tt-Db_filesize.Site_ID = Cf_Sample.Site_ID
                tt-Db_filesize.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_filesize.filesize_EndTime = s-end-time
                tt-Db_filesize.filesize_StartTime = s-beg-time 
                tt-Db_filesize.filesize_Max = Sys_Filesize.filesize_size 
                tt-Db_filesize.filesize_Min = Sys_Filesize.filesize_size
                tt-Db_filesize.filesize_RecordCount = tt-Db_filesize.filesize_RecordCount + 1
                tt-db_filesize.filesize_length = tt-db_filesize.filesize_Length + Cf_Sample.Sample_len
                tt-Db_filesize.filesize_Transactions = tt-Db_filesize.filesize_Transactions + Cf_Sample.Sample_Trans.
               new-recs = new-recs + 1.
        END.
    END. /* IF AVAILABLE sys_filesize THEN */
END.  /* FOR EACH W-Table by w-time by w-date: */


/* Modify & Write out the records */

write-count = 0.
FOR EACH tt-db_filesize
    WHERE tt-db_filesize.filesize_archiveType = "H":

        IF NOT CAN-FIND (FIRST Ar_filesize
            WHERE Ar_filesize.filesize_archiveType = "H"
              AND Ar_filesize.Site_ID              = tt-Db_FileSize.Site_ID
              AND Ar_filesize.Resrc_ID             = tt-Db_FileSize.Resrc_ID
              AND Ar_filesize.filesize_Name        = tt-Db_FileSize.Filesize_name
              AND Ar_filesize.filesize_StartDate   = tt-Db_FileSize.filesize_StartDate
              AND Ar_filesize.filesize_StartTime   = tt-Db_FileSize.filesize_StartTime
              AND Ar_filesize.filesize_EndTime     = tt-Db_FileSize.filesize_EndTime)
          THEN DO:
               tt-db_filesize.filesize_size = tt-db_filesize.filesize_size / tt-db_filesize.filesize_RecordCount.
               CREATE Ar_filesize.
               BUFFER-COPY tt-db_filesize TO Ar_filesize.
               RELEASE AR_filesize.
               write-count = write-count + 1.
          END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Sys_FileSize table : " write-count.

RUN delete-Sys_FileSize.
/* 
** Ar-h-filesys.p
** This include will archive the sys_filesys rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_filesys definition
 - added an index on tt-DB_filesys table to match the WHERE clause
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement  
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_FileSys query to refer to AR_FileSys not to temp-table  
   
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_FileSys
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_filesys NO-UNDO LIKE Ar_filesys
    INDEX myindex1 filesys_archiveType site_id resrc_id filesys_mount filesys_startdate filesys_starttime filesys_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH sys_filesys WHERE 
        sys_filesys.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
    
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "sys_filesys"} 
        {include/ar-setuptimes.i}

        /* 
        ** Look for the temp record.  If it exists then update it.  If it doesn't
        ** exist then create the appropriate one.
        */

        FIND FIRST tt-dB_filesys
             WHERE tt-Db_filesys.filesys_archiveType = "H"
               AND tt-Db_filesys.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_filesys.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_filesys.filesys_mount = sys_filesys.filesys_mount
               AND tt-Db_filesys.filesys_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_filesys.filesys_StartTime = s-beg-time
               AND tt-Db_filesys.filesys_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_filesys
         THEN DO:
            ASSIGN
                tt-db_FileSys.FileSys_Mount   = Sys_FileSys.FileSys_Mount
                tt-db_FileSys.FileSys_Name    = Sys_FileSys.FileSys_Name
                tt-db_FileSys.FileSys_UsedPct = tt-db_FileSys.FileSys_UsedPct +
                                                (Sys_FileSys.FileSys_UsedPct *
                                                 Cf_Sample.Sample_Len)
                tt-Db_filesys.filesys_RecordCount = tt-Db_filesys.filesys_RecordCount + 1
                tt-db_filesys.filesys_length = tt-db_filesys.filesys_Length +
                                               Cf_Sample.Sample_len
                tt-Db_filesys.filesys_Transactions = tt-Db_filesys.filesys_Transactions +
                                                     Cf_Sample.Sample_Trans
                tt-db_FileSys.FileSys_Avail = tt-db_FileSys.FileSys_Avail +
                                              Sys_FileSys.FileSys_Avail.

            /*  Special processing not to just sum the fields */
            IF tt-db_FileSys.FileSys_Capacity = 0 THEN tt-db_FileSys.FileSys_Capacity = Sys_FileSys.FileSys_Capacity.
            IF tt-db_FileSys.FileSys_Capacity LT Sys_FileSys.FileSys_Capacity THEN tt-db_FileSys.FileSys_Capacity = Sys_FileSys.FileSys_Capacity.
         END.
         ELSE DO:
             CREATE tt-Db_filesys.
             BUFFER-COPY sys_filesys EXCEPT sys_filesys.Sample_ID TO tt-db_filesys.
             ASSIGN
                tt-Db_filesys.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_FileSys.FileSys_UsedPct = (Sys_FileSys.FileSys_UsedPct * Cf_Sample.Sample_Len)
                tt-Db_filesys.filesys_archiveType = "H" 
                tt-Db_filesys.filesys_EndDate = Cf_Sample.Sample_Date
                tt-Db_filesys.filesys_StartDate = Cf_Sample.Sample_Date
                tt-Db_filesys.Site_ID = Cf_Sample.Site_ID
                tt-Db_filesys.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_filesys.filesys_EndTime = s-end-time
                tt-Db_filesys.filesys_StartTime = s-beg-time 
                tt-Db_filesys.filesys_RecordCount = 1
                tt-db_filesys.filesys_length = Cf_Sample.Sample_len
                tt-Db_filesys.filesys_Transactions = Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
        END.
    END.
END.

/* Modify & Write out the records */

write-count = 0.
FOR EACH tt-db_filesys
    WHERE tt-db_filesys.filesys_archiveType = "H":
        
      IF NOT CAN-FIND (FIRST Ar_filesys
            WHERE AR_filesys.filesys_archiveType = "H" 
              AND Ar_filesys.Site_ID             = tt-Db_FileSys.Site_ID
              AND Ar_filesys.Resrc_ID            = tt-Db_FileSys.Resrc_ID
              AND Ar_filesys.filesys_mount       = tt-Db_FileSys.filesys_mount
              AND Ar_filesys.filesys_StartDate   = tt-Db_FileSys.filesys_StartDate
              AND Ar_filesys.filesys_StartTime   = tt-Db_FileSys.filesys_StartTime
              AND Ar_filesys.filesys_EndTime     = tt-Db_FileSys.filesys_EndTime)
        THEN DO:
              ASSIGN tt-db_filesys.filesys_usedpct = tt-db_filesys.filesys_usedpct / tt-db_filesys.filesys_Length
                     tt-db_FileSys.FileSys_Avail = tt-db_FileSys.FileSys_Avail / tt-Db_filesys.filesys_RecordCount.
              CREATE Ar_filesys.
              BUFFER-COPY tt-db_filesys TO Ar_filesys.
              RELEASE AR_filesys.
              write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Sys_FileSys table : " write-count.

RUN delete-Sys_FileSys.
/* 
** Ar-h-indexstat.p
** This include will archive the db_indexstat rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_IndexStat definition
 - added an index on tt-DB_IndexStat table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_IndexStat query to refer to AR_IndexStat not to temp-table   
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_IndexStat
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_indexstat NO-UNDO LIKE Ar_indexstat
    INDEX myindex1 indexstat_archivetype site_id resrc_id indexstat_idxnum indexstat_startdate indexstat_starttime indexstat_endtime.

FOR EACH W-Table by w-time by w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH Db_indexstat WHERE 
        Db_indexstat.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_indexstat"} 
        {include/ar-setuptimes.i}
        
        /* Search for temp record.  If one exists then update it.  If it doesn't
           exist then we need to create it and update it. */
        FIND FIRST tt-dB_indexstat
             WHERE tt-Db_indexstat.indexstat_archiveType = "H"
               AND tt-Db_indexstat.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_indexstat.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_indexstat.indexstat_idxnum = Db_indexstat.indexstat_idxnum
               AND tt-Db_indexstat.indexstat_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_indexstat.indexstat_StartTime = s-beg-time
               AND tt-Db_indexstat.indexstat_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_indexstat
         THEN ASSIGN
                tt-Db_IndexStat.IndexStat_Blockdelete = tt-Db_IndexStat.IndexStat_Blockdelete + Db_IndexStat.IndexStat_Blockdelete
                tt-Db_IndexStat.IndexStat_Create    = tt-Db_IndexStat.IndexStat_Create    + Db_IndexStat.IndexStat_Create
                tt-Db_IndexStat.IndexStat_Delete    = tt-Db_IndexStat.IndexStat_Delete    + Db_IndexStat.IndexStat_Delete
                tt-Db_IndexStat.IndexStat_Read      = tt-Db_IndexStat.IndexStat_Read      + Db_IndexStat.IndexStat_Read
                tt-Db_IndexStat.IndexStat_Split     = tt-Db_IndexStat.IndexStat_Split     + Db_IndexStat.IndexStat_Split
                tt-Db_IndexStat.IndexStat_IndexName = Db_IndexStat.IndexStat_IndexName
                tt-Db_IndexStat.IndexStat_IdxNum    = Db_IndexStat.IndexStat_IdxNum
                tt-Db_IndexStat.IndexStat_TableName = Db_IndexStat.IndexStat_TableName
                tt-Db_indexstat.indexstat_RecordCount = tt-Db_indexstat.indexstat_RecordCount + 1
                tt-db_indexstat.indexstat_length = tt-db_indexstat.indexstat_Length + Cf_Sample.Sample_len
                tt-Db_indexstat.indexstat_Transactions = tt-Db_indexstat.indexstat_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
            CREATE tt-Db_indexstat.
            BUFFER-COPY Db_indexstat EXCEPT Db_indexstat.Sample_ID TO tt-db_indexstat.
            ASSIGN
                tt-Db_indexstat.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_indexstat.indexstat_archiveType = "H" 
                tt-Db_indexstat.indexstat_EndDate = Cf_Sample.Sample_Date
                tt-Db_indexstat.indexstat_StartDate = Cf_Sample.Sample_Date
                tt-Db_indexstat.Site_ID = Cf_Sample.Site_ID
                tt-Db_indexstat.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_indexstat.indexstat_EndTime = s-end-time
                tt-Db_indexstat.indexstat_StartTime = s-beg-time 
                tt-Db_indexstat.indexstat_RecordCount = tt-Db_indexstat.indexstat_RecordCount + 1
                tt-db_indexstat.indexstat_length = tt-db_indexstat.indexstat_Length + Cf_Sample.Sample_len
                tt-Db_indexstat.indexstat_Transactions = tt-Db_indexstat.indexstat_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
        END.
    END.
END.

/* Write out the records */

write-count = 0.
FOR EACH tt-db_indexstat
    WHERE tt-db_indexstat.indexstat_archiveType = "H":

       IF NOT CAN-FIND (FIRST Ar_indexstat
           WHERE Ar_indexstat.indexstat_archiveType = "H" 
             AND Ar_indexstat.Site_ID               = tt-Db_IndexStat.Site_ID
             AND Ar_indexstat.Resrc_ID              = tt-Db_IndexStat.Resrc_ID 
             AND Ar_indexstat.indexstat_idxnum      = tt-Db_IndexStat.indexstat_idxnum
             AND Ar_indexstat.indexstat_EndDate     = tt-Db_indexstat.indexstat_EndDate
             AND Ar_indexstat.indexstat_EndTime     = tt-Db_indexstat.indexstat_EndTime
             AND Ar_indexstat.indexstat_StartTime   = tt-Db_indexstat.indexstat_StartTime)
        THEN DO:
             CREATE Ar_indexstat.
             BUFFER-COPY tt-db_indexstat TO Ar_indexstat.
             RELEASE AR_indexstat.
             write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_IndexStat table : " write-count.

RUN delete-Db_IndexStat.
/* 
** Ar-h-mem.p
** This include will archive the Sys_mem rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_mem definition
 - added an index on tt-DB_mem table to match the WHERE clause
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement  
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_Mem query to refer to AR_Mem not to temp-table   
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_Mem
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-Db_mem NO-UNDO LIKE Ar_mem
    INDEX myindex1 mem_archivetype site_id resrc_id mem_startDate mem_starttime mem_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST Sys_mem WHERE Sys_mem.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    IF AVAILABLE Sys_mem
     THEN DO:
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "sys_mem"} 
        {include/ar-setuptimes.i}
        
        /* Find the appropriate temp record.  If it exists then update it.  If
           it doesn't exist then we are going to create a new one. */
        FIND FIRST tt-dB_mem
             WHERE tt-Db_mem.mem_archiveType = "H"
               AND tt-Db_mem.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_mem.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_mem.mem_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_mem.mem_StartTime = s-beg-time
               AND tt-Db_mem.mem_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_mem
         THEN DO:
            ASSIGN
                tt-db_Mem.Mem_PgIn = tt-db_Mem.Mem_PgIn + Sys_Mem.Mem_PgIn
                tt-db_Mem.Mem_PgOut = tt-db_Mem.Mem_PgOut + Sys_Mem.Mem_PgOut
                tt-db_Mem.Mem_SysFree = tt-db_Mem.Mem_SysFree + (Cf_Sample.Sample_Len * Sys_Mem.Mem_SysFree)
                tt-db_Mem.Mem_VirtFree = tt-db_Mem.Mem_VirtFree + (Cf_Sample.Sample_Len * Sys_Mem.Mem_VirtFree)
                tt-Db_mem.mem_RecordCount = tt-Db_mem.mem_RecordCount + 1
                tt-db_mem.mem_length = tt-db_mem.mem_Length + Cf_Sample.Sample_len
                tt-Db_mem.mem_Transactions = tt-Db_mem.mem_Transactions + Cf_Sample.Sample_Trans.

                IF tt-db_Mem.Mem_VirtTot LT Sys_Mem.Mem_VirtTot THEN
                    tt-db_Mem.Mem_VirtTot = Sys_Mem.Mem_VirtTot.
                IF tt-db_Mem.Mem_SysTot LT Sys_Mem.Mem_SysTot THEN
                    tt-db_Mem.Mem_SysTot = Sys_Mem.Mem_SysTot.
         END.
         ELSE DO:
            CREATE tt-Db_mem.
            BUFFER-COPY Sys_mem EXCEPT Sys_mem.Sample_ID TO tt-db_mem.
            ASSIGN
                tt-Db_mem.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_mem.mem_archiveType = "H" 
                tt-Db_mem.mem_EndDate = Cf_Sample.Sample_Date
                tt-Db_mem.mem_StartDate = Cf_Sample.Sample_Date
                tt-Db_mem.Site_ID = Cf_Sample.Site_ID
                tt-Db_mem.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_mem.mem_EndTime = s-end-time
                tt-Db_mem.mem_StartTime = s-beg-time 
                tt-Db_mem.mem_RecordCount = tt-Db_mem.mem_RecordCount + 1
                tt-db_mem.mem_length = tt-db_mem.mem_Length + Cf_Sample.Sample_len
                tt-Db_mem.mem_Transactions = tt-Db_mem.mem_Transactions + Cf_Sample.Sample_Trans
                tt-db_Mem.Mem_PgIn = Sys_Mem.Mem_PgIn
                tt-db_Mem.Mem_PgOut = Sys_Mem.Mem_PgOut
                tt-db_Mem.Mem_SysFree = (Cf_Sample.Sample_Len * Sys_Mem.Mem_SysFree)
                tt-db_Mem.Mem_VirtFree = (Cf_Sample.Sample_Len * Sys_Mem.Mem_VirtFree).
                new-recs = new-recs + 1.
        END.
    END. /*  IF AVAILABLE Sys_mem THEN */
END.  /* FOR EACH W-Table by w-time by w-date */

/* Modify & Write out the records */

write-count = 0.
FOR EACH tt-db_mem 
    WHERE tt-db_mem.mem_archiveType = "H":

        IF NOT CAN-FIND (FIRST Ar_mem
            WHERE Ar_mem.mem_archiveType = "H" 
              AND Ar_mem.Site_ID         = tt-Db_Mem.Site_ID
              AND Ar_mem.Resrc_ID        = tt-Db_Mem.Resrc_ID 
              AND Ar_mem.mem_StartDate   =  tt-Db_Mem.mem_StartDate
              AND Ar_mem.mem_StartTime   = tt-Db_Mem.mem_StartTime
              AND Ar_mem.mem_EndTime     = tt-Db_Mem.mem_EndTime)
         THEN DO:
              ASSIGN
                tt-db_Mem.Mem_PgIn     = tt-db_Mem.Mem_PgIn 
                tt-db_Mem.Mem_PgOut    = tt-db_Mem.Mem_PgOut
                tt-db_Mem.Mem_VirtFree = tt-db_Mem.Mem_VirtFree / tt-db_Mem.Mem_Length
                tt-db_mem.mem_sysfree  = tt-db_mem.mem_sysfree / tt-db_mem.mem_Length.
              CREATE Ar_mem.
              BUFFER-COPY tt-db_mem TO Ar_mem.
              RELEASE Ar_mem.
              write-count = write-count + 1.
         END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Sys_Mem table : " write-count.

RUN delete-Sys_Mem.
/* 
** Ar-h-net.p
** This include will archive the net_data rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-DB_Net definition
 - added an index on tt-DB_Net table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_Net query to refer to AR_Net not to temp-table   
 - reorder WHERE clause to match the newly added index
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-DB_Mem
*/

{include/ar-definitions.i}

DEFINE TEMP-TABLE tt-Db_net NO-UNDO LIKE Ar_net
    INDEX net_archivetype site_id resrc_id net_startDate net_starttime net_endtime net_status.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST net_data WHERE net.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
    IF AVAILABLE net_data
     THEN DO:
        /* Add to the temp table for deletes*/
        {include/ar-delete-table.i "net_data"}.
        {include/ar-setuptimes.i}.

        FIND FIRST tt-dB_net
             WHERE tt-Db_net.net_archiveType = "H"
               AND tt-Db_net.Site_ID         = Cf_Sample.Site_ID
               AND tt-Db_net.Resrc_ID        = Cf_Sample.Resrc_ID
               AND tt-Db_net.net_StartDate   = Cf_Sample.Sample_Date
               AND tt-Db_net.net_StartTime   = s-beg-time 
               AND tt-Db_net.net_EndTime     = s-end-time
               AND tt-Db_net.Net_Status      = Net_Data.Net_Status
        NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_net
         THEN DO:
              ASSIGN
                tt-db_net.Net_Time = tt-db_net.Net_Time + Net_Data.Net_Time
                tt-Db_net.net_RecordCount = tt-Db_net.net_RecordCount + 1
                tt-db_net.net_length = tt-db_net.net_Length + Cf_Sample.Sample_len
                tt-Db_net.net_Transactions = tt-Db_net.net_Transactions + Cf_Sample.Sample_Trans.

              IF tt-db_net.Net_Max LT Net_Data.Net_Time THEN tt-db_net.Net_Max = Net_Data.Net_Time.
              IF tt-db_net.Net_Min = 0 THEN tt-db_net.Net_Min = Net_Data.Net_Time.
              IF tt-db_net.Net_Min GT Net_Data.Net_Time THEN tt-db_net.Net_Min = Net_Data.Net_Time.
         END.
         ELSE DO:
              CREATE tt-Db_net.
              BUFFER-COPY net_data EXCEPT net.Sample_ID TO tt-db_net.
              ASSIGN
                tt-Db_net.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-db_net.net_archivetype = "H" 
                tt-db_net.net_enddate = Cf_Sample.Sample_Date
                tt-db_net.net_startdate = Cf_Sample.Sample_Date
                tt-db_net.site_id = Cf_Sample.Site_ID
                tt-db_net.resrc_id = Cf_Sample.Resrc_ID
                tt-db_net.net_endtime = s-end-time
                tt-db_net.net_starttime = s-beg-time 
                tt-db_net.net_max = Net_Data.Net_Time
                tt-db_net.net_min = Net_Data.Net_Time
                tt-db_net.net_recordcount = tt-Db_net.net_RecordCount + 1
                tt-db_net.net_length = tt-db_net.net_Length + Cf_Sample.Sample_len
                tt-db_net.net_transactions = tt-Db_net.net_Transactions + Cf_Sample.Sample_Trans.
                new-recs = new-recs + 1.
         END.
    END.
END.

/* Write out the records */

DEF VAR write-i AS INT NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-db_net WHERE tt-db_net.net_archiveType = "H" NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
         IF count-i <> 0 THEN FIND NEXT tt-db_net WHERE tt-db_net.net_archiveType = "H" NO-LOCK NO-ERROR.
         IF AVAILABLE tt-db_net
          THEN DO:
               count-i = count-i + 1.
               IF NOT CAN-FIND (FIRST Ar_net
                   WHERE Ar_net.net_archiveType = "H" 
                     AND Ar_net.Site_ID         = tt-Db_Net.Site_ID
                     AND Ar_net.Resrc_ID        = tt-Db_Net.Resrc_ID
                     AND Ar_net.Net_Status      = tt-Db_Net.Net_Status 
                     AND Ar_net.net_StartDate   = tt-Db_Net.net_StartDate
                     AND Ar_net.net_StartTime   = tt-Db_Net.net_StartTime
                     AND Ar_net.net_EndTime     = tt-Db_Net.net_EndTime)
                 THEN DO:
                      tt-db_net.Net_Time = tt-db_net.Net_Time / tt-db_net.net_RecordCount.
                      CREATE Ar_net.
                      BUFFER-COPY tt-db_net TO Ar_net.
                      RELEASE AR_net.
                      write-count = write-count + 1.
                 END.
          END.
          ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Net_Data table : " write-count.
               write-i = 99999.
               LEAVE.
          END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-Net_Data.
/* 
** Ar-h-oe_actASProc.p
** This program will archive the OE_ActASProc rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-ar-OEActASProc definition
 - added an index on tt-ar-OEActASProc table to match the WHERE clause
 - removed first DO TRANSACTION from repeat2-loop as we're operating on the temp-tables only
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - reorder the query for AR_OE* table to better match newly added index
 
llaubach 08/2006
 - moved FIND FIRST tt-DB_CPU outside the REPEAT & WHILE loops and added dedicated counter,
   as we could end up in neverending loop
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-OEAct..
*/

{include/ar-definitions.i}

sec-name = "Starting Hourly Section".
{include/ar-debug.i "sec-name"}

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActASProc: Begin creating hourly records...".

DEFINE TEMP-TABLE tt-ar-OEActASProc NO-UNDO LIKE Ar_OE_ActASProc
    INDEX myindex1 ActASProc_archivetype actasproc_startdate actasproc_starttime site_id resrc_id actbrk_uuid actbrk_pid actasproc_endtime actasproc_name.

DEFINE VARIABLE i2 AS INT NO-UNDO.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST OE_ActASProc WHERE OE_ActASProc.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.

IF AVAILABLE OE_ActASProc
THEN DO:

repeat2-loop:

REPEAT:
    DO i2 = 1 to 5000:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "OE_ActASProc"} 
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */
        FIND FIRST tt-ar-OEActASProc
             WHERE tt-ar-OEActASProc.ActASProc_archiveType = "H"
               AND tt-ar-OEActASProc.ActASProc_StartDate = Cf_Sample.Sample_Date
               AND tt-ar-OEActASProc.ActASProc_StartTime = s-beg-time
               AND tt-ar-OEActASProc.Site_ID = Cf_Sample.Site_ID
               AND tt-ar-OEActASProc.Resrc_ID = Cf_Sample.Resrc_ID 
               AND tt-ar-OEActASProc.ActBrk_UUID = OE_ActASProc.ActBrk_UUID
               AND tt-ar-OEActASProc.ActBrk_PID = OE_ActASProc.ActBrk_PID
               AND tt-ar-OEActASProc.ActASProc_EndTime = s-end-time
               AND tt-ar-OEActASProc.ActASProc_Name = OE_ActASProc.ActASProc_Name
        NO-LOCK NO-ERROR.

        IF NOT AVAILABLE tt-ar-OEActASProc
         THEN DO:
            CREATE tt-ar-OEActASProc.
            ASSIGN
                tt-ar-OEActASProc.ActBrk_PID =         OE_ActASProc.ActBrk_PID
                tt-ar-OEActASProc.ActBrk_UUID =        OE_ActASProc.ActBrk_UUID
                tt-ar-OEActASProc.ActASProc_Parent =   OE_ActASProc.ActASProc_Parent
                tt-ar-OEActASProc.ActASProc_ProcType = OE_ActASProc.ActASProc_ProcType
                tt-ar-OEActASProc.ActASProc_Name =     OE_ActASProc.ActASProc_Name
                tt-ar-OEActASProc.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-ar-OEActASProc.ActASProc_archiveType  = "H" 
                tt-ar-OEActASProc.ActASProc_EndDate      = Cf_Sample.Sample_Date
                tt-ar-OEActASProc.ActASProc_StartDate    = Cf_Sample.Sample_Date
                tt-ar-OEActASProc.Site_ID             = Cf_Sample.Site_ID
                tt-ar-OEActASProc.Resrc_ID            = Cf_Sample.Resrc_ID
                tt-ar-OEActASProc.ActASProc_EndTime      = s-end-time
                tt-ar-OEActASProc.ActASProc_StartTime    = s-beg-time. 
                new-recs = new-recs + 1.
         END.
       
    ASSIGN
        tt-ar-OEActASProc.ActASProc_Calls        = tt-ar-OEActASProc.ActASProc_Calls + OE_ActASProc.ActASProc_Calls
        tt-ar-OEActASProc.ActASProc_TotTime      = tt-ar-OEActASProc.ActASProc_TotTime + OE_ActASProc.ActASProc_TotTime
        tt-ar-OEActASProc.ActASProc_SuccessCount = tt-ar-OEActASProc.ActASProc_SuccessCount + OE_ActASProc.ActASProc_SuccessCount
        tt-ar-OEActASProc.ActASProc_ErrorCount   = tt-ar-OEActASProc.ActASProc_ErrorCount + OE_ActASProc.ActASProc_ErrorCount
        tt-ar-OEActASProc.ActASProc_QuitCount    = tt-ar-OEActASProc.ActASProc_QuitCount + OE_ActASProc.ActASProc_QuitCount
        tt-ar-OEActASProc.ActASProc_StopCount    = tt-ar-OEActASProc.ActASProc_StopCount + OE_ActASProc.ActASProc_StopCount
        tt-ar-OEActASProc.ActASProc_DebugCount   = tt-ar-OEActASProc.ActASProc_DebugCount + OE_ActASProc.ActASProc_DebugCount
        tt-ar-OEActASProc.ActASProc_RecordCount  = tt-ar-OEActASProc.ActASProc_RecordCount   + 1
        tt-ar-OEActASProc.ActASProc_Length       = tt-ar-OEActASProc.ActASProc_Length + Cf_Sample.Sample_len.

        IF tt-ar-OEActASProc.ActASProc_MaxTime LT OE_ActASProc.ActASProc_MaxTime THEN tt-ar-OEActASProc.ActASProc_MaxTime  = OE_ActASProc.ActASProc_MaxTime.
        FIND NEXT OE_ActASProc WHERE OE_ActASProc.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
        IF NOT AVAILABLE OE_ActASProc THEN LEAVE Repeat2-loop.
        
    END. /* DO i2 = 1 to 5000 */
END. /* REPEAT LOOP */
END. /* IF AVAILABLE FIRST OE_ACTASPROC */
END. /* For each W-Table by w-time by w-date: */

/* Modify & Write out the records */

EMPTY TEMP-TABLE hour-table.

DEF VAR write-i AS INT NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-ar-OEActASProc NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
         IF count-i <> 0 THEN FIND NEXT tt-ar-OEActASProc NO-LOCK NO-ERROR.
         IF AVAILABLE tt-ar-OEActASProc
          THEN DO:
               count-i = count-i + 1.
               IF NOT CAN-FIND (FIRST Ar_OE_ActASProc WHERE 
                   Ar_OE_ActASProc.ActASProc_archiveType = "H" AND
                   Ar_OE_ActASProc.Site_ID =               tt-ar-OEActASProc.Site_ID AND
                   Ar_OE_ActASProc.Resrc_ID =              tt-ar-OEActASProc.Resrc_ID AND
                   Ar_OE_ActASProc.ActASProc_StartDate =   tt-ar-OEActASProc.ActASProc_StartDate AND
                   Ar_OE_ActASProc.ActASProc_EndDate =     tt-ar-OEActASProc.ActASProc_EndDate AND
                   Ar_OE_ActASProc.ActBrk_UUID =           tt-ar-OEActASProc.ActBrk_UUID AND
                   Ar_OE_ActASProc.ActBrk_PID =            tt-ar-OEActASProc.ActBrk_PID AND
                   Ar_OE_ActASProc.ActASProc_Name =        tt-ar-OEActASProc.ActASProc_Name AND
                   Ar_OE_ActASProc.ActASProc_StartTime =   tt-ar-OEActASProc.ActASProc_StartTime)
                THEN DO:
                     CREATE Ar_OE_ActASProc.
                     BUFFER-COPY tt-ar-OEActASProc TO Ar_OE_ActASProc.
                     CREATE hour-table.
                     hour-rowid = ROWID(Ar_OE_ActASProc).
                     RELEASE Ar_OE_ActASProc.
                     RELEASE hour-table.
                     write-count = write-count + 1.
                END.
          END.
          ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly compaction records written for OE_ActASProc table : " write-count.
               write-i = 99999.
               LEAVE.
          END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-OE_ActASProc.

sec-name = "Ending Hourly Section".
{include/ar-debug.i "sec-name"}
/* 
** Ar-h-oe_actbrk.p
** This program will archive the OE_ActBrk rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-ar-OEActBrk definition
 - added an index on tt-ar-OEActBrk table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replaced FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  

llaubach 08/2006 
 - moved FIND FIRST tt-DB_CPU outside the REPEAT & WHILE loops and added dedicated counter,
   as we could end up in neverending loop
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-OEAct..
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-ar-OEActBrk NO-UNDO LIKE Ar_OE_ActBrk
    INDEX myindex1 actbrk_archivetype actbrk_startdate actbrk_starttime site_id resrc_id actbrk_uuid actbrk_pid actbrk_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH OE_ActBrk WHERE 
        OE_ActBrk.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes*/
        {include/ar-delete-table.i "OE_ActBrk"} 
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */
        FIND FIRST tt-ar-OEActBrk
             WHERE tt-ar-OEActBrk.ActBrk_archiveType = "H"
               AND tt-ar-OEActBrk.ActBrk_StartDate = Cf_Sample.Sample_Date
               AND tt-ar-OEActBrk.ActBrk_StartTime = s-beg-time
               AND tt-ar-OEActBrk.Site_ID = Cf_Sample.Site_ID 
               AND tt-ar-OEActBrk.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-ar-OEActBrk.ActBrk_UUID = OE_ActBrk.ActBrk_UUID
               AND tt-ar-OEActBrk.ActBrk_PID = OE_ActBrk.ActBrk_PID
               AND tt-ar-OEActBrk.ActBrk_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF NOT AVAILABLE tt-ar-OEActBrk
         THEN DO:
              CREATE tt-ar-OEActBrk.
                
            /* BUFFER-COPY OE_ActBrk EXCEPT 
                OE_ActBrk.Sample_ID 
                OE_ActBrk.ActBrk_CurrClients
                OE_ActBrk.ActBrk_CurrServers
                OE_ActBrk.ActBrk_CurrQueue
                OE_ActBrk.ActBrk_ReqRec 
                OE_ActBrk.ActBrk_ReqComp 
                OE_ActBrk.ActBrk_ReqQueued
                OE_ActBrk.ActBrk_TotClients
                OE_ActBrk.ActBrk_ReqRejected
                OE_ActBrk.ActBrk_RecordCount  
                OE_ActBrk.ActBrk_Length
            
            TO tt-ar-OEActBrk. */

            ASSIGN
                tt-ar-OEActBrk.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-ar-OEActBrk.ActBrk_archiveType  = "H" 
                tt-ar-OEActBrk.ActBrk_EndDate      = Cf_Sample.Sample_Date
                tt-ar-OEActBrk.ActBrk_StartDate    = Cf_Sample.Sample_Date
                tt-ar-OEActBrk.Resrc_ID            = Cf_Sample.Resrc_ID
                tt-ar-OEActBrk.Site_ID             = Cf_Sample.Site_ID
                tt-ar-OEActBrk.ActBrk_PID          = OE_ActBrk.ActBrk_PID
                tt-ar-OEActBrk.ActBrk_UUID         = OE_ActBrk.ActBrk_UUID
                tt-ar-OEActBrk.ActBrk_Name         = OE_ActBrk.ActBrk_Name
                tt-ar-OEActBrk.ActBrk_Mode         = OE_ActBrk.ActBrk_Mode
                tt-ar-OEActBrk.ActBrk_EndTime      = s-end-time
                tt-ar-OEActBrk.ActBrk_StartTime    = s-beg-time. 
                new-recs = new-recs + 1.
        END.
       
        ASSIGN
            tt-ar-OEActBrk.ActBrk_CurrClients  = tt-ar-OEActBrk.ActBrk_CurrClients + OE_ActBrk.ActBrk_CurrClients
            tt-ar-OEActBrk.ActBrk_CurrServers  = tt-ar-OEActBrk.ActBrk_CurrServers + OE_ActBrk.ActBrk_CurrServers
            tt-ar-OEActBrk.ActBrk_CurrQueue    = tt-ar-OEActBrk.ActBrk_CurrQueue + OE_ActBrk.ActBrk_CurrQueue
            tt-ar-OEActBrk.ActBrk_ReqRec       = tt-ar-OEActBrk.ActBrk_ReqRec + OE_ActBrk.ActBrk_ReqRec
            tt-ar-OEActBrk.ActBrk_ReqComp      = tt-ar-OEActBrk.ActBrk_ReqComp + OE_ActBrk.ActBrk_ReqComp
            tt-ar-OEActBrk.ActBrk_ReqQueued    = tt-ar-OEActBrk.ActBrk_ReqQueued + OE_ActBrk.ActBrk_ReqQueued
            tt-ar-OEActBrk.ActBrk_ReqRejected  = tt-ar-OEActBrk.ActBrk_ReqRejected + OE_ActBrk.ActBrk_ReqRejected
            tt-ar-OEActBrk.ActBrk_RecordCount  = tt-ar-OEActBrk.ActBrk_RecordCount + 1
            tt-ar-OEActBrk.ActBrk_Length       = tt-ar-OEActBrk.ActBrk_Length + Cf_Sample.Sample_len.

          IF tt-ar-OEActBrk.ActBrk_TotClients   LT OE_ActBrk.ActBrk_TotClients
           THEN tt-ar-OEActBrk.ActBrk_TotClients   = OE_ActBrk.ActBrk_TotClients.
        
    END. /* IF AVAILABLE OE_ActBrk THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

EMPTY TEMP-TABLE hour-table.

DEF VAR write-i AS INT NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-ar-OEActBrk WHERE tt-ar-OEActBrk.ActBrk_archiveType = "H" NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
         IF count-i <> 0 THEN FIND NEXT tt-ar-OEActBrk WHERE tt-ar-OEActBrk.ActBrk_archiveType = "H" NO-LOCK NO-ERROR.
         IF AVAILABLE tt-ar-OEActBrk
          THEN DO:
               count-i = count-i + 1.
               IF NOT CAN-FIND (FIRST Ar_OE_ActBrk WHERE
                        Ar_OE_ActBrk.ActBrk_archiveType = "H" AND
                        Ar_OE_ActBrk.ActBrk_StartDate = tt-ar-OEActBrk.ActBrk_StartDate AND
                        Ar_OE_ActBrk.ActBrk_StartTime = tt-ar-OEActBrk.ActBrk_StartTime AND
                        Ar_OE_ActBrk.ActBrk_EndTime = tt-ar-OEActBrk.ActBrk_EndTime AND
                        Ar_OE_ActBrk.Site_ID = tt-ar-OEActBrk.Site_ID AND
                        ar_OE_ActBrk.Resrc_ID = tt-ar-OEActBrk.Resrc_ID AND
                        Ar_OE_ActBrk.ActBrk_UUID = tt-ar-OEActBrk.ActBrk_UUID AND
                        Ar_OE_ActBrk.ActBrk_PID = tt-ar-OEActBrk.ActBrk_PID)
                THEN DO:
                     ASSIGN
                         tt-ar-OEActBrk.ActBrk_CurrClients = tt-ar-OEActBrk.ActBrk_CurrClients / tt-ar-OEActBrk.ActBrk_RecordCount
                         tt-ar-OEActBrk.ActBrk_CurrServers = tt-ar-OEActBrk.ActBrk_CurrServers / tt-ar-OEActBrk.ActBrk_RecordCount
                         tt-ar-OEActBrk.ActBrk_CurrQueue   = tt-ar-OEActBrk.ActBrk_CurrQueue / tt-ar-OEActBrk.ActBrk_RecordCount.
                     CREATE Ar_OE_ActBrk.
                     BUFFER-COPY tt-ar-OEActBrk TO Ar_OE_ActBrk.
                     CREATE hour-table.
                     hour-rowid = ROWID(Ar_OE_ActBrk).
                     RELEASE Ar_OE_ActBrk.
                     RELEASE hour-table.
                     write-count = write-count + 1.
                END.
          END.
          ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for OE_ActBrk table : " write-count.
               write-i = 99999.
               LEAVE.
          END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-OE_ActBrk.

sec-name = "Ending Hourly Section".
{include/ar-debug.i "sec-name"}

/* 
** Ar-h-oe_actserv.p
** This program will archive the OE_ActSrv rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-ar-OEActASServ definition
 - added an index on tt-ar-OEActASserv table to match the WHERE clause
 - removed first DO TRANSACTION from repeat2-loop as we're operating on the temp-tables only
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_OE* query to refer to AR_OE* not to temp-table   
 - reorder WHERE clause to match the newly added index
 
llaubach 08/2006 
 - moved FIND FIRST tt-DB_CPU outside the REPEAT & WHILE loops and added dedicated counter,
   as we could end up in neverending loop
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-OEAct..
*/

{include/ar-definitions.i}

DEFINE TEMP-TABLE tt-ar-OEActServ NO-UNDO LIKE Ar_OE_ActServ
    INDEX myindex1 actserv_archivetype actserv_startdate actserv_starttime site_id resrc_id actbrk_uuid actserv_pid actserv_status actserv_endtime.

DEFINE VARIABLE i3 AS INTEGER NO-UNDO.
DEFINE VARIABLE loop-cnt AS INTEGER NO-UNDO.

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActSrv: Begin creating hourly records...".

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FIND FIRST OE_ActSrv WHERE OE_ActSrv.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.

IF AVAILABLE OE_ActSrv THEN
DO:

repeat-loop:

REPEAT:
   DO i3 = 1 to 5000:

        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "OE_ActSrv"} 
        {include/ar-setuptimes.i}

        /* Search for the temp record. If it exists then update it.  If it doesn't
           exist then create a new one. */
        FIND FIRST tt-ar-OEActServ
             WHERE tt-ar-OEActServ.ActServ_archiveType = "H" 
               AND tt-ar-OEActServ.ActServ_StartDate = Cf_Sample.Sample_Date
               AND tt-ar-OEActServ.ActServ_StartTime = s-beg-time
               AND tt-ar-OEActServ.Site_ID = Cf_Sample.Site_ID 
               AND tt-ar-OEActServ.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-ar-OEActServ.ActBrk_UUID = OE_ActSrv.ActBrk_UUID
               AND tt-ar-OEActServ.ActServ_PID = OE_ActSrv.ActSrv_PID
               AND tt-ar-OEActServ.ActServ_Status = Oe_ActSrv.ActSrv_Status
               AND tt-ar-OEActServ.ActServ_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF NOT AVAILABLE tt-ar-OEActServ
         THEN DO:
              CREATE tt-ar-OEActServ.
              BUFFER-COPY OE_ActSrv EXCEPT 
                OE_ActSrv.Sample_ID 
                OE_ActSrv.ActSrv_IdleCount
                OE_ActSrv.ActSrv_IdleTime
                OE_ActSrv.ActSrv_BusyCount
                OE_ActSrv.ActSrv_BusyTime
                OE_ActSrv.ActSrv_LockedCount
                OE_ActSrv.ActSrv_LockedTime
                TO tt-ar-OEActServ.
            
              ASSIGN
                tt-ar-OEActServ.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-ar-OEActServ.ActServ_archiveType  = "H" 
                tt-ar-OEActServ.ActServ_EndDate      = Cf_Sample.Sample_Date
                tt-ar-OEActServ.ActServ_StartDate    = Cf_Sample.Sample_Date
                tt-ar-OEActServ.Site_ID             = Cf_Sample.Site_ID
                tt-ar-OEActServ.Resrc_ID            = Cf_Sample.Resrc_ID
                tt-ar-OEActServ.ActServ_PID         = OE_ActSrv.ActSrv_PID
                tt-ar-OEActServ.ActServ_Status         = OE_ActSrv.ActSrv_Status
                tt-ar-OEActServ.ActServ_EndTime      = s-end-time
                tt-ar-OEActServ.ActServ_StartTime    = s-beg-time. 
                new-recs = new-recs + 1.
         END.
         ASSIGN
           tt-ar-OEActServ.ActServ_IdleCount   = tt-ar-OEActServ.ActServ_IdleCount + OE_ActSrv.ActSrv_IdleCount
           tt-ar-OEActServ.ActServ_IdleTime    = tt-ar-OEActServ.ActServ_IdleTime + OE_ActSrv.ActSrv_IdleTime
           tt-ar-OEActServ.ActServ_BusyCount   = tt-ar-OEActServ.ActServ_BusyCount + OE_ActSrv.ActSrv_BusyCount
           tt-ar-OEActServ.ActServ_BusyTime    = tt-ar-OEActServ.ActServ_BusyTime + OE_ActSrv.ActSrv_BusyTime
           tt-ar-OEActServ.ActServ_LockedCount = tt-ar-OEActServ.ActServ_LockedCount + OE_ActSrv.ActSrv_LockedCount
           tt-ar-OEActServ.ActServ_LockedTime  = tt-ar-OEActServ.ActServ_LockedTime + OE_ActSrv.ActSrv_LockedTime
           tt-ar-OEActServ.ActServ_RecordCount =  tt-ar-OEActServ.ActServ_RecordCount + 1
           tt-ar-OEActServ.ActServ_Length      =  tt-ar-OEActServ.ActServ_Length + Cf_Sample.Sample_len.

        FIND NEXT OE_ActSrv WHERE OE_ActSrv.Sample_ID = Cf_Sample.Sample_ID NO-LOCK NO-ERROR.
        IF NOT AVAILABLE OE_ActSrv THEN LEAVE Repeat-loop.
        
    END. /* IF AVAILABLE OE_ActSrv THEN */
END. /* DO i3 = 1 to 5000 */
END. /* AVAILABLE */
END. /* FOR EACH  */

/* Modify & Write out the records */

EMPTY TEMP-TABLE hour-table.

DEF VAR write-i AS INT NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-ar-OEActServ WHERE tt-ar-OEActServ.ActServ_archiveType = "H" NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
         IF count-i <> 0 THEN FIND NEXT tt-ar-OEActServ WHERE tt-ar-OEActServ.ActServ_archiveType = "H" NO-LOCK NO-ERROR.
         IF AVAILABLE tt-ar-OEActServ
          THEN DO:
               count-i = count-i + 1.
               IF NOT CAN-FIND (FIRST Ar_OE_ActServ
                   WHERE Ar_OE_ActServ.ActServ_archiveType = "H"
                     AND Ar_OE_ActServ.Site_ID             = tt-ar-OEActServ.Site_ID
                     AND Ar_OE_ActServ.Resrc_ID            = tt-ar-OEActServ.Resrc_ID
                     AND Ar_OE_ActServ.ActBrk_UUID         = tt-ar-OEActServ.ActBrk_UUID
                     AND Ar_OE_ActServ.ActServ_PID         = tt-ar-OEActServ.ActServ_PID
                     AND Ar_OE_ActServ.ActServ_Status      = tt-ar-OEActServ.ActServ_Status
                     AND Ar_OE_ActServ.ActServ_StartDate   = tt-ar-OEActServ.ActServ_StartDate
                     AND Ar_OE_ActServ.ActServ_StartTime   = tt-ar-OEActServ.ActServ_StartTime
                     AND Ar_OE_ActServ.ActServ_EndTime     = tt-ar-OEActServ.ActServ_EndTime)
                THEN DO:
                     CREATE Ar_OE_ActServ.
                     BUFFER-COPY tt-ar-OEActServ TO Ar_OE_ActServ.
                     CREATE hour-table.
                     hour-rowid = ROWID(Ar_OE_ActServ).
                     RELEASE Ar_OE_ActServ.
                     RELEASE hour-table.
                     write-count = write-count + 1.
                 END.
          END.
          ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActSrv: Hourly Compaction Records Written for OE_ActSrv table : " write-count SKIP.
               write-i = 99999.
               LEAVE.
          END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-OE_ActSrv.

sec-name = "Ending Hourly Section".
{include/ar-debug.i "sec-name"}
/* 
** Ar-h-oe_actWSProc.p
** This program will archive the OE_ActWSProc rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-ar-OEActWSProc definition
 - added an index on tt-ar-OEActWSProc table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - reorder WHERE clause to match the newly added index
 
llaubach 08/2006 
 - moved FIND FIRST tt-DB_CPU outside the REPEAT & WHILE loops and added dedicated counter,
   as we could end up in neverending loop
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-OEAct..
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-ar-OEActWSProc NO-UNDO LIKE Ar_OE_ActWSProc
    INDEX myindex1 actwsproc_archivetype actwsproc_startdate actwsproc_starttime site_id resrc_id actbrk_uuid actbrk_pid actwsproc_endtime actwsproc_name.

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActWSProc: Begin hourly record creation. " SKIP.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH OE_ActWSProc WHERE 
        OE_ActWSProc.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "OE_ActWSProc"} 
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */
        FIND FIRST tt-ar-OEActWSProc
             WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "H"
               AND tt-ar-OEActWSProc.ActWSProc_StartDate   = Cf_Sample.Sample_Date
               AND tt-ar-OEActWSProc.ActWSProc_StartTime   = s-beg-time
               AND tt-ar-OEActWSProc.Site_ID               = Cf_Sample.Site_ID
               AND tt-ar-OEActWSProc.Resrc_ID              = Cf_Sample.Resrc_ID
               AND tt-ar-OEActWSProc.ActBrk_UUID           = OE_ActWSProc.ActBrk_UUID
               AND tt-ar-OEActWSProc.ActBrk_PID            = OE_ActWSProc.ActBrk_PID
               AND tt-ar-OEActWSProc.ActWSProc_EndTime     = s-end-time
               AND tt-ar-OEActWSProc.ActWSProc_Name        = OE_ActWSProc.ActWSProc_Name
        NO-LOCK NO-ERROR.

        IF NOT AVAILABLE tt-ar-OEActWSProc
         THEN DO:
              CREATE tt-ar-OEActWSProc.
              ASSIGN
                tt-ar-OEActWSProc.ActBrk_PID            = OE_ActWSProc.ActBrk_PID
                tt-ar-OEActWSProc.ActBrk_UUID           = OE_ActWSProc.ActBrk_UUID
                tt-ar-OEActWSProc.ActWSProc_Parent      = OE_ActWSProc.ActWSProc_Parent
                tt-ar-OEActWSProc.ActWSProc_ProcType    = OE_ActWSProc.ActWSProc_ProcType
                tt-ar-OEActWSProc.ActWSProc_Name        = OE_ActWSProc.ActWSProc_Name
                tt-ar-OEActWSProc.sample_id             = NEXT-VALUE (ar_sample-seq)
                tt-ar-OEActWSProc.ActWSProc_archiveType = "H" 
                tt-ar-OEActWSProc.ActWSProc_EndDate     = Cf_Sample.Sample_Date
                tt-ar-OEActWSProc.ActWSProc_StartDate   = Cf_Sample.Sample_Date
                tt-ar-OEActWSProc.Site_ID               = Cf_Sample.Site_ID
                tt-ar-OEActWSProc.Resrc_ID              = Cf_Sample.Resrc_ID
                tt-ar-OEActWSProc.ActWSProc_EndTime     = s-end-time
                tt-ar-OEActWSProc.ActWSProc_StartTime   = s-beg-time
                new-recs = new-recs + 1.
         END.
       
    ASSIGN
       tt-ar-OEActWSProc.ActWSProc_Calls       = tt-ar-OEActWSProc.ActWSProc_Calls + OE_ActWSProc.ActWSProc_Calls
       tt-ar-OEActWSProc.ActWSProc_TotTime     = tt-ar-OEActWSProc.ActWSProc_TotTime + OE_ActWSProc.ActWSProc_TotTime
       tt-ar-OEActWSProc.ActWSProc_RecordCount = tt-ar-OEActWSProc.ActWSProc_RecordCount   + 1
       tt-ar-OEActWSProc.ActWSProc_Length      = tt-ar-OEActWSProc.ActWSProc_Length + Cf_Sample.Sample_len.
     
    IF tt-ar-OEActWSProc.ActWSProc_MaxTime  LT OE_ActWSProc.ActWSProc_MaxTime
     THEN tt-ar-OEActWSProc.ActWSProc_MaxTime  = OE_ActWSProc.ActWSProc_MaxTime .
        
    END. /* IF AVAILABLE OE_ActWSProc THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

EMPTY TEMP-TABLE hour-table.

DEF VAR write-i AS INT NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-ar-OEActWSProc WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "H" NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
         IF count-i <> 0 THEN FIND NEXT tt-ar-OEActWSProc WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "H" NO-LOCK NO-ERROR.
         IF AVAILABLE tt-ar-OEActWSProc
          THEN DO:
               count-i = count-i + 1.
               IF NOT CAN-FIND (FIRST Ar_OE_ActWSProc WHERE
                   Ar_OE_ActWSProc.ActWSProc_archiveType = "H" AND
                   Ar_OE_ActWSProc.Site_ID =               tt-ar-OEActWSProc.Site_ID AND
                   Ar_OE_ActWSProc.Resrc_ID =              tt-ar-OEActWSProc.Resrc_ID AND
                   Ar_OE_ActWSProc.ActBrk_UUID =           tt-ar-OEActWSProc.ActBrk_UUID AND
                   Ar_OE_ActWSProc.ActBrk_PID =            tt-ar-OEActWSProc.ActBrk_PID AND
                   Ar_OE_ActWSProc.ActWSProc_Name =        tt-ar-OEActWSProc.ActWSProc_Name AND
                   Ar_OE_ActWSProc.ActWSProc_StartDate =   tt-ar-OEActWSProc.ActWSProc_StartDate AND
                   Ar_OE_ActWSProc.ActWSProc_StartTime =   tt-ar-OEActWSProc.ActWSProc_StartTime AND
                   Ar_OE_ActWSProc.ActWSProc_EndTime =     tt-ar-OEActWSProc.ActWSProc_EndTime)
                THEN DO:
                     CREATE Ar_OE_ActWSProc.
                     BUFFER-COPY tt-ar-OEActWSProc TO Ar_OE_ActWSProc.
                     CREATE hour-table.
                     hour-rowid = ROWID(Ar_OE_ActWSProc).
                     RELEASE Ar_OE_ActWSProc.
                     RELEASE hour-table.
                     write-count = write-count + 1.
                END.
          END.
          ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly compaction records written for OE_ActWSProc table : " write-count SKIP.
               write-i = 99999.
               LEAVE.
          END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-OE_ActWSProc.

sec-name = "Ending Hourly Section".
{include/ar-debug.i "sec-name"}


/* 
** Ar-h-oe_actserv.p
** This program will archive the OE_AppService rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-ar-OEAppService definition
 - added an index on tt-ar-OEAppService table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_OE* query to refer to AR_OE* not to temp-table    
 
llaubach 08/2006 
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-OEAct..
*/

{include/ar-definitions.i}

DEFINE TEMP-TABLE tt-ar-OEAppService NO-UNDO LIKE Ar_OE_AppService
    INDEX myindex actbrk_UUID apps_servicename.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH OE_AppService WHERE 
        OE_AppService.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "OE_AppService"} 
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */
        FIND FIRST tt-ar-OEAppService
             WHERE tt-ar-OEAppService.ActBrk_UUID = OE_AppService.ActBrk_UUID 
               AND tt-ar-OEAppService.APPS_ServiceName = OE_AppService.APPS_ServiceName
        NO-LOCK NO-ERROR.

        IF NOT AVAILABLE tt-ar-OEAppService
         THEN DO:
              CREATE tt-ar-OEAppService.
              BUFFER-COPY OE_AppService EXCEPT OE_AppService.Sample_ID TO tt-ar-OEAppService.
              ASSIGN tt-ar-OEAppService.sample_id = NEXT-VALUE (ar_sample-seq)
                     new-recs = new-recs + 1.
        END.
    END. /* IF AVAILABLE OE_AppService THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

EMPTY TEMP-TABLE hour-table.

write-count = 0.
FOR EACH tt-ar-OEAppService:
        
        IF NOT CAN-FIND (FIRST Ar_OE_AppService
            WHERE Ar_OE_AppService.ActBrk_UUID = Ar_OE_AppService.ActBrk_UUID
              AND tt-ar-OEAppService.APPS_ServiceName = Ar_OE_AppService.APPS_ServiceName)
         THEN DO:
              CREATE Ar_OE_AppService.
              BUFFER-COPY tt-ar-OEAppService TO Ar_OE_AppService.
	          CREATE hour-table.
	          hour-rowid = ROWID(Ar_OE_AppService).
	          RELEASE Ar_OE_AppService.
	          RELEASE hour-table.
              write-count = write-count + 1.
         END.
END.
IF Fathom-i-ActionCode = "H"
 THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for OE_AppService table : " write-count SKIP.

RUN delete-oe_appservice.
/* 
** Ar-h-process.p
** This program will archive the Process rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-ar-process definition
 - added an index on tt-ar-process table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - reorder WHERE clause to match the newly added index 
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ar-Process
*/

{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-ar-Process NO-UNDO LIKE Ar_Process
    INDEX myindex1 PROCESS_archivetype PROCESS_startdate PROCESS_starttime site_id resrc_id PROCESS_pid PROCESS_endtime.

FOR EACH W-Table BY w-time BY w-date:
    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH Sys_Process WHERE 
        Sys_Process.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
        
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "Sys_Process"} 
        {include/ar-setuptimes.i}

        /* 
        ** Search for the temp record. If it exists then update it.  If it doesn't
        ** exist then create a new one.
        */
        FIND FIRST tt-ar-Process
             WHERE tt-ar-Process.Process_archiveType = "H"
               AND tt-ar-Process.Process_StartDate = Cf_Sample.Sample_Date
               AND tt-ar-Process.Process_StartTime = s-beg-time
               AND tt-ar-Process.Site_ID = Cf_Sample.Site_ID
               AND tt-ar-Process.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-ar-Process.Process_PID = Sys_Process.Process_PID
               AND tt-ar-Process.Process_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF NOT AVAILABLE tt-ar-Process
         THEN DO:
              CREATE tt-ar-Process.
              BUFFER-COPY Sys_Process EXCEPT 
                Sys_Process.Sample_ID 
                Sys_Process.Process_CPUPct
                Sys_Process.Process_CPUPctWt
                Sys_Process.Process_VirtMem
                Sys_Process.Process_ResMemory
                Sys_Process.Process_CPUUser
                Sys_Process.Process_CPUSystem
                Sys_Process.Process_ElapsedTime
                TO tt-ar-Process.

              ASSIGN
                tt-ar-Process.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-ar-Process.Process_archiveType  = "H" 
                tt-ar-Process.Process_EndDate      = Cf_Sample.Sample_Date
                tt-ar-Process.Process_StartDate    = Cf_Sample.Sample_Date
                tt-ar-Process.Site_ID             = Cf_Sample.Site_ID
                tt-ar-Process.Resrc_ID            = Cf_Sample.Resrc_ID
                tt-ar-Process.Process_EndTime      = s-end-time
                tt-ar-Process.Process_StartTime    = s-beg-time. 
                new-recs = new-recs + 1.
         END.
       
    ASSIGN
        tt-ar-Process.Process_CPUPct      = tt-ar-Process.Process_CPUPct + (Sys_Process.Process_CPUPct * Cf_Sample.Sample_Len)
        tt-ar-Process.Process_CPUPctWt    = tt-ar-Process.Process_CPUPctWt + (Sys_Process.Process_CPUPctWt * Cf_Sample.Sample_Len)
        tt-ar-Process.Process_VirtMem     = tt-ar-Process.Process_VirtMem + Sys_Process.Process_VirtMem
        tt-ar-Process.Process_ResMemory   = tt-ar-Process.Process_ResMemory + Sys_Process.Process_ResMemory 
        tt-ar-Process.Process_CPUUser     = tt-ar-Process.Process_CPUUser + Sys_Process.Process_CPUUser
        tt-ar-Process.Process_CPUSystem   = tt-ar-Process.Process_CPUSystem + Sys_Process.Process_CPUSystem
        tt-ar-Process.Process_ElapsedTime = tt-ar-Process.Process_ElapsedTime + Sys_Process.Process_ElapsedTime
        tt-ar-Process.Process_RecordCount = tt-ar-Process.Process_RecordCount   + 1
        tt-ar-Process.Process_Length      = tt-ar-Process.Process_Length + Cf_Sample.Sample_len.
        
    END. /* IF AVAILABLE Sys_Process THEN */
END. /* FOR EACH W-Table by w-time by w-date: */

/* Modify & Write out the records */

EMPTY TEMP-TABLE hour-table.

DEF VAR write-i AS INT NO-UNDO.
DEF VAR count-i AS INT NO-UNDO.

ASSIGN write-count = 0
           count-i = 0.
FIND FIRST tt-ar-Process NO-LOCK NO-ERROR.

REPEAT:

   DO TRANSACTION:
    DO write-i = 1 to 500:
         
         IF count-i <> 0 THEN FIND NEXT tt-ar-Process NO-LOCK NO-ERROR.
         IF AVAILABLE tt-ar-Process
          THEN DO:
               count-i = count-i + 1.
               IF NOT CAN-FIND (FIRST Ar_Process
                   WHERE Ar_Process.Process_ArchiveType = "H"
                     AND Ar_Process.Site_ID             = tt-ar-Process.Site_ID
                     AND Ar_Process.Resrc_ID            = tt-ar-Process.Resrc_ID
                     AND Ar_Process.Process_PID         = tt-ar-Process.Process_PID
                     AND Ar_Process.Process_StartDate   = tt-ar-Process.Process_StartDate
                     AND Ar_Process.Process_StartTime   = tt-ar-Process.Process_StartTime
                     AND Ar_Process.Process_EndTime     = tt-ar-Process.Process_EndTime)
                THEN DO:
                     ASSIGN
                       tt-ar-Process.Process_CPUPct    = INTEGER (tt-ar-Process.Process_CPUPct / tt-ar-Process.Process_Length)
                       tt-ar-Process.Process_CPUPctWt  = INTEGER (tt-ar-Process.Process_CPUPctWt / tt-ar-Process.Process_Length)
                       tt-ar-Process.Process_VirtMem   = INTEGER (tt-ar-Process.Process_VirtMem / tt-ar-Process.Process_RecordCount)
                       tt-ar-Process.Process_ResMemory = INTEGER (tt-ar-Process.Process_ResMemory / tt-ar-Process.Process_RecordCount).
                     CREATE Ar_Process.
                     BUFFER-COPY tt-ar-Process TO Ar_Process.
                     CREATE hour-table.
                     hour-rowid = ROWID(Ar_Process).
                     RELEASE Ar_Process.
                     RELEASE hour-table.
                     write-count = write-count + 1.
                END.
          END.
          ELSE DO:
               PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Process table : " write-count SKIP.
               write-i = 99999.
               LEAVE.
          END.
    END. /* DO I LOOP */
   END. /* DO TRANSACTION */
   
   IF write-i = 99999 THEN LEAVE.
  
END. /* of REPEAT */

RUN delete-Sys_Process.
/* 
** Ar-h-tablestat.p
** This include will archive the db_tablestat rows into hourly rows.
*/

/*
llaubach 10/2005
 - added NO-UNDO to tt-db_tablestat definition
 - added an index on tt-db_tablestat table to match the WHERE clause
 - moved DO TRANSACTION block into the last FOR EACH to avoid blowing -L table (20050909-004)
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing  
 - fixed WHERE clause for AR_TableStat query to refer to AR_TableStat not to temp-table    
 
llaubach 08/2006
 - replaced FOR FIRST with IF NOT CAN-FIND() in order to further speed up the query
 - since we have full index matching the WHERE condition, put back FIND FIRST for tt-ar-Process
*/

{include/ar-definitions.i}

DEFINE TEMP-TABLE tt-Db_tablestat NO-UNDO LIKE Ar_tablestat
    INDEX myindex1 tablestat_archivetype site_id resrc_id tablestat_tableid tablestat_tablename tablestat_startdate tablestat_starttime tablestat_endtime.

/* Read through the work table and process the appropriate records */
FOR EACH W-Table BY w-time BY w-date:

    FIND FIRST Cf_Sample WHERE ROWID(Cf_Sample) = W-Table.W-Rowid NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Sample THEN NEXT.

    FOR EACH Db_tablestat WHERE 
        Db_tablestat.Sample_ID = Cf_Sample.Sample_ID 
        NO-LOCK:
  
        /* Add to the temp table for deletes */
        {include/ar-delete-table.i "db_tablestat"}  
        {include/ar-setuptimes.i}

        /* See if the temp record already exists.  If it does then add to it.
           If it doesn't then create a new one */
        FIND FIRST tt-dB_tablestat
             WHERE tt-Db_tablestat.tablestat_archiveType = "H"
               AND tt-Db_tablestat.Site_ID = Cf_Sample.Site_ID
               AND tt-Db_tablestat.Resrc_ID = Cf_Sample.Resrc_ID
               AND tt-Db_tablestat.tablestat_tableID = Db_tablestat.tablestat_tableID
               AND tt-Db_tablestat.tablestat_TableName = db_tablestat.Tablestat_tablename
               AND tt-Db_tablestat.tablestat_StartDate = Cf_Sample.Sample_Date
               AND tt-Db_tablestat.tablestat_StartTime = s-beg-time
               AND tt-Db_tablestat.tablestat_EndTime = s-end-time
        NO-LOCK NO-ERROR.

        IF AVAILABLE tt-db_tablestat
         THEN ASSIGN
                tt-Db_TableStat.TableStat_Create       = tt-Db_TableStat.TableStat_Create    + Db_TableStat.TableStat_Create
                tt-Db_TableStat.TableStat_Delete       = tt-Db_TableStat.TableStat_Delete    + Db_TableStat.TableStat_Delete
                tt-Db_TableStat.TableStat_Read         = tt-Db_TableStat.TableStat_Read      + Db_TableStat.TableStat_Read
                tt-Db_TableStat.TableStat_TableID      = Db_TableStat.TableStat_TableID
                tt-Db_TableStat.TableStat_TableName    = Db_TableStat.TableStat_TableName
                tt-Db_TableStat.TableStat_Update       = tt-Db_TableStat.TableStat_Update    + Db_TableStat.TableStat_Update
                tt-Db_tablestat.tablestat_RecordCount  = tt-Db_tablestat.tablestat_RecordCount + 1
                tt-db_tablestat.tablestat_length       = tt-db_tablestat.tablestat_Length + Cf_Sample.Sample_len
                tt-Db_tablestat.tablestat_Transactions = tt-Db_tablestat.tablestat_Transactions + Cf_Sample.Sample_Trans.
         ELSE DO:
              CREATE tt-Db_tablestat.
              BUFFER-COPY Db_tablestat EXCEPT Db_tablestat.Sample_ID TO tt-db_tablestat.
              ASSIGN
                tt-Db_tablestat.sample_id = NEXT-VALUE (ar_sample-seq)
                tt-Db_tablestat.tablestat_archiveType = "H" 
                tt-Db_tablestat.tablestat_EndDate = Cf_Sample.Sample_Date
                tt-Db_tablestat.tablestat_StartDate = Cf_Sample.Sample_Date
                tt-Db_tablestat.Site_ID = Cf_Sample.Site_ID
                tt-Db_tablestat.Resrc_ID = Cf_Sample.Resrc_ID
                tt-Db_tablestat.tablestat_EndTime = s-end-time
                tt-Db_tablestat.tablestat_StartTime = s-beg-time 
                tt-Db_tablestat.tablestat_RecordCount = tt-Db_tablestat.tablestat_RecordCount + 1
                tt-db_tablestat.tablestat_length = tt-db_tablestat.tablestat_Length + Cf_Sample.Sample_len
                tt-Db_tablestat.tablestat_Transactions = tt-Db_tablestat.tablestat_Transactions + Cf_Sample.Sample_Trans.
               new-recs = new-recs + 1.
         END.
    END.
END.

/* Write out the records from the temp table to the database table */

write-count = 0.
FOR EACH tt-db_tablestat 
    WHERE tt-db_tablestat.tablestat_archiveType = "H":

       IF NOT CAN-FIND (FIRST Ar_tablestat 
           WHERE Ar_tablestat.tablestat_archiveType = "H"
             AND Ar_tablestat.Site_ID               = tt-Db_TableStat.Site_ID
             AND Ar_tablestat.Resrc_ID              = tt-Db_TableStat.Resrc_ID
             AND Ar_tablestat.tablestat_tableID     = tt-Db_TableStat.tablestat_tableID
             AND Ar_tablestat.tablestat_TableName   = tt-Db_TableStat.Tablestat_tablename
             AND Ar_tablestat.tablestat_StartDate   = tt-Db_TableStat.tablestat_StartDate
             AND Ar_tablestat.tablestat_StartTime   = tt-Db_TableStat.tablestat_StartTime
             AND Ar_tablestat.tablestat_EndTime     = tt-Db_TableStat.tablestat_EndTime)
        THEN DO:
             CREATE Ar_tablestat.
             BUFFER-COPY tt-db_tablestat TO Ar_tablestat.
             RELEASE AR_tablestat.
             write-count = write-count + 1.
        END.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Hourly Compaction Records Written for Db_TableStat table : " write-count.

RUN delete-Db_TableStat.
/* 
** ar_indexstat.p
**
** This include will archive the ar_indexstat rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-IndexStat temp-table now defined with NO-UNDO
 - defined an index on tt-ar-IndexStat table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_IndexStat WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-indexstat NO-UNDO LIKE ar_indexstat
    INDEX myindex1 site_id resrc_id indexstat_archivetype indexstat_idxnum indexstat_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-indexstat.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_indexstat
    WHERE Ar_indexstat.indexstat_ArchiveType = "H"
      AND Ar_indexstat.indexstat_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-indexstat
        WHERE tt-ar-indexstat.Site_Id = ar_indexstat.site_id
          AND tt-ar-indexstat.Resrc_Id = ar_indexstat.Resrc_id
          AND tt-ar-indexstat.indexstat_archiveType = "D"
          AND tt-ar-indexstat.indexstat_idxnum = ar_indexstat.indexstat_idxnum
          AND tt-ar-indexstat.indexstat_startDate = ar_indexstat.indexstat_startdate:
        RUN add-indexstat.
    END.
    
    IF NOT AVAILABLE tt-ar-indexstat
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-indexstat.indexstat_StartDate = Ar_indexstat.indexstat_StartDate
            tt-ar-indexstat.indexstat_EndDate = Ar_indexstat.indexstat_EndDate
            tt-ar-indexstat.indexstat_archiveType = "D".
     END.
    RELEASE tt-ar-indexstat.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-indexstat
        WHERE tt-ar-indexstat.Site_Id = ar_indexstat.site_id
          AND tt-ar-indexstat.Resrc_Id = ar_indexstat.Resrc_id
          AND tt-ar-indexstat.indexstat_archiveType = "W"
          AND tt-ar-indexstat.indexstat_idxnum = ar_indexstat.indexstat_idxnum
          AND ar_indexstat.indexstat_startdate GE tt-ar-indexstat.indexstat_startDate
          AND ar_indexstat.indexstat_startdate LE tt-ar-indexstat.indexstat_enddate:
        RUN add-indexstat.
    END.

    IF NOT AVAILABLE tt-ar-indexstat
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-indexstat.indexstat_StartDate = Ar_indexstat.indexstat_StartDate - (WEEKDAY(Ar_indexstat.indexstat_StartDate) - 1)
            tt-ar-indexstat.indexstat_EndDate = tt-ar-indexstat.indexstat_StartDate + 6
            tt-ar-indexstat.indexstat_archiveType = "W".
     END.
    RELEASE tt-ar-indexstat.
END. /*  Of for each Ar_indexstat */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Begin writing data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out ar-indexstat */
    FOR EACH tt-ar-indexstat
        WHERE tt-ar-indexstat.indexstat_archiveType = "D":
        FOR FIRST ar_indexstat
            WHERE Ar_IndexStat.indexstat_archiveType = "D"
              AND tt-ar-indexstat.Site_Id = ar_indexstat.site_id
              AND tt-ar-indexstat.Resrc_Id = ar_indexstat.Resrc_id
              AND tt-ar-indexstat.indexstat_idxnum = ar_indexstat.indexstat_idxnum
              AND tt-ar-indexstat.indexstat_startDate = ar_indexstat.indexstat_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_indexstat
         THEN DO TRANSACTION:
                 CREATE Ar_indexstat.
                 BUFFER-COPY tt-ar-indexstat TO Ar_indexstat.
                 RELEASE Ar_indexstat.
         END.
    END.
        
    /* Write out ar-indexstat */
    FOR EACH tt-ar-indexstat
        WHERE tt-ar-indexstat.indexstat_archiveType = "W":
        FOR FIRST ar_indexstat
            WHERE Ar_IndexStat.indexstat_archiveType = "W"
              AND tt-ar-indexstat.Site_Id = ar_indexstat.site_id
              AND tt-ar-indexstat.Resrc_Id = ar_indexstat.Resrc_id
              AND tt-ar-indexstat.indexstat_idxnum = ar_indexstat.indexstat_idxnum
              AND ar_indexstat.indexstat_startdate GE tt-ar-indexstat.indexstat_startDate
              AND ar_indexstat.indexstat_startdate LE tt-ar-indexstat.indexstat_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_indexstat
         THEN DO TRANSACTION:
                 CREATE Ar_indexstat.
                 BUFFER-COPY tt-ar-indexstat TO Ar_indexstat.
                 RELEASE Ar_indexstat.
         END.
    END.

    sec-name = "Ending writing data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-indexstat.
    BUFFER-COPY ar_indexstat TO tt-ar-indexstat.
    ASSIGN
      tt-ar-indexstat.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-indexstat.indexstat_EndTime = {&DAY_END_TIME}
      tt-ar-indexstat.indexstat_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-indexstat.
   ASSIGN
        tt-ar-IndexStat.IndexStat_RecordCount  = tt-ar-IndexStat.IndexStat_RecordCount + Ar_IndexStat.IndexStat_RecordCount 
        tt-ar-IndexStat.IndexStat_transactions = tt-ar-IndexStat.IndexStat_transactions + Ar_IndexStat.IndexStat_transactions 
        tt-ar-IndexStat.IndexStat_Length       = tt-ar-IndexStat.IndexStat_Length + Ar_IndexStat.IndexStat_Length 
        tt-ar-IndexStat.IndexStat_Blockdelete  = tt-ar-IndexStat.IndexStat_Blockdelete + Ar_IndexStat.IndexStat_Blockdelete
        tt-ar-IndexStat.IndexStat_Create    = tt-ar-IndexStat.IndexStat_Create    + Ar_IndexStat.IndexStat_Create
        tt-ar-IndexStat.IndexStat_Delete    = tt-ar-IndexStat.IndexStat_Delete    + Ar_IndexStat.IndexStat_Delete
        tt-ar-IndexStat.IndexStat_IdxNum    = Ar_IndexStat.IndexStat_IdxNum
        tt-ar-IndexStat.IndexStat_IndexName = Ar_IndexStat.IndexStat_IndexName
        tt-ar-IndexStat.IndexStat_Read      = tt-ar-IndexStat.IndexStat_Read      + Ar_IndexStat.IndexStat_Read
        tt-ar-IndexStat.IndexStat_Split     = tt-ar-IndexStat.IndexStat_Split     + Ar_IndexStat.IndexStat_Split
        tt-ar-IndexStat.IndexStat_TableName = Ar_IndexStat.IndexStat_TableName   .
END PROCEDURE.
/*
** ar-lock.p
**
** This program will lock compaction so that another process cannot run
** compaction at the same time.
*/

/*
llaubach 10/2005
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
*/

FIND FIRST Cf_Control where ID = "Lock_Compact" NO-LOCK NO-ERROR.
IF AVAILABLE Cf_Control
 THEN DO:
      PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Archiving Locked - cannot be run more than one at a time!".
      QUIT.
 END.
 ELSE DO:
      CREATE Cf_Control.
      ASSIGN 
        ID = "Lock_Compact"
        c1 = STRING(TODAY) + " " + STRING(TIME, "HH:MM:SS").
      RELEASE Cf_Control.
 END.
/* 
** ar_mem.p
**
** This include will archive the ar_mem rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-mem temp-table now defined with NO-UNDO
 - defined an index on tt-ar-mem table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_mem WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-mem NO-UNDO LIKE ar_mem
    INDEX myindex1 mem_archiveType Site_id Resrc_id mem_startDate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-mem.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

FOR EACH Ar_mem
    WHERE Ar_mem.mem_ArchiveType = "H"
      AND Ar_mem.mem_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-mem
        WHERE tt-ar-mem.mem_archiveType = "D"
          AND tt-ar-mem.Site_Id = ar_mem.site_id
          AND tt-ar-mem.Resrc_Id = ar_mem.Resrc_id
          AND tt-ar-mem.mem_startDate = ar_mem.mem_startdate:
        RUN add-mem.
    END.
    
    IF NOT AVAILABLE tt-ar-mem
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-mem.mem_StartDate = Ar_mem.mem_StartDate
            tt-ar-mem.mem_EndDate = Ar_mem.mem_EndDate
            tt-ar-mem.mem_archiveType = "D".
     END.
    RELEASE tt-ar-mem.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-mem
        WHERE tt-ar-mem.mem_archiveType = "W"
          AND tt-ar-mem.Site_Id = ar_mem.site_id
          AND tt-ar-mem.Resrc_Id = ar_mem.Resrc_id
          AND ar_mem.mem_startdate GE tt-ar-mem.mem_startDate
          AND ar_mem.mem_startdate LE tt-ar-mem.mem_enddate:
        RUN add-mem.
    END.
    
    IF NOT AVAILABLE tt-ar-mem
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-mem.mem_StartDate = Ar_mem.mem_StartDate - (WEEKDAY(Ar_mem.mem_StartDate) - 1)
            tt-ar-mem.mem_EndDate = tt-ar-mem.mem_StartDate + 6
            tt-ar-mem.mem_archiveType = "W".
     END.
    RELEASE tt-ar-mem.
END. /*  Of for each Ar_mem */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Begin writing data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_mem */
    FOR EACH tt-ar-mem
        WHERE tt-ar-mem.mem_archiveType = "D":
        FOR FIRST ar_mem
            WHERE Ar_Mem.mem_archiveType = "D"
              AND tt-ar-mem.Site_Id = ar_mem.site_id
              AND tt-ar-mem.Resrc_Id = ar_mem.Resrc_id
              AND tt-ar-mem.mem_startDate = ar_mem.mem_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_mem
         THEN DO TRANSACTION:
                 ASSIGN
                   tt-ar-Mem.Mem_PgIn = tt-ar-Mem.Mem_PgIn 
                   tt-ar-Mem.Mem_PgOut = tt-ar-Mem.Mem_PgOut 
                   tt-ar-Mem.Mem_VirtFree = tt-ar-Mem.Mem_VirtFree / tt-ar-Mem.Mem_Length
                   tt-ar-Mem.mem_sysfree = tt-ar-Mem.mem_sysfree / tt-ar-Mem.mem_Length.
                 CREATE Ar_mem.
                 BUFFER-COPY tt-ar-mem TO Ar_mem.
                 RELEASE Ar_mem.
         END.
    END.
        
    /* Write out db_mem */
    FOR EACH tt-ar-mem
        WHERE tt-ar-mem.mem_archiveType = "W":
        FOR FIRST ar_mem
            WHERE Ar_Mem.mem_archiveType = "W"
              AND tt-ar-mem.Site_Id = ar_mem.site_id
              AND tt-ar-mem.Resrc_Id = ar_mem.Resrc_id
              AND ar_mem.mem_startdate GE tt-ar-mem.mem_startDate
              AND ar_mem.mem_startdate LE tt-ar-mem.mem_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_mem
         THEN DO:
                ASSIGN
                  tt-ar-Mem.Mem_PgIn = tt-ar-Mem.Mem_PgIn 
                  tt-ar-Mem.Mem_PgOut = tt-ar-Mem.Mem_PgOut
                  tt-ar-Mem.Mem_VirtFree = tt-ar-Mem.Mem_VirtFree / tt-ar-Mem.Mem_Length
                  tt-ar-Mem.mem_sysfree = tt-ar-Mem.mem_sysfree / tt-ar-Mem.mem_Length.
                CREATE Ar_mem.
                BUFFER-COPY tt-ar-mem TO Ar_mem.
                RELEASE Ar_mem.
         END.
    END.

    sec-name = "Ending writing data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-mem.
    BUFFER-COPY ar_mem TO tt-ar-mem.
    ASSIGN
        tt-ar-Mem.Mem_PgIn     = tt-ar-Mem.Mem_PgIn 
        tt-ar-Mem.Mem_PgOut    = tt-ar-Mem.Mem_PgOut
        tt-ar-Mem.Mem_SysFree  = tt-ar-Mem.Mem_SysFree * tt-Ar-Mem.Mem_Length
        tt-ar-Mem.Mem_VirtFree = tt-ar-Mem.Mem_VirtFree * tt-Ar-Mem.Mem_Length
        tt-ar-mem.sample_id = NEXT-VALUE(ar_sample-seq)
        tt-ar-mem.mem_EndTime = {&DAY_END_TIME}
        tt-ar-mem.mem_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-mem.
    ASSIGN
        tt-ar-Mem.Mem_Length       = tt-ar-Mem.Mem_Length     + ar_Mem.Mem_Length
        tt-ar-Mem.Mem_Transactions = tt-ar-Mem.Mem_Transactions     + ar_Mem.Mem_Transactions
        tt-ar-Mem.Mem_RecordCount  = tt-ar-Mem.Mem_RecordCount     + ar_Mem.Mem_RecordCount
        tt-ar-Mem.Mem_PgIn     = tt-ar-Mem.Mem_PgIn + ar_Mem.Mem_PgIn
        tt-ar-Mem.Mem_PgOut    = tt-ar-Mem.Mem_PgOut + ar_Mem.Mem_PgOut
        tt-ar-Mem.Mem_SysFree  = tt-ar-Mem.Mem_SysFree  + (Ar_Mem.Mem_Length * ar_Mem.Mem_SysFree)
        tt-ar-Mem.Mem_VirtFree = tt-ar-Mem.Mem_VirtFree + (Ar_Mem.Mem_Length * ar_Mem.Mem_VirtFree)
        tt-ar-Mem.Mem_SysTot   = tt-ar-Mem.Mem_SysTot
        tt-ar-Mem.Mem_VirtTot  = tt-ar-Mem.Mem_VirtTot.
END PROCEDURE. 
/* 
** ar_net.p
**
** This include will archive the ar_net rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-net temp-table now defined with NO-UNDO
 - defined an index on tt-ar-net table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_net WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-net NO-UNDO LIKE ar_net_data
    INDEX myindex1 site_id resrc_id net_archivetype net_startdate net_status.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-net.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_Net_data
    WHERE Ar_Net_data.Net_ArchiveType = "H"
      AND Ar_Net_data.Net_StartDate LT Fathom-i-Date NO-LOCK:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-net
        WHERE tt-ar-net.Site_Id = ar_net.site_id
          AND tt-ar-net.Resrc_Id = ar_net.Resrc_id
          AND tt-ar-net.net_archiveType = "D"
          AND tt-ar-net.net_startDate = ar_net_data.Net_startdate
          AND tt-ar-net.Net_Status = Ar_Net_Data.Net_Status:
        RUN add-net.
    END.
    
    IF NOT AVAILABLE tt-ar-net
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-net.net_StartDate = Ar_net.net_StartDate
            tt-ar-net.net_EndDate = Ar_net.net_EndDate
            tt-ar-net.net_archiveType = "D".
     END.
    RELEASE tt-ar-net.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-net
        WHERE tt-ar-net.Site_Id = ar_net.site_id
          AND tt-ar-net.Resrc_Id = ar_net.Resrc_id
          AND tt-ar-net.net_archiveType = "W"
          AND ar_net_data.Net_startdate GE tt-ar-net.net_startDate
          AND ar_net_data.Net_startdate LE tt-ar-net.net_enddate
          AND tt-ar-net.Net_Status = Ar_Net_Data.Net_Status:
        RUN add-net.
    END.
    
    IF NOT AVAILABLE tt-ar-net
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-net.net_StartDate = Ar_net.net_StartDate - (WEEKDAY(Ar_net.net_StartDate) - 1)
            tt-ar-net.net_EndDate = tt-ar-net.net_StartDate + 6
            tt-ar-net.net_archiveType = "W".
     END.
    RELEASE tt-ar-net.
END. /*  Of for each Ar_Net_data */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Begin writing data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out db_net */
    FOR EACH tt-ar-net
        WHERE tt-ar-net.net_archiveType = "D":
        FOR FIRST ar_net_data
            WHERE ar_net.net_archiveType = "D"
              AND tt-ar-net.Site_Id = ar_net.site_id
              AND tt-ar-net.Resrc_Id = ar_net.Resrc_id
              AND tt-ar-net.net_status = ar_net_data.Net_status
              AND tt-ar-net.net_startDate = ar_net_data.Net_startdate NO-LOCK: END.
        IF NOT AVAILABLE ar_net_data
         THEN DO TRANSACTION:
                 tt-ar-net.Net_Time = tt-ar-net.Net_Time / tt-ar-net.net_RecordCount.
                 CREATE Ar_Net_data.
                 BUFFER-COPY tt-ar-Net TO Ar_Net_data.
                 RELEASE Ar_Net_data.
         END.
    END.
        
    /* Write out db_net */
    FOR EACH tt-ar-net
        WHERE tt-ar-net.net_archiveType = "W":
        FOR FIRST ar_net_data
            WHERE ar_net.net_archiveType = "W"
              AND tt-ar-net.Site_Id = ar_net.site_id
              AND tt-ar-net.Resrc_Id = ar_net.Resrc_id 
              AND tt-ar-net.net_status = ar_net_data.Net_status
              AND ar_net_data.Net_startdate GE tt-ar-net.net_startDate
              AND ar_net_data.Net_startdate LE tt-ar-net.net_enddate NO-LOCK: END.
        IF NOT AVAILABLE ar_net_data
         THEN DO TRANSACTION:
                 tt-ar-net.Net_Time = tt-ar-net.Net_Time / tt-ar-net.net_RecordCount.
                 CREATE Ar_Net_data.
                 BUFFER-COPY tt-ar-Net TO Ar_Net_data.
                 RELEASE Ar_Net_data.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-net.
    BUFFER-COPY ar_net_data TO tt-ar-net.
    ASSIGN
      tt-ar-Net.Net_Time = Ar_Net_Data.Net_Time * Ar_Net_Data.Net_RecordCount
      tt-ar-net.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-net.Net_EndTime = {&DAY_END_TIME}
      tt-ar-net.Net_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-net.
    ASSIGN
        tt-ar-Net.Net_Time         = tt-ar-net.Net_Time + (Ar_Net_Data.Net_Time * Ar_Net_Data.Net_RecordCount)
        tt-ar-Net.Net_RecordCount  = tt-ar-net.Net_RecordCount + ar_Net_Data.Net_RecordCount
        tt-ar-Net.Net_Transactions = tt-ar-net.Net_Transactions + ar_Net_Data.Net_Transactions
        tt-ar-Net.Net_Length       = tt-ar-net.Net_Length + ar_Net_Data.Net_Length.
     IF tt-ar-net.Net_Max LT ar_Net_Data.Net_Max
      THEN tt-ar-net.Net_Max = ar_Net_Data.Net_Time.
     IF tt-ar-net.Net_Min = 0
      THEN tt-ar-net.Net_Min = ar_Net_Data.Net_Time.
     IF tt-ar-net.Net_Min GT ar_Net_Data.Net_Min
      THEN tt-ar-net.Net_Min = ar_Net_Data.Net_Time.
END PROCEDURE.
/* 
** ar_OE_ActASProc.p
**
** This include will archive the ar_OE_ActASProc rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
*/

/*
llaubach 10/2005
 - tt-oe_actasproc temp-table now defined with NO-UNDO
 - defined an index on tt-oe_actasproc table to match WHERE clause
 - added NO-LOCK to FOR EACH oe_actasproc WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - removed first DO TRANSACTION block as it was only operation on temp-tables
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.

sec-name = "OE_ActASProc: Starting Processing".
{include/ar-debug.i "sec-name"}

DEFINE TEMP-TABLE tt-ar-OEActASProc NO-UNDO LIKE ar_OE_ActASProc
    INDEX myindex1 actasproc_archivetype actbrk_uuid actasproc_startdate site_id resrc_id actasproc_name.

/* CREATE THE HOURLY RECORDS */
IF doHourlyRecords THEN RUN archive/ar-h-oe_actasproc.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
sec-name = "OE_ActASProc: Start Processing Daily/Weekly Records".
{include/ar-debug.i "sec-name"}

DEFINE VARIABLE rec-cnt AS INTEGER NO-UNDO.
DEFINE VARIABLE i3 AS INTEGER NO-UNDO.
DEFINE VARIABLE loop-cnt AS INTEGER NO-UNDO.

FOR EACH hour-table: loop-cnt = loop-cnt + 1. END.

FIND FIRST hour-table NO-ERROR.
IF AVAILABLE hour-table
 THEN DO:

repeat-loop:

REPEAT:
     DO i3 = 1 to 5000:

            rec-cnt = rec-cnt + 1.
   
            FIND FIRST Ar_OE_ActASProc where hour-rowid = ROWID(Ar_OE_ActASProc) NO-ERROR.
            /*
            ** If the Ar_OE_ActASProc row is there then we will process it 
            ** otherwise we will skip the rowid and move on to the next one.
            */
        
            IF AVAILABLE Ar_OE_ActASProc
              THEN DO:
                
                /* PROCESS DAILY RECORDS */
                FOR FIRST tt-ar-OEActASProc
                    WHERE tt-ar-OEActASProc.ActASProc_archiveType = "D"
                      AND tt-ar-OEActASProc.ActBrk_UUID           =  Ar_OE_ActASProc.ActBrk_UUID
                      AND tt-ar-OEActASProc.ActASProc_startDate   =  Ar_OE_ActASProc.ActASProc_startdate
                      AND tt-ar-OEActASProc.Site_Id               =  Ar_OE_ActASProc.site_id
                      AND tt-ar-OEActASProc.Resrc_Id              =  Ar_OE_ActASProc.Resrc_id
                      AND tt-ar-OEActASProc.ActASProc_Name        =  Ar_OE_ActASProc.ActASProc_Name:
                    RUN add-OEActASProc.
                END.
                
                IF NOT AVAILABLE tt-ar-OEActASProc
                   THEN DO:
                        RUN create-record.
                        ASSIGN
                          tt-ar-OEActASProc.ActASProc_StartDate = Ar_OE_ActASProc.ActASProc_StartDate
                          tt-ar-OEActASProc.ActASProc_EndDate = Ar_OE_ActASProc.ActASProc_EndDate
                          tt-ar-OEActASProc.ActASProc_archiveType = "D".
                   END.
                RELEASE tt-ar-OEActASProc.
                
                /* PROCESS WEEKLY RECORDS */
                FOR FIRST tt-ar-OEActASProc
                    WHERE tt-ar-OEActASProc.ActASProc_archiveType =  "W"
                      AND tt-ar-OEActASProc.ActBrk_UUID           =  Ar_OE_ActASProc.ActBrk_UUID
                      AND tt-ar-OEActASProc.ActASProc_startDate   LE Ar_OE_ActASProc.ActASProc_startdate
                      AND tt-ar-OEActASProc.ActASProc_enddate     GE Ar_OE_ActASProc.ActASProc_startdate
                      AND tt-ar-OEActASProc.Site_Id               =  Ar_OE_ActASProc.site_id
                      AND tt-ar-OEActASProc.Resrc_Id              =  Ar_OE_ActASProc.Resrc_id
                      AND tt-ar-OEActASProc.ActASProc_Name        =  Ar_OE_ActASProc.ActASProc_Name:
                    RUN add-OEActASProc.
                END.

                IF NOT AVAILABLE tt-ar-OEActASProc
                 THEN DO:
                      RUN create-record.
                      ASSIGN
                        tt-ar-OEActASProc.ActASProc_StartDate   = Ar_OE_ActASProc.ActASProc_StartDate - (WEEKDAY(Ar_OE_ActASProc.ActASProc_StartDate) - 1)
                        tt-ar-OEActASProc.ActASProc_EndDate     = tt-ar-OEActASProc.ActASProc_StartDate + 6
                        tt-ar-OEActASProc.ActASProc_archiveType = "W".
                 END.
                RELEASE tt-ar-OEActASProc.
        
            END. /* OF IF AVAILABLE Ar_OE_ActASProc. */

            FIND NEXT hour-table NO-ERROR.
            IF NOT AVAILABLE hour-table THEN LEAVE repeat-loop.

        END. /*  Of DO i3 = 1 to 5000 */

        PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Processed " rec-cnt " hourly records of " loop-cnt " records...".

END. /* of REPEAT LOOP */
END. /* OF if First hour-record available */
        
/* This will write out the temp tables to the appropriate files. */
sec-name = "OE_ActASProc: Writing Daily/Weekly data to disk ".
{include/ar-debug.i "sec-name"}

ASSIGN
   rec-cnt = 0
   write-count = 0.

FOR EACH tt-ar-oeactasproc
    WHERE tt-ar-OEActASProc.ActASProc_archiveType = "D":
    rec-cnt = rec-cnt + 1.
END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Record count for daily records: " rec-cnt.
rec-cnt = 0.

repeat-loop:

REPEAT:
    DO i3 = 1 to 5000:
            IF rec-cnt = 0 
             THEN FIND FIRST tt-ar-OEActASProc WHERE tt-ar-OEActASProc.ActASProc_archiveType = "W" NO-LOCK NO-ERROR.
             ELSE FIND NEXT tt-ar-OEActASProc WHERE tt-ar-OEActASProc.ActASProc_archiveType = "W" NO-LOCK NO-ERROR.

            rec-cnt = rec-cnt + 1.
   
            IF NOT AVAILABLE tt-ar-OEActASProc THEN LEAVE repeat-loop.

            FOR FIRST ar_OE_ActASProc
                WHERE ar_OE_ActASProc.ActASProc_archiveType = "W"
                  AND tt-ar-OEActASProc.Site_Id =             Ar_OE_ActASProc.site_id
                  AND tt-ar-OEActASProc.Resrc_Id =            Ar_OE_ActASProc.Resrc_id
                  AND tt-ar-OEActASProc.ActASProc_startDate = Ar_OE_ActASProc.ActASProc_startdate
                  AND tt-ar-OEActASProc.ActASProc_enddate =   Ar_OE_ActASProc.ActASProc_startdate
                  AND tt-ar-OEActASProc.ActBrk_UUID =         Ar_OE_ActASProc.ActBrk_UUID
                  AND tt-ar-OEActASProc.ActBrk_PID =          Ar_OE_ActASProc.ActBrk_PID
                  AND tt-ar-OEActASProc.ActASProc_Name =      Ar_OE_ActASProc.ActASProc_Name NO-LOCK: END.
            IF NOT AVAILABLE ar_OE_ActASProc THEN DO TRANSACTION: RUN write-record. END.
    END.
END.

rec-cnt = 0.

sec-name = "OE_ActASProc: Completed Weekly data".
{include/ar-debug.i "sec-name"}

repeat-loop:

REPEAT:
    DO i3 = 1 to 5000:
            IF rec-cnt = 0
             THEN FIND FIRST tt-ar-OEActASProc WHERE tt-ar-OEActASProc.ActASProc_archiveType = "D" NO-LOCK NO-ERROR.
             ELSE FIND NEXT tt-ar-OEActASProc WHERE tt-ar-OEActASProc.ActASProc_archiveType = "D" NO-LOCK NO-ERROR.
            
            rec-cnt = rec-cnt + 1.
   
            IF NOT AVAILABLE tt-ar-OEActASProc THEN LEAVE repeat-loop.

            FOR FIRST ar_OE_ActASProc
                WHERE ar_OE_ActASProc.ActASProc_archiveType = "D"
                  AND ar_OE_ActASProc.site_id = tt-ar-OEActASProc.Site_Id
                  AND tt-ar-OEActASProc.Resrc_Id = ar_OE_ActASProc.Resrc_id
                  AND tt-ar-OEActASProc.ActASProc_startDate = ar_OE_ActASProc.ActASProc_startdate
                  AND tt-ar-OEActASProc.ActASProc_enddate = ar_OE_ActASProc.ActASProc_startdate
                  AND tt-ar-OEActASProc.ActBrk_UUID = ar_OE_ActASProc.ActBrk_UUID
                  AND tt-ar-OEActASProc.ActBrk_PID = ar_OE_ActASProc.ActBrk_PID
                  AND tt-ar-OEActASProc.ActASProc_Name = Ar_OE_ActASProc.ActASProc_Name NO-LOCK: END.
            IF NOT AVAILABLE ar_OE_ActASProc THEN DO TRANSACTION: RUN write-record. END.
    END.
END.

sec-name = "OE_ActASProc: Completed Daily data".
{include/ar-debug.i "sec-name"}

PUT SKIP TODAY " "  STRING(TIME, "HH:MM:SS")  " OE_ActASProc: Daily/Weekly Compaction Records Written: " write-count SKIP.

sec-name = "OE_ActASProc: Ending Processing".
{include/ar-debug.i "sec-name"}

PROCEDURE write-record.
    /* This procedure will write out the record appropriately. */
    CREATE Ar_OE_ActASProc.    
    BUFFER-COPY tt-ar-OEActASProc TO Ar_OE_ActASProc.
    RELEASE Ar_OE_ActASProc.
    write-count = write-count + 1.
END PROCEDURE.

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-OEActASProc.
    ASSIGN
        tt-ar-OEActASProc.ActBrk_PID          = Ar_OE_ActASProc.ActBrk_PID
        tt-ar-OEActASProc.ActBrk_UUID         = Ar_OE_ActASProc.ActBrk_UUID
        tt-ar-OEActASProc.ActASProc_Parent    = Ar_OE_ActASProc.ActASProc_Parent
        tt-ar-OEActASProc.ActASProc_ProcType  = Ar_OE_ActASProc.ActASProc_ProcType
        tt-ar-OEActASProc.ActASProc_Name      = Ar_OE_ActASProc.ActASProc_Name
        tt-ar-OEActASProc.Resrc_ID            = Ar_OE_ActASProc.Resrc_ID
        tt-ar-OEActASProc.Site_ID             = Ar_OE_ActASProc.Site_ID
        tt-ar-OEActASProc.sample_id           = NEXT-VALUE(ar_sample-seq)
        tt-ar-OEActASProc.ActASProc_EndTime   = {&DAY_END_TIME}
        tt-ar-OEActASProc.ActASProc_StartTime = 0.
    RUN add-oeActASProc.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-OEActASProc.
   ASSIGN
      tt-ar-OEActASProc.ActASProc_Calls        = tt-ar-OEActASProc.ActASProc_Calls + ar_OE_ActASProc.ActASProc_Calls
      tt-ar-OEActASProc.ActASProc_TotTime      =  tt-ar-OEActASProc.ActASProc_TotTime + ar_OE_ActASProc.ActASProc_TotTime
      tt-ar-OEActASProc.ActASProc_SuccessCount = tt-ar-OEActASProc.ActASProc_SuccessCount + ar_OE_ActASProc.ActASProc_SuccessCount
      tt-ar-OEActASProc.ActASProc_ErrorCount   = tt-ar-OEActASProc.ActASProc_ErrorCount + ar_OE_ActASProc.ActASProc_ErrorCount
      tt-ar-OEActASProc.ActASProc_QuitCount    =  tt-ar-OEActASProc.ActASProc_QuitCount + ar_OE_ActASProc.ActASProc_QuitCount
      tt-ar-OEActASProc.ActASProc_StopCount    = tt-ar-OEActASProc.ActASProc_StopCount + ar_OE_ActASProc.ActASProc_StopCount
      tt-ar-OEActASProc.ActASProc_DebugCount   = tt-ar-OEActASProc.ActASProc_DebugCount + ar_OE_ActASProc.ActASProc_DebugCount
      tt-ar-OEActASProc.ActASProc_RecordCount  = tt-ar-OEActASProc.ActASProc_RecordCount + ar_OE_ActASProc.ActASProc_RecordCount
      tt-ar-OEActASProc.ActASProc_Length       = tt-ar-OEActASProc.ActASProc_Length + ar_OE_ActASProc.ActASProc_Length.
   IF tt-ar-OEActASProc.ActASProc_MaxTime LT Ar_OE_ActASProc.ActASProc_Length
    THEN tt-ar-OEActASProc.ActASProc_MaxTime = ar_OE_ActASProc.ActASProc_MaxTime.
END PROCEDURE.

/* 
** ar_OE_ActBrk.p
**
** This include will archive the ar_OE_ActBrk rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
*/

/*
llaubach 10/2005
 - tt-oe_actbrk temp-table now defined with NO-UNDO
 - defined an index on tt-oe_actbrk table to match WHERE clause
 - added NO-LOCK to FOR EACH oe_actbrk WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - removed first DO TRANSACTION block as it was only operation on temp-tables
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.

sec-name = "OE_ActBrk: Starting Archiving".
{include/ar-debug.i "sec-name"}

DEFINE TEMP-TABLE tt-ar-OEActBrk NO-UNDO LIKE ar_OE_ActBrk
    INDEX myindex1 actbrk_archivetype actbrk_startdate site_id resrc_id actbrk_uuid actbrk_pid.

/* CREATE THE HOURLY RECORDS */
IF doHourlyRecords THEN RUN archive/ar-h-oe_actbrk.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

sec-name = "OE_ActBrk: Starting Daily/Weekly Archiving".
{include/ar-debug.i "sec-name"}

FOR EACH hour-table:
    FIND FIRST Ar_OE_Actbrk WHERE hour-rowid = ROWID(Ar_OE_ActBrk) NO-ERROR.
    
    /* If the Ar_OE_ActBrk row is there then we will process it otherwise we will skip the 
       rowid and move on to the next one */

    IF AVAILABLE Ar_OE_Actbrk
       THEN DO:

    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-OEActBrk
        WHERE tt-ar-OEActBrk.ActBrk_archiveType = "D"
          AND tt-ar-OEActBrk.ActBrk_startDate = ar_OE_ActBrk.ActBrk_startdate
          AND tt-ar-OEActBrk.Site_Id = ar_OE_ActBrk.site_id
          AND tt-ar-OEActBrk.Resrc_Id = ar_OE_ActBrk.Resrc_id
          AND tt-ar-OEActBrk.ActBrk_UUID = ar_OE_ActBrk.ActBrk_UUID
          AND tt-ar-OEActBrk.ActBrk_PID = ar_OE_ActBrk.ActBrk_PID:
        RUN add-OEActBrk.
    END.

    IF NOT AVAILABLE tt-ar-OEActBrk
     THEN DO:
            CREATE tt-ar-OEActBrk.
            ASSIGN            
                tt-ar-OEActBrk.Resrc_ID            = Ar_OE_ActBrk.Resrc_ID
                tt-ar-OEActBrk.Site_ID             = Ar_OE_ActBrk.Site_ID
                tt-ar-OEActBrk.ActBrk_PID          = Ar_OE_ActBrk.ActBrk_PID
                tt-ar-OEActBrk.ActBrk_UUID         = Ar_OE_ActBrk.ActBrk_UUID
                tt-ar-OEActBrk.ActBrk_Name         = Ar_OE_ActBrk.ActBrk_Name
                tt-ar-OEActBrk.ActBrk_Mode         = Ar_OE_ActBrk.ActBrk_Mode
                tt-ar-OEActBrk.sample_id           = NEXT-VALUE(ar_sample-seq)
                tt-ar-OEActBrk.ActBrk_EndTime    = {&DAY_END_TIME}
                tt-ar-OEActBrk.ActBrk_StartTime  = 0.
            RUN add-oeactbrk.
            ASSIGN
               tt-ar-OEActBrk.ActBrk_StartDate = Ar_OE_ActBrk.ActBrk_StartDate
               tt-ar-OEActBrk.ActBrk_EndDate = Ar_OE_ActBrk.ActBrk_EndDate
               tt-ar-OEActBrk.ActBrk_archiveType = "D".
     END.
    RELEASE tt-ar-OEActBrk.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-OEActBrk 
        WHERE tt-ar-OEActBrk.ActBrk_archiveType = "W"
          AND tt-ar-OEActBrk.ActBrk_startDate LE ar_OE_ActBrk.ActBrk_startdate
          AND tt-ar-OEActBrk.ActBrk_enddate GE ar_OE_ActBrk.ActBrk_startdate
          AND tt-ar-OEActBrk.Site_Id = ar_OE_ActBrk.site_id
          AND tt-ar-OEActBrk.Resrc_Id = ar_OE_ActBrk.Resrc_id
          AND tt-ar-OEActBrk.ActBrk_UUID = ar_OE_ActBrk.ActBrk_UUID
          AND tt-ar-OEActBrk.ActBrk_PID = ar_OE_ActBrk.ActBrk_PID:
        RUN ADD-OeActBrk.
    END.
    
    IF NOT AVAILABLE tt-ar-OEActBrk
     THEN DO:
          CREATE tt-ar-OEActBrk.
          ASSIGN            
              tt-ar-OEActBrk.Resrc_ID            = Ar_OE_ActBrk.Resrc_ID
              tt-ar-OEActBrk.Site_ID             = Ar_OE_ActBrk.Site_ID
              tt-ar-OEActBrk.ActBrk_PID          = Ar_OE_ActBrk.ActBrk_PID
              tt-ar-OEActBrk.ActBrk_UUID         = Ar_OE_ActBrk.ActBrk_UUID
              tt-ar-OEActBrk.ActBrk_Name         = Ar_OE_ActBrk.ActBrk_Name
              tt-ar-OEActBrk.ActBrk_Mode         = Ar_OE_ActBrk.ActBrk_Mode
              tt-ar-OEActBrk.sample_id           = NEXT-VALUE(ar_sample-seq)
              tt-ar-OEActBrk.ActBrk_EndTime    = {&DAY_END_TIME}
              tt-ar-OEActBrk.ActBrk_StartTime  = 0.
          RUN add-oeactbrk.
          ASSIGN
              tt-ar-OEActBrk.ActBrk_StartDate = Ar_OE_ActBrk.ActBrk_StartDate - (WEEKDAY(Ar_OE_ActBrk.ActBrk_StartDate) - 1)
              tt-ar-OEActBrk.ActBrk_EndDate = tt-ar-OEActBrk.ActBrk_StartDate + 6
              tt-ar-OEActBrk.ActBrk_archiveType = "W".
     END.
    RELEASE tt-ar-OEActBrk.

    END. /* OF IF AVAILABLE Ar_OE_ActBrk. */
END. /*  Of for each hour-table */

/* This will write out the temp tables to the appropriate files. */

ASSIGN
  write-count = 0
  sec-name = "OE_ActBrk: Writing Data to disk ".
{include/ar-debug.i "sec-name"}

    /* Write out ar_OE_ActBrk */
    FOR EACH tt-ar-OEActBrk
        WHERE tt-ar-OEActBrk.ActBrk_archiveType = "W":
        FOR FIRST ar_OE_ActBrk
            WHERE ar_OE_ActBrk.ActBrk_archiveType = "W"
              AND tt-ar-OEActBrk.Site_Id = ar_OE_ActBrk.site_id
              AND tt-ar-OEActBrk.Resrc_Id = ar_OE_ActBrk.Resrc_id
              AND tt-ar-OEActBrk.ActBrk_UUID = ar_OE_ActBrk.ActBrk_UUID
              AND tt-ar-OEActBrk.ActBrk_PID = ar_OE_ActBrk.ActBrk_PID
              AND tt-ar-OEActBrk.ActBrk_startDate = ar_OE_ActBrk.ActBrk_startdate
              AND tt-ar-OEActBrk.ActBrk_enddate = ar_OE_ActBrk.ActBrk_startdate  NO-LOCK: END.
        IF NOT AVAILABLE ar_OE_ActBrk THEN DO TRANSACTION: RUN write-record. END.
    END.
    
    /* Write out Ar_OE_ActBrk */
    FOR EACH tt-ar-OEActBrk
        WHERE tt-ar-OEActBrk.ActBrk_archiveType = "D":
        FOR FIRST ar_OE_ActBrk
            WHERE ar_OE_ActBrk.ActBrk_archiveType = "D"
              AND tt-ar-OEActBrk.Site_Id = ar_OE_ActBrk.site_id
              AND tt-ar-OEActBrk.Resrc_Id = ar_OE_ActBrk.Resrc_id
              AND tt-ar-OEActBrk.ActBrk_UUID = ar_OE_ActBrk.ActBrk_UUID
              AND tt-ar-OEActBrk.ActBrk_PID = ar_OE_ActBrk.ActBrk_PID
              AND tt-ar-OEActBrk.ActBrk_startDate = ar_OE_ActBrk.ActBrk_startdate
              AND tt-ar-OEActBrk.ActBrk_enddate = ar_OE_ActBrk.ActBrk_startdate  NO-LOCK: END.
        IF NOT AVAILABLE ar_OE_ActBrk THEN DO TRANSACTION: RUN write-record. END.
    END.

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActBrk: Daily/Weekly Compaction Records Written: " write-count SKIP.

sec-name = "OE_ActBrk: Ending Archiving".
{include/ar-debug.i "sec-name"}

/* This procedure will write out the record appropriately. */
PROCEDURE write-record.
    CREATE Ar_OE_ActBrk.    
    ASSIGN
        tt-ar-OEActBrk.ActBrk_CurrClients = tt-ar-OEActBrk.ActBrk_CurrClients / tt-ar-OEActBrk.ActBrk_RecordCount
        tt-ar-OEActBrk.ActBrk_CurrServers = tt-ar-OEActBrk.ActBrk_CurrServers / tt-ar-OEActBrk.ActBrk_RecordCount
        tt-ar-OEActBrk.ActBrk_CurrQueue   = tt-ar-OEActBrk.ActBrk_CurrQueue / tt-ar-OEActBrk.ActBrk_RecordCount.
    BUFFER-COPY tt-ar-OEActBrk TO Ar_OE_ActBrk.
    RELEASE Ar_OE_ActBrk.
    write-count = write-count + 1.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-OEActBrk.
    ASSIGN
        tt-ar-OEActBrk.ActBrk_CurrClients  = tt-ar-OEActBrk.ActBrk_CurrClients + (Ar_OE_ActBrk.ActBrk_CurrClients * Ar_OE_ActBrk.ActBrk_RecordCount)
        tt-ar-OEActBrk.ActBrk_CurrServers  = tt-ar-OEActBrk.ActBrk_CurrServers + (Ar_OE_ActBrk.ActBrk_CurrServers * Ar_OE_ActBrk.ActBrk_RecordCount)
        tt-ar-OEActBrk.ActBrk_CurrQueue    = tt-ar-OEActBrk.ActBrk_CurrQueue + (Ar_OE_ActBrk.ActBrk_CurrQueue * Ar_OE_ActBrk.ActBrk_RecordCount)
        tt-ar-OEActBrk.ActBrk_ReqRec       = tt-ar-OEActBrk.ActBrk_ReqRec + Ar_OE_ActBrk.ActBrk_ReqRec
        tt-ar-OEActBrk.ActBrk_ReqComp      = tt-ar-OEActBrk.ActBrk_ReqComp + Ar_OE_ActBrk.ActBrk_ReqComp
        tt-ar-OEActBrk.ActBrk_ReqQueued    = tt-ar-OEActBrk.ActBrk_ReqQueued + Ar_OE_ActBrk.ActBrk_ReqQueued
        tt-ar-OEActBrk.ActBrk_ReqRejected  = tt-ar-OEActBrk.ActBrk_ReqRejected + Ar_OE_ActBrk.ActBrk_ReqRejected
        tt-ar-OEActBrk.ActBrk_RecordCount  = tt-ar-OEActBrk.ActBrk_RecordCount   + Ar_OE_ActBrk.ActBrk_RecordCount
        tt-ar-OEActBrk.ActBrk_Length       = tt-ar-OEActBrk.ActBrk_Length + Ar_OE_ActBrk.ActBrk_Length.
    IF tt-ar-OEActBrk.ActBrk_TotClients   LT Ar_OE_ActBrk.ActBrk_TotClients
     THEN tt-ar-OEActBrk.ActBrk_TotClients   = Ar_OE_ActBrk.ActBrk_TotClients.
END PROCEDURE.
/* 
** ar_OE_ActServ.p
**
** This include will archive the ar_OE_ActServ rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
*/

/*
llaubach 10/2005
 - tt-oe_actsrv temp-table now defined with NO-UNDO
 - defined an index on tt-oe_actsrv table to match WHERE clause
 - added NO-LOCK to FOR EACH oe_actsrv WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - removed first DO TRANSACTION block as it was only operation on temp-tables
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-OEActServ NO-UNDO LIKE ar_OE_ActServ
    INDEX myindex1 actserv_archivetype actserv_startdate site_id resrc_id actbrk_uuid actserv_pid actserv_status.

DEF VAR i4 as integer NO-UNDO.
DEF VAR tot-recs AS INTEGER NO-UNDO FORMAT ">>>,>>>,>>9".
DEF VAR cum-recs AS INTEGER NO-UNDO FORMAT ">>>,>>>,>>9".

/* CREATE THE HOURLY RECORDS */
IF doHourlyRecords THEN RUN archive/ar-h-oe_actsrv.p.

/* Count up the hourly records so that we can output a status */
FOR EACH hour-table NO-LOCK: tot-recs = tot-recs + 1. END.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

FIND FIRST hour-table NO-LOCK NO-ERROR.

IF AVAILABLE hour-table
 THEN DO:

repeat2-loop:

REPEAT:
    DO i4 = 1 to 5000:

          FIND FIRST Ar_OE_ActServ WHERE hour-rowid = ROWID(Ar_OE_ActServ) NO-ERROR.
          
          /* If the Ar_OE_ActServ row is there then we will process it otherwise we will skip the 
             rowid and move on to the next one */
          IF AVAILABLE Ar_OE_ActServ
           THEN DO:
             
             /* PROCESS DAILY RECORDS */
             FOR FIRST tt-ar-OEActServ
                 WHERE tt-ar-OEActServ.ActServ_archiveType = "D" 
                   AND tt-ar-OEActServ.ActServ_startDate =   Ar_OE_ActServ.ActServ_startdate
                   AND tt-ar-OEActServ.Site_Id =             Ar_OE_ActServ.site_id
                   AND tt-ar-OEActServ.Resrc_Id =            Ar_OE_ActServ.Resrc_id
                   AND tt-ar-OEActServ.ActBrk_UUID =         Ar_OE_ActServ.ActBrk_UUID 
                   AND tt-ar-OEActServ.ActServ_PID =         Ar_OE_ActServ.ActServ_PID
                   AND tt-ar-OEActServ.ActServ_Status =      Ar_OE_ActServ.ActServ_Status:
                 RUN add-OEActServ.
             END.

             IF NOT AVAILABLE tt-ar-OEActServ
              THEN DO:
                   RUN create-record.
                   ASSIGN
                      tt-ar-OEActServ.ActServ_StartDate = Ar_OE_ActServ.ActServ_StartDate
                      tt-ar-OEActServ.ActServ_EndDate = Ar_OE_ActServ.ActServ_EndDate
                      tt-ar-OEActServ.ActServ_archiveType = "D".
              END.
             RELEASE tt-ar-OEActServ.
                 
             /* PROCESS WEEKLY RECORDS */
             FOR FIRST tt-ar-OEActServ
                 WHERE tt-ar-OEActServ.ActServ_archiveType = "W"
                   AND tt-ar-OEActServ.ActServ_startDate LE  Ar_OE_ActServ.ActServ_startdate
                   AND tt-ar-OEActServ.ActServ_enddate GE    Ar_OE_ActServ.ActServ_startdate
                   AND tt-ar-OEActServ.Site_Id =             Ar_OE_ActServ.site_id
                   AND tt-ar-OEActServ.Resrc_Id =            Ar_OE_ActServ.Resrc_id
                   AND tt-ar-OEActServ.ActBrk_UUID =         Ar_OE_ActServ.ActBrk_UUID
                   AND tt-ar-OEActServ.ActServ_PID =         Ar_OE_ActServ.ActServ_PID
                   AND tt-ar-OEActServ.ActServ_Status =      Ar_OE_ActServ.ActServ_Status:
                 RUN add-OEActServ.
             END.
             
             IF NOT AVAILABLE tt-ar-OEActServ
              THEN DO:
                   RUN create-record.
                   ASSIGN
                     tt-ar-OEActServ.ActServ_StartDate = Ar_OE_ActServ.ActServ_StartDate - (WEEKDAY(Ar_OE_ActServ.ActServ_StartDate) - 1)
                     tt-ar-OEActServ.ActServ_EndDate = tt-ar-OEActServ.ActServ_StartDate + 6
                     tt-ar-OEActServ.ActServ_archiveType = "W".
              END.
             RELEASE tt-ar-OEActServ.
             cum-recs = cum-recs + 1.

             FIND NEXT hour-table NO-ERROR.
             IF NOT AVAILABLE hour-table THEN LEAVE repeat2-loop.
          END.
   END.  /* DO i4 = 1 to 5000 */

   PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActSrv:  Processed " cum-recs " hourly records of " tot-recs "..." SKIP.
END. /* Repeat Loope */
END. /*  IF AVAILABLE hour-table */

/* This will write out the temp tables to the appropriate files. */
ASSIGN
  write-count = 0
  tot-recs = 0
  cum-recs = 0.

/* figure out how many records we have to write out */
FOR EACH tt-ar-OEActServ NO-LOCK: tot-recs = tot-recs + 1. END.

sec-name = "OE_ActSrv: Writing Weekly Data to disk ".
{include/ar-debug.i "sec-name"}

FIND FIRST tt-ar-OEActServ
     WHERE tt-ar-OEActServ.ActServ_archiveType = "W" NO-ERROR.
IF AVAILABLE tt-ar-oeactserv
 THEN DO:
   repeat3-loop:

   REPEAT:
      DO i4 = 1 to 5000:
            /* Write out ar_OE_ActServ */
            FOR FIRST ar_OE_ActServ
                WHERE Ar_OE_ActServ.ActServ_archiveType = "W"
                  AND tt-ar-OEActServ.Site_Id = Ar_OE_ActServ.site_id
                  AND tt-ar-OEActServ.Resrc_Id = Ar_OE_ActServ.Resrc_id
                  AND tt-ar-OEActServ.ActBrk_UUID = Ar_OE_ActServ.ActBrk_UUID
                  AND tt-ar-OEActServ.ActServ_PID = Ar_OE_ActServ.ActServ_PID
                  AND tt-ar-OEActServ.ActServ_Status = Ar_OE_ActServ.ActServ_Status 
                  AND tt-ar-OEActServ.ActServ_startDate = Ar_OE_ActServ.ActServ_startdate
                  AND tt-ar-OEActServ.ActServ_enddate = Ar_OE_ActServ.ActServ_startdate NO-LOCK: END.
             IF NOT AVAILABLE ar_OE_ActServ THEN DO TRANSACTION: RUN write-record. END.
             
            FIND NEXT tt-ar-OEActServ WHERE tt-ar-OEActServ.ActServ_archiveType = "W" NO-ERROR.
            IF NOT AVAILABLE tt-ar-oeactserv THEN LEAVE repeat3-loop.
      END. /* DO i4 = 1 to 5000 */
      PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActSrv:  Wrote " cum-recs " of " tot-recs "..." SKIP.
  END. /* Repeat */
END.

sec-name = "OE_ActSrv: Writing Weekly Data to disk ".
{include/ar-debug.i "sec-name"}

FIND FIRST tt-ar-OEActServ WHERE tt-ar-OEActServ.ActServ_archiveType = "D" NO-ERROR.

IF AVAILABLE tt-ar-oeactserv
 THEN DO:
   repeat3-loop:

   REPEAT:
        DO i4 = 1 to 5000:
            FOR FIRST ar_OE_ActServ
                WHERE ar_OE_ActServ.ActServ_archiveType = "D"
                  AND tt-ar-OEActServ.Site_Id = Ar_OE_ActServ.site_id
                  AND tt-ar-OEActServ.Resrc_Id = Ar_OE_ActServ.Resrc_id
                  AND tt-ar-OEActServ.ActBrk_UUID = Ar_OE_ActServ.ActBrk_UUID
                  AND tt-ar-OEActServ.ActServ_PID = Ar_OE_ActServ.ActServ_PID 
                  AND tt-ar-OEActServ.ActServ_Status = Ar_OE_ActServ.ActServ_Status
                  AND tt-ar-OEActServ.ActServ_startDate = Ar_OE_ActServ.ActServ_startdate
                  AND tt-ar-OEActServ.ActServ_enddate = Ar_OE_ActServ.ActServ_startdate NO-LOCK: END.
            IF NOT AVAILABLE ar_OE_ActServ THEN DO TRANSACTION: RUN write-record. END.
            
            FIND NEXT tt-ar-OEActServ WHERE tt-ar-OEActServ.ActServ_archiveType = "D" NO-ERROR.
            IF NOT AVAILABLE tt-ar-oeactserv THEN LEAVE repeat3-loop.
        END.
        PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActSrv:  Wrote " cum-recs " of " tot-recs "..." SKIP.
    END.
END.

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActSrv:  Daily/Weekly Compaction Records Written : " write-count SKIP.

sec-name = "OE_ActSrv: Ending Processing".
{include/ar-debug.i "sec-name"}

/* This procedure will write out the record appropriately. */
PROCEDURE write-record.
    CREATE Ar_OE_ActServ.    
    BUFFER-COPY tt-ar-OEActServ TO Ar_OE_ActServ.
    RELEASE Ar_OE_ActServ.
    ASSIGN
      write-count = write-count + 1
      cum-recs = cum-recs + 1.
END PROCEDURE.

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-OEActServ.
    BUFFER-COPY ar_OE_ActServ EXCEPT               
        Ar_OE_ActServ.ActServ_IdleCount
        Ar_OE_ActServ.ActServ_IdleTime
        Ar_OE_ActServ.ActServ_BusyCount
        Ar_OE_ActServ.ActServ_BusyTime
        Ar_OE_ActServ.ActServ_LockedCount
        Ar_OE_ActServ.ActServ_LockedTime
        Ar_OE_ActServ.ActServ_Length
        Ar_OE_ActServ.ActServ_RecordCount
        TO tt-ar-OEActServ.

    ASSIGN            
        tt-ar-OEActServ.sample_id          = NEXT-VALUE(ar_sample-seq)
        tt-ar-OEActServ.ActServ_EndTime    = {&DAY_END_TIME}
        tt-ar-OEActServ.ActServ_StartTime  = 0.
    RUN add-oeActServ.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-OEActServ.
    ASSIGN
        tt-ar-OEActServ.ActServ_IdleCount   = tt-ar-OEActServ.ActServ_IdleCount + ar_OE_ActServ.ActServ_IdleCount
        tt-ar-OEActServ.ActServ_IdleTime    = tt-ar-OEActServ.ActServ_IdleTime + ar_OE_ActServ.ActServ_IdleTime
        tt-ar-OEActServ.ActServ_BusyCount   = tt-ar-OEActServ.ActServ_BusyCount + ar_OE_ActServ.ActServ_BusyCount
        tt-ar-OEActServ.ActServ_BusyTime    = tt-ar-OEActServ.ActServ_BusyTime + ar_OE_ActServ.ActServ_BusyTime
        tt-ar-OEActServ.ActServ_LockedCount = tt-ar-OEActServ.ActServ_LockedCount + ar_OE_ActServ.ActServ_LockedCount
        tt-ar-OEActServ.ActServ_LockedTime  = tt-ar-OEActServ.ActServ_LockedTime + ar_OE_ActServ.ActServ_LockedTime
        tt-ar-OEActServ.ActServ_RecordCount = tt-ar-OEActServ.ActServ_RecordCount + ar_OE_ActServ.ActServ_RecordCount
        tt-ar-OEActServ.ActServ_Length      = tt-ar-OEActServ.ActServ_Length + ar_OE_ActServ.ActServ_Length.
END PROCEDURE.
/* 
** ar_OE_ActWSProc.p
**
** This include will archive the ar_OE_ActWSProc rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
*/

/*
llaubach 10/2005
 - tt-oe_actwsproc temp-table now defined with NO-UNDO
 - defined an index on tt-oe_actwsproc table to match WHERE clause
 - added NO-LOCK to FOR EACH oe_actwsproc WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - removed first DO TRANSACTION block as it was only operation on temp-tables
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.

sec-name = "OE_ActWSProc: Starting archiving".
{include/ar-debug.i "sec-name"}

DEFINE TEMP-TABLE tt-ar-OEActWSProc NO-UNDO LIKE ar_OE_ActWSProc
    INDEX myindex1 actwsproc_archivetype actwsproc_startdate site_id resrc_id actbrk_uuid actbrk_pid actwsproc_name.

/* CREATE THE HOURLY RECORDS */

IF doHourlyRecords THEN RUN archive/ar-h-oe_actwsproc.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT 
   SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */

sec-name = "OE_ActWSProc: Starting Processing Daily/Weekly Records".
{include/ar-debug.i "sec-name"}

DEFINE VARIABLE rec-cnt AS INTEGER NO-UNDO.
DEFINE VARIABLE i5 AS INTEGER NO-UNDO.
DEFINE VARIABLE loop-cnt AS INTEGER NO-UNDO.

FOR EACH hour-table: loop-cnt = loop-cnt + 1. END.

FIND FIRST hour-table NO-ERROR.
IF AVAILABLE hour-table
 THEN DO:

 repeat-loop:

REPEAT:
      DO i5 = 1 to 5000:
   
            rec-cnt = rec-cnt + 1.
   
            FIND FIRST Ar_OE_ActWSProc where hour-rowid = ROWID(Ar_OE_ActWSProc) NO-ERROR.
            
            /* If the Ar_OE_ActWSProc row is there then we will process it otherwise we will skip the 
             rowid and move on to the next one */
        
            IF AVAILABLE Ar_OE_ActWSProc
             THEN DO:
                  /* PROCESS DAILY RECORDS */
                  FOR FIRST tt-ar-OEActWSProc
                      WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "D"
                        AND tt-ar-OEActWSProc.ActWSProc_startDate = ar_OE_ActWSProc.ActWSProc_startdate
                        AND tt-ar-OEActWSProc.Site_Id = ar_OE_ActWSProc.site_id
                        AND tt-ar-OEActWSProc.Resrc_Id = ar_OE_ActWSProc.Resrc_id
                        AND tt-ar-OEActWSProc.ActBrk_UUID = ar_OE_ActWSProc.ActBrk_UUID
                        AND tt-ar-OEActWSProc.ActBrk_PID = ar_OE_ActWSProc.ActBrk_PID
                        AND tt-ar-OEActWSProc.ActWSProc_Name =  Ar_OE_ActWSProc.ActWSProc_Name:
                      RUN add-OEActWSProc.
                  END.

                  IF NOT AVAILABLE tt-ar-OEActWSProc
                   THEN DO:
                        RUN create-record.
                        ASSIGN
                          tt-ar-OEActWSProc.ActWSProc_StartDate = Ar_OE_ActWSProc.ActWSProc_StartDate
                          tt-ar-OEActWSProc.ActWSProc_EndDate = Ar_OE_ActWSProc.ActWSProc_EndDate
                          tt-ar-OEActWSProc.ActWSProc_archiveType = "D".
                   END.
                  RELEASE tt-ar-OEActWSProc.
                    
                  /* PROCESS WEEKLY RECORDS */
                  FOR FIRST tt-ar-OEActWSProc
                      WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "W"
                        AND tt-ar-OEActWSProc.ActWSProc_startDate LE ar_OE_ActWSProc.ActWSProc_startdate
                        AND tt-ar-OEActWSProc.ActWSProc_enddate GE ar_OE_ActWSProc.ActWSProc_startdate
                        AND tt-ar-OEActWSProc.Site_Id = ar_OE_ActWSProc.site_id
                        AND tt-ar-OEActWSProc.Resrc_Id = ar_OE_ActWSProc.Resrc_id
                        AND tt-ar-OEActWSProc.ActBrk_UUID = ar_OE_ActWSProc.ActBrk_UUID
                        AND tt-ar-OEActWSProc.ActBrk_PID = ar_OE_ActWSProc.ActBrk_PID
                        AND tt-ar-OEActWSProc.ActWSProc_Name =  Ar_OE_ActWSProc.ActWSProc_Name:
                      RUN add-OEActWSProc.
                END.
                
                IF NOT AVAILABLE tt-ar-OEActWSProc
                 THEN DO:
                      RUN create-record.
                      ASSIGN
                        tt-ar-OEActWSProc.ActWSProc_StartDate = Ar_OE_ActWSProc.ActWSProc_StartDate - (WEEKDAY(Ar_OE_ActWSProc.ActWSProc_StartDate) - 1)
                        tt-ar-OEActWSProc.ActWSProc_EndDate = tt-ar-OEActWSProc.ActWSProc_StartDate + 6
                        tt-ar-OEActWSProc.ActWSProc_archiveType = "W".
                  END.
                RELEASE tt-ar-OEActWSProc.
            END. /* OF IF AVAILABLE tt-ar-oeactwsproc */

            FIND NEXT hour-table NO-ERROR.
            IF NOT AVAILABLE hour-table THEN LEAVE repeat-loop.

        END. /* OF DO I = 1 to 50000 */

        PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Processed " rec-cnt " hourly records of " loop-cnt " records...".

END. /*  Of Repeat Loop: */
END. /* OF if First hour-record available */

/* This will write out the temp tables to the appropriate files. */
sec-name = "OE_ActWSProc: Writing Daily/Weekly data to disk ".
{include/ar-debug.i "sec-name"}

/* Write out ar_OE_ActWSProc */
ASSIGN
  rec-cnt = 0
  write-count = 0.

repeat-loop:

REPEAT:
     DO i5 = 1 to 5000:
            IF rec-cnt = 0
             THEN FIND FIRST tt-ar-OEActWSProc WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "W" NO-LOCK NO-ERROR.
             ELSE FIND NEXT tt-ar-OEActWSProc WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "W" NO-LOCK NO-ERROR.

            rec-cnt = rec-cnt + 1.
   
            IF NOT AVAILABLE tt-ar-OEActWSProc THEN LEAVE repeat-loop.
   
            FOR FIRST ar_OE_ActWSProc
                WHERE ar_OE_ActWSProc.ActWSProc_archiveType = "W"
                  AND tt-ar-OEActWSProc.Site_Id = ar_OE_ActWSProc.site_id
                  AND tt-ar-OEActWSProc.Resrc_Id = ar_OE_ActWSProc.Resrc_id
                  AND tt-ar-OEActWSProc.ActBrk_UUID = ar_OE_ActWSProc.ActBrk_UUID
                  AND tt-ar-OEActWSProc.ActBrk_PID = ar_OE_ActWSProc.ActBrk_PID
                  AND tt-ar-OEActWSProc.ActWSProc_Name =  Ar_OE_ActWSProc.ActWSProc_Name
                  AND tt-ar-OEActWSProc.ActWSProc_startDate = ar_OE_ActWSProc.ActWSProc_startdate
                  AND tt-ar-OEActWSProc.ActWSProc_enddate = ar_OE_ActWSProc.ActWSProc_startdate NO-LOCK: END.
            IF NOT AVAILABLE ar_OE_ActWSProc THEN DO TRANSACTION: RUN write-record. END.
     END.
END.
        
/* Write out Ar_OE_ActWSProc */
rec-cnt = 0.

repeat-loop:
REPEAT:
     DO i5 = 1 to 5000:
            IF rec-cnt = 0
             THEN FIND FIRST tt-ar-OEActWSProc WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "D" NO-LOCK NO-ERROR.
             ELSE FIND NEXT tt-ar-OEActWSProc WHERE tt-ar-OEActWSProc.ActWSProc_archiveType = "D" NO-LOCK NO-ERROR.

            rec-cnt = rec-cnt + 1.
   
            IF NOT AVAILABLE tt-ar-OEActWSProc THEN LEAVE repeat-loop.
   
            FOR FIRST ar_OE_ActWSProc
                WHERE ar_OE_ActWSProc.ActWSProc_archiveType = "D"
                  AND tt-ar-OEActWSProc.Site_Id = ar_OE_ActWSProc.site_id
                  AND tt-ar-OEActWSProc.Resrc_Id = ar_OE_ActWSProc.Resrc_id
                  AND tt-ar-OEActWSProc.ActBrk_UUID = ar_OE_ActWSProc.ActBrk_UUID
                  AND tt-ar-OEActWSProc.ActBrk_PID = ar_OE_ActWSProc.ActBrk_PID
                  AND tt-ar-OEActWSProc.ActWSProc_Name =  Ar_OE_ActWSProc.ActWSProc_Name
                  AND tt-ar-OEActWSProc.ActWSProc_startDate = ar_OE_ActWSProc.ActWSProc_startdate
                  AND tt-ar-OEActWSProc.ActWSProc_enddate = ar_OE_ActWSProc.ActWSProc_startdate NO-LOCK: END.
            IF NOT AVAILABLE ar_OE_ActWSProc THEN DO TRANSACTION: RUN write-record. END.
        END.
END.

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " OE_ActWSProc: Daily/Weekly Compaction Records Written: " write-count SKIP.

sec-name = "OE_ActWSProc: Ending Processing".
{include/ar-debug.i "sec-name"}

/* This procedure will write out the record appropriately. */
PROCEDURE write-record.
    CREATE Ar_OE_ActWSProc.    
    BUFFER-COPY tt-ar-OEActWSProc TO Ar_OE_ActWSProc.
    RELEASE Ar_OE_ActWSProc.
    write-count = write-count + 1.
END PROCEDURE.

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-OEActWSProc.
    ASSIGN
        tt-ar-OEActWSProc.ActBrk_PID =         Ar_OE_ActWSProc.ActBrk_PID
        tt-ar-OEActWSProc.ActBrk_UUID =        Ar_OE_ActWSProc.ActBrk_UUID
        tt-ar-OEActWSProc.ActWSProc_Parent =   Ar_OE_ActWSProc.ActWSProc_Parent
        tt-ar-OEActWSProc.ActWSProc_ProcType = Ar_OE_ActWSProc.ActWSProc_ProcType
        tt-ar-OEActWSProc.ActWSProc_Name =     Ar_OE_ActWSProc.ActWSProc_Name
        tt-ar-OEActWSProc.Resrc_ID =           Ar_OE_ActWSProc.Resrc_ID
        tt-ar-OEActWSProc.Site_ID =            Ar_OE_ActWSProc.Site_ID
        tt-ar-OEActWSProc.sample_id           = NEXT-VALUE(ar_sample-seq)
        tt-ar-OEActWSProc.ActWSProc_EndTime    = {&DAY_END_TIME}
        tt-ar-OEActWSProc.ActWSProc_StartTime  = 0.
    RUN add-oeactwsproc.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-OEActWSProc.
  ASSIGN
     tt-ar-OEActWSProc.ActWSProc_Calls       =  tt-ar-OEActWSProc.ActWSProc_Calls + ar_OE_ActWSProc.ActWSProc_Calls
     tt-ar-OEActWSProc.ActWSProc_TotTime      = tt-ar-OEActWSProc.ActWSProc_TotTime + ar_OE_ActWSProc.ActWSProc_TotTime
     tt-ar-OEActWSProc.ActWSProc_RecordCount  = tt-ar-OEActWSProc.ActWSProc_RecordCount + ar_OE_ActWSProc.ActWSProc_RecordCount
     tt-ar-OEActWSProc.ActWSProc_Length       = tt-ar-OEActWSProc.ActWSProc_Length + ar_OE_ActWSProc.ActWSProc_Length.

  IF tt-ar-OEActWSProc.ActWSProc_MaxTime  LT Ar_OE_ActWSProc.ActWSProc_Length
   THEN tt-ar-OEActWSProc.ActWSProc_MaxTime  = ar_OE_ActWSProc.ActWSProc_MaxTime.
END PROCEDURE.
/* 
** ar_oe_appservice.p
**
** This include will archive the ar_OE_AppService rows that are designated 
** "H" to Day and Weekly.
*/

/*
llaubach 10/2005
 - tt-ar-oeappservice temp-table now defined with NO-UNDO
 - defined an index on tt-ar-oeappervice table to match WHERE clause
*/


{include/ar-definitions.i}
DEFINE TEMP-TABLE tt-ar-OEAppService NO-UNDO LIKE Ar_OE_AppService
    INDEX myindex actbrk_UUID apps_servicename.

sec-name = "Writing Data to disk ".
{include/ar-debug.i "sec-name"}

RUN archive/ar-h-oe_appservice.p.

sec-name = "Ending Writing Data to disk".
{include/ar-debug.i "sec-name"}
/* 
** ar_Process.p
**
** This include will archive the ar_Process rows that are designated "H" to Day and Weekly.
**
** The processing happens in the following stages:
*/

/*
llaubach 10/2005
 - tt-ar-process temp-table now defined with NO-UNDO
 - defined an index on tt-ar-process table to match WHERE clause
 - added NO-LOCK to FOR EACH ar_process WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - removed first DO TRANSACTION block as it was only operation on temp-tables
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope 
*/

{include/ar-definitions.i}.

sec-name = "Ar_Process: Starting Archiving".
{include/ar-debug.i "sec-name"}

DEFINE TEMP-TABLE tt-ar-Process NO-UNDO LIKE ar_Process
    INDEX myindex1 PROCESS_archivetype PROCESS_startdate site_id resrc_id PROCESS_pid.

/* CREATE THE HOURLY RECORDS */
IF doHourlyRecords THEN RUN archive/ar-h-process.p.

DEFINE VARIABLE rec-cnt AS INTEGER NO-UNDO.
DEFINE VARIABLE i3 AS INTEGER NO-UNDO.
DEFINE VARIABLE loop-cnt AS INTEGER NO-UNDO.

/* Empty the temp table for performance and to improve the writing */
EMPTY TEMP-TABLE tt-ar-process.

/* 
** SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK
*/

sec-name = "Ar_Process: Starting Daily/Weekly Archiving".
{include/ar-debug.i "sec-name"}

FOR EACH hour-table:
    FIND FIRST Ar_Process where hour-rowid = ROWID(Ar_Process) NO-ERROR.
    
    /* If the Ar_Process row is there then we will process it otherwise we will skip the 
       rowid and move on to the next one */

    IF AVAILABLE Ar_Process
     THEN DO:

        /* PROCESS DAILY RECORDS */
        FOR FIRST tt-ar-Process
            WHERE tt-ar-Process.Process_archiveType = "D"
              AND tt-ar-Process.Process_startDate = ar_Process.Process_startdate
              AND tt-ar-Process.Site_Id = ar_Process.site_id
              AND tt-ar-Process.Resrc_Id = ar_Process.Resrc_id
              AND tt-ar-Process.Process_PID = ar_Process.Process_PID:
            RUN add-process.
        END.
        
        IF NOT AVAILABLE tt-ar-Process
         THEN DO:
              CREATE tt-ar-Process.
              BUFFER-COPY ar_Process EXCEPT
                Ar_Process.Sample_ID 
                Ar_Process.Process_CPUPct
                Ar_Process.Process_CPUPctWt
                Ar_Process.Process_VirtMem
                Ar_Process.Process_ResMemory
                Ar_Process.Process_CPUUser
                Ar_Process.Process_CPUSystem
                Ar_Process.Process_ElapsedTime
                Ar_Process.Process_Length  
                Ar_Process.Process_RecordCount
              TO tt-ar-Process.
              ASSIGN            
                tt-ar-Process.sample_id          = NEXT-VALUE(ar_sample-seq)
                tt-ar-Process.Process_EndTime    = {&DAY_END_TIME}
                tt-ar-Process.Process_StartTime  = 0.
              RUN add-process. 
              ASSIGN
                tt-ar-Process.Process_StartDate = Ar_Process.Process_StartDate
                tt-ar-Process.Process_EndDate = Ar_Process.Process_EndDate
                tt-ar-Process.Process_archiveType = "D".
         END.
        RELEASE tt-ar-Process.
            
        /* PROCESS WEEKLY RECORDS */
        FOR FIRST tt-ar-Process
            WHERE tt-ar-Process.Process_archiveType = "W"
              AND tt-ar-Process.Process_startDate LE ar_Process.Process_startdate
              AND tt-ar-Process.Process_enddate GE ar_Process.Process_enddate
              AND tt-ar-Process.Site_Id = ar_Process.site_id
              AND tt-ar-Process.Resrc_Id = ar_Process.Resrc_id
              AND tt-ar-Process.Process_PID = ar_Process.Process_PID:
            RUN add-process.
        END.
        
        IF NOT AVAILABLE tt-ar-Process
         THEN DO:
              CREATE tt-ar-Process.
              BUFFER-COPY ar_Process EXCEPT
                Ar_Process.Sample_ID 
                Ar_Process.Process_CPUPct
                Ar_Process.Process_CPUPctWt
                Ar_Process.Process_VirtMem
                Ar_Process.Process_ResMemory
                Ar_Process.Process_CPUUser
                Ar_Process.Process_CPUSystem
                Ar_Process.Process_ElapsedTime
                Ar_Process.Process_Length  
                Ar_Process.Process_RecordCount
              TO tt-ar-Process.
              ASSIGN            
                tt-ar-Process.sample_id          = NEXT-VALUE(ar_sample-seq)
                tt-ar-Process.Process_EndTime    = {&DAY_END_TIME}
                tt-ar-Process.Process_StartTime  = 0.
              RUN add-process. 
              ASSIGN
                tt-ar-Process.Process_StartDate = Ar_Process.Process_StartDate - (WEEKDAY(Ar_Process.Process_StartDate) - 1)
                tt-ar-Process.Process_EndDate = tt-ar-Process.Process_StartDate + 6
                tt-ar-Process.Process_archiveType = "W".
         END.
        RELEASE tt-ar-Process.
    
    END. /* OF IF AVAILABLE Ar_Process. */
END. /*  Of for each hour-table */

/* This will write out the temp tables to the appropriate files. */
sec-name = "Ar_Process: Writing Daily/Weekly data to disk ".
{include/ar-debug.i "sec-name"}

/* Daily portion of the writing */

ASSIGN
  rec-cnt = 0
  write-count = 0.

FOR EACH tt-ar-process WHERE tt-ar-process.process_archiveType = "D" NO-LOCK: rec-cnt = rec-cnt + 1. END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Record count for daily records : " rec-cnt.

FIND FIRST tt-ar-process WHERE tt-ar-Process.Process_archiveType = "D" NO-ERROR.
IF AVAILABLE tt-ar-process
 THEN DO:
   repeat-loop:

   REPEAT:
      /*
      ** Do All of the records
      */
         /* Write out ar_Process */
          DO i3 = 1 to 5000:
             FOR FIRST ar_Process
                 WHERE Ar_Process.Process_archiveType = "D"
                   AND tt-ar-Process.Site_Id = ar_Process.site_id
                   AND tt-ar-Process.Resrc_Id = ar_Process.Resrc_id
                   AND tt-ar-Process.Process_PID = ar_Process.Process_PID 
                   AND tt-ar-Process.Process_startDate = ar_Process.Process_startdate
                   AND tt-ar-Process.Process_enddate = ar_Process.Process_startdate NO-LOCK: END.

             IF NOT AVAILABLE ar_Process THEN DO TRANSACTION: RUN write-record. END.

             FIND NEXT tt-ar-process WHERE tt-ar-Process.Process_archiveType = "D" NO-ERROR.
             IF NOT AVAILABLE tt-ar-process THEN LEAVE repeat-loop.

          END. /* OF DO i3 = 1 to 5000 */

       PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Processed " write-count " daily records of " rec-cnt.

   END. /* Of REPEAT */
END. /* OF IF AVAILABLE tt-ar-process */

/* Do the weekly records */

ASSIGN
  rec-cnt = 0
  write-count = 0.

FOR EACH tt-ar-process WHERE tt-ar-process.process_archiveType = "W" NO-LOCK: rec-cnt = rec-cnt + 1. END.
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Record count for weekly records : " rec-cnt.

FIND FIRST tt-ar-process WHERE tt-ar-Process.Process_archiveType = "W" NO-ERROR.
IF AVAILABLE tt-ar-process
 THEN DO:
   repeat-loop:

   REPEAT:
      /*
      ** Do All of the records
      */
       /* Write out ar_Process */
          DO i3 = 1 to 5000:
             FOR FIRST ar_Process
                 WHERE Ar_Process.Process_archiveType = "W"
                   AND tt-ar-Process.Site_Id = ar_Process.site_id
                   AND tt-ar-Process.Resrc_Id = ar_Process.Resrc_id
                   AND tt-ar-Process.Process_PID = ar_Process.Process_PID
                   AND tt-ar-Process.Process_startDate = ar_Process.Process_startdate
                   AND tt-ar-Process.Process_enddate = ar_Process.Process_startdate NO-LOCK: END.

             IF NOT AVAILABLE ar_Process THEN RUN write-record.

             FIND NEXT tt-ar-process WHERE tt-ar-Process.Process_archiveType = "W" NO-ERROR.
             IF NOT AVAILABLE tt-ar-process THEN LEAVE repeat-loop.

          END. /* OF DO i3 = 1 to 5000 */

    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Processed " write-count " weekly records of " rec-cnt.

   END. /* Of REPEAT */
END. /* OF IF AVAILABLE tt-ar-process */

PUT SKIP TODAY " "STRING(TIME, "HH:MM:SS") " Ar_Process: Completed daily and weekly compaction for Sys_Process. " SKIP.

sec-name = "Ar_Process: Ending Archiving".
{include/ar-debug.i "sec-name"}

/* This procedure will write out the record appropriately. */
PROCEDURE write-record.
    CREATE Ar_Process.    
    ASSIGN
        tt-ar-Process.Process_CPUPct = tt-ar-Process.Process_CPUPct / tt-ar-Process.Process_Length
        tt-ar-Process.Process_CPUPctWt = tt-ar-Process.Process_CPUPctWt / tt-ar-Process.Process_Length
        tt-ar-Process.Process_VirtMem = INTEGER (tt-ar-Process.Process_VirtMem / tt-ar-Process.Process_RecordCount)
        tt-ar-Process.Process_ResMemory = INTEGER (tt-ar-Process.Process_ResMemory / tt-ar-Process.Process_RecordCount).
    BUFFER-COPY tt-ar-Process TO Ar_Process.
    RELEASE Ar_Process.
    write-count = write-count + 1.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-process.
    ASSIGN
        tt-ar-Process.Process_CPUPct      = tt-ar-Process.Process_CPUPct + (Ar_Process.Process_CPUPct * Ar_Process.Process_Length)
        tt-ar-Process.Process_CPUPctWt    = tt-ar-Process.Process_CPUPctWt + (Ar_Process.Process_CPUPctWt * Ar_Process.Process_Length)
        tt-ar-Process.Process_VirtMem     = tt-ar-Process.Process_VirtMem + (Ar_Process.Process_VirtMem * Ar_Process.Process_RecordCount)
        tt-ar-Process.Process_ResMemory   = tt-ar-Process.Process_ResMemory + (Ar_Process.Process_ResMemory * Ar_Process.Process_RecordCount)
        tt-ar-Process.Process_CPUUser     = tt-ar-Process.Process_CPUUser + Ar_Process.Process_CPUUser
        tt-ar-Process.Process_CPUSystem   = tt-ar-Process.Process_CPUSystem + Ar_Process.Process_CPUSystem
        tt-ar-Process.Process_ElapsedTime = tt-ar-Process.Process_ElapsedTime + Ar_Process.Process_ElapsedTime
        tt-ar-Process.Process_RecordCount =   tt-ar-Process.Process_RecordCount + Ar_Process.Process_RecordCount
        tt-ar-Process.Process_Length      =   tt-ar-Process.Process_Length + Ar_Process.Process_Length.
END PROCEDURE.
/*
** ar-report-add-actapw.p
**
** Adds ai data from the archive Ar_ActAPW table into the data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index.
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-actapw.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActAPW:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActAPW NO-LOCK WHERE " +
                 "Ar_ActAPW.ActAPW_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActAPW.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActAPW.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActAPW.ActAPW_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActAPW.ActAPW_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActAPW.ActAPW_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActAPW.ActAPW_StartTime LE " + STRING(Fathom-i-End_time)). 
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = actapw_Recordcount.
        WHEN "S" THEN fathom-store-value = actapw_length.
        WHEN "M" THEN fathom-store-value = actapw_length / 60.
        WHEN "H" THEN fathom-store-value = ((actapw_length / 60) / 60).
        WHEN "T" THEN fathom-store-value = actapw_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActAPW.ActAPW_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActAPW.ActAPW_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActAPW.ActAPW_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActAPW.ActAPW_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActAPW.ActAPW_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActAPW.ActAPW_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActAPW.ActAPW_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    FIND FIRST data_store WHERE name = "ActAPW_APWEnq" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_APWEnq .                                            

    FIND FIRST data_store WHERE name = "ActAPW_APWQWrites" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_APWQWrites .                                        

    FIND FIRST data_store WHERE name = "ActAPW_BufsCkpt" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_BufsCkpt .                                          

    FIND FIRST data_store WHERE name = "ActAPW_BufsScanned" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_BufsScanned .                                       

    FIND FIRST data_store WHERE name = "ActAPW_CkptQWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_CkptQWrites .                                       

    FIND FIRST data_store WHERE name = "ActAPW_Ckpts" NO-LOCK NO-ERROR.                                           
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_Ckpts .                                             

    FIND FIRST data_store WHERE name = "ActAPW_DBWrites" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_DBWrites .                                          

    FIND FIRST data_store WHERE name = "ActAPW_Flushed" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_Flushed .                                           

    FIND FIRST data_store WHERE name = "ActAPW_Marked" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_Marked .                                            

    FIND FIRST data_store WHERE name = "ActAPW_ScanCycles" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_ScanCycles .                                        

    FIND FIRST data_store WHERE name = "ActAPW_ScanWrites" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_ScanWrites .                                        

    FIND FIRST data_store WHERE name = "ActAPW_TotDBWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActAPW.ActAPW_TotDBWrites .                                       

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actbuf.p
**
** Adds ai data from the archive Ar_ActBuf table into the data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index. 
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-actbuf.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActBuf:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActBuf NO-LOCK WHERE " +
                 "Ar_ActBuf.ActBuf_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActBuf.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActBuf.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActBuf.ActBuf_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActBuf.ActBuf_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActBuf.ActBuf_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActBuf.ActBuf_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = Actbuf_Recordcount.
        WHEN "S" THEN fathom-store-value = Actbuf_length.
        WHEN "M" THEN fathom-store-value = Actbuf_length / 60.
        WHEN "H" THEN fathom-store-value = Actbuf_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = Actbuf_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActBuf.ActBuf_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActBuf.ActBuf_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActBuf.ActBuf_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActBuf.ActBuf_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters THEN
    DO:
        fathom-rec-count = fathom-rec-count + Ar_ActBuf.ActBuf_RecordCount.
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActBuf.ActBuf_Length.
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActBuf.ActBuf_RecordCount. 
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.
    END.

    FIND FIRST data_store WHERE name = "ActBuf_Deferred" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActBuf.ActBuf_Deferred .                                          

    FIND FIRST data_store WHERE name = "ActBuf_Flushed" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActBuf.ActBuf_Flushed .                                           

    FIND FIRST data_store WHERE name = "ActBuf_LogicReads" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActBuf.ActBuf_LogicReads .                                        

    FIND FIRST data_store WHERE name = "ActBuf_LogicWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActBuf.ActBuf_LogicWrites .                                       

    FIND FIRST data_store WHERE name = "ActBuf_OSReads" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActBuf.ActBuf_OSReads .                                           

    FIND FIRST data_store WHERE name = "ActBuf_OSWrites" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActBuf.ActBuf_OSWrites .                                          

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actidx.p
**
** Adds data from the archive Ar_ActIdx table into the data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index. 
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-actidx.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActIdx:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActIdx NO-LOCK WHERE " +
                 "Ar_ActIdx.ActIdx_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActIdx.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActIdx.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActIdx.ActIdx_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActIdx.ActIdx_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActIdx.ActIdx_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActIdx.ActIdx_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = Actidx_Recordcount.
        WHEN "S" THEN fathom-store-value = Actidx_length.
        WHEN "M" THEN fathom-store-value = Actidx_length / 60.
        WHEN "H" THEN fathom-store-value = Actidx_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = Actidx_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActIdx.ActIdx_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActIdx.ActIdx_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActIdx.ActIdx_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActIdx.ActIdx_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActIdx.ActIdx_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActIdx.ActIdx_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActIdx.ActIdx_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    FIND FIRST data_store WHERE name = "ActIdx_Create" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIdx.ActIdx_Create .                                            

    FIND FIRST data_store WHERE name = "ActIdx_Delete" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIdx.ActIdx_Delete .                                            

    FIND FIRST data_store WHERE name = "ActIdx_Find" NO-LOCK NO-ERROR.                                            
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIdx.ActIdx_Find .                                              

    FIND FIRST data_store WHERE name = "ActIdx_Free" NO-LOCK NO-ERROR.                                            
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIdx.ActIdx_Free .                                              

    FIND FIRST data_store WHERE name = "ActIdx_Remove" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIdx.ActIdx_Remove .                                            

    FIND FIRST data_store WHERE name = "ActIdx_Splits" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIdx.ActIdx_Splits .                                            

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actiofile.p
**
** Adds data from the archive Ar_ActIOFile table into the
** data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index. 
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.
    
ASSIGN
  pgm-name = "ar-report-add-actiofile.p"
  sec-name = "Running procedure add-actiofile".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActIOFile:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActIOFile NO-LOCK WHERE " +
                 "Ar_ActIOFile.ActIOFile_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActIOFile.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActIOFile.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActIOFile.ActIOFile_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActIOFile.ActIOFile_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActIOFile.ActIOFile_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActIOFile.ActIOFile_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = actiofile_Recordcount.
        WHEN "S" THEN fathom-store-value = actiofile_length.
        WHEN "M" THEN fathom-store-value = actiofile_length / 60.
        WHEN "H" THEN fathom-store-value = actiofile_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = actiofile_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.
    
    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.
            
    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActIOFile.ActIOFile_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActIOFile.ActIOFile_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActIOFile.ActIOFile_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActIOFile.ActIOFile_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActIOFile.ActIOFile_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActIOFile.ActIOFile_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActIOFile.ActIOFile_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    /*
    ** Process each field that is on the report
    */
    FIND FIRST data_store WHERE name = "ActIOFile_BufReads" EXCLUSIVE-LOCK NO-ERROR.  
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOFile.ActIOFile_BufReads.
    
    FIND FIRST data_store WHERE name = "ActIOFile_BufWrites" EXCLUSIVE-LOCK NO-ERROR.      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOFile.ActIOFile_BufWrites .
    
    FIND FIRST data_store WHERE name = "ActIOFile_Extends" EXCLUSIVE-LOCK NO-ERROR.  
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOFile.ActIOFile_Extends .
    
    FIND FIRST data_store WHERE name = "ActIOFile_Reads" EXCLUSIVE-LOCK NO-ERROR.        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOFile.ActIOFile_Reads .
    
    FIND FIRST data_store WHERE name = "ActIOFile_UnbufReads" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOFile.ActIOFile_UnbufReads.
    
    FIND FIRST data_store WHERE name = "ActIOFile_UnbufWrites" EXCLUSIVE-LOCK NO-ERROR.      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOFile.ActIOFile_UnbufWrites .
    
    FIND FIRST data_store WHERE name = "ActIOFile_Writes" EXCLUSIVE-LOCK NO-ERROR.            
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOFile.ActIOFile_Writes .

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actiotype.p
**
** Adds data from the archive Ar_ActIOType table into the
** data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index.  
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-actiotype.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActIOType:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActIOType NO-LOCK WHERE " +
                 "Ar_ActIOType.ActIOType_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActIOType.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActIOType.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActIOType.ActIOType_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActIOType.ActIOType_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActIOType.ActIOType_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActIOType.ActIOType_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = Actiotype_Recordcount.
        WHEN "S" THEN fathom-store-value = Actiotype_length.
        WHEN "M" THEN fathom-store-value = Actiotype_length / 60.
        WHEN "H" THEN fathom-store-value = Actiotype_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = Actiotype_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActIOType.ActIOType_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActIOType.ActIOType_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActIOType.ActIOType_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActIOType.ActIOType_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActIOType.ActIOType_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActIOType.ActIOType_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActIOType.ActIOType_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    FIND FIRST data_store WHERE name = "ActIOType_AiReads" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_AiReads .                                     

    FIND FIRST data_store WHERE name = "ActIOType_AiWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_AiWrites .                                    

    FIND FIRST data_store WHERE name = "ActIOType_BiReads" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_BiReads .                                     

    FIND FIRST data_store WHERE name = "ActIOType_BiWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_BiWrites .                                    

    FIND FIRST data_store WHERE name = "ActIOType_DataReads" NO-LOCK NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_DataReads .                                   

    FIND FIRST data_store WHERE name = "ActIOType_DataWrites" NO-LOCK NO-ERROR.                                   
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_DataWrites .                                  

    FIND FIRST data_store WHERE name = "ActIOType_IdxReads" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_IdxReads .                                    

    FIND FIRST data_store WHERE name = "ActIOType_IdxWrites" NO-LOCK NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActIOType.ActIOType_IdxWrites .                                   

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actlock.p
**
** Adds data from the archive Ar_ActLock table into the
** data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index. 
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-actlock.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActLock:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActLock NO-LOCK WHERE " +
                 "Ar_ActLock.ActLock_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActLock.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActLock.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActLock.ActLock_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActLock.ActLock_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActLock.ActLock_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActLock.ActLock_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = Actlock_Recordcount.
        WHEN "S" THEN fathom-store-value = Actlock_length.
        WHEN "M" THEN fathom-store-value = Actlock_length / 60.
        WHEN "H" THEN fathom-store-value = Actlock_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = Actlock_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActLock.ActLock_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActLock.ActLock_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActLock.ActLock_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActLock.ActLock_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActLock.ActLock_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActLock.ActLock_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActLock.ActLock_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    FIND FIRST data_store WHERE name = "ActLock_CanclReq" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_CanclReq .                                        

    FIND FIRST data_store WHERE name = "ActLock_Downgrade" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_Downgrade .                                       

    FIND FIRST data_store WHERE name = "ActLock_ExclFind" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ExclFind .                                        

    FIND FIRST data_store WHERE name = "ActLock_ExclLock" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ExclLock .                                        

    FIND FIRST data_store WHERE name = "ActLock_ExclReq" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ExclReq .                                         

    FIND FIRST data_store WHERE name = "ActLock_ExclWait" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ExclWait .                                        

    FIND FIRST data_store WHERE name = "ActLock_RecGetLock" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_RecGetLock .                                      

    FIND FIRST data_store WHERE name = "ActLock_RecGetReq" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_RecGetReq .                                       

    FIND FIRST data_store WHERE name = "ActLock_RecGetWait" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_RecGetWait .                                      

    FIND FIRST data_store WHERE name = "ActLock_ShrFind" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ShrFind .                                         

    FIND FIRST data_store WHERE name = "ActLock_ShrLock" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ShrLock .                                         

    FIND FIRST data_store WHERE name = "ActLock_ShrReq" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ShrReq .                                          

    FIND FIRST data_store WHERE name = "ActLock_ShrWait" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_ShrWait .                                         

    FIND FIRST data_store WHERE name = "ActLock_UpgLock" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_UpgLock .                                         

    FIND FIRST data_store WHERE name = "ActLock_UpgReq" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_UpgReq .                                          

    FIND FIRST data_store WHERE name = "ActLock_UpgWait" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLock.ActLock_UpgWait .                                         

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actlog-ai.p
**
** Adds ai data from the archive Ar_ActLog table into the data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index. 
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-actlog-ai.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActLog:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActLog NO-LOCK WHERE " +
                 "Ar_ActLog.ActLog_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActLog.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActLog.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActLog.ActLog_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActLog.ActLog_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActLog.ActLog_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActLog.ActLog_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = actlog_Recordcount.
        WHEN "S" THEN fathom-store-value = actlog_length.
        WHEN "M" THEN fathom-store-value = actlog_length / 60.
        WHEN "H" THEN fathom-store-value = ((actlog_length / 60) / 60).
        WHEN "T" THEN fathom-store-value = actlog_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      fathom-rec-count = fathom-rec-count + ar_actlog.Actlog_RecordCount
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
       Fathom-i = Fathom-i + 1.
       IF Ar_ActLog.ActLog_startdate GE Fathom-t-beg-date[Fathom-i] AND
           Ar_ActLog.ActLog_startdate LE Fathom-t-end-date[Fathom-i] THEN
       DO:
           IF Ar_ActLog.ActLog_starttime GE Fathom-t-beg-time[Fathom-i] AND
               Ar_ActLog.ActLog_starttime LE Fathom-t-end-time[Fathom-i] THEN
               LEAVE.
       END.
       IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActLog.ActLog_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActLog.ActLog_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActLog.ActLog_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    /*
    ** Process each field that is on the report
    */
    FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIBBufWaits.

    FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIByteWrites.

    FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AINoBufAvail.

    FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIPartialWrites.

    FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIRecWrites.

    FIND FIRST data_store WHERE name = "ActLog_AITotWrites" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AITotWrites.

    FIND FIRST data_store WHERE name = "ActLog_AIWWrites" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIWWrites.

END. /* of REPEAT.*/

qh:QUERY-CLOSE().
DELETE OBJECT qh.



/*
** ar-report-add-actlog-aibi.p
**
** Adds bi data from the archive Ar_ActLog table into the
** data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index. 
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-add-actlog-aibi.p"
  sec-name = "running procedure add-actlog".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActLog:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActLog NO-LOCK WHERE " +
                 "Ar_ActLog.ActLog_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActLog.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActLog.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActLog.ActLog_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActLog.ActLog_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActLog.ActLog_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActLog.ActLog_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = Actlog_Recordcount.
        WHEN "S" THEN fathom-store-value = Actlog_length.
        WHEN "M" THEN fathom-store-value = Actlog_length / 60.
        WHEN "H" THEN fathom-store-value = Actlog_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = Actlog_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.
    
    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActLog.ActLog_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActLog.ActLog_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActLog.ActLog_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActLog.ActLog_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
        fathom-rec-count = fathom-rec-count + Ar_ActLog.ActLog_RecordCount
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActLog.ActLog_Length
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActLog.ActLog_RecordCount
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIBBufWaits .                                       

    FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" NO-LOCK NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIByteWrites .                                      

    FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" NO-LOCK NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AINoBufAvail .                                      

    FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" NO-LOCK NO-ERROR.                                 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIPartialWrites .                                   

    FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIRecWrites .                                       

    FIND FIRST data_store WHERE name = "ActLog_AITotWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AITotWrites .                                       

    FIND FIRST data_store WHERE name = "ActLog_AIWWrites" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_AIWWrites .                                         

    FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIBBufWaits .                                       

    FIND FIRST data_store WHERE name = "ActLog_BIByteReads" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIByteReads .                                       

    FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" NO-LOCK NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIByteWrites .                                      

    FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIEBufWaits .                                       

    FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" NO-LOCK NO-ERROR.                                 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIPartialWrites .                                   

    FIND FIRST data_store WHERE name = "ActLog_BIRecReads" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIRecReads .                                        

    FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIRecWrites .                                       

    FIND FIRST data_store WHERE name = "ActLog_BITotReads" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BITotReads .                                        
    
    FIND FIRST data_store WHERE name = "ActLog_BITotWrites" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BITotWrites .                                       
    
    FIND FIRST data_store WHERE name = "ActLog_BIWWrites" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIWWrites .                                         
    
END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actlog-bi.p
**
** Adds bi data from the archive Ar_ActLog table into the data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index.  
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-add-actlog-bi.p"
  sec-name = "running procedure add-actlog".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActLog:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActLog NO-LOCK WHERE " +
                 "Ar_ActLog.ActLog_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActLog.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActLog.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActLog.ActLog_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActLog.ActLog_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActLog.ActLog_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActLog.ActLog_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = actlog_Recordcount.
        WHEN "S" THEN fathom-store-value = actlog_length.
        WHEN "M" THEN fathom-store-value = actlog_length / 60.
        WHEN "H" THEN fathom-store-value = actlog_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = actlog_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.
    
    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.
        
    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActLog.ActLog_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActLog.ActLog_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActLog.ActLog_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActLog.ActLog_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActLog.ActLog_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActLog.ActLog_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActLog.ActLog_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    /*
    ** Process each field that is on the report
    */
    FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIBBufWaits.
    
    FIND FIRST data_store WHERE name = "ActLog_BIByteReads" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIByteReads.
    
    FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIByteWrites.
    
    FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIEBufWaits.
    
    FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIPartialWrites.
    
    FIND FIRST data_store WHERE name = "ActLog_BIRecReads" EXCLUSIVE-LOCK NO-ERROR.         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIRecReads.
    
    FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" EXCLUSIVE-LOCK NO-ERROR.  
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIRecWrites.
    
    FIND FIRST data_store WHERE name = "ActLog_BITotReads" EXCLUSIVE-LOCK NO-ERROR.  
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BITotReads .
    
    FIND FIRST data_store WHERE name = "ActLog_BITotWrites" EXCLUSIVE-LOCK NO-ERROR.   
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BITotWrites.
    
    FIND FIRST data_store WHERE name = "ActLog_BIWWrites" EXCLUSIVE-LOCK NO-ERROR.      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActLog.ActLog_BIWWrites.
    
END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actrec.p
**
** Adds data from the archive Ar_ActRec table into the data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index.
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-actrec.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActRec:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActRec NO-LOCK WHERE " +
                 "Ar_ActRec.ActRec_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActRec.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActRec.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActRec.ActRec_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActRec.ActRec_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActRec.ActRec_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActRec.ActRec_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = Actrec_Recordcount.
        WHEN "S" THEN fathom-store-value = Actrec_length.
        WHEN "M" THEN fathom-store-value = Actrec_length / 60.
        WHEN "H" THEN fathom-store-value = Actrec_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = Actrec_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActRec.ActRec_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActRec.ActRec_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActRec.ActRec_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActRec.ActRec_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
        fathom-rec-count = fathom-rec-count + Ar_ActRec.ActRec_RecordCount
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActRec.ActRec_Length
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActRec.ActRec_RecordCount
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    FIND FIRST data_store WHERE name = "ActRec_ByteCreate" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_ByteCreate .                                        

    FIND FIRST data_store WHERE name = "ActRec_ByteDel" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_ByteDel .                                           

    FIND FIRST data_store WHERE name = "ActRec_ByteRead" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_ByteRead .                                          

    FIND FIRST data_store WHERE name = "ActRec_ByteUpd" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_ByteUpd .                                           

    FIND FIRST data_store WHERE name = "ActRec_FragCreate" NO-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_FragCreate .                                        

    FIND FIRST data_store WHERE name = "ActRec_FragDel" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_FragDel .                                           

    FIND FIRST data_store WHERE name = "ActRec_FragRead" NO-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_FragRead .                                          

    FIND FIRST data_store WHERE name = "ActRec_FragUpd" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_FragUpd .                                           

    FIND FIRST data_store WHERE name = "ActRec_RecCreate" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_RecCreate .                                         

    FIND FIRST data_store WHERE name = "ActRec_RecDel" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_RecDel .                                            

    FIND FIRST data_store WHERE name = "ActRec_RecLock" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_RecLock .                                           

    FIND FIRST data_store WHERE name = "ActRec_RecRead" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_RecRead .                                           

    FIND FIRST data_store WHERE name = "ActRec_RecUpd" NO-LOCK NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_RecUpd .                                            

    FIND FIRST data_store WHERE name = "ActRec_RecWait" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActRec.ActRec_RecWait .                                           

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-actsum.p
**
** Adds data from the archive Ar_ActSum table into the
** data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index.   
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.
    
ASSIGN
  pgm-name = "ar-report-add-actsum.p"
  sec-name = "Running procedure add-actsum".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_ActSum:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_ActSum NO-LOCK WHERE " +
                 "Ar_ActSum.ActSum_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_ActSum.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_ActSum.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_ActSum.ActSum_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_ActSum.ActSum_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_ActSum.ActSum_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_ActSum.ActSum_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = actsum_Recordcount.
        WHEN "S" THEN fathom-store-value = actsum_length.
        WHEN "M" THEN fathom-store-value = actsum_length / 60.
        WHEN "H" THEN fathom-store-value = actsum_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = actsum_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.
    
    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_ActSum.ActSum_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_ActSum.ActSum_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_ActSum.ActSum_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_ActSum.ActSum_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_ActSum.ActSum_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_ActSum.ActSum_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActSum.ActSum_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    /*
    ** Process each field that is on the report
    */
    FIND FIRST data_store WHERE name = "ActSum_AllocNewRm" EXCLUSIVE-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_AllocNewRm.
    
    FIND FIRST data_store WHERE name = "ActSum_BytesAlloc" EXCLUSIVE-LOCK NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_BytesAlloc .
    
    FIND FIRST data_store WHERE name = "ActSum_Examined" EXCLUSIVE-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_Examined .
    
    FIND FIRST data_store WHERE name = "ActSum_FromFree" EXCLUSIVE-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_FromFree.
    
    FIND FIRST data_store WHERE name = "ActSum_FromRm" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_FromRm .
    
    FIND FIRST data_store WHERE name = "ActSum_Removed" EXCLUSIVE-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_Removed.
    
    FIND FIRST data_store WHERE name = "ActSum_RetFree" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_RetFree.
    
    FIND FIRST data_store WHERE name = "ActSum_TakeFree" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_TakeFree .
    
    FIND FIRST data_store WHERE name = "ActSum_AiWrites" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_AiWrites .
    
    FIND FIRST data_store WHERE name = "ActSum_BiReads" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_BiReads .
    
    FIND FIRST data_store WHERE name = "ActSum_BiWrites" EXCLUSIVE-LOCK NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_BiWrites .
    
    FIND FIRST data_store WHERE name = "ActSum_Commits" EXCLUSIVE-LOCK NO-ERROR.  
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_Commits .
    
    FIND FIRST data_store WHERE name = "ActSum_DbAccesses" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_DbAccesses .
    
    FIND FIRST data_store WHERE name = "ActSum_DbExtend" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_DbExtend .
    
    FIND FIRST data_store WHERE name = "ActSum_DbReads" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_DbReads .
    
    FIND FIRST data_store WHERE name = "ActSum_DbWrites" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_DbWrites .
    
    FIND FIRST data_store WHERE name = "ActSum_Undos" EXCLUSIVE-LOCK NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_ActSum.ActSum_Undos .
    
END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-add-tablestat.p
**
** Adds data from the archive Ar_TableStat table into the
** data_store temp table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index.   
 
llaubach 08/2006
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}.
{include/trendDBsingle-temptable.i "SHARED"}.
{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

ASSIGN
  pgm-name = "ar-report-add-tablestat.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_TableStat:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_TableStat NO-LOCK WHERE " +
                 "Ar_TableStat.TableStat_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_TableStat.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_TableStat.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_TableStat.TableStat_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_TableStat.TableStat_StartDate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_TableStat.TableStat_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_TableStat.TableStat_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = tablestat_Recordcount.
        WHEN "S" THEN fathom-store-value = tablestat_length.
        WHEN "M" THEN fathom-store-value = tablestat_length / 60.
        WHEN "H" THEN fathom-store-value = tablestat_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = tablestat_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    /* 
    ** Determine which date column the record falls into
    */
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_TableStat.TableStat_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_TableStat.TableStat_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_TableStat.TableStat_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_TableStat.TableStat_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    IF doCounters
     THEN ASSIGN
            fathom-rec-count = fathom-rec-count + Ar_TableStat.TableStat_RecordCount
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_TableStat.TableStat_Length
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_TableStat.TableStat_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

    FIND FIRST data_store WHERE name = "TableStat_Create" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_TableStat.TableStat_Create .                                      

    FIND FIRST data_store WHERE name = "TableStat_Delete" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_TableStat.TableStat_Delete .                                      

    FIND FIRST data_store WHERE name = "TableStat_Read" NO-LOCK NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_TableStat.TableStat_Read .                                        

    FIND FIRST data_store WHERE name = "TableStat_Table_ID" NO-LOCK NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_TableStat.TableStat_TableID .                                    

    FIND FIRST data_store WHERE name = "TableStat_Update" NO-LOCK NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + Ar_TableStat.TableStat_Update .                                      

END. /* of REPEAT. */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/*
** ar-report-dbai.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actlog-ai.p.
/*
** ar-report-dbbi.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actiofile.p.

doCounters = NO.

RUN archive/ar-report-add-actsum.p.
RUN archive/ar-report-add-actlog-bi.p.


/* ar-report-dbdet.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actapw.p.

doCounters = NO.

RUN archive/ar-report-add-actbuf.p.
RUN archive/ar-report-add-actidx.p.
RUN archive/ar-report-add-actiofile.p.
RUN archive/ar-report-add-actlock.p.
RUN archive/ar-report-add-actrec.p.
RUN archive/ar-report-add-actsum.p.
RUN archive/ar-report-add-tablestat.p.
RUN archive/ar-report-add-actlog-aibi.p.
RUN archive/ar-report-add-actiotype.p.
/*
** ar-report-dbdisk.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actapw.p.

doCounters = NO.

RUN archive/ar-report-add-actsum.p.
RUN archive/ar-report-add-actiotype.p.
/*
** ar-report-dblocks.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actlock.p.
/* ar-report-dbmem.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actbuf.p.

doCounters = NO.

RUN archive/ar-report-add-actlog-aibi.p.
/*
** ar-report-actrec.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actrec.p.
/*
** ar-report-dbsum.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

{include/definitions.i "SHARED"}.

doCounters = YES.

RUN archive/ar-report-add-actsum.p.

doCounters = NO.

RUN archive/ar-report-add-actapw.p.
RUN archive/ar-report-add-actiotype.p.
RUN archive/ar-report-add-actbuf.p.
RUN archive/ar-report-add-actlog-aibi.p. 
RUN archive/ar-report-add-actidx.p.
RUN archive/ar-report-add-actlock.p.
RUN archive/ar-report-add-actrec.p.
RUN archive/ar-report-add-tablestat.p.
/* ar-report-cpu.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - data_store temp-table defined as NO-UNDO
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - reorder QUERY-PREPARE to match the field order in an index.    
 
llaubach 08/2006
 - fixed the incorrect value of the "pgm-name" variable
 - fixed the incorrect syntax in the dynamic query (20060802-020)
*/

{include/definitions.i "SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD ResrcID AS INTEGER
   FIELD data AS decimal EXTENT 366
   FIELD txn AS decimal  EXTENT 366
   FIELD Sec AS decimal  EXTENT 366
   FIELD lable AS character 
   FIELD name2 AS character 
   FIELD file AS character 
   FIELD sort-order AS integer 
   INDEX one FILE 
   INDEX two TYPE 
   INDEX three NAME
   INDEX four sort-order
   INDEX five ResrcID.

ASSIGN
  pgm-name = "ar-report-cpu.p"
  sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}

{include/archive-type.i}.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
DEFINE VARIABLE qh                 AS WIDGET-HANDLE.
    
ASSIGN
  pgm-name = "ar-report-add-syscpu.p"
  sec-name = "Running procedure add-syscpu".
{include/debug.i "pgm-name" "sec-name"}.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER Ar_CPU:HANDLE).
qh:QUERY-PREPARE("FOR EACH Ar_CPU NO-LOCK WHERE " +
                 "Ar_CPU.CPU_ArchiveType EQ """ + archiveType + """ AND " +
                 "Ar_CPU.Site_ID EQ """ + Fathom-i-site_ID + """ AND " +
                 "Ar_CPU.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                 "Ar_CPU.CPU_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                 "Ar_CPU.CPU_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                 "Ar_CPU.CPU_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                 "Ar_CPU.CPU_StartTime LE " + STRING(Fathom-i-End_time)).
qh:QUERY-OPEN().

REPEAT:
    qh:GET-NEXT.
    IF qh:QUERY-OFF-END THEN LEAVE.

    /*
    ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
    */
    CASE Fathom-i-intervaltype:
        WHEN "R" THEN fathom-store-value = cpu_Recordcount.
        WHEN "S" THEN fathom-store-value = cpu_length.
        WHEN "M" THEN fathom-store-value = cpu_length / 60.
        WHEN "H" THEN fathom-store-value = cpu_length / 60 / 60.
        WHEN "T" THEN fathom-store-value = cpu_transactions.
        OTHERWISE fathom-store-value = 1.
    END CASE.

    /* 
    ** Determine which date column the record falls into
    */
    
    ASSIGN
      Fathom-ar-count[1] = Fathom-ar-count[1] + 1
      Fathom-i = 0.

    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Ar_CPU.CPU_startdate GE Fathom-t-beg-date[Fathom-i] AND
            Ar_CPU.CPU_startdate LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Ar_CPU.CPU_starttime GE Fathom-t-beg-time[Fathom-i] AND
                Ar_CPU.CPU_starttime LE Fathom-t-end-time[Fathom-i] THEN
                LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    ASSIGN
      fathom-rec-count = fathom-rec-count + ar_cpu.cpu_RecordCount
      Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + ar_cpu.cpu_Length
      Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + ar_cpu.cpu_RecordCount
      Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1
      Fathom-numsamples[Fathom-i] = Fathom-numsamples[Fathom-i] + 1.

    /*
    ** Process each field that is on the report
    */

    FIND FIRST data_store WHERE name = "CPU_System" EXCLUSIVE-LOCK NO-ERROR.                                             
    if available data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + (ar_CPU.CPU_System * ar_cpu.cpu_Length).

    FIND FIRST data_store WHERE name = "CPU_Usr" EXCLUSIVE-LOCK NO-ERROR.                                                
    if available data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + (ar_CPU.CPU_Usr * ar_cpu.cpu_Length).

    FIND FIRST data_store WHERE name = "CPU_Wait" EXCLUSIVE-LOCK NO-ERROR.                                               
    if available data_store THEN data_store.data[Fathom-i] = 
        data_store.data[Fathom-i] + (ar_CPU.CPU_Wait * ar_cpu.cpu_Length).

END. /* of for each procedure */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/* ar-report-sysmem.p
**
** This include will add data to the appropriate temp table based on date information.
** The query will select daily sample records for dates that don't exist in the sample
** data.  It will then add the data to the data_store table.
*/

/*
llaubach 10/2005
 - added NO-LOCK to QUERY-PREPARE
 - data_store temp-table defined as NO-UNDO
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - removed unneccessary THEN DO: END. blocks
 - reorder QUERY-PREPARE to match the field order in an index.    
*/

{include/definitions.i "SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name          AS CHARACTER
    FIELD Type          AS CHARACTER
    FIELD physicalavg   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicalmax   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicalused  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicaltotal AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualavg    AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualmax    AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualused   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualtotal  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD pagein        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD pageout       AS DECIMAL EXTENT 366 INITIAL 0
    FIELD cnt           AS DECIMAL EXTENT 366 INITIAL 0
    INDEX three NAME.

DEFINE VARIABLE physicalused AS DECIMAL INITIAL 0 NO-UNDO.
DEFINE VARIABLE virtualused  AS DECIMAL INITIAL 0 NO-UNDO.

ASSIGN
 pgm-name = "ar-report-sysmem.p"
 sec-name = "Start Archive Processing to find records".
{include/debug.i "pgm-name" "sec-name"}.

{include/archive-type.i}.

DEFINE VARIABLE qh                 AS WIDGET-HANDLE.

FOR EACH tmp-resrc:

    FIND FIRST data_store WHERE data_store.name = tmp-resrc.tResrcName NO-LOCK NO-ERROR.
    
    IF NOT AVAILABLE data_store THEN
    DO:
        CREATE data_store.
        data_store.name = tResrcName.
    END.

    ASSIGN
      pgm-name = "ar-report-add-actsum.p"
      sec-name = "Running procedure add-actsum".
    {include/debug.i "pgm-name" "sec-name"}.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_Mem:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_Mem NO-LOCK WHERE " +
                     "Ar_Mem.Mem_ArchiveType EQ ~"" + archiveType + " AND " +
                     "Ar_Mem.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_Mem.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_Mem.Mem_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_Mem.Mem_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_Mem.Mem_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_Mem.Mem_StartTime LE " + STRING(Fathom-i-End_time) + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.
    
        /* 
        ** Determine which date column the record falls into
        */

        ASSIGN
          Fathom-ar-count[1] = Fathom-ar-count[1] + 1
          Fathom-i = 0.
    
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_Mem.Mem_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_Mem.Mem_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
                IF Ar_Mem.Mem_starttime GE Fathom-t-beg-time[Fathom-i] AND
                   Ar_Mem.Mem_starttime LE Fathom-t-end-time[Fathom-i] THEN
                   LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.
    
        ASSIGN
          fathom-rec-count = fathom-rec-count + Ar_Mem.Mem_RecordCount
          Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_Mem.Mem_Length
          Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_Mem.Mem_Transactions
          Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + Ar_Mem.Mem_RecordCount
          physicalused = Ar_Mem.Mem_SysTot - Ar_Mem.Mem_SysFree
          virtualused  = Ar_Mem.Mem_VirtTot - Ar_Mem.Mem_VirtFree
          data_store.physicalavg[Fathom-i]   = data_store.physicalavg[Fathom-i] + physicalused
          data_store.physicalused[Fathom-i]  = data_store.physicalused[Fathom-i] + physicalused
          data_store.physicaltotal[Fathom-i] = data_store.physicaltotal[Fathom-i] + Ar_Mem.Mem_SysTot
          data_store.virtualavg[Fathom-i]    = data_store.virtualavg[Fathom-i] + virtualused
          data_store.virtualused[Fathom-i]   = data_store.virtualused[Fathom-i] + virtualused
          data_store.virtualtotal[Fathom-i]  = data_store.virtualtotal[Fathom-i] + Ar_Mem.Mem_VirtTot
          data_store.pagein[Fathom-i]        = data_store.pagein[Fathom-i] + Ar_Mem.Mem_PgIn
          data_store.pageout[Fathom-i]       = data_store.pageout[Fathom-i] + Ar_Mem.Mem_PgOut
          data_store.cnt[Fathom-i]           = data_store.cnt[Fathom-i] + 1.
        
        /* NOTE: No maximums in the archived data. */
        /* Physical Maximum Used. */
        IF data_store.physicalmax[Fathom-i] LT 1 THEN data_store.physicalmax[Fathom-i] = -1.

        /* Virtual Maximum Used. */
        IF data_store.virtualmax[Fathom-i] LT 1 THEN data_store.virtualmax[Fathom-i] = -1.

    END. /* of for each procedure */

END. /* FOR EACH tmp-resrc: */

qh:QUERY-CLOSE().
DELETE OBJECT qh.
/* 
** ar_tablestat.p
**
** This include will archive the ar_tablestat rows that are designated "H" to Day and Weekly.
**
*/

/*
llaubach 10/2005
 - tt-ar-tablestat temp-table now defined with NO-UNDO
 - defined an index on tt-ar-tablestat table to match WHERE clause
 - added NO-LOCK to FOR EACH Ar_TableStat WHERE phrase
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
 - replace FIND FIRST's with FOR FIRST ... END. in order to support index bracketing
 - moved DO TRANSACTION blocks into FOR EACH to reduce the size of the scope
*/

{include/ar-definitions.i}.
DEFINE TEMP-TABLE tt-ar-tablestat NO-UNDO LIKE ar_tablestat
    INDEX myindex1 site_id resrc_id tablestat_archivetype tablestat_tableid tablestat_startdate.

/* CREATE THE HOURLY RECORDS */
RUN archive/ar-h-tablestat.p.

/* SELECT THE APPROPRIATE HOURLY RECORDS THAT SHOULD HAVE ALREADY BEEN WRITTEN TO DISK */
FOR EACH Ar_tablestat
    WHERE Ar_tablestat.tablestat_ArchiveType = "H"
      AND Ar_tablestat.tablestat_StartDate LT Fathom-i-Date NO-LOCK:
    
    /* PROCESS DAILY RECORDS */
    FOR FIRST tt-ar-tablestat
        WHERE tt-ar-tablestat.Site_Id = ar_tablestat.site_id
          AND tt-ar-tablestat.Resrc_Id = ar_tablestat.Resrc_id
          AND tt-ar-tablestat.tablestat_archiveType = "D"
          AND tt-ar-tablestat.tablestat_tableid = ar_tablestat.tablestat_tableid
          AND tt-ar-tablestat.tablestat_startDate = ar_tablestat.tablestat_startdate:
        RUN add-tablestat.
    END.
    
    IF NOT AVAILABLE tt-ar-tablestat
     THEN DO: 
          RUN create-record.
          ASSIGN
            tt-ar-tablestat.tablestat_StartDate = Ar_tablestat.tablestat_StartDate
            tt-ar-tablestat.tablestat_EndDate = Ar_tablestat.tablestat_EndDate
            tt-ar-tablestat.tablestat_archiveType = "D".
     END.
    RELEASE tt-ar-tablestat.
        
    /* PROCESS WEEKLY RECORDS */
    FOR FIRST tt-ar-tablestat
        WHERE tt-ar-tablestat.Site_Id = ar_tablestat.site_id
          AND tt-ar-tablestat.Resrc_Id = ar_tablestat.Resrc_id
          AND tt-ar-tablestat.tablestat_archiveType = "W"
          AND tt-ar-tablestat.tablestat_tableid = ar_tablestat.tablestat_tableid
          AND ar_tablestat.tablestat_startdate GE tt-ar-tablestat.tablestat_startDate
          AND ar_tablestat.tablestat_startdate LE tt-ar-tablestat.tablestat_enddate:
        RUN add-tablestat.
    END.
    
    IF NOT AVAILABLE tt-ar-tablestat
     THEN DO:
          RUN create-record.
          ASSIGN
            tt-ar-tablestat.tablestat_StartDate = Ar_tablestat.tablestat_StartDate - (WEEKDAY(Ar_tablestat.tablestat_StartDate) - 1)
            tt-ar-tablestat.tablestat_EndDate = tt-ar-tablestat.tablestat_StartDate + 6
            tt-ar-tablestat.tablestat_archiveType = "W".
     END.
    RELEASE tt-ar-tablestat.
END. /*  Of for each Ar_tablestat */

/* This will write out the temp tables to the appropriate files. */

    sec-name = "Begin writing Data to disk ".
    {include/ar-debug.i "sec-name"}

    /* Write out ar-tablestat */
    FOR EACH tt-ar-tablestat
        WHERE tt-ar-tablestat.tablestat_archiveType = "D":
        FOR FIRST ar_tablestat
            WHERE Ar_Tablestat.tablestat_archiveType = "D" 
              AND tt-ar-tablestat.Site_Id = ar_tablestat.site_id 
              AND tt-ar-tablestat.Resrc_Id = ar_tablestat.Resrc_id
              AND tt-ar-tablestat.tablestat_tableid = ar_tablestat.tablestat_tableid
              AND tt-ar-tablestat.tablestat_startDate = ar_tablestat.tablestat_startdate NO-LOCK: END.
         
        IF NOT AVAILABLE ar_tablestat
         THEN DO TRANSACTION:
                 CREATE Ar_tablestat.
                 BUFFER-COPY tt-ar-tablestat TO Ar_tablestat.
                 RELEASE Ar_tablestat.
          END.
    END.
        
    /* Write out ar-tablestat */
    FOR EACH tt-ar-tablestat
        WHERE tt-ar-tablestat.tablestat_archiveType = "W":
        FOR FIRST ar_tablestat
            WHERE Ar_Tablestat.tablestat_archiveType = "W"
            AND tt-ar-tablestat.Site_Id = ar_tablestat.site_id
            AND tt-ar-tablestat.Resrc_Id = ar_tablestat.Resrc_id
            AND tt-ar-tablestat.tablestat_tableid = ar_tablestat.tablestat_tableid
            AND ar_tablestat.tablestat_startdate GE tt-ar-tablestat.tablestat_startDate
            AND ar_tablestat.tablestat_startdate LE tt-ar-tablestat.tablestat_enddate NO-LOCK: END.
         
        IF NOT AVAILABLE ar_tablestat
         THEN DO TRANSACTION:
                 CREATE Ar_tablestat.
                 BUFFER-COPY tt-ar-tablestat TO Ar_tablestat.
                 RELEASE Ar_tablestat.
         END.
    END.

    sec-name = "Ending Writing Data to disk".
    {include/ar-debug.i "sec-name"}

/* This procedure will create the initial records to be populated. */
PROCEDURE create-record.
    CREATE tt-ar-tablestat.
    BUFFER-COPY ar_tablestat TO tt-ar-tablestat.
    ASSIGN
      tt-ar-tablestat.sample_id = NEXT-VALUE(ar_sample-seq)
      tt-ar-tablestat.tablestat_EndTime = {&DAY_END_TIME}
      tt-ar-tablestat.tablestat_StartTime = 0.
END PROCEDURE.

/* This procedure will add to an existing record */
PROCEDURE add-tablestat.
    ASSIGN 
       tt-ar-TableStat.TableStat_RecordCount  = tt-ar-TableStat.TableStat_RecordCount + Ar_TableStat.TableStat_RecordCount 
       tt-ar-TableStat.TableStat_transactions = tt-ar-TableStat.TableStat_transactions + Ar_TableStat.TableStat_transactions 
       tt-ar-TableStat.TableStat_Length       = tt-ar-TableStat.TableStat_Length + Ar_TableStat.TableStat_Length 
       tt-ar-TableStat.TableStat_Create       = tt-ar-TableStat.TableStat_Create + Ar_TableStat.TableStat_Create
       tt-ar-TableStat.TableStat_Delete       = tt-ar-TableStat.TableStat_Delete + Ar_TableStat.TableStat_Delete
       tt-ar-TableStat.TableStat_Read         = tt-ar-TableStat.TableStat_Read   + Ar_TableStat.TableStat_Read
       tt-ar-TableStat.TableStat_TableID      = Ar_TableStat.TableStat_TableID
       tt-ar-TableStat.TableStat_TableName    = Ar_TableStat.TableStat_TableName
       tt-ar-TableStat.TableStat_Update       = tt-ar-TableStat.TableStat_Update + Ar_TableStat.TableStat_Update.
END PROCEDURE. 
/*
** ar-lock.p
**
** This program will lock compaction so that another process cannot run
** compaction at the same time.
*/

FIND FIRST Cf_Control where ID = "Lock_Compact" EXCLUSIVE-LOCK NO-ERROR.
IF AVAILABLE Cf_Control THEN
DO:
    DELETE Cf_Control.
    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Archiving unlocked." SKIP.
END.
ELSE
DO:
    PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Archiving Not Locked - It should be..." SKIP.
    QUIT.
END.
/*
** compact_fix_30a.p
**
** This program will fix any issues found in 21a archiving.
** It will run only once on any given database, putting a
** control record in the database to prevent subsequent
** processing.
**
** This program runs when archiving is run.
*/

{include/ar-definitions.i}.

/*
llaubach 10/2005
- all variables define as NO-UNDO
*/

/*
** Add the Cf_Control record in with working status.
** This will be updated when the processing is complete.
*/
FIND FIRST Cf_Control WHERE ID = "compact_fix_30a" AND c1 NE "working" NO-LOCK NO-ERROR.
IF NOT AVAILABLE Cf_Control THEN
DO ON ERROR UNDO, RETURN ERROR "ERROR adding Cf_Control record with ID compact_fix_30a.":
   PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Starting Compaction Fix Program Version 3.0a".
   PUT SKIP "                  This is a one time program to validate Daily and Weekly Records.".
   PUT SKIP "                  This message will appear only once.".
   CREATE Cf_Control.
   ASSIGN ID = "compact_fix_30a"
          c1 = "working"
          c2 = STRING( TIME, "HH:MM:SS" ).
   RELEASE Cf_Control.
END.
ELSE RETURN.


/*
** This fix is for a problem with the weekly record calculation in 2.1a.
** The archiving process is supposed to end on a Saturday so that weekly
** records will be full (Sunday-Saturday).  Due to the miscalculation,
** there could be weekly records that did not use all the hourly records
** available when it was created.
**
** Delete the weekly records here.  Most will be recreated in each archive
** program.  Some archive programs use a different algorithm to replace
** them, so we need to force those archive programs to recreate them.
** 
** We will also delete all daily records for a fix to compact_sub_fix.p.
** This program ran correctly in 2.0, but then broke in 2.1.  Thus, we
** need to recreate these records, and it's easiest to do it inside this
** loop.
**
** See 2003 09 24-007.
** See 2004 03 16-011.
*/
DEFINE VARIABLE queryHandle  AS WIDGET-HANDLE.
DEFINE VARIABLE bufferHandle AS WIDGET-HANDLE.
DEFINE VARIABLE i AS INTEGER INITIAL 0 NO-UNDO.
DEFINE VARIABLE j AS INTEGER INITIAL 0 NO-UNDO.
DEFINE VARIABLE tableName AS CHARACTER NO-UNDO.
CREATE QUERY queryHandle.


FOR EACH _field WHERE _field-name MATCHES "*ArchiveType":

    FIND FIRST _file WHERE _field._file-recid = RECID(_file) NO-ERROR.

    IF AVAILABLE _file THEN
    DO:
        CREATE BUFFER bufferHandle FOR TABLE _file._file-name.
        queryHandle:SET-BUFFERS(bufferHandle).

        queryHandle:QUERY-PREPARE("FOR EACH " + _file._file-name + " WHERE (" +
                                  _field-name + " EQ ~"W~" OR " +
                                  _field-name + " EQ ~"D~") EXCLUSIVE-LOCK").
        queryHandle:QUERY-OPEN().
    
        deleteLoop:
        REPEAT:
            /*
            ** The tranaction and do loops here are for performance.
            ** We will process do loop records before any I/O occurs.
            */
            DO TRANSACTION:
                DO i = 1 TO 100:
                    queryHandle:GET-NEXT().
                    IF queryHandle:QUERY-OFF-END THEN LEAVE deleteLoop.
            
                    bufferHandle = queryHandle:GET-BUFFER-HANDLE().
    
                    IF bufferHandle:CAN-DELETE THEN
                    DO:
                        tableName = bufferHandle:NAME.
                        bufferHandle:BUFFER-DELETE() NO-ERROR.
    
                        IF ERROR-STATUS:ERROR THEN
                        DO:
                            sec-name = "ERROR: Deleting weekly records in compact_fix_30a for table " +
                                tableName + " failed.  Messages follow:".
                            {include/ar-debug.i "sec-name"}.
    
                            DO j = 1 TO ERROR-STATUS:NUM-MESSAGES:
                                sec-name = STRING(ERROR-STATUS:GET-NUMBER(j)).
                                {include/ar-debug.i "sec-name"}.
                                sec-name = ERROR-STATUS:GET-MESSAGE(j).
                                {include/ar-debug.i "sec-name"}.
                            END.
                        END.
    
                    END. /* IF bufferHandle:CAN-DELETE */
    
                END. /* DO i = 1 TO 100 */
    
            END. /* DO TRANSACTION */
    
        END. /* REPEAT */

    END. /* IF AVAILABLE _file */

    queryHandle:QUERY-CLOSE().

END. /* FOR EACH _field */

DELETE OBJECT bufferHandle.
DELETE OBJECT queryHandle.

/*
** All weekly records should be gone, now.  Some archive programs
** need a temp table populated to recreate the weekly records.
** Populate the temp table and call the necessary programs.
*/
doHourlyRecords = NO.

EMPTY TEMP-TABLE hour-table.
FOR EACH Ar_OE_ActASProc WHERE
    Ar_OE_ActASProc.ActASProc_ArchiveType EQ "H" NO-LOCK:
	CREATE hour-table.
	hour-rowid = ROWID(Ar_OE_ActASProc).
	RELEASE Ar_OE_ActASProc.
	RELEASE hour-table.
END.
RUN archive/ar-oe_actasproc.p.

EMPTY TEMP-TABLE hour-table.
FOR EACH Ar_OE_ActWSProc WHERE
    Ar_OE_ActWSProc.ActWSProc_ArchiveType EQ "H" NO-LOCK:
	CREATE hour-table.
	hour-rowid = ROWID(Ar_OE_ActWSProc).
	RELEASE Ar_OE_ActWSProc.
	RELEASE hour-table.
END.
RUN archive/ar-oe_actwsproc.p.

EMPTY TEMP-TABLE hour-table.
FOR EACH Ar_OE_ActServ WHERE
    Ar_OE_ActServ.ActServ_ArchiveType EQ "H" NO-LOCK:
	CREATE hour-table.
	hour-rowid = ROWID(Ar_OE_ActServ).
	RELEASE Ar_OE_ActServ.
	RELEASE hour-table.
END.
RUN archive/ar-oe_actsrv.p.

EMPTY TEMP-TABLE hour-table.
FOR EACH Ar_OE_ActBrk WHERE
    Ar_OE_ActBrk.ActBrk_ArchiveType EQ "H" NO-LOCK:
	CREATE hour-table.
	hour-rowid = ROWID(Ar_OE_ActBrk).
	RELEASE Ar_OE_ActBrk.
	RELEASE hour-table.
END.
RUN archive/ar-oe_actbrk.p.

EMPTY TEMP-TABLE hour-table.
FOR EACH Ar_Process WHERE
    Ar_Process.Process_ArchiveType EQ "H" NO-LOCK:
	CREATE hour-table.
	hour-rowid = ROWID(Ar_Process).
	RELEASE Ar_Process.
	RELEASE hour-table.
END.
RUN archive/ar-process.p.


EMPTY TEMP-TABLE hour-table.
doHourlyRecords = YES.

/*
** End of fix for 2003 09 24-007, 2004 03 16-011.
*/



/*
** This fix is to change the seconds of the archive records.
** The seconds of the day go from 0-86399, and we have 0-86400.
** The hourly records need to be 0-3599, 3600-7199, etc.
** Currently, we have 0-3600, 3601-7200, etc.
**
** See 2004 03 16-004.
*/
DEFINE VARIABLE hourQueryHandle  AS WIDGET-HANDLE.
DEFINE VARIABLE hourBufferHandle AS WIDGET-HANDLE.
DEFINE VARIABLE fieldHandle      AS WIDGET-HANDLE.
CREATE QUERY hourQueryHandle.

FOR EACH _field WHERE _field-name MATCHES "*ArchiveType":

    FIND FIRST _file WHERE _field._file-recid = RECID(_file) NO-ERROR.

    IF AVAILABLE _file THEN
    DO:
        CREATE BUFFER hourBufferHandle FOR TABLE _file._file-name.
        hourQueryHandle:SET-BUFFERS(hourBufferHandle).

        hourQueryHandle:QUERY-PREPARE("FOR EACH " + _file._file-name + " WHERE " +
                                      _field-name + " EQ ~"H~" EXCLUSIVE-LOCK").
        hourQueryHandle:QUERY-OPEN().
    
        hourLoop:
        REPEAT:
            /*
            ** The tranaction and do loops here are for performance.
            ** We will process do loop records before any I/O occurs.
            */
            DO TRANSACTION:
                DO i = 1 TO 100:
                    hourQueryHandle:GET-NEXT().
                    IF hourQueryHandle:QUERY-OFF-END THEN LEAVE hourLoop.
            
                    hourBufferHandle = hourQueryHandle:GET-BUFFER-HANDLE().
    
                    REPEAT j = 1 TO hourBufferHandle:NUM-FIELDS:
                        fieldHandle = hourBufferHandle:BUFFER-FIELD(j).
                        IF fieldHandle:NAME MATCHES "*_StartTime" AND
                            fieldHandle:BUFFER-VALUE NE 0 AND
                            (fieldHandle:BUFFER-VALUE MOD 10) NE 0 THEN
                        DO:
                            ASSIGN fieldHandle:BUFFER-VALUE = fieldHandle:BUFFER-VALUE - 1.
                        END.

                        IF fieldHandle:NAME MATCHES "*_EndTime" AND
                            (fieldHandle:BUFFER-VALUE MOD 10) = 0 THEN
                        DO:
                            ASSIGN fieldHandle:BUFFER-VALUE = fieldHandle:BUFFER-VALUE - 1.
                        END.
    
                    END. /* REPEAT j = 1 TO hourBufferHandle:NUM-FIELDS */
    
                END. /* DO i = 1 TO 100 */
    
            END. /* DO TRANSACTION */
    
        END. /* REPEAT */

    END. /* IF AVAILABLE _file */

    hourQueryHandle:QUERY-CLOSE().

END. /* FOR EACH _field */

DELETE OBJECT hourBufferHandle.
DELETE OBJECT hourQueryHandle.

/*
** End of fix for 2004 03 16-004.
*/



/*
** Processing complete, finish the Cf_Control record update.
*/
DO TRANSACTION:
    FIND FIRST Cf_Control WHERE ID = "compact_fix_30a" AND c1 EQ "working" EXCLUSIVE-LOCK NO-ERROR.
    IF AVAILABLE Cf_Control THEN
    DO ON ERROR UNDO, RETURN ERROR "ERROR updating Cf_Control record with ID compact_fix_30a.":
       PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Finishing Compaction Fix Program Version 3.0a".
       PUT SKIP "                  Updating Cf_Control record to reflect completed status.".
       ASSIGN c1 = STRING( TODAY ).
       RELEASE Cf_Control.
    END.
    ELSE RETURN.
END.
/* 
** archive/purge-data.p
**
** This program will purge all of the data for the tables.
*/

{include/ar-definitions.i}

DEF VAR Fathom-purgecntr AS INTEGER NO-UNDO.

Find first w-table NO-LOCK NO-ERROR.

repeat-section:
Repeat:
   DO TRANSACTION :
      DO fathom-purgecntr = 1 to 500:
         IF AVAILABLE w-table THEN
         DO:
   
            FIND FIRST Cf_Sample where rowid(Cf_Sample) = w-rowid EXCLUSIVE-LOCK NO-ERROR.
            IF AVAILABLE Cf_Sample THEN
            DO:
               Delete Cf_Sample.
               recs-kept = recs-kept + 1.
            END.
         END. /* of if availabel cf_sample */
         ELSE LEAVE repeat-section.
         FIND NEXT w-table NO-LOCK NO-ERROR.
      END. /* OF Counter Loop */
   END. /* OF TRANSACTION LOOP */
END.

/* Program archivedetail.p
**
** This program will compress data based on the values you feed into the program.
** There are several values that the program accepts:
**        1 - Date to start compression on
**        2 - Resource Name to be compressed - if it is blank then all resources are done
**        3 - Type of compression (H = hourly, D = daily, W = weekly, R = Ratio)
** When the ratio is chosen there is a 4th parameter that is the ratio to compress
** to.
*/

/*
** Setup definitions
*/

/*
llaubach 10/25
 - all variables defined with NO-UNDO
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement 
*/

{include/ar-definitions.i}

/* 
** Local variables only available here
*/
DEFINE VARIABLE Fathom-SpecialProgram AS CHARACTER FORMAT "X(25)" NO-UNDO.
DEFINE VARIABLE xx AS CHARACTER FORMAT "X(25)" NO-UNDO.
DEFINE VARIABLE yy AS CHARACTER FORMAT "X(25)" NO-UNDO.

/*
** Debug code to start program
*/
sec-name = "Running Program".
{include/ar-debug.i "sec-name"}

/*
** Main processing
*/

/*
** Build the work table of samples to deal with
*/
Fathom-runpgm = "archive/ar-".

sec-name = "Starting Selection criteria".
{include/ar-debug.i "sec-name"}

/* 
** Select the sample records to be process and place them in the work table
** W-table
*/

{include/ar-select-criteria.i}

/*
** Parse through the schema tables and run the appropriate programs
*/

FOR EACH _File WHERE 
    _File-num GT 0 and _file-num LT 1024:
    IF _File-name BEGINS "Cf_" THEN NEXT.
    IF _File-name BEGINS "Ar_" THEN NEXT.
    IF _File-name BEGINS "Rp_" THEN NEXT.
    IF _File-name BEGINS "Cl_" THEN NEXT.
    IF _File-name BEGINS "OE_" THEN
    DO:
       xx = LOWER(_file-name).
    END.
    ELSE
    DO:
       xx = LOWER(ENTRY(2,_file-name,"_")).
    END.
   
    CASE xx:
        WHEN "idxanalysis" THEN xx = xx.
        WHEN "tabanalysis" THEN xx = xx.
        WHEN "data" THEN
        DO:
             xx = "net".
             fathom-specialprogram = "net".
             RUN run-pgm.
        END.
        OTHERWISE
        DO:
             RUN run-pgm.
        END.
    END CASE.
END.

/*
** Purge Sample Records Only
*/

IF Fathom-purgeflag = "TRUE" THEN
DO:
   RUN archive/purge-data.p.
END.

/*
** Purge historical information if the purge number is set.
*/
IF Fathom-purgenumber GT 0 THEN
DO:
    RUN delete-hist.p.
END.

/*
** Log information to the Fathom database log file 
*/

ASSIGN
 Fathom-t-msg1 = STRING (TODAY) + " " + STRING (TIME, "HH:MM:SS").
 Fathom-t-msg2 = STRING (TODAY) + " " + STRING (TIME, "HH:MM:SS") + " ".
 Fathom-t-msg2 = Fathom-t-msg2 + "New Archive Records: " + STRING (new-recs).
 Fathom-t-msg3 = STRING (TODAY) + " " + STRING (TIME, "HH:MM:SS") + "  " +
               "Data older than " + STRING (fathom-i-date) + " has been archived.".

IF Fathom-i-site-id NE "" THEN Fathom-t-msg2 = Fathom-t-msg2 + " Site ID: " + Fathom-i-site-id.

IF Fathom-purgenumber GT 0 THEN
DO:
    Fathom-t-msg4 = STRING (TODAY) + " " + STRING (TIME, "HH:MM:SS") + "  " +
                    "Historical data older than " + STRING (TODAY - Fathom-purgenumber) + " days has been deleted.".
END.

IF Fathom-i-ActionCode = "H" THEN
DO:
   {include/ar-log-msgs.i}
END.

/*
** Debug code to end program
*/
sec-name = "Exiting Program".
{include/ar-debug.i "sec-name"}

/*
** BEGIN PROCEDURES
*/

PROCEDURE run-pgm.
/* 
** This procedure will actually run the program to do the compression.
*/
   ASSIGN
    yy = fathom-runpgm + xx + ".r"
    xx = fathom-runpgm + xx + ".p".     

    if SEARCH(xx) NE ? THEN
    DO:
        RUN VALUE(xx).
        sec-name = "Completed Program : " + xx.
        {include/ar-debug.i "sec-name"}
    END.
    ELSE
    DO:
        if SEARCH(yy) NE ? THEN
        DO:
            RUN VALUE(yy).
            sec-name = "Completed Program : " + yy.
            {include/ar-debug.i "sec-name"}
        END.
        ELSE
        DO:
            sec-name = "Did not run program : " + xx + " or " + yy.
            {include/ar-debug.i "sec-name"}
            
        END.
    END.
    /*
    ** This resets the work tables for the next procedure
    */
    {include/ar-reset.i}

END PROCEDURE.

/* This program will drive the archive process.  It will fill in the blanks for the selections
** the user has chosen.  For example:  If the user has only chosen a resource type then this
** will set up a loop for all of the resources of that type and process them all accordingly.
**
** If the user has chosen a site and resource ID then we are all set.  All archiving will occur on a 
** Resource Level NO MATTER WHAT.  The UI may look different, but this will be true.
**
** The following values are parsed from the -param command line:
**
** 1 - Time to archive older than (used only for hourly).
** 2 - Date to archive older than (used for daily and weekly).
** 3 - Resource Type to archive
** 4 - Site ID to archive (If no site ID then all sites are done).
** 5 - Resource Name to Archive (If no resource name is provided then all resources for that site are done).
** 6 - Action Code to be performed - possible codes are (H)ourly, (D)aily, (W)eekly.
** 
*/

/* 
** Initialize definitions
*/

/*
llaubach 10/2005
 - t-site now defined with NO-UNDO and so does "j" variable
 - grouped multiple var1 = value. var2 = value into 1 ASSIGN statement
 
llaubach 03/2014
 - t-site.site_id is now being passed into FIND FIRST cf_Resc instead of cf_Site.site_id 
*/

{include/ar-setupdefs.i}.

DEF NEW SHARED TEMP-TABLE t-site NO-UNDO LIKE Cf_Site.
DEFINE VARIABLE j AS INTEGER INITIAL 0 NO-UNDO.

/*
** Locking the database 
*/

RUN archive/ar-lock.p.

FOR EACH Cf_Site:
   CREATE t-site.
   BUFFER-COPY Cf_Site TO t-site.
END.

debug-4gl = INTEGER (OS-GETENV("fathomDebug4gl")) no-error.
IF debug-4gl GT 0 THEN debug-4gl = 1.

/* 
** Parse the input passed in
*/

FOR EACH t-site:
    fathom-i-site-id = t-site.site_id.

    {include/ar-pass-input.i}

    sec-name = "archivedriver.p - t-site.site_id: " + t-site.site_id.
    {include/ar-debug.i "sec-name"}

    FIND FIRST CF_Resrc WHERE Cf_Resrc.Site_ID = t-site.Site_ID NO-LOCK NO-ERROR.
    IF AVAILABLE Cf_Resrc
    THEN DO: 

        ASSIGN
         Fathom-i-resrc-name = Cf_Resrc.Resrc_Name
         Fathom-i-resrc-ID = Cf_Resrc.Resrc_ID    
         Fathom-i-Resrc-type = Cf_Resrc.Resrc_Type.
   
        RUN archiverundetail.
    END. /* of IF */
END. /* of FOR EACH t-site */

/*
** Debug code to start program
*/
sec-name = "Completed running the compaction program! ".
{include/ar-debug.i "sec-name"}

RUN archive/ar-unlock.p.

QUIT.

/*
** Internal Procedures
*/

PROCEDURE archiverundetail.

    /* 
    ** This procedure determines how many times to run the archive process
    ** and with which action code to do it in.
    */

    Fathom-t-ActionCode = Fathom-i-ActionCode.

    IF Fathom-t-ActionCode NE "A" AND Fathom-t-ActionCode NE "" THEN
    DO:
        RUN archivedetail.p.
    END.
    ELSE
    DO:
        RUN archive/compact_fix_30a.p.

        IF ERROR-STATUS:ERROR THEN
        DO:
            sec-name = "ERROR in compact_fix_30a.p.  Messages follow:".
            {include/ar-debug.i "sec-name"}.

            DO j = 1 TO ERROR-STATUS:NUM-MESSAGES:
                sec-name = STRING(ERROR-STATUS:GET-NUMBER(j)).
                {include/ar-debug.i "sec-name"}.
                sec-name = ERROR-STATUS:GET-MESSAGE(j).
                {include/ar-debug.i "sec-name"}.
           END.
        END.

        PUT SKIP STRING (TODAY) " " STRING (TIME, "HH:MM:SS") " Running archive for all tables.".       

        Fathom-i-ActionCode = "H".
        RUN archivedetail.p.
        
    END.
END PROCEDURE.
 
/* Program ar-rundetail.i
**
** This program will drive the archive process and determine what archive type to run.
** 
** Possible archive types are : H- Hourly
**                              D- Daily
**                              W- Weekly
**                              A- All
**
** In the event that all is the option it will run the process 3 times changing the 
** Fathom-i-ActionCode appropriately for each run.
** 
*/

/*
** Main processing
**
** Start parsing the data and combining it based on compression type
**
*/
{ include/ar-definitions.i}

Fathom-t-ActionCode = Fathom-i-ActionCode.

CASE Fathom-t-ActionCode:
   WHEN "A" THEN
   DO:
       Fathom-i-ActionCode = "H".
       RUN archivedetail.p.
       Fathom-i-ActionCode = "D".
       RUN archivedetail.p.
       Fathom-i-ActionCode = "W".
       RUN archivedetail.p.
   END.
   OTHERWISE
   DO:
       RUN archivedetail.p.
   END.
END CASE
/*
** compactindex.p
**
** This program will run index compaction for the specific index passed
** in the Alert-Detail variable.
**
** The first field is always the Table Name.
** The second field is always the Index Name.
** The third field is always the Compaction Percentage.
**
*/
/* 
** llaubach 20140124
** - added extra logging of the full command line prior OS-COMMAND
** - removed NO-ERROR out of OS-COMMAND as it is not a valid syntax and on some *nixes it was corrupting the _dbutil line
*/

{include/dbstatus-definitions.i " "}
{include/alert-definitions.i "SHARED"}
    
sec-name = "Starting Program".
{include/ar-debug.i "sec-name"}

DEF VAR cmdline AS CHARACTER NO-UNDO.
DEF VAR cmd2line AS CHARACTER NO-UNDO INITIAL "1 -msg '".
DEF VAR progresscmd AS CHARACTER NO-UNDO.

/*
** Validate the environment
*/

progresscmd = OS-GETENV ("progressInstallDirShort").

IF progresscmd = "" OR progresscmd = ? THEN
DO:
    progresscmd = OS-GETENV ("DLC").
    IF progresscmd = "" OR progresscmd = ? THEN
    DO:
        PUT SKIP "ERROR - progressInstallDirShort environment variable not set!".
        LEAVE.
    END.
END.

/*
** Begin building the common command line
*/
                              
sec-name = "Building Command Line".
{include/ar-debug.i "sec-name"}

/*
** Build the Utility command
*/

cmdline = progresscmd + Fathom-t-separator + "bin" + Fathom-t-separator + "_proutil ".

sec-name = "generating utility command - details = " + alert-Detail.
{include/ar-debug.i "sec-name"}
/*
** Adding the Database Path
*/

IF Fathom-i-dbpath = "" or Fathom-i-dbpath = ? THEN
DO:
    PUT SKIP "ERROR - Database Path is not defined!".
    LEAVE.
END.
cmdline = cmdline + chr(34) + Fathom-i-dbpath + chr(34).

/*
** Adding the Arguement set (-C)
*/

cmdline = cmdline + " -C idxcompact ".

/*
** Adding the Table Name
*/

IF ENTRY (1, Alert-Detail) = "" or ENTRY (1, Alert-Detail) = ? THEN
DO:
    PUT SKIP "ERROR - Table Name is not defined!".
    LEAVE.
END.
cmdline = cmdline + TRIM ( ENTRY (1, Alert-Detail)) + ".".

/*
** Adding the Index Name
*/

IF ENTRY (2, Alert-Detail) = "" or ENTRY (2, Alert-Detail) = ? THEN
DO:
    PUT SKIP "ERROR - Index Name is not defined!".
    LEAVE.
END.
cmdline = cmdline + TRIM ( ENTRY (2, Alert-Detail)).

/*
** Adding the Compaction Percentage
*/

IF ENTRY (3, Alert-Detail) = "" or ENTRY (3, Alert-Detail) = ? THEN
DO:
    PUT SKIP "ERROR - Index Compaction Level is not defined!".
    LEAVE.
END.
cmdline = cmdline + " " + ENTRY (3, Alert-Detail).

/*
** Run the process
*/

sec-name = "Command Line : " + SUBSTRING (cmdline,1,212) .
{include/ar-debug.i "sec-name"}
sec-name = "Command Line 2 : " + SUBSTRING (cmdline,213) .
{include/ar-debug.i "sec-name"}
sec-name = "Full cmdline : " + cmdline.
{include/ar-debug.i "sec-name"}

    OS-COMMAND NO-CONSOLE VALUE (cmdline).

IF OS-ERROR NE 0 THEN
DO:
    sec-name = "Index compaction exit code : " + STRING (OS-ERROR).
    {include/ar-debug.i "sec-name"}
END.

/*
** Convenience procedure to compile outside the build.
** Comment out whatever is not needed.
**
** To run, connect to the trend database and prepend
** "<fathominstalldir>/src;" to propath.
**
** To add cross-reference file:
** COMPILE openedge/asprofile.p SAVE XREF asprofile.xrf.
** To add listing file:
** COMPILE openedge/asprofile.p SAVE LISTING asprofile.lst.
*/


/*DISPLAY PROPATH.*/


COMPILE trenddriver.p SAVE.


/*
** Alerts.
*/
COMPILE alertindividual.p SAVE.
COMPILE xml-alertindividual.p SAVE.
COMPILE alertgeneral.p SAVE.
COMPILE xml-alertgeneral.p SAVE.
COMPILE gen-alert.p SAVE.


/*
** Db.
*/
COMPILE dba-load.p SAVE.
COMPILE dbafterimage.p SAVE.
COMPILE dbareastatus.p SAVE.
COMPILE xml-dbareastatus.p SAVE.
COMPILE dbbeforeimage.p SAVE.
COMPILE dbcheckpoint.p SAVE.
COMPILE xml-dbcheckpoint.p SAVE.
COMPILE dbdisk.p SAVE.
COMPILE xml-dbdisk.p.
COMPILE dbindexstat.p SAVE.
COMPILE xml-dbindexstat.p SAVE.
COMPILE dbtablestat.p SAVE.
COMPILE xml-dbtablestat.p SAVE.
COMPILE dblocks.p SAVE.
COMPILE dbmemory.p SAVE.
COMPILE dbrecord.p SAVE.
COMPILE delete-hist.p SAVE.
COMPILE deletedata.p SAVE.
COMPILE xml-dbsingle.p SAVE.
COMPILE trendDBsingle.p SAVE.
COMPILE dbsummary.p SAVE.
COMPILE dbserver.p SAVE.
COMPILE xml-dbserver.p SAVE.
COMPILE compactindex.p SAVE.
COMPILE purgedb_indexstat.p SAVE.
COMPILE purgedb_tablestat.p SAVE.
COMPILE dbdetail.p SAVE.
COMPILE dbidxanalysis.p SAVE.
COMPILE xml-dbidxanalysis.p SAVE.
COMPILE dbtabanalysis.p SAVE.
COMPILE xml-dbtabanalysis.p SAVE.


/*
** Network.
*/
COMPILE network.p SAVE.
COMPILE xml-network.p SAVE.


/*
** System.
*/
COMPILE cpu_fix.p SAVE.
COMPILE systemdisk.p SAVE.
COMPILE xml-systemdisk.p SAVE.
COMPILE systemfilesize.p SAVE.
COMPILE xml-systemfilesize.p SAVE.
COMPILE systemfilesystem.p SAVE.
COMPILE xml-systemfilesystem.p SAVE.
COMPILE systemmemory.p SAVE.
COMPILE xml-systemmemory.p SAVE.
COMPILE systemcpu.p SAVE.


/*
** Misc.
*/
COMPILE 21asampledate.p SAVE.
COMPILE 21afix.p SAVE.
COMPILE statussummary.p SAVE.
COMPILE statusdetail.p SAVE.
COMPILE mig10_20a.p SAVE.
COMPILE orphan.p SAVE.
COMPILE customreport.p SAVE.



/*
** Compile open edge directory.
*/
COMPILE openedge/performance.p SAVE.
COMPILE openedge/brokeractivity.p SAVE.
COMPILE openedge/clientactivity.p SAVE.
COMPILE openedge/serveractivity.p SAVE.
COMPILE openedge/asprofile.p SAVE.
COMPILE openedge/xml-asprofile.p SAVE.
COMPILE openedge/wsprofile.p SAVE.
COMPILE openedge/xml-wsprofile.p SAVE.



/*
** Compile archive files.
*/
COMPILE archive/ar-oe_actasproc.p SAVE.
COMPILE archive/ar-h-oe_actasproc.p SAVE.
COMPILE archivedriver.p SAVE.
COMPILE archivedetail.p SAVE.
COMPILE archiverundetail.p SAVE.
COMPILE archive/compact_fix_30a.p SAVE.
COMPILE archive/ar-h-oe_appservice.p SAVE.
COMPILE archive/ar-oe_appservice.p SAVE.
COMPILE archive/ar-oe_actsrv.p SAVE.
COMPILE archive/ar-h-oe_actbrk.p SAVE.
COMPILE archive/ar-oe_actbrk.p SAVE.
COMPILE archive/ar-h-oe_actsrv.p SAVE.
COMPILE archive/ar-oe_actsrv.p SAVE.
COMPILE archive/ar-h-oe_actwsproc.p SAVE.
COMPILE archive/ar-oe_actwsproc.p SAVE.
COMPILE archive/ar-h-oe_actasproc.p SAVE.
COMPILE archive/ar-oe_actasproc.p SAVE.
COMPILE archive/ar-h-process.p SAVE.
COMPILE archive/ar-process.p SAVE.


/*
COMPILE archive/ar-h-oe_actbrk.p xref hactbrk.xrf.
COMPILE archive/ar-oe_actwsproc.p xref actwsproc.xrf.
COMPILE archive/ar-oe_actasproc.p xref actasproc.xrf.
COMPILE archive/ar-oe_actbrk.p xref actbrk.xrf.
COMPILE archive/ar-h-oe_actsrv.p xref hactsrv.xrf.
COMPILE archive/ar-oe_actsrv.p xref actsrv.xrf.
COMPILE archive/ar-h-oe_actwsproc.p xref hactwsproc.xrf.
COMPILE archive/ar-process.p xref process.xrf.
COMPILE archive/ar-h-oe_appservice.p xref happservice.xrf.
COMPILE archive/ar-oe_appservice.p xref appservice.xrf.
*/


COMPILE archive/ar-actapw.p SAVE.
COMPILE archive/ar-actbuf.p SAVE.
COMPILE archive/ar-actidx.p SAVE.
COMPILE archive/ar-actiofile.p SAVE.
COMPILE archive/ar-actiotype.p SAVE.
COMPILE archive/ar-actlock.p SAVE.
COMPILE archive/ar-actlog.p SAVE.
COMPILE archive/ar-actrec.p SAVE.
COMPILE archive/ar-actserv.p SAVE.
COMPILE archive/ar-actsum.p SAVE.
COMPILE archive/ar-areastatus.p SAVE.
COMPILE archive/ar-checkpoint.p SAVE.
COMPILE archive/ar-dev.p SAVE.
COMPILE archive/ar-filesize.p SAVE.
COMPILE archive/ar-filesys.p SAVE.
COMPILE archive/ar-h-actapw.p SAVE.
COMPILE archive/ar-h-actbuf.p SAVE.
COMPILE archive/ar-h-actidx.p SAVE.
COMPILE archive/ar-h-actiofile.p SAVE.
COMPILE archive/ar-h-actiotype.p SAVE.
COMPILE archive/ar-h-actlock.p SAVE.
COMPILE archive/ar-h-actlog.p SAVE.
COMPILE archive/ar-h-actrec.p SAVE.
COMPILE archive/ar-h-actserv.p SAVE.
COMPILE archive/ar-h-actsum.p SAVE.
COMPILE archive/ar-h-areastatus.p SAVE.
COMPILE archive/ar-h-dev.p SAVE.
COMPILE archive/ar-h-filesize.p SAVE.
COMPILE archive/ar-h-filesys.p SAVE.
COMPILE archive/ar-h-indexstat.p SAVE.
COMPILE archive/ar-h-mem.p SAVE.
COMPILE archive/ar-h-checkpoint.p SAVE.
COMPILE archive/ar-h-net.p SAVE.
COMPILE archive/ar-h-tablestat.p SAVE.
COMPILE archive/ar-indexstat.p SAVE.
COMPILE archive/ar-mem.p SAVE.
COMPILE archive/ar-net.p SAVE.
COMPILE archive/purge-data.p SAVE.
COMPILE archive/ar-h-cpu.p SAVE.
COMPILE archive/ar-cpu.p SAVE.
COMPILE archive/ar-lock.p SAVE.
COMPILE archive/ar-unlock.p SAVE.
COMPILE archive/ar-tablestat.p SAVE.



COMPILE archive/ar-report-dbai.p SAVE.
COMPILE archive/ar-report-dbbi.p SAVE.
COMPILE archive/ar-report-dbdet.p SAVE.
COMPILE archive/ar-report-dbdisk.p SAVE.
COMPILE archive/ar-report-dblocks.p SAVE.
COMPILE archive/ar-report-dbmem.p SAVE.
COMPILE archive/ar-report-dbrec.p SAVE.
COMPILE archive/ar-report-dbsum.p SAVE.
COMPILE archive/ar-report-syscpu.p SAVE.
COMPILE archive/ar-report-sysmem.p SAVE.
COMPILE archive/ar-report-add-actiofile.p SAVE.
COMPILE archive/ar-report-add-actsum.p SAVE.
COMPILE archive/ar-report-add-actlog-ai.p SAVE.
COMPILE archive/ar-report-add-actlog-bi.p SAVE.
COMPILE archive/ar-report-add-actlog-aibi.p SAVE.
COMPILE archive/ar-report-add-actapw.p SAVE.
COMPILE archive/ar-report-add-actbuf.p SAVE.
COMPILE archive/ar-report-add-actidx.p SAVE.
COMPILE archive/ar-report-add-actlock.p SAVE.
COMPILE archive/ar-report-add-actrec.p SAVE.
COMPILE archive/ar-report-add-tablestat.p SAVE.
COMPILE archive/ar-report-add-actiotype.p SAVE.


/*
COMPILE archive/ar-actapw.p XREF "report.xrf".
COMPILE archive/ar-actbuf.p XREF "report.xrf".
COMPILE archive/ar-actidx.p XREF "report.xrf".
COMPILE archive/ar-actiofile.p XREF "report.xrf".
COMPILE archive/ar-actiotype.p XREF "report.xrf".
COMPILE archive/ar-actlock.p XREF "report.xrf".
COMPILE archive/ar-actlog.p XREF "report.xrf".
COMPILE archive/ar-actrec.p XREF "report.xrf".
COMPILE archive/ar-actserv.p XREF "report.xrf".
COMPILE archive/ar-actsum.p XREF "report.xrf".
COMPILE archive/ar-areastatus.p XREF "report.xrf".
COMPILE archive/ar-checkpoint.p XREF "report.xrf".
COMPILE archive/ar-dev.p XREF "report.xrf".
COMPILE archive/ar-filesize.p XREF "report.xrf".
COMPILE archive/ar-filesys.p XREF "report.xrf".
COMPILE archive/ar-h-actapw.p XREF "report.xrf".
COMPILE archive/ar-h-actbuf.p XREF "report.xrf".
COMPILE archive/ar-h-actidx.p XREF "report.xrf".
COMPILE archive/ar-h-actiofile.p XREF "report.xrf".
COMPILE archive/ar-h-actiotype.p XREF "report.xrf".
COMPILE archive/ar-h-actlock.p XREF "report.xrf".
COMPILE archive/ar-h-actlog.p XREF "report.xrf".
COMPILE archive/ar-h-actrec.p XREF "report.xrf".
COMPILE archive/ar-h-actserv.p XREF "report.xrf".
COMPILE archive/ar-h-actsum.p XREF "report.xrf".
COMPILE archive/ar-h-areastatus.p XREF "report.xrf".
COMPILE archive/ar-h-dev.p XREF "report.xrf".
COMPILE archive/ar-h-filesize.p XREF "report.xrf".
COMPILE archive/ar-h-filesys.p XREF "report.xrf".
COMPILE archive/ar-h-indexstat.p XREF "report.xrf".
COMPILE archive/ar-h-mem.p XREF "report.xrf".
COMPILE archive/ar-h-checkpoint.p XREF "report.xrf".
COMPILE archive/ar-h-net.p XREF "report.xrf".
COMPILE archive/ar-h-tablestat.p XREF "report.xrf".
COMPILE archive/ar-indexstat.p XREF "report.xrf".
COMPILE archive/ar-mem.p XREF "report.xrf".
COMPILE archive/ar-net.p XREF "report.xrf".
*/

DISPLAY "done".

QUIT.
/*  updatecpu.p
**
** This program will update the CPU Idle table with the correct values.
*/

DEFINE VARIABLE qh1 AS WIDGET-HANDLE.

DEFINE VARIABLE i AS INTEGER NO-UNDO. 
DEFINE VARIABLE j AS INTEGER NO-UNDO.
DEFINE VARIABLE fathominstalldir AS CHARACTER.

fathominstalldir = OS-GETENV ("fathomInstallDir").

IF fathominstalldir = "" OR fathominstalldir = ? THEN
    PUT SKIP "ERROR - FathomInstallDir not set - can't complete resource migration" SKIP.

CREATE QUERY qh1.

qh1:SET-BUFFERS(BUFFER Sys_CPU:HANDLE).
    
qh1:QUERY-PREPARE("FOR EACH Sys_CPU exclusive-lock "). 
    
qh1:QUERY-OPEN().
    
FIND FIRST cf_control WHERE id = "version" NO-LOCK NO-ERROR.
IF AVAILABLE cf_control THEN
DO:
    PUT SKIP "Updating CPU Table - Control Table Entry Found! " SKIP.
    IF cf_control.c2 NE "Version" THEN
    DO:
        PUT SKIP "Updating CPU Table - CPU Table has already been upgraded! " SKIP.
        QUIT.
    END.
END.
PUT SKIP "Updating CPU Table - Preparing to update 100 records per transaction " SKIP.
REPEAT:
    DO TRANSACTION:
       DO i = 1 to 100:

           qh1:GET-NEXT.
    
           IF qh1:QUERY-OFF-END THEN LEAVE.
        
           Sys_CPU.CPU_Idle = 100 - Sys_CPU.CPU_Idle.

           RELEASE Sys_CPU. 
                    
       END.
    END.
    
/*     PUT SKIP "Updating CPU Table - Updated " (i - 1) " records! ".  */
    j = j + i - 1.
    IF qh1:QUERY-OFF-END THEN LEAVE.
END.

/* 
** Update the control table appropriately
*/

PUT SKIP "Updating CPU Table - Total Update Count : " j SKIP.

DO TRANSACTION:
    PUT SKIP "Updating CPU Table - Updating Control Table to show Patch 01 applied" SKIP.
    FIND FIRST Cf_Control WHERE ID = "version" NO-ERROR.
    IF AVAILABLE Cf_Control THEN C2 = "Patch 01".
END.

IF fathominstalldir NE "" AND fathominstalldir NE ? THEN
DO:
    fathominstalldir = fathominstalldir + "/src/orphan.p".
    RUN VALUE (fathominstalldir).
END.
QUIT.
/*
** customreport.p
** This program will test the custom report functionality.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

{include/definitions.i "SHARED"} /* Field definitions common across programs */

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Begin Main Processing
*/

pgm-name = "customreport.p".
sec-name = "Running this report".
{include/debug.i "pgm-name" "sec-name"}  /* Debugging output */

{include/trenddates.i}  /* Setting up Trend Date and time buckets for reporting */

{ include/report-name.i } /* Set up report directory and names */

/*OUTPUT STREAM ReportOutput TO VALUE(Fathom-t-rep_name) APPEND.

{include/report-header.i}  /* Insert standard report header information */
/* 
** Start outputting the detail information.
**
*/
    PUT STREAM ReportOutput SKIP(1).

    PUT STREAM ReportOutput SKIP "This is where the user-defined report goes! ".

    PUT STREAM ReportOutput SKIP(1) "PARAMETERS FED INTO CUSTOMREPORT.P".
    PUT STREAM ReportOutput SKIP  Fathom-i-rep_name FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  Fathom-i-resrc_name FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  Fathom-i-site_id FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  Fathom-i-rep_type FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  string(Fathom-t-Start_date) FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  string(Fathom-t-End_date) FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  string(Fathom-i-start_time) FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  string(Fathom-i-end_time) FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  string(Fathom-i-periods) FORMAT "x(64)".
    PUT STREAM ReportOutput SKIP  Fathom-i-filename FORMAT "x(64)".   
    PUT STREAM ReportOutput SKIP  Fathom-i-Title FORMAT "x(64)".   
    PUT STREAM ReportOutput SKIP(2).

OUTPUT STREAM ReportOutput CLOSE.*/

pgm-name = "customreport.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}  /* Debugging Output */

QUIT.
/* 
**  Dbanalysis_load.p
**
** This program will load a dbanalysis into the database.  If an input file
** is not provided it will try and find the database (if the name is provided) 
** and run the dbanalysis.
**
** The input parameters are:
**    1 - temp file name for dbanalysis
**    2 - Full path to the database
**    3 - Resrc Name
**    4 - Site ID
**    5 - Utilization Percentage (for Alert) (OPTIONAL)
**    6 - Number of Blocks (for Alert) (OPTIONAL)
**
*/
    
/*
**  Parameter definitions
*/
{include/dbstatus-definitions.i "NEW GLOBAL"}

{include/alert-definitions.i "NEW GLOBAL SHARED"}

PROPATH = os-getenv("fathomInstallDir") + "/src," + os-getenv("fathomInstallDir") + "," + PROPATH.

IF OS-GETENV("fathomDebug4gl") NE ? THEN debug-4gl = 1.

sec-name = "Begin Database Analysis Load Program".
{include/ar-debug.i "sec-name"}


DEF VAR input-params AS CHARACTER NO-UNDO.
DEF VAR Fathom-i-container-name AS CHARACTER NO-UNDO.

input-params = SESSION:PARAMETER.

/*
** Set the numeric decimal and separator to a common value so that the
** dbanalysis will work appropriately.
*/

SESSION:SET-NUMERIC-FORMAT(",", ".").

/*
** Parse the environment variables prior to looking at the command line
**
** These environment variables are up for discussion
**
**	DATABASENAME	The name of this database.
**	DATABASEBPATHNAME	Path name to the database.
**	DATABASECONFIG	As defined in the conmgr.properties.
**	DATABASEDISPLAY As defined in the conmgr.properties.
**	DATABASEPORT	The port where the database is currently running.
**	DATABASEHOST	The host machine where the db is running (i.e. localhost).
**	RESOURCEKEY  	The fully qualified Fathom resource identifier.
**	RESOURCENAME	The simple name of a Fathom resource.
**
*/

Fathom-i-tmpfile = OS-GETENV ("FM_DBATMPFILE") NO-ERROR.
Fathom-i-dbname = OS-GETENV ("RESRC_DBNAME") NO-ERROR.
Fathom-i-dbPath = OS-GETENV ("RESRC_DBPATH") NO-ERROR.
Fathom-i-container-name = OS-GETENV ("FM_CONTAINERNAME") NO-ERROR.
Fathom-i-resrc-name = OS-GETENV ("RESRC_NAME") NO-ERROR.
Fathom-i-site-ID = OS-GETENV ("FM_SITEID") NO-ERROR.
Fathom-i-Utilization = OS-GETENV ("FM_DBAUTILIZATIONNUMBER") NO-ERROR.
Fathom-i-blocks = OS-GETENV ("FM_DBABLOCKNUMBER") NO-ERROR.
Fathom-i-RunCompaction = OS-GETENV ("FM_DBAINDEXCOMPACTION") NO-ERROR.

/* 
** Parse the input parameters if the environment variables are not set.
*/

IF Fathom-i-tmpfile = ? THEN fathom-i-tmpfile = ENTRY(1, input-params) NO-ERROR.
IF Fathom-i-dbPath = ? THEN fathom-i-dbPath = ENTRY(2, input-params) NO-ERROR.
IF Fathom-i-resrc-name = ? THEN fathom-i-resrc-name = ENTRY(3, input-params) NO-ERROR.
IF Fathom-i-site-ID = ? THEN fathom-i-site-ID = ENTRY(4, input-params) NO-ERROR.
If Fathom-i-utilization = ? THEN fathom-i-utilization = ENTRY(5, input-params) NO-ERROR.
IF Fathom-i-blocks = ? THEN fathom-i-blocks = ENTRY(6, input-params) NO-ERROR.
IF Fathom-i-RunCompaction = ? THEN fathom-i-RunCompaction = ENTRY(7, input-params) NO-ERROR.

IF fathom-i-utilization NE "" THEN
DO:
    Fathom-t-utilization = DECIMAL (Fathom-i-utilization).
    Fathom-t-blocks = INTEGER (Fathom-i-blocks).
END.
ELSE
DO:
    Fathom-t-utilization = 0.
    Fathom-t-blocks = 0.
END.

/*
** Prepend the container name on the front of the resource name.
*/
Fathom-i-resrc-name = Fathom-i-container-name + "." + Fathom-i-resrc-name.

/*
** Set up the file separator for the appropriate file system
*/

IF OPSYS = "UNIX" THEN Fathom-t-separator = chr(47).
ELSE Fathom-t-separator = chr(92).

IF Fathom-i-tmpfile = "" OR Fathom-i-tmpfile = ? THEN
DO:
    IF Fathom-i-dbname = ? THEN
    DO:
        Fathom-i-dbname = SUBSTRING ( Fathom-i-dbpath, R-INDEX ( Fathom-i-dbpath, Fathom-t-separator) + 1 ).
    END.
    IF Fathom-i-dbname = "" OR Fathom-i-dbname = ? THEN
    DO:
        PUT SKIP "Environment variable RESRC_DBNAME was not set".
        PUT SKIP "Fathom cannot identify the database".
        PUT SKIP "Exiting database analysis".
        QUIT.
    END.
END.

sec-name = "Temp File : " + Fathom-i-tmpfile.
{include/ar-debug.i "sec-name"}
sec-name = "Database Name : " + Fathom-i-dbname.
{include/ar-debug.i "sec-name"}
sec-name = "Variable Database Path : " + Fathom-i-dbPath.
{include/ar-debug.i "sec-name"}
sec-name = "Variable Resource Name : " + Fathom-i-resrc-name.
{include/ar-debug.i "sec-name"}
sec-name = "Variable Site ID : " + Fathom-i-site-ID.
{include/ar-debug.i "sec-name"}
sec-name = "Variable Utilization : " + Fathom-i-Utilization.
{include/ar-debug.i "sec-name"}
sec-name = "Variable Blocks : " + Fathom-i-blocks.
{include/ar-debug.i "sec-name"}
sec-name = "Variable Run Compaction : " + Fathom-i-RunCompaction.
{include/ar-debug.i "sec-name"}

/*
** Process input values appropriate
*/

fathom-t-id = NEXT-VALUE(TAB_id_Sequence).

szTmpFile = fathom-i-tmpfile.

FIND FIRST cf_resrc WHERE cf_resrc.resrc_name = fathom-i-resrc-name AND
                          Cf_Resrc.Site_ID = fathom-i-site-ID NO-LOCK NO-ERROR.
IF AVAILABLE cf_resrc THEN
DO:
    fathom-i-resrc-id = cf_resrc.Resrc_ID.
END.
ELSE
DO:
    szTmpFile = 
        "Resource record for " + fathom-i-resrc-name + " and site " + Fathom-i-site-id + " was not found.".
    PUT SKIP.
    PUT UNFORMATTED szTmpFile.
    PUT SKIP "This is due to the resource not being trended or having a status change.".
    PUT SKIP "Exiting database analysis.".
    QUIT.
END.
RUN Get-input-data.

/*
**  Local variables
*/

DEFINE VARIABLE szType      AS CHARACTER                NO-UNDO.
DEFINE VARIABLE szInput     AS CHARACTER    EXTENT 9    NO-UNDO.
DEFINE VARIABLE szTableName AS CHARACTER FORMAT "X(30)" NO-UNDO.
DEFINE VARIABLE szAreaName  AS CHARACTER FORMAT "X(20)" NO-UNDO.


INPUT FROM VALUE(szTmpFile).
szType = "".

/* 
**
** START THE MAIN PROCESSING OF THE DBANALYSIS
**
*/

REPEAT:
    /*
    **  Read a line from file
    */

    szInput = "".
    IMPORT szInput.
    IF ReadAgain = 1 THEN 
    DO:
       ReadAgain = 0.
       szInput[9] = szInput[8].
       szInput[8] = szInput[7].
       szInput[7] = szInput[6].
       szInput[6] = szInput[5].
       szInput[5] = szInput[4].
       szInput[4] = szInput[3].
       szInput[3] = szInput[2].
       szInput[2] = szInput[1].
       szInput[1] = HoldTableName.
       HoldTableName = "".
    END.
    Fathom-t-ValidateFile = Fathom-t-ValidateFile + 1.
 
    If szInput[3] = "Analysis" THEN ValidFile = 1.
    
    IF Fathom-t-ValidateFile GT 10 THEN
    DO:
        If ValidFile = 0 THEN
        DO:
            PUT SKIP "Database analysis file is not a valid format!".
            PUT SKIP "Exiting database analysis".
            QUIT.
        END.
    END.
    ELSE
    DO:
         sec-name = "Validated file is correct.".
         {include/ar-debug.i "sec-name"}
    END.
               
    /*
    **  Skip empty lines
    */

    IF szInput[1] = "" THEN
    DO:
        szType = "".
        NEXT.
    END.

    IF  szInput[2] = "BLOCK"
         AND szInput[3] = "SUMMARY"
         AND szInput[5] = "SHARED" THEN 
	 DO:
             IF (szInput[1] = "RECORD" AND szInput[6] = "TABLES") THEN DO:
                 szType = "tabanalys".
                 IMPORT szInput.
                 IMPORT szInput.
                 IMPORT szInput.
                 IMPORT szInput.
	     END.
             ELSE IF (szInput[1] = "INDEX" AND szInput[6] = "OBJECTS:") THEN DO:
                 szType = "ixanalys".
                 NEXT.
	     END.
    END. 


    /*
    **  Check for header and set status
    */

    IF szInput[2] = "BLOCK"
        AND szInput[3] = "SUMMARY"
        AND szInput[5] = "AREA" THEN
    DO:

        szAreaName = szInput[6].

        CASE szInput[1]:
            WHEN "RECORD" THEN 
            DO:
                szType = "tabanalys".
                NEXT.
            END.

            WHEN "INDEX" THEN
            DO:
                szType = "ixanalys".
                NEXT.
            END.
        END CASE.
    END.

    if szInput[1] = "Date:" THEN
    DO:
        Fathom-t-time = INTEGER (SUBSTRING(szInput[5],1,2)) * 60 * 60 +
                        INTEGER (SUBSTRING(szInput[5],4,2)) * 60 +
                        INTEGER (SUBSTRING(szInput[5],7,2)).
        Case szInput[3]:
           WHEN "Jan" THEN Fathom-w-date = "01/".
           WHEN "Feb" THEN Fathom-w-date = "02/".
           WHEN "Mar" THEN Fathom-w-date = "03/".
           WHEN "Apr" THEN Fathom-w-date = "04/".
           WHEN "May" THEN Fathom-w-date = "05/".
           WHEN "Jun" THEN Fathom-w-date = "06/".
           WHEN "Jul" THEN Fathom-w-date = "07/".
           WHEN "Aug" THEN Fathom-w-date = "08/".
           WHEN "Sep" THEN Fathom-w-date = "09/".
           WHEN "Oct" THEN Fathom-w-date = "10/".
           WHEN "Nov" THEN Fathom-w-date = "11/".
           WHEN "Dec" THEN Fathom-w-date = "12/".
        END CASE. 
        Fathom-w-date = Fathom-w-date + szInput[4] + "/" + szInput[6].
        Fathom-t-date = DATE(Fathom-w-date).
        sec-name = "Date job run is:" + STRING (Fathom-t-date).
        {include/ar-debug.i "sec-name"}
    END.
    /*
    **  Loop until we have a status (szType is set)
    */

    IF szType = "" THEN NEXT.

    /*
    **  Record Block Summary header line
    */

    IF szType = "tabanalys" AND
       szInput[1] = "Table" AND
       szInput[2] = "Records" THEN
    DO:
        szType = szType + "-ready".
        sec-name = "Eliminating Record Block header".
        {include/ar-debug.i "sec-name"}
        NEXT.
    END.

    /*
    **  Index Block Summary line with tablename
    */

    IF szType = "ixanalys" AND
       szInput[2] = "Index" AND
       szInput[3] = "Fields" THEN
    DO:
        szType = szType + "-ready".
        sec-name = "Eliminating Index Block header".
        {include/ar-debug.i "sec-name"}
        NEXT.
    END.


    IF szType = "ixanalys-ready" THEN 
    DO: 
        If substring (szInput[1],1,1) = "_" THEN DO:
            szType = "".
	    ThreeLineIndex = 0.
            NEXT.
	END.
	ELSE
	DO:
            IF szInput[2] = "" THEN
	    DO:
	        ThreeLineIndex = ThreeLineIndex + 1.
		IF ThreeLineIndex = 1 THEN
		DO:
                    szTableName = szInput[1].
		    Fathom-indexline[1] = "".
		END.
		ELSE HoldIndexName = szInput[1].
	    END.
	    ELSE
	    DO:
                /*
                **  Create and load a DB_SAMPLE_IDX record
                */
	        IF ThreeLineIndex GT 1 OR szInput[8] = "" THEN
                DO:
                    szInput[9] = szInput[8].
                    szInput[8] = szInput[7].
                    szInput[7] = szInput[6].
                    szInput[6] = szInput[5].
                    szInput[5] = szInput[4].
                    szInput[4] = szInput[3].
                    szInput[3] = szInput[2].
                    szInput[2] = szInput[1].
                    szInput[1] = HoldIndexName.
                END.
		sec-name = "Line Written: ".
		DO Twolineindex = 1 to 9:
                    sec-name = sec-name + "szinput[" + 
		         String(twolineindex) +
		         "]=" +
			 szinput[twolineindex] + " ".
		END.
                {include/ar-debug.i "sec-name"}
                RUN create_idx.
	        ThreeLineIndex = 0.
	    END.
	END.
        NEXT.
    END.
    
    /*
    **  We do not want underscore table and index data
    */
    /*Rohit- Starting 11.0, all tables are prefixed with "PUB.", hence substring should start at 5 */
    IF szType = "tabanalys-ready"
        AND substring (szInput[1],5,1) = "_" THEN
        /* AND (szInput[1] = "_Db" OR szInput[1] = "_Area") THEN */
    DO:
        /*
        **  Skip database underscore files
        */
        szType = "".
        NEXT.
    END.

    /*
    **  Load the data
    */
    
    CASE szType:
        WHEN "tabanalys-ready" THEN
        DO:
            /*
            **  Create and load a DB_SAMPLE_TAB record
            */
            IF TRIM(szInput[2]) = "" THEN
            DO:
                HoldTableName = szInput[1].
                ReadAgain = 1.
            END.
            ELSE
            DO:
                szTableName = SUBSTRING(szInput[1],5).
                RUN create_tab.
            END.
        END.
        
        WHEN "ixanalys-ready" THEN
        DO:
            /*
            **  Create and load a DB_SAMPLE_IDX record
            */
	    IF ThreeLineIndex GE 1 THEN
            DO:
                szInput[9] = szInput[8].
                szInput[8] = szInput[7].
                szInput[7] = szInput[6].
                szInput[6] = szInput[5].
                szInput[5] = szInput[4].
                szInput[4] = szInput[3].
                szInput[3] = szInput[2].
                szInput[2] = szInput[1].
                szInput[1] = HoldIndexName.
            END.
	    IF SUBSTRING (szInput[1],1,1) NE "_" THEN
	    DO:
                RUN create_idx.
            END.
	    ThreeLineIndex = 0.
        END.
    END CASE.
    
END. /* REPEAT */

/*
**  Close input stream
*/

INPUT CLOSE.

/*
** Clean up temp file.  If TempDir not empty then we have to delete the 
** file to clean up.
*/
IF TempDir NE "" AND TempDir NE ? THEN
DO:
    IF debug-4gl NE 1 THEN
    DO:

        OS-DELETE VALUE (TempDir).

        IF OS-ERROR NE 0 THEN
        DO:
            PUT SKIP "Problem deleting temporary file: " Tempdir.
            PUT SKIP "Error returned from delete is : " OS-ERROR.
            QUIT.
        END. 
	ELSE
	DO:
	    PUT SKIP "Temporary file " Tempdir " deleted successfully.".
	END.
    END.
    ELSE
    DO:
        sec-name = "4GL Debugging turned on.  Temporary file " + Tempdir + " will not be deleted".
        {include/ar-debug.i "sec-name"}
    END.
END.

/*
** Process to take any index entries that have failed the query and
** create an alert for them to be fired off
*/

IF Fathom-i-RunCompaction = "TRUE" AND 
   Fathom-t-IndexNames NE "" THEN
DO:
    /*
    ** Generic alert generator based on what alert type is passed
    ** in the first position
    ** There are 6 parameters that must be passed
    */
    
    Alert-site_id = Fathom-i-site-id.
    Alert-resrc_name = fathom-i-resrc-name.
    Alert-alert_type = "IdxAnalysisAlert".
    Alert-cmd_action = "".

    sec-name = "Begin IdxAnalysisAlert Alert".
    {include/ar-debug.i "sec-name"}
    
    DEFINE VARIABLE cnt1 AS INTEGER NO-UNDO.
    DEFINE VARIABLE cnt2 AS INTEGER NO-UNDO.

    REPEAT:
        IF Fathom-t-IndexNames = "" THEN
	DO:
	    cnt1 = 0.
	    LEAVE.
	END.
        cnt1 = cnt1 + 1.
        IF ENTRY(cnt1, Fathom-t-IndexNames) NE "" THEN cnt2 = cnt2 + 1.
        ELSE LEAVE.
    END.

    IF Fathom-i-RunCompaction = "TRUE" AND cnt1 gt 0 THEN
    Alert-Detail = "'The following indexes will be compacted ".
    ELSE
    Alert-Detail = "'The following indexes should be considered for index compaction ".

    DO cnt1 = 1 TO cnt2:
        Alert-Detail = Alert-Detail +
                   " : " +
                 STRING ( ENTRY ( cnt1, Fathom-t-TableNames)) +
                   "." +
                  STRING ( ENTRY ( cnt1, Fathom-t-IndexNames)) + 
                   " (Utilization Percent - " +
                  STRING ( ENTRY ( cnt1, Fathom-t-IndexFailed)) +
                   "  Number of blocks - " +
                  STRING ( ENTRY ( cnt1, Fathom-t-IndexBlocks)) + 
                   " ) ". 
    END.
    
    Alert-Detail = Alert-Detail + "' ".
   
   IF alert-cmd_action NE "" THEN
    DO:
        Alert-Detail = Alert-Detail + " -action " + alert-cmd_action.
    END.

    /* 
    ** Alert level is currently severe
    */

    Alert-Severity = "1".

    IF Fathom-i-RunCompaction = "TRUE" AND cnt1 gt 0 THEN
    DO: 
        RUN gen-alert.p.
    END.
END.
ELSE
DO:
    sec-name = "No index analysis alert needed.".
    {include/ar-debug.i "sec-name"}
END.

/*
** Process to run index compaction if the user so desires (and there are 
** indexes to be compacted)
*/

IF Fathom-i-RunCompaction = "TRUE" AND cnt1 gt 0 THEN
DO:

    Fathom-i-CompactionPCT = OS-GETENV ("FM_COMPACTIONNUMBER").
    IF Fathom-i-CompactionPCT = ? THEN Fathom-i-CompactionPCT = "80".
    DO cnt1 = 1 TO cnt2:
        Alert-Detail = ENTRY (cnt1, Fathom-t-Tablenames) +
                   "," +
                   ENTRY (cnt1, Fathom-t-IndexNames) + 
                   "," +
                   Fathom-i-CompactionPCT.
        
        RUN compactindex.p.
	
    END.
    Alert-Detail = "'Index Compaction Completed for ".
    DO cnt1 = 1 to cnt2:
        Alert-Detail = Alert-Detail + 
	       " : " +
	       ENTRY (cnt1, Fathom-t-Tablenames) +
               "." +
               ENTRY (cnt1, Fathom-t-IndexNames) .
    END.
   
    Alert-Severity = "2".
    Alert-alert_type = "IndexCompactionComplete".
    Alert-Detail = Alert-Detail + "'". 

    RUN gen-alert.p.
        
END.
ELSE
DO:
    sec-name = "Program Completed - No alerts generated.".
    {include/ar-debug.i "sec-name"}
END.

/* 
** PROCEDURE getnumbytes 
*/

PROCEDURE getnumbytes:

sec-name = "Called Procedure getnumbytes".
{include/ar-debug.i "sec-name"}

&SCOPED-DEFINE BYTES        (1)
&SCOPED-DEFINE KILOBYTES    (1024 * {&BYTES})
&SCOPED-DEFINE MEGABYTES    (1024 * {&KILOBYTES})
&SCOPED-DEFINE GIGABYTES    (1024 * {&MEGABYTES})
&SCOPED-DEFINE TERABYTES    (1024 * {&GIGABYTES})

    DEFINE INPUT  PARAMETER szSize      AS CHARACTER.
    DEFINE OUTPUT PARAMETER nBytes      AS DECIMAL.

    DEFINE VARIABLE szUnit      AS CHARACTER    NO-UNDO.
    DEFINE VARIABLE nNumber     AS DECIMAL      NO-UNDO.
    
    /*
    **  Calculate the number of bytes for this entry. The size indication
    **  can have several additions to the number as shown below:
    **
    **  Size key:
    **      B = bytes       ( x 1 )
    **      K = kilobytes   ( x 1024B )
    **      M = megabytes   ( x 1024K )
    **      G = gigabytes   ( x 1024M )
    **      T = terabytes   ( x 1024G )
    **
    **  So we will find out what the unit is and then strip it off.
    **  We will multiple the number with the unit to get the real number
    **  of bytes.
    */

    /*
    **  Get the unit of display
    */
    IF LENGTH(szSize) LT 1 THEN szSize = "0B".

    /*
    **  Get the number
    */
    szUnit = SUBSTRING(szSize, LENGTH(szSize), 1).
    nNumber = DECIMAL(SUBSTRING(szSize, 1, LENGTH(szSize) - 1)).    
    nBytes  = nNumber * IF szUnit = "B" THEN {&BYTES} ELSE
                        IF szUnit = "K" THEN {&KILOBYTES} ELSE
                        IF szUnit = "M" THEN {&MEGABYTES} ELSE
                        IF szUnit = "G" THEN {&GIGABYTES}
                                        ELSE {&TERABYTES}.
sec-name = "szSize: " + STRING (szSize) + 
           "szUnit: " + STRING (szUnit) + 
           "nBytes: " + STRING (nBytes) +
           "nNumber: "  + STRING (nNumber).
{include/ar-debug.i "sec-name"}

END PROCEDURE.

/* 
** PROCEDURE create_tab 
*/

PROCEDURE create_tab:

sec-name = "create_tab - creating table : " + szTableName.
{include/ar-debug.i "sec-name"}

    DEFINE VARIABLE nBytes      AS DECIMAL      NO-UNDO.

    /*
    **  Get the number of bytes for this table
    */

    RUN getnumbytes(INPUT szInput[3], OUTPUT nBytes).

    /*
    **  Create tab analys record for this table and fill out
    */

    CREATE Db_TabAnalysis.
    ASSIGN
        Db_TabAnalysis.TAB_AreaName = szAreaName
        Db_TabAnalysis.TAB_AvgRecSize = INTEGER(szInput[6])
        Db_TabAnalysis.TAB_Bytes = nBytes
        Db_TabAnalysis.TAB_Date = Fathom-t-date
        Db_TabAnalysis.TAB_FragmentCount = INTEGER(szInput[7])
        Db_TabAnalysis.TAB_FragmentFactor = DECIMAL(szInput[8])
        Db_TabAnalysis.TAB_ID = Fathom-t-ID
        Db_TabAnalysis.TAB_MaxRecSize = INTEGER(szInput[5])
        Db_TabAnalysis.TAB_MinRecSize = INTEGER(szInput[4])
        Db_TabAnalysis.TAB_RecordCount = INT64(szInput[2])
        Db_TabAnalysis.TAB_ScatterFactor = DECIMAL(szInput[9])
        Db_TabAnalysis.TAB_TableName  = szTableName
        Db_TabAnalysis.TAB_Time = Fathom-t-time
        Db_TabAnalysis.Resrc_ID = Fathom-i-resrc-ID
        Db_TabAnalysis.TAB_ResrcName = Fathom-i-resrc-name
        Db_TabAnalysis.Site_ID = Fathom-i-site-ID.
        
END PROCEDURE.


/* 
** PROCEDURE create_idx 
*/

PROCEDURE create_idx:

sec-name = "create_idx - creating index : " + szInput[1].
 {include/ar-debug.i "sec-name"}
    DEFINE VARIABLE nBytes      AS INT64      NO-UNDO.
    DEFINE VARIABLE shiftnum    AS INTEGER      NO-UNDO.

    /*
    **  Get the number of bytes for this table
    */

    RUN getnumbytes(INPUT szInput[6], OUTPUT nBytes).

    IF szInput[1] BEGINS "_" THEN
    DO:
        NEXT.
    END.
    ELSE
    DO:
        CREATE Db_IdxAnalysis.
        ASSIGN
            Db_IdxAnalysis.IDX_AreaName = szAreaName
            Db_IdxAnalysis.IDX_Blocks = INTEGER(szInput[5])
            Db_IdxAnalysis.IDX_Bytes = nBytes
            Db_IdxAnalysis.IDX_IndexName = szInput[1]
            Db_IdxAnalysis.IDX_Number = INT64(szInput[2])
            Db_IdxAnalysis.IDX_Levels = INTEGER(szInput[4])
            Db_IdxAnalysis.IDX_Blocks = INTEGER(szInput[5])
            Db_IdxAnalysis.IDX_TableName = SUBSTRING (szTableName,5)
            Db_IdxAnalysis.IDX_UtilizationFactor = DECIMAL(szInput[8])
            Db_IdxAnalysis.IDX_UtilizationPct = DECIMAL(szInput[7])
            Db_IdxAnalysis.IDX_Date = Fathom-t-date
            Db_IdxAnalysis.TAB_ID = Fathom-t-ID  
            Db_IdxAnalysis.Resrc_ID = Fathom-i-resrc-ID
            Db_IdxAnalysis.IDX_ResrcName = Fathom-i-resrc-name
            Db_IdxAnalysis.Site_ID = Fathom-i-site-ID
            Db_IdxAnalysis.IDX_Time = Fathom-t-time.
	    
        IF Fathom-t-utilization GT 0 and Fathom-t-blocks GT 0 THEN
	DO:
	    
            sec-name = "Testing for compaction (idxblocks, utilPCT) : " + 
	               STRING (Db_IdxAnalysis.IDX_Blocks) + 
	               " " + STRING (Db_IdxAnalysis.IDX_UtilizationPct).
            {include/ar-debug.i "sec-name"}

	    IF Db_IdxAnalysis.IDX_Blocks GE Fathom-t-blocks AND
	       Db_IdxAnalysis.IDX_UtilizationPct LE Fathom-t-utilization THEN
	    DO:
	        Fathom-t-indexNames = 
		    Fathom-t-indexNames + TRIM (Db_IdxAnalysis.IDX_IndexName) + ",".
	        Fathom-t-TableNames = 
		    Fathom-t-TableNames + TRIM (Db_IdxAnalysis.IDX_TableName) + ",".
	        Fathom-t-indexfailed = 
		    Fathom-t-indexfailed + STRING (Db_IdxAnalysis.IDX_UtilizationPct) + ",".
	        Fathom-t-IndexBlocks = 
		    Fathom-t-indexBlocks + STRING (Db_IdxAnalysis.IDX_Blocks) + ",".
	    END.
	END.
    END.
END PROCEDURE.
PROCEDURE Get-input-data.

/* sec-name = "Called Procedure get-input-data".
{include/ar-debug.i "sec-name"} */

/* 
** Test if the temp file was passed.  If it wasn't passed then go see if
** it already exists on disk.  If it doesn't then build it...
*/

IF szTmpFile = "" OR sztmpFile = ? THEN
DO:
    sec-name = "Temporary File Not found. Value: " + szTmpFile.
    {include/ar-debug.i "sec-name"}

    IF fathom-i-dbname NE "" THEN
    DO:
        /*
        ** See if the file is out there
        */

        If OPSYS = "UNIX" THEN
        DO:
           TempDir = Fathom-t-separator + "tmp" + Fathom-t-separator.   
           sec-name = "TempDir : " + TempDir.
           {include/ar-debug.i "sec-name"}
        END.
        ELSE
        DO:
            TempDir = OS-GETENV("TMPDIR") NO-ERROR.
            IF TempDir EQ "" OR TempDir EQ ? THEN
            DO:
                TempDir = OS-GETENV("TMP") NO-ERROR.
                IF TempDir EQ "" OR TempDir EQ ? THEN
                DO:
                   TempDir = OS-GETENV("fathomWorkDir") NO-ERROR.
                   IF TempDir EQ "" OR TempDir EQ ? THEN
                   DO:
                       TempDir = "C:" + Fathom-t-separator.
                       sec-name = "TempDir : " + TempDir.
                       {include/ar-debug.i "sec-name"}
                   END.
                   ELSE
                   DO:
                       TempDir = TempDir + Fathom-t-separator.
                       sec-name = "TempDir : " + TempDir.
                       {include/ar-debug.i "sec-name"}
                   END.
                END.
		ELSE 
                DO:
                    TempDir = TempDir + Fathom-t-separator.
                    sec-name = "TempDir : " + TempDir.
                    {include/ar-debug.i "sec-name"}
                END.
            END.
	    ELSE 
            DO:
                TempDir = TempDir + Fathom-t-separator.
                sec-name = "TempDir : " + TempDir.
                {include/ar-debug.i "sec-name"}
            END.
        END.

        TempDir = TempDir + "FathomDBA." + Fathom-i-dbname.

        sec-name = "Temporary file used will be : " + TempDir.
        {include/ar-debug.i "sec-name"}
        /* 
        ** This validates that the file exists
        ** If the copy is successful then the delete will be successful
        ** and the file must exist.  If the copy fails then the delete will
        ** Fail and I am assuming the file does not exist.
        ** NOTE: This does not take into account permissions problems directly
        ** but does in the long run as if we can't read it to copy it we have 
        ** to create a new one anyway.
        */

        OS-COPY VALUE(TempDir) VALUE(TempDir + "OLD").

        OS-DELETE VALUE (TempDir + "OLD").

        IF OS-ERROR = 2 THEN
        DO:
           
            sec-name = "File not found - running database analysis.".
            {include/ar-debug.i "sec-name"}
            /* 
            ** Set up the command to run to generate the file
            */
 
            runcmd = OS-GETENV("progressInstallDirShort") NO-ERROR.
            IF runcmd NE "" AND runcmd NE ? THEN
            DO:
                runcmd = runcmd + Fathom-t-separator +
                     "bin" + Fathom-t-separator +
                     "_proutil " + chr(34) + fathom-i-dbpath + chr(34) +
                     " -C dbanalys >" + chr(34) + TempDir + chr(34).
            END.
            ELSE
            DO:
                runcmd = OS-GETENV("DLC") NO-ERROR.
                IF runcmd NE "" AND runcmd NE ? THEN
                DO:
                    runcmd = runcmd + Fathom-t-separator +
                             "bin" + Fathom-t-separator +
                             "_proutil " + chr(34) + fathom-i-dbpath + chr(34) +
                             " -C dbanalys >" + chr(34) + TempDir + chr(34).
                END.
                ELSE
                DO:
                    PUT SKIP "DLC environment variable not set.".
                    PUT SKIP "Exiting database analysis".
                    QUIT.
                END.
            END.

            /*
            ** Test the database for status
            */

            fathom-t-dbname = fathom-i-dbpath.

            {include/db-status.i}

            Case Fathom-t-dbstatus:
                WHEN "Multi" THEN
                DO:
                END.
                OTHERWISE
                DO:
                    PUT SKIP "Database is not in use in multi-user mode!".
                    PUT SKIP "database found in "  fathom-t-dbstatus format "x(30)".
                    PUT SKIP "Dbanalysis will not be run!".
                    QUIT.
                END.
            END CASE.

            /*
            ** Database is up and running so go ahead with the command
            */

            sec-name = "Running external command for database analysis.  Command : " + runcmd.
            {include/ar-debug.i "sec-name"}

            OS-COMMAND NO-CONSOLE VALUE(runcmd).
            IF OS-ERROR NE 0 THEN 
            DO:
                PUT SKIP "Problem encountered while generating database analysis data.".
                PUT SKIP "Error number : " OS-ERROR.
                PUT SKIP "Exiting database analysis".
                QUIT.
            END.
            sec-name = "Completed external command for database analysis".
            {include/ar-debug.i "sec-name"}
            szTmpFile = TempDir.

            sec-name = "Completed running database analysis.".
            {include/ar-debug.i "sec-name"}
        END. /* Of if NOT valid name */
        ELSE
        DO:
            /*
            ** It is a valid name so we will use it
            */

            sec-name = "Valid file found - using it.".
            {include/ar-debug.i "sec-name"}
            szTmpFile = TempDir.

        END.
    END.
    ELSE
    DO:
        PUT SKIP "Environment variable RESRC_DBNAME was not set.".
        PUT SKIP "Exiting database analysis".
        QUIT.
    END.
END. /* If szTmpFile = NULL */

sec-name = "Completed getting File Information".
{include/ar-debug.i "sec-name"}

END PROCEDURE.

QUIT.
/*
** This program is an intermediate program for trenddbsingle.p
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

    Fathom-t-rep_type = "dbai".

RUN src/trendDBsingle.p.
/*
** dbareastatus.p
** This program will present a trend report for the area status.  This is 
** based on the dates provided to the report.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** NOTE:The header information for the report does not use the standard include.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:

    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Define temp table to store data output
*/

DEF NEW SHARED TEMP-TABLE data_store NO-UNDO
    FIELD name AS character 
    FIELD areanum AS DECIMAL
    FIELD freenum AS INT64 EXTENT 366 INITIAL 0
    FIELD totblks AS DECIMAL EXTENT 366 INITIAL 0
    FIELD hiwater AS DECIMAL EXTENT 366 INITIAL 0
    FIELD rmnum AS INT64 EXTENT 366 INITIAL 0
    FIELD blksavail AS DECIMAL EXTENT 366 INITIAL 0
    FIELD max-rmnum AS INT64 INITIAL 0
    FIELD max-freenum AS INT64 INITIAL 0
    FIELD max-totblks AS DECIMAL INITIAL 0
    FIELD max-hiwater AS DECIMAL INITIAL 0
    FIELD min-rmnum AS INT64 INITIAL 0
    FIELD min-freenum AS INT64 INITIAL 0
    FIELD min-totblks AS DECIMAL INITIAL 0
    FIELD min-hiwater AS DECIMAL INITIAL 0
    FIELD cnt AS INTEGER EXTENT 366 INITIAL 0
    INDEX three name
    INDEX two areanum.

DEF VAR x-display AS DECIMAL NO-UNDO.

DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.
DEF VAR Fathom-add-counter-test AS INTEGER NO-UNDO INITIAL 0.

/* 
** Begin Main Processing
*/
/*
** Process the trend dates
*/

{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }.

/*
** Setting the Fathom-i-IntervalType to "R" as raw values are the only
** logical valid values for this report
*/

IF Fathom-i-IntervalType NE "D" THEN
DO:
    PUT SKIP TODAY  " "  STRING (TIME, "HH:MM:SS")  
        " Changing output type to Per Record output (only valid report format).". 
    PUT SKIP.
    Fathom-i-IntervalType = "D".
END.

/*
** Read samples and process them into the rpt table
*/

pgm-name = "dbareastatus.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

{include/sample-query.i}.

{include/setup-i.i}.
      
/* 
*/
     FIND FIRST db_areastatus WHERE
     cf_sample.sample_id = db_areastatus.sample_id NO-LOCK NO-ERROR.
     IF AVAILABLE db_areastatus THEN
     DO:
         Fathom-rec-count = fathom-rec-count + 1.
     END.

     FOR EACH db_areastatus
          WHERE
          cf_sample.sample_id = db_areastatus.sample_id:

          IF Fathom-add-counter-test = 0 THEN
          DO:
              Fathom-Interval-Count[Fathom-i] = 
                  Fathom-Interval-Count[Fathom-i] + Cf_Sample.Sample_Len.
              Fathom-Transaction-Count[Fathom-i] = 
                  Fathom-Transaction-Count[Fathom-i] + Cf_Sample.Sample_Trans.
          END.
          Fathom-add-counter-test = 1.
          
          FIND FIRST data_store
              WHERE
              data_store.NAME = db_areastatus.AreaStatus_AreaName AND
              data_store.areanum = db_areastatus.areastatus_areanum
              NO-ERROR.
          IF NOT AVAILABLE data_store THEN 
          DO:
              CREATE data_store.
              ASSIGN 
                  data_store.NAME = db_areastatus.areastatus_areaName
                  data_store.areanum = db_areastatus.areastatus_areanum.
                  DO fathom-j = 1 TO fathom-i-periods:
                      ASSIGN 
                          freenum[fathom-j] = 0
                          totblks[fathom-j] = 0
                          hiwater[fathom-j] = 0
                          rmnum[fathom-j] = 0
                          cnt[fathom-j] = 0
                          blksavail[fathom-j] = 0.
                  END.
          END.
          ASSIGN
             data_store.freenum[Fathom-i] = 
                 data_store.freenum[Fathom-i] + db_areastatus.areastatus_freenum
             data_store.hiwater[Fathom-i] = 
                 data_store.hiwater[Fathom-i] + db_areastatus.areastatus_hiwater
             data_store.rmnum[Fathom-i] = 
                 data_store.rmnum[Fathom-i] + db_areastatus.areastatus_rmnum
             data_store.totblks[Fathom-i] = 
                 data_store.totblks[Fathom-i] + db_areastatus.areastatus_totblocks
             data_store.blksavail[fathom-i] =
                 data_store.blksavail[Fathom-i] + 
                 ((db_areastatus.areastatus_totblocks - db_areastatus.areastatus_hiwater) +
                 db_areastatus.areastatus_freenum)
             data_store.cnt[Fathom-i] = 
                 data_store.cnt[Fathom-i] + 1
             Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

          /* Min Available */
          IF data_store.min-freenum GT db_areastatus.areastatus_freenum THEN
              data_store.min-freenum = db_areastatus.areastatus_freenum.
          IF data_store.min-hiwater GT db_areastatus.areastatus_hiwater THEN
              data_store.min-hiwater = db_areastatus.areastatus_hiwater.
          IF data_store.min-rmnum GT db_areastatus.areastatus_rmnum THEN
              data_store.min-rmnum = db_areastatus.areastatus_rmnum.
          IF data_store.min-totblks GT db_areastatus.areastatus_totblocks THEN
              data_store.min-totblks = db_areastatus.areastatus_totblocks.
          
          /* Max Available */
          IF data_store.max-freenum LT db_areastatus.areastatus_freenum THEN
              data_store.max-freenum = db_areastatus.areastatus_freenum.
          IF data_store.max-hiwater LT db_areastatus.areastatus_hiwater THEN
              data_store.max-hiwater = db_areastatus.areastatus_hiwater.
          IF data_store.max-rmnum LT db_areastatus.areastatus_rmnum THEN
              data_store.max-rmnum = db_areastatus.areastatus_rmnum.
          IF data_store.max-totblks LT db_areastatus.areastatus_totblocks THEN
              data_store.max-totblks = db_areastatus.areastatus_totblocks.
          
      END. /* of FOR EACH */
      IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
      ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).

        Fathom-add-counter-test = 0.
   END. /* of assignment of FOR EACH */

/* 
** Do Archive processing
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "dbareastatus.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}

    {include/archive-type.i}.

    DEFINE VARIABLE Hold-date AS DATE NO-UNDO.
    DEFINE VARIABLE qh        AS WIDGET-HANDLE.

    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_AreaStatus:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_AreaStatus WHERE " +
                     "Ar_AreaStatus.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_AreaStatus.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_AreaStatus.AreaStatus_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_AreaStatus.AreaStatus_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_AreaStatus.AreaStatus_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_AreaStatus.AreaStatus_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_AreaStatus.AreaStatus_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.

        /*
        ** Setting Fathom-store-value to 1 because this is the only valid
        ** type of display for this report.
        */
        fathom-store-value = 1.

        /* 
        ** Determine which date column the record falls into
        */
        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        
        Fathom-i = 0.
    
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_AreaStatus.AreaStatus_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_AreaStatus.AreaStatus_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
                IF Ar_AreaStatus.AreaStatus_starttime GE Fathom-t-beg-time[Fathom-i] AND
                    Ar_AreaStatus.AreaStatus_starttime LE Fathom-t-end-time[Fathom-i] THEN
                    LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.
   
        Fathom-Rec-Count = Fathom-Rec-Count + ar_areastatus.areastatus_recordcount.
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + ar_areastatus.areastatus_Length.
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + ar_areastatus.areastatus_transactions.
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store
            WHERE
            data_store.NAME = ar_areastatus.AreaStatus_AreaName AND
            data_store.areanum = ar_areastatus.areastatus_areanum
            NO-ERROR.
        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.NAME = ar_areastatus.areastatus_areaName
                data_store.areanum = ar_areastatus.areastatus_areanum.
                DO fathom-j = 1 TO fathom-i-periods:
                    ASSIGN 
                        freenum[fathom-j] = 0
                        totblks[fathom-j] = 0
                        hiwater[fathom-j] = 0
                        rmnum[fathom-j] = 0
                        cnt[fathom-j] = 0
                        blksavail[fathom-j] = 0.
                END.
        END.
        ASSIGN
            data_store.freenum[Fathom-i] = 
                data_store.freenum[Fathom-i] + 
                ar_areastatus.areastatus_freenum /* / 
                Fathom-store-value */
            data_store.hiwater[Fathom-i] = 
                data_store.hiwater[Fathom-i] + 
                ar_areastatus.areastatus_hiwater /* /
                Fathom-store-value */
            data_store.rmnum[Fathom-i] = 
                data_store.rmnum[Fathom-i] + 
                ar_areastatus.areastatus_rmnum  /*/
                Fathom-store-value */
            data_store.totblks[Fathom-i] = 
                data_store.totblks[Fathom-i] + 
                ar_areastatus.areastatus_totblocks  /*/
                Fathom-store-value */
            data_store.blksavail[fathom-i] =
                data_store.blksavail[Fathom-i] + 
                ((ar_areastatus.areastatus_totblocks - 
                ar_areastatus.areastatus_hiwater) +
                ar_areastatus.areastatus_freenum) /*/
                Fathom-store-value */
            data_store.cnt[Fathom-i] = 
                data_store.cnt[Fathom-i] + ar_areastatus.areastatus_recordcount.
                /* data_store.cnt[Fathom-i] + 1.  */

        /* Min Available */
        IF data_store.min-freenum GT ar_areastatus.areastatus_freenum THEN
            data_store.min-freenum = ar_areastatus.areastatus_freenum.
        IF data_store.min-hiwater GT ar_areastatus.areastatus_hiwater THEN
            data_store.min-hiwater = ar_areastatus.areastatus_hiwater.
        IF data_store.min-rmnum GT ar_areastatus.areastatus_rmnum THEN
            data_store.min-rmnum = ar_areastatus.areastatus_rmnum.
        IF data_store.min-totblks GT ar_areastatus.areastatus_totblocks THEN
            data_store.min-totblks = ar_areastatus.areastatus_totblocks.

        /* Max Available */
        IF data_store.max-freenum LT ar_areastatus.areastatus_freenum THEN
            data_store.max-freenum = ar_areastatus.areastatus_freenum.
        IF data_store.max-hiwater LT ar_areastatus.areastatus_hiwater THEN
            data_store.max-hiwater = ar_areastatus.areastatus_hiwater.
        IF data_store.max-rmnum LT ar_areastatus.areastatus_rmnum THEN
            data_store.max-rmnum = ar_areastatus.areastatus_rmnum.
        IF data_store.max-totblks LT ar_areastatus.areastatus_totblocks THEN
            data_store.max-totblks = ar_areastatus.areastatus_totblocks.
    END. /* of for each ar* */

    pgm-name = "dbareastatus.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}.

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

END. /* of date testing for archives */

   /* 
   ** Validate data stores against # of samples...  
   */
   FIND FIRST data_store NO-LOCK NO-ERROR.
   IF NOT AVAILABLE data_store THEN Fathom-Rec-Count = 0.
   
/*
** Print Section
*/

sec-name = "Printing Output".
pgm-name = "dbareastatus.p".
{include/debug.i "pgm-name" "sec-name"}.

{ include/report-name.i }.

RUN xml-dbareastatus.p.

sec-name = "Exiting Program".
pgm-name = "dbareastatus.p".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** This program is an intermediate program for trenddbsingle.p
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:

    {include/fathom-dir.i}

    {include/passinput.i}
END.

    fathom-t-rep_type = "dbbi".

RUN src/trendDBsingle.p.
/*
** trendcheckpoint.p
** This program will present a trend report for checkpoints.  This is 
** based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Number, the resource ID and the Site ID.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:

    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Set up local variables 
*/

    DEF NEW SHARED VAR data_len AS DECIMAL EXTENT 366.
    DEF NEW SHARED VAR data_flush AS DECIMAL EXTENT 366.
    DEF NEW SHARED VAR data_ckptq AS DECIMAL EXTENT 366.
    DEF NEW SHARED VAR data_scan AS DECIMAL EXTENT 366.
    DEF NEW SHARED VAR data_apwq AS DECIMAL EXTENT 366.
    DEF NEW SHARED VAR data_cnt AS DECIMAL EXTENT 366.

    DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.
    DEF VAR Hold-record AS INTEGER NO-UNDO.
/* 
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/
{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/

pgm-name = "dbcheckpoint.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}

{include/sample-query.i}

{include/setup-i.i}
      
      FOR EACH db_Checkpoint
          WHERE
          cf_sample.sample_id = db_checkpoint.sample_id:

          ASSIGN
              data_len[Fathom-i] = data_len[Fathom-i] + Db_Checkpoint.Checkpoint_Length
              data_cnt[Fathom-i] = data_cnt[Fathom-i] + 1
              data_flush[Fathom-i] = data_flush[Fathom-i] + Db_Checkpoint.Checkpoint_Flush
              data_ckptq[Fathom-i] = data_ckptq[Fathom-i] + Db_Checkpoint.Checkpoint_CkptQ
              data_apwq[Fathom-i] = data_apwq[Fathom-i] + Db_Checkpoint.Checkpoint_ApwQ
              data_scan[Fathom-i] = data_scan[Fathom-i] +  Db_Checkpoint.Checkpoint_Scan.
       
          /*
          ** Adding counter in here because # of samples should equal # of checkpoints
          ** ONLY for checkpoint table is the number of checkpoints (AKA # of recs) important
          */
          Fathom-Rec-Count = Fathom-Rec-Count + 1.

       END. /* of FOR EACH DB_Checkpoint */

       
       IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
       ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).
   
   END. /* of assignment of FOR EACH */

/*
** Process archive records appropriately
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "dbcheckpoint.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    /*
    ** We need to make sure certain counters only get incremented once
    ** per day or hour, depending on the report type.
    */
    DEFINE TEMP-TABLE counterTester
        FIELD startTime AS INTEGER
        FIELD startDate AS DATE.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.

    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_Checkpoint:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_Checkpoint WHERE " +
                     "Ar_Checkpoint.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_Checkpoint.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_Checkpoint.Checkpoint_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_Checkpoint.Checkpoint_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_Checkpoint.Checkpoint_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_Checkpoint.Checkpoint_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_Checkpoint.Checkpoint_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.
    
        /*
        ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
        */
	    /*
	    ** Commented out because the archive values are averaged out already!!!!!
	    **
        CASE Fathom-i-intervaltype:
            WHEN "R" THEN fathom-store-value = checkpoint_Recordcount.
            WHEN "S" THEN fathom-store-value = checkpoint_length.
            WHEN "M" THEN fathom-store-value = checkpoint_length / 60.
            WHEN "H" THEN fathom-store-value = checkpoint_length / 60 / 60.
            WHEN "T" THEN fathom-store-value = checkpoint_transactions.
            OTHERWISE fathom-store-value = 1.
        END CASE.
        */
    
        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        Fathom-i = 0.

        /* 
        ** Determine which date column the record falls into
        */
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_Checkpoint.Checkpoint_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_Checkpoint.Checkpoint_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
                IF Ar_Checkpoint.Checkpoint_starttime GE Fathom-t-beg-time[Fathom-i] AND
                    Ar_Checkpoint.Checkpoint_starttime LE Fathom-t-end-time[Fathom-i] THEN
                    LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.

        FIND FIRST counterTester WHERE
            startDate EQ Ar_Checkpoint.Checkpoint_StartDate AND
            startTime EQ Ar_Checkpoint.Checkpoint_StartTime NO-ERROR.

        IF NOT AVAILABLE counterTester THEN
        DO:
            fathom-rec-count = fathom-rec-count + Ar_Checkpoint.Checkpoint_RecordCount.
            CREATE counterTester.
            ASSIGN
                startDate = Ar_Checkpoint.Checkpoint_StartDate
                startTime = Ar_Checkpoint.Checkpoint_StartTime.
        END.
           
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + ar_checkpoint.Checkpoint_Length.
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + ar_checkpoint.checkpoint_RecordCount. 
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

        /*
        ** Process each field that is on the report
        */
        ASSIGN
           data_len[Fathom-i] = data_len[Fathom-i] + Ar_Checkpoint.Checkpoint_Length 
           data_cnt[Fathom-i] = data_cnt[Fathom-i] + Ar_Checkpoint.Checkpoint_RecordCount
           data_flush[Fathom-i] = data_flush[Fathom-i] + Ar_Checkpoint.Checkpoint_Flush
           data_ckptq[Fathom-i] = data_ckptq[Fathom-i] + Ar_Checkpoint.Checkpoint_CkptQ
           data_apwq[Fathom-i] = data_apwq[Fathom-i] + Ar_Checkpoint.Checkpoint_ApwQ
           data_scan[Fathom-i] = data_scan[Fathom-i] +  Ar_Checkpoint.Checkpoint_Scan.

    END. /* of FOR EACH Ar_Checkpoint */
   
    pgm-name = "dbcheckpoint.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}.

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

END.

/*
** Print Section
*/
pgm-name = "dbcheckpoint.p".
sec-name = "Printing Output".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }.

RUN xml-dbcheckpoint.p.

pgm-name = "dbcheckpoint.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** This program is an intermediate program for trenddbsingle.p
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:

    {include/fathom-dir.i}

    {include/passinput.i}
END.

    fathom-t-rep_type = "dbdet".

RUN src/trendDBsingle.p.
/*
** dbdisk.p
** This program will present a trend report for File I/O.  This is 
** based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
IF Fathom-PassInput NE 1 THEN
DO:

    {include/fathom-dir.i}

    {include/passinput.i}
END.

/*
** Define temp table to store results in 
*/

DEF NEW SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD reads AS DECIMAL EXTENT 366
   FIELD writes AS DECIMAL  EXTENT 366
   FIELD bufwrites AS DECIMAL EXTENT 366
   FIELD unbufwrites AS DECIMAL EXTENT 366
   FIELD bufreads AS DECIMAL EXTENT 366
   FIELD unbufreads AS DECIMAL EXTENT 366
   INDEX two TYPE 
   INDEX three NAME.

DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.

/* 
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/
{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/

sec-name = "Processing Samples".
pgm-name = "dbdisk.p".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

/*
** Set up the initial query
*/

{include/sample-query.i}

{include/setup-i.i}
      
/*
** Increment the appropriat counters
*/
Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Cf_Sample.Sample_Len.
Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Cf_Sample.Sample_Trans.
Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.
      
      FOR EACH db_ActIOFile
          WHERE
          cf_sample.sample_id = db_actiofile.sample_id:
Fathom-Rec-Count = Fathom-Rec-Count + 1.

          FIND FIRST data_store
              WHERE
              data_store.NAME = STRING (Db_actiofile.actiofile_FileName)
              NO-ERROR.
          IF NOT AVAILABLE data_store THEN 
          DO:
              CREATE data_store.
              ASSIGN 
                  data_store.NAME = STRING (Db_actiofile.actiofile_FileName).
          END.
          ASSIGN
             data_store.reads[Fathom-i] = data_store.reads[Fathom-i] + Db_ActIOFile.ActIOFile_Reads
             data_store.writes[Fathom-i] = data_store.writes[Fathom-i] + Db_ActIOFile.ActIOFile_Writes
             data_store.bufwrites[Fathom-i] = data_store.bufwrites[Fathom-i] + Db_ActIOFile.ActIOFile_BufWrites
             data_store.unbufwrites[Fathom-i] = data_store.unbufwrites[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufWrites
             data_store.bufreads[Fathom-i] = data_store.bufreads[Fathom-i] + Db_ActIOFile.ActIOFile_BufReads
             data_store.unbufreads[Fathom-i] = data_store.unbufreads[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufReads.
      END. /* of FOR EACH DB_ActServ */

      IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
      ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).

   END. /* of assignment of FOR EACH */

/*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "dbdisk.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}.

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}.


IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "dbdisk.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    /*
    ** We need to make sure certain counters only get incremented once
    ** per day or hour, depending on the report type.
    */
    DEFINE TEMP-TABLE counterTester
        FIELD startTime AS INTEGER
        FIELD startDate AS DATE.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_ActIOFile:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_ActIOFile WHERE " +
                     "Ar_ActIOFile.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_ActIOFile.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_ActIOFile.ActIOFile_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_ActIOFile.ActIOFile_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_ActIOFile.ActIOFile_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_ActIOFile.ActIOFile_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_ActIOFile.ActIOFile_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.
    
        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        Fathom-i = 0.

        /*
        ** Determine which date column the record falls into
        */
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_ActIOFile.ActIOFile_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_ActIOFile.ActIOFile_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
                IF Ar_ActIOFile.ActIOFile_starttime GE Fathom-t-beg-time[Fathom-i] AND
                    Ar_ActIOFile.ActIOFile_starttime LE Fathom-t-end-time[Fathom-i] THEN
                    LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.

        FIND FIRST counterTester WHERE
            startDate EQ Ar_ActIOFile.ActIOFile_StartDate AND
            startTime EQ Ar_ActIOFile.ActIOFile_StartTime NO-ERROR.
            
        IF NOT AVAILABLE counterTester THEN
        DO:
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + ar_actiofile.Actiofile_Length.
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + ar_actiofile.Actiofile_Transactions. 
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + ar_actiofile.Actiofile_RecordCount. 
            CREATE counterTester.
            ASSIGN
                startDate = Ar_ActIOFile.ActIOFile_StartDate
                startTime = Ar_ActIOFile.ActIOFile_StartTime.
        END.
          
        fathom-rec-count = fathom-rec-count + ar_actiofile.Actiofile_RecordCount.

        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store WHERE
            data_store.NAME = STRING (Ar_ActIOFile.ActIOFile_FileName) NO-ERROR.

        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.NAME = STRING (Ar_ActIOFile.ActIOFile_FileName).
        END.

        ASSIGN
            data_store.reads[Fathom-i] = 
                data_store.reads[Fathom-i] + Ar_ActIOFile.ActIOFile_Reads 
            data_store.writes[Fathom-i] = 
                data_store.writes[Fathom-i] + Ar_ActIOFile.ActIOFile_Writes 
            data_store.bufwrites[Fathom-i] = 
                data_store.bufwrites[Fathom-i] + Ar_ActIOFile.ActIOFile_BufWrites 
            data_store.unbufwrites[Fathom-i] = 
                data_store.unbufwrites[Fathom-i] + Ar_ActIOFile.ActIOFile_UnbufWrites 
            data_store.bufreads[Fathom-i] = 
                data_store.bufreads[Fathom-i] + Ar_ActIOFile.ActIOFile_BufReads 
            data_store.unbufreads[Fathom-i] = 
                data_store.unbufreads[Fathom-i] + Ar_ActIOFile.ActIOFile_UnbufReads .

    END. /* of REPEAT. */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

    pgm-name = "dbdisk.p".
    sec-name = "Finished accessing archive information".
    {include/debug.i "pgm-name" "sec-name"}.

END. /* of Date test */

/*
** Print Section
*/
sec-name = "Printing output".
pgm-name = "dbdisk.p".
{include/debug.i "pgm-name" "sec-name"}.

{ include/report-name.i }.

RUN xml-dbdisk.p.

sec-name = "Exiting Program".
pgm-name = "dbdisk.p".
{include/debug.i "pgm-name" "sec-name"}.

QUIT.
/*
** dbidxanalysis.p
** This program will present a trend report for table analysis and index analysis.
** This is based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Number, the resource ID and the Site ID.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:

    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Set up local variables 
*/

DEF VAR t-table-count AS DECIMAL NO-UNDO.
DEF VAR t-index-count AS DECIMAL NO-UNDO.
DEF VAR t-hold-areaname AS CHARACTER NO-UNDO.
DEF VAR t-hold-tablename AS CHARACTER NO-UNDO.
DEF VAR t-hold-indexname AS CHARACTER NO-UNDO.
DEF VAR t-output-value AS DECIMAL NO-UNDO.
DEF VAR t-display-count AS INTEGER NO-UNDO.
DEF VAR save-tablename AS CHARACTER NO-UNDO.

DEF NEW SHARED TEMP-TABLE hold-date
    FIELD h-date AS DATE 
    FIELD h-time AS INTEGER 
    INDEX one h-date
    INDEX two h-time.

DEF NEW GLOBAL SHARED TEMP-TABLE tt-data
    FIELD table-name as CHARACTER
    FIELD index-name as CHARACTER
    FIELD area-name as CHARACTER
    FIELD lable as CHARACTER
    FIELD Max-records as DECIMAL
	FIELD i-rec-count as DECIMAL EXTENT 366
	FIELD i-max-blocks as DECIMAL EXTENT 366
	FIELD i-min-blocks as DECIMAL EXTENT 366
	FIELD i-avg-blocks as DECIMAL EXTENT 366
	FIELD i-max-bytes as DECIMAL EXTENT 366
	FIELD i-min-bytes as DECIMAL EXTENT 366
	FIELD i-avg-bytes as DECIMAL EXTENT 366
	FIELD i-max-utilpct as DECIMAL EXTENT 366
	FIELD i-min-utilpct as DECIMAL EXTENT 366
	FIELD i-avg-utilpct as DECIMAL EXTENT 366
	FIELD i-max-levels as DECIMAL EXTENT 366
	FIELD i-min-levels as DECIMAL EXTENT 366
	FIELD i-avg-levels as DECIMAL EXTENT 366
	INDEX one table-name
	INDEX two index-name
	INDEX three area-name
	INDEX Four Max-Records DESCENDING
	.
/*
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}.

/*
** Read samples and process them into the rpt table
*/

pgm-name = "dbidxanalysis.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}

/*
** Sort through the Index analysis stuff and do the same processing.
*/

FOR EACH Db_Idxanalysis  
    WHERE 
    Db_Idxanalysis.Idx_ResrcName  = Fathom-i-Resrc_Name AND
    Db_Idxanalysis.Site_ID   = Fathom-i-site_ID AND
    Db_Idxanalysis.Idx_Date GE Fathom-t-beg-date[1] AND      
    Db_Idxanalysis.Idx_Date LE Fathom-t-end-date[Fathom-i-periods] AND  
    Db_Idxanalysis.Idx_Time GE Fathom-t-beg-time[1] AND      
    Db_Idxanalysis.Idx_Time LE Fathom-t-end-time[Fathom-i-periods]
    BY Db_Idxanalysis.Idx_TableName
    BY Db_Idxanalysis.Idx_IndexName
    BY Db_Idxanalysis.Idx_Date 
    BY Db_Idxanalysis.Idx_Time:
    /*
    ** Do the record counting stuff for totals
    */
    FIND FIRST hold-date WHERE
       h-date = Db_Idxanalysis.Idx_date AND
       h-time = Db_Idxanalysis.Idx_time NO-ERROR.
    IF NOT AVAILABLE hold-date THEN
    DO:
        Create hold-date.
        ASSIGN
            h-date = Db_Idxanalysis.Idx_date
            h-time = Db_Idxanalysis.Idx_time.
        Fathom-rec-count = fathom-rec-count + 1.
    END.
    /*
    ** Determine where in the date ranges this data fits into.
    */

    t-index-count = t-index-count + 1.
    Fathom-i = 0.
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Db_Idxanalysis.Idx_Date GE Fathom-t-beg-date[Fathom-i] AND
            Db_Idxanalysis.Idx_Date LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Db_Idxanalysis.Idx_Time GE Fathom-t-beg-time[Fathom-i] AND
            Db_Idxanalysis.Idx_Time LE Fathom-t-end-time[Fathom-i] THEN
            LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    /*
    ** Determine if the record already exists.  If it does add to it, if it
    ** doesn't create it and add to it.
    */

    FIND FIRST tt-data WHERE
        Db_Idxanalysis.Idx_AreaName = tt-data.area-name AND
        Db_Idxanalysis.Idx_TableName = tt-data.Table-name AND
        Db_Idxanalysis.Idx_IndexName = tt-data.Index-name AND
        Db_Idxanalysis.Idx_Date GE Fathom-t-beg-date[1] AND      
        Db_Idxanalysis.Idx_Date LE Fathom-t-end-date[Fathom-i-periods] AND  
        Db_Idxanalysis.Idx_Time GE Fathom-t-beg-time[1] AND      
        Db_Idxanalysis.Idx_Time LE Fathom-t-end-time[Fathom-i-periods] NO-ERROR.
	
    IF AVAILABLE tt-data THEN
    DO:
        /*
	** Check to see if the table has changed.
	*/
        IF save-tablename NE tt-data.Table-name THEN
	DO:
	    RELEASE tt-data.
	    CREATE tt-data.
	    ASSIGN
                table-name = Db_Idxanalysis.Idx_Tablename
                area-name = Db_Idxanalysis.Idx_AreaName
                lable = ""
	        save-tablename = Db_Idxanalysis.Idx_Tablename.
	END.
    END.
    ELSE
    DO:
	CREATE tt-data.
	ASSIGN
            table-name = Db_Idxanalysis.Idx_Tablename
            index-name = Db_Idxanalysis.Idx_Indexname
            area-name = Db_Idxanalysis.Idx_AreaName
            lable = ""
	    save-tablename = Db_Idxanalysis.Idx_Tablename.
    END.

    i-rec-count[fathom-i] = i-rec-count[fathom-i] + 1.
      
    ASSIGN
	i-avg-blocks[fathom-i] = i-max-blocks[fathom-i] + 
	    Db_Idxanalysis.Idx_blocks
	i-avg-bytes[fathom-i] = i-avg-bytes[fathom-i] + 
	    Db_Idxanalysis.Idx_Bytes
	i-avg-utilpct[fathom-i] = i-avg-utilpct[fathom-i] + 
	    Db_Idxanalysis.Idx_UtilizationPct
	i-avg-levels[fathom-i] = i-avg-levels[fathom-i] + 
	    Db_Idxanalysis.Idx_levels.

     IF Max-Records LT Db_IdxAnalysis.Idx_blocks THEN Max-Records = Db_Idxanalysis.Idx_blocks.

	IF i-max-blocks[fathom-i] LT Db_Idxanalysis.Idx_blocks THEN
	    i-max-blocks[fathom-i] = Db_Idxanalysis.Idx_blocks.
	IF i-min-blocks[fathom-i] GT Db_Idxanalysis.Idx_blocks THEN
	    i-min-blocks[fathom-i] = Db_Idxanalysis.Idx_blocks.

	IF i-max-bytes[fathom-i] LT Db_Idxanalysis.Idx_Bytes THEN
	    i-max-bytes[fathom-i] = Db_Idxanalysis.Idx_Bytes.
	IF i-min-bytes[fathom-i] GT Db_Idxanalysis.Idx_Bytes THEN
	    i-min-bytes[fathom-i] = Db_Idxanalysis.Idx_Bytes.

	IF i-max-utilpct[fathom-i] LT Db_Idxanalysis.Idx_UtilizationPct THEN
	    i-max-utilpct[fathom-i] = Db_Idxanalysis.Idx_UtilizationPct.
	IF i-min-utilpct[fathom-i] GT Db_Idxanalysis.Idx_UtilizationPct THEN
	    i-min-utilpct[fathom-i] = Db_Idxanalysis.Idx_UtilizationPct.

	IF i-max-levels[fathom-i] LT Db_Idxanalysis.Idx_levels THEN
	    i-max-levels[fathom-i] = Db_Idxanalysis.Idx_levels.
	IF i-min-levels[fathom-i] GT Db_Idxanalysis.Idx_levels THEN
	    i-min-levels[fathom-i] = Db_Idxanalysis.Idx_levels.

END. /* of FOR EACH DB_Idxanalysis */

pgm-name = "dbidxanalysis.p".
sec-name = "Finished gathering Index Samples".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }
/* OUTPUT STREAM ReportOutput TO VALUE(Fathom-t-rep_name) APPEND.

OUTPUT STREAM ReportOutput CLOSE.*/

RUN xml-dbidxanalysis.p.

pgm-name = "dbidxanalysis.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** dbindexstat.p
** This program will present a trend report for index statistics.  This is 
** based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/*
** Define temp table for stroring results
*/

DEF NEW GLOBAL SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS CHARACTER
   FIELD Name2 AS CHARACTER FORMAT "X(28)"
   FIELD TableName AS CHARACTER FORMAT "x(28)"
   FIELD Type AS CHARACTER 
   FIELD reads AS DECIMAL EXTENT 366
   FIELD splits AS DECIMAL  EXTENT 366
   FIELD creates AS DECIMAL  EXTENT 366
   FIELD deletes AS DECIMAL EXTENT 366
   INDEX three NAME2
   INDEX one Type Name2.

DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.

/* 
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/

sec-name = "Processing Samples".
pgm-name = "dbindexstat.p".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}


{include/sample-query.i}

{include/setup-i.i}
      
/* 
** Increment Counters
*/

    /* See 2003 09 11-030. */
    /*{include/fathom-counters.i}*/
    FIND FIRST db_IndexStat
        WHERE cf_sample.sample_id = DB_IndexStat.sample_id NO-LOCK NO-ERROR.
    IF AVAILABLE Db_IndexStat THEN
    DO:
       Fathom-Rec-Count = Fathom-Rec-Count + 1.
       Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Cf_Sample.Sample_Len.
       Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Cf_Sample.Sample_Trans.
       release Db_IndexStat.
    END.
      
      FOR EACH db_IndexStat
          WHERE
          cf_sample.sample_id = DB_IndexStat.sample_id:

          FIND FIRST data_store
              WHERE
              data_store.name = STRING (Db_IndexStat.IndexStat_IdxNum)
              NO-ERROR.
          IF NOT AVAILABLE data_store THEN 
          DO:
              CREATE data_store.
              ASSIGN data_store.name = STRING (DB_IndexStat.IndexStat_IdxNum)
                     data_store.TableName = DB_IndexStat.IndexStat_TableName
                     data_store.name2 = DB_IndexStat.IndexStat_IndexName.
          END.
          ASSIGN
              data_store.reads[Fathom-i] = data_store.reads[Fathom-i] + Db_IndexStat.IndexStat_Read
              data_store.splits[Fathom-i] = data_store.splits[Fathom-i] + Db_IndexStat.IndexStat_Split
              data_store.creates[Fathom-i] = data_store.creates[Fathom-i] + Db_IndexStat.IndexStat_Create
              data_store.deletes[Fathom-i] = data_store.deletes[Fathom-i] + Db_IndexStat.IndexStat_Delete
              Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

      END. /* of FOR EACH DB_ActServ */

      IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
      ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).

   END. /* of assignment of FOR EACH */

   /*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "dbindexstat.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "dbindexstat.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    /*
    ** We need to make sure certain counters only get incremented once
    ** per day or hour, depending on the report type.
    */
    DEFINE TEMP-TABLE counterTester
        FIELD startTime AS INTEGER
        FIELD startDate AS DATE.

    {include/archive-type.i}.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_IndexStat:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_IndexStat WHERE " +
                     "Ar_IndexStat.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_IndexStat.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_IndexStat.IndexStat_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_IndexStat.IndexStat_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_IndexStat.IndexStat_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_IndexStat.IndexStat_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_IndexStat.IndexStat_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.
    
        /*
        ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
        */
        CASE Fathom-i-intervaltype:
            WHEN "R" THEN fathom-store-value = indexstat_Recordcount.
            WHEN "S" THEN fathom-store-value = indexstat_length.
            WHEN "M" THEN fathom-store-value = indexstat_length / 60.
            WHEN "H" THEN fathom-store-value = indexstat_length / 60 / 60.
            WHEN "T" THEN fathom-store-value = indexstat_transactions.
            OTHERWISE fathom-store-value = 1.
        END CASE.
    
        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        Fathom-i = 0.
    
        /* 
        ** Determine which date column the record falls into
        */
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_IndexStat.IndexStat_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_IndexStat.IndexStat_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
                IF Ar_IndexStat.IndexStat_starttime GE Fathom-t-beg-time[Fathom-i] AND
                     Ar_IndexStat.IndexStat_starttime LE Fathom-t-end-time[Fathom-i] THEN
                     LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.

        /*
        ** Process the counters
        */
        FIND FIRST counterTester WHERE
            startDate EQ Ar_IndexStat.IndexStat_StartDate AND
            startTime EQ Ar_IndexStat.IndexStat_StartTime NO-ERROR.

        IF NOT AVAILABLE counterTester THEN
        DO:
            Fathom-Rec-Count = 
               Fathom-Rec-Count + ar_indexstat.indexstat_RecordCount.
            Fathom-Interval-Count[Fathom-i] = 
               Fathom-Interval-Count[Fathom-i] + ar_indexstat.indexstat_Length.
            Fathom-Transaction-Count[Fathom-i] = 
               Fathom-Transaction-Count[Fathom-i] + ar_indexstat.indexstat_Transactions.
            Fathom-Interval-recs[fathom-i] = 
               Fathom-Interval-recs[fathom-i] + 1.
            CREATE counterTester.
            ASSIGN
                startDate = Ar_IndexStat.IndexStat_StartDate
                startTime = Ar_IndexStat.IndexStat_StartTime.
        END.

        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store
            WHERE
            data_store.name = STRING (ar_IndexStat.IndexStat_IdxNum)
            NO-ERROR.
        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN data_store.name = STRING (Ar_IndexStat.IndexStat_IdxNum)
                data_store.TableName = Ar_IndexStat.IndexStat_TableName
                data_store.name2 = Ar_IndexStat.IndexStat_IndexName.
        END.
        ASSIGN
            data_store.reads[Fathom-i] = 
                data_store.reads[Fathom-i] + Ar_IndexStat.IndexStat_Read 
            data_store.splits[Fathom-i] = 
                data_store.splits[Fathom-i] + Ar_IndexStat.IndexStat_Split 
            data_store.creates[Fathom-i] = 
                data_store.creates[Fathom-i] + Ar_IndexStat.IndexStat_Create 
            data_store.deletes[Fathom-i] = 
                data_store.deletes[Fathom-i] + Ar_IndexStat.IndexStat_Delete.

    END. /* of REPEAT. */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

    pgm-name = "dbindexstat.p".
    sec-name = "Completed accessing archive information".
    {include/debug.i "pgm-name" "sec-name"}.

END. /* of date tests */

/*
** Print Section
*/
sec-name = "Printing Output".
pgm-name = "dbindexstat.p".
{include/debug.i "pgm-name" "sec-name"}.

{ include/report-name.i }.

RUN xml-dbindexstat.p.

sec-name = "Exiting Program".
pgm-name = "dbindexstat.p".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** This program is an intermediate program for trenddbsingle.p
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

    Fathom-t-rep_type = "dblocks".

RUN src/trendDBsingle.p.
/*
** This program is an intermediate program for trenddbsingle.p
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

    fathom-t-rep_type = "dbmem".

RUN src/trendDBsingle.p.
/*
** This program is an intermediate program for trenddbsingle.p
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

    Fathom-t-rep_type = "dbrec".

RUN src/trendDBsingle.p.
/*
** trendservers.p
** This program will present a trend report for Server Information.  This is 
** based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

{include/report-name.i}.

/* 
** Define Temp table to store results.
*/

DEF NEW GLOBAL SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name     AS character 
   FIELD Type     AS character 
   FIELD msgrec   AS DECIMAL EXTENT 366
   FIELD msgsent  AS DECIMAL EXTENT 366
   FIELD byterec  AS DECIMAL EXTENT 366
   FIELD bytesent AS DECIMAL EXTENT 366
   FIELD recrec   AS DECIMAL EXTENT 366
   FIELD recsent  AS DECIMAL EXTENT 366
   FIELD minusers AS DECIMAL EXTENT 366
   FIELD maxusers AS DECIMAL EXTENT 366
   FIELD avgusers AS DECIMAL EXTENT 366
   FIELD seconds  AS DECIMAL EXTENT 366
   INDEX two TYPE 
   INDEX three NAME.

/* 
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}

/*
** Read the resource record for resource ID
*/
{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/

sec-name = "Processing Samples".
pgm-name = "dbserver.p".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

{include/sample-query.i}

{include/setup-i.i}
      
/*
** Increment Counters
*/

    /* See 2003 09 11-030. */
    /*{include/fathom-counters.i}*/

    /* Add length and transactions only once for each sample. */
    FIND FIRST db_ActServ WHERE cf_sample.sample_id = db_ActServ.sample_id NO-ERROR.
    IF AVAILABLE db_ActServ THEN
    DO:
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Cf_Sample.Sample_Len.
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Cf_Sample.Sample_Trans.
    END.
      
        FOR EACH db_ActServ
            WHERE
            cf_sample.sample_id = db_ActServ.sample_id:

            FIND FIRST data_store
                WHERE
                data_store.NAME = STRING (Db_ActServ.ActServ_Num)
                NO-ERROR.
            IF NOT AVAILABLE data_store THEN 
            DO:
                CREATE data_store.
                ASSIGN 
                    data_store.NAME = STRING (Db_ActServ.ActServ_Num)
                    data_store.TYPE = Db_ActServ.ActServ_Type.
            END.
            ASSIGN
                data_store.msgrec[Fathom-i] = data_store.msgrec[Fathom-i] + Db_ActServ.ActServ_MsgRec
                data_store.msgsent[Fathom-i] = data_store.msgsent[Fathom-i] + Db_ActServ.ActServ_MsgSent
                data_store.byterec[Fathom-i] = data_store.byterec[Fathom-i] + Db_ActServ.ActServ_ByteRec
                data_store.bytesent[Fathom-i] = data_store.bytesent[Fathom-i] + Db_ActServ.ActServ_ByteSent
                data_store.recrec[Fathom-i] = data_store.recrec[Fathom-i] + Db_ActServ.ActServ_RecRec
                data_store.recsent[Fathom-i] = data_store.recsent[Fathom-i] + Db_ActServ.ActServ_RecSent
                data_store.avgusers[Fathom-i] = data_store.avgusers[Fathom-i] +
                                                (Db_ActServ.ActServ_currusers *
                                                 Cf_Sample.Sample_Len)
                Fathom-Rec-Count = Fathom-Rec-Count + 1
                Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1
                data_store.seconds[Fathom-i] = data_store.seconds[Fathom-i] + Cf_Sample.Sample_Len.
          
            /* Min User Counts */
            IF data_store.minusers[Fathom-i] LT 1 THEN 
                DO:
                data_store.minusers[Fathom-i] = DB_ActServ.ActServ_Currusers.
            END.
            ELSE IF Db_ActServ.ActServ_CurrUsers GT 0 THEN 
                DO:
                IF data_store.minusers[Fathom-i] GT Db_ActServ.ActServ_CurrUsers THEN
                    data_store.minusers[Fathom-i] = Db_ActServ.ActServ_CurrUsers.
            END.
          
            /* Max User Counts */
            IF data_store.maxusers[Fathom-i] LT 1 THEN 
            DO:
                data_store.maxusers[Fathom-i] = Db_ActServ.ActServ_MaxUsers.
            END.
            ELSE IF Db_ActServ.ActServ_MaxUsers GT 0 THEN 
            DO:
                IF Db_ActServ.ActServ_MaxUsers GT data_store.maxusers[Fathom-i] THEN
                    data_store.maxusers[Fathom-i] = Db_ActServ.ActServ_MaxUsers.
            END.
        END. /* of FOR EACH DB_ActServ */
           
        IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
        ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN
            fathom-ar-date = (cf_sample.sample_date - 1).

    END. /* of assignment of FOR EACH */

/*
** DO Processing for archive information
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "dbserver.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    /*
    ** We only want the transaction and length counts to increment once
    ** for each set of servers, not on each server.  This will keep
    ** track of periods so that these metrics are only updated once per,
    ** say, 5 servers.
    */
    DEFINE TEMP-TABLE counterTester
        FIELD startTime AS INTEGER
        FIELD startDate AS DATE.

    {include/archive-type.i}.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_ActServ:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_ActServ WHERE " +
                     "Ar_ActServ.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_ActServ.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_ActServ.ActServ_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_ActServ.ActServ_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_ActServ.ActServ_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_ActServ.ActServ_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_ActServ.ActServ_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.

        /* 
        ** Determine which date column the record falls into
        */
        Fathom-i = 0.
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_ActServ.ActServ_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_ActServ.ActServ_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
                IF Ar_ActServ.ActServ_starttime GE Fathom-t-beg-time[Fathom-i] AND
                    Ar_ActServ.ActServ_starttime LE Fathom-t-end-time[Fathom-i] THEN
                    LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.


        FIND FIRST counterTester WHERE
            startDate EQ Ar_ActServ.ActServ_StartDate AND
            startTime EQ Ar_ActServ.ActServ_StartTime NO-ERROR.

        IF NOT AVAILABLE counterTester THEN
        DO:
            Fathom-Interval-Count[Fathom-i]    = Fathom-Interval-Count[Fathom-i]    + Ar_ActServ.ActServ_Length.
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_ActServ.ActServ_Transactions.
            CREATE counterTester.
            ASSIGN
                startDate = Ar_ActServ.ActServ_StartDate
                startTime = Ar_ActServ.ActServ_StartTime.
        END.

        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store
        WHERE
        data_store.NAME = STRING (Ar_ActServ.ActServ_Num)
        NO-ERROR.
   
        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.NAME = STRING (Ar_ActServ.ActServ_Num)
                data_store.TYPE = Ar_ActServ.ActServ_Type.
        END.

        ASSIGN
            data_store.msgrec[Fathom-i]    = data_store.msgrec[Fathom-i]    + Ar_ActServ.ActServ_MsgRec
            data_store.msgsent[Fathom-i]   = data_store.msgsent[Fathom-i]   + Ar_ActServ.ActServ_MsgSent
            data_store.byterec[Fathom-i]   = data_store.byterec[Fathom-i]   + Ar_ActServ.ActServ_ByteRec
            data_store.bytesent[Fathom-i]  = data_store.bytesent[Fathom-i]  + Ar_ActServ.ActServ_ByteSent
            data_store.recrec[Fathom-i]    = data_store.recrec[Fathom-i]    + Ar_ActServ.ActServ_RecRec
            data_store.recsent[Fathom-i]   = data_store.recsent[Fathom-i]   + Ar_ActServ.ActServ_RecSent
            data_store.avgusers[Fathom-i]  = data_store.avgusers[Fathom-i]  +
                                             (Ar_ActServ.ActServ_currusers *
                                              Ar_ActServ.ActServ_Length)
            Fathom-Rec-Count               = Fathom-Rec-Count               + Ar_ActServ.ActServ_RecordCount
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + Ar_ActServ.ActServ_RecordCount
            Fathom-ar-count[1]             = Fathom-ar-count[1] + 1
            data_store.seconds[Fathom-i]   = data_store.seconds[Fathom-i]   + Ar_ActServ.ActServ_Length.
      
        /* Min User Counts */
        IF data_store.minusers[Fathom-i] LT 1 THEN 
        DO:
            data_store.minusers[Fathom-i] = -1.
        END.
      
        /* Max User Counts */
        IF data_store.maxusers[Fathom-i] LT 1 THEN 
        DO:
            data_store.maxusers[Fathom-i] = Ar_ActServ.ActServ_MaxUsers.
        END.
        ELSE IF Ar_ActServ.ActServ_MaxUsers GT 0 THEN 
        DO:
            IF Ar_ActServ.ActServ_MaxUsers GT data_store.maxusers[Fathom-i] THEN 
                data_store.maxusers[Fathom-i] = Ar_ActServ.ActServ_MaxUsers.
        END.

        pgm-name = "dbserver.p".
        sec-name = "Accessing Archive Information Complete".
        {include/debug.i "pgm-name" "sec-name"}.

    END. /* of REPEAT. */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

END. /* of Date testing */


/*
** Print Section
*/
RUN xml-dbserver.p.

sec-name = "Exiting Program".
pgm-name = "dbserver.p".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** This program is an intermediate program for trenddbsingle.p
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

Fathom-t-rep_type = "dbsum".

RUN src/trendDBsingle.p.
/*
** dbtabanalysis.p
** This program will present a trend report for table analysis and index analysis.
** This is based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Number, the resource ID and the Site ID.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:

    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Set up local variables 
*/

    DEF VAR t-table-count AS DECIMAL NO-UNDO.
    DEF VAR t-index-count AS DECIMAL NO-UNDO.
    DEF VAR t-hold-areaname AS CHARACTER NO-UNDO.
    DEF VAR t-hold-tablename AS CHARACTER NO-UNDO.
    DEF VAR t-hold-indexname AS CHARACTER NO-UNDO.
    DEF VAR t-output-value AS DECIMAL NO-UNDO.
    DEF VAR t-display-count AS INTEGER NO-UNDO.
    DEF VAR save-tablename AS CHARACTER NO-UNDO.

    DEF NEW SHARED TEMP-TABLE hold-date
       FIELD h-date AS DATE 
       FIELD h-time AS INTEGER 
       INDEX one h-date
       INDEX two h-time.
       
    DEF NEW GLOBAL SHARED TEMP-TABLE tt-data
        FIELD table-name as CHARACTER
        FIELD area-name as CHARACTER
        FIELD lable as CHARACTER
	FIELD Max-records as DECIMAL
	FIELD r-rec-count as DECIMAL EXTENT 366
	FIELD r-max-reccount as DECIMAL EXTENT 366
	FIELD r-min-reccount as DECIMAL EXTENT 366
	FIELD r-avg-reccount as DECIMAL EXTENT 366
	FIELD r-max-bytes as DECIMAL EXTENT 366
	FIELD r-min-bytes as DECIMAL EXTENT 366
	FIELD r-avg-bytes as DECIMAL EXTENT 366
	FIELD r-max-fragcount as DECIMAL EXTENT 366
	FIELD r-min-fragcount as DECIMAL EXTENT 366
	FIELD r-avg-fragcount as DECIMAL EXTENT 366
	FIELD r-max-scatter as DECIMAL EXTENT 366
	FIELD r-min-scatter as DECIMAL EXTENT 366
	FIELD r-avg-scatter as DECIMAL EXTENT 366
	INDEX one table-name
	INDEX three area-name
	INDEX two Max-records DESCENDING
	.
/*
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}.

/*
** Read samples and process them into the rpt table
*/

pgm-name = "dbtabanalysis.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}

/* Standard Sample query used in most programs */

FOR EACH Db_Tabanalysis  
    WHERE 
    Db_Tabanalysis.Tab_ResrcName = Fathom-i-Resrc_Name AND
    Db_Tabanalysis.Site_ID   = Fathom-i-site_ID AND
    Db_Tabanalysis.Tab_Date GE Fathom-t-beg-date[1] AND      
    Db_Tabanalysis.Tab_Date LE Fathom-t-end-date[Fathom-i-periods] AND  
    Db_Tabanalysis.Tab_Time GE Fathom-t-beg-time[1] AND      
    Db_Tabanalysis.Tab_Time LE Fathom-t-end-time[Fathom-i-periods]
    BY Db_Tabanalysis.Tab_TableName
    BY Db_Tabanalysis.Tab_Date 
    BY Db_Tabanalysis.Tab_Time:

    /*
    ** Do the record counting stuff for totals
    */
    FIND FIRST hold-date WHERE
       h-date = Db_Tabanalysis.tab_date AND
       h-time = Db_Tabanalysis.tab_time NO-ERROR.
    IF NOT AVAILABLE hold-date THEN
    DO:
        Create hold-date.
        ASSIGN
            h-date = Db_Tabanalysis.tab_date
            h-time = Db_Tabanalysis.tab_time.
        Fathom-rec-count = fathom-rec-count + 1.
    END.
    /*
    ** Determine where in the date ranges this data fits into.
    */

    t-table-count = t-table-count + 1.
    Fathom-i = 0.
    REPEAT:
        Fathom-i = Fathom-i + 1.
        IF Db_Tabanalysis.Tab_Date GE Fathom-t-beg-date[Fathom-i] AND
            Db_Tabanalysis.Tab_Date LE Fathom-t-end-date[Fathom-i] THEN
        DO:
            IF Db_Tabanalysis.Tab_Time GE Fathom-t-beg-time[Fathom-i] AND
            Db_Tabanalysis.Tab_Time LE Fathom-t-end-time[Fathom-i] THEN
            LEAVE.
        END.
        IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
    END.

    /*
    ** Determine if the record already exists.  If it does add to it, if it
    ** doesn't create it and add to it.
    */

    FIND FIRST tt-data WHERE
        Db_Tabanalysis.Tab_AreaName = tt-data.area-name AND
        Db_Tabanalysis.Tab_TableName = tt-data.Table-name AND
        Db_Tabanalysis.Tab_Date GE Fathom-t-beg-date[1] AND      
        Db_Tabanalysis.Tab_Date LE Fathom-t-end-date[Fathom-i-periods] AND  
        Db_Tabanalysis.Tab_Time GE Fathom-t-beg-time[1] AND      
        Db_Tabanalysis.Tab_Time LE Fathom-t-end-time[Fathom-i-periods] NO-ERROR.
	
    IF AVAILABLE tt-data THEN
    DO:
        /*
	** Check to see if the table has changed.
	*/
        IF save-tablename NE tt-data.Table-name THEN
	DO:
	    RELEASE tt-data.
	    CREATE tt-data.
	    ASSIGN
                table-name = Db_Tabanalysis.Tab_Tablename
                area-name = Db_Tabanalysis.Tab_AreaName
                lable = ""
	        save-tablename = Db_Tabanalysis.Tab_Tablename.
	END.
    END.
    ELSE
    DO:
	CREATE tt-data.
	ASSIGN
            table-name = Db_Tabanalysis.Tab_Tablename
            area-name = Db_Tabanalysis.Tab_AreaName
            lable = ""
	    save-tablename = Db_Tabanalysis.Tab_Tablename.
    END.

    r-rec-count[fathom-i] = r-rec-count[fathom-i] + 1.
      
    ASSIGN
	r-avg-reccount[fathom-i] = r-max-reccount[fathom-i] + 
	    Db_Tabanalysis.Tab_RecordCount
	r-avg-bytes[fathom-i] = r-avg-bytes[fathom-i] + 
	    Db_Tabanalysis.Tab_Bytes
	r-avg-fragcount[fathom-i] = r-avg-fragcount[fathom-i] + 
	    Db_Tabanalysis.Tab_FragmentCount
	r-avg-scatter[fathom-i] = r-avg-scatter[fathom-i] + 
	    Db_Tabanalysis.Tab_Scatterfactor.

        IF Max-Records LT Db_Tabanalysis.Tab_RecordCount THEN
	    Max-records = Db_Tabanalysis.Tab_RecordCount.

	IF r-max-reccount[fathom-i] LT Db_Tabanalysis.Tab_RecordCount THEN
	    r-max-reccount[fathom-i] = Db_Tabanalysis.Tab_RecordCount.
	IF r-min-reccount[fathom-i] GT Db_Tabanalysis.Tab_RecordCount THEN
	    r-min-reccount[fathom-i] = Db_Tabanalysis.Tab_RecordCount.

	IF r-max-bytes[fathom-i] LT Db_Tabanalysis.Tab_Bytes THEN
	    r-max-bytes[fathom-i] = Db_Tabanalysis.Tab_Bytes.
	IF r-min-bytes[fathom-i] GT Db_Tabanalysis.Tab_Bytes THEN
	    r-min-bytes[fathom-i] = Db_Tabanalysis.Tab_Bytes.

	IF r-max-fragcount[fathom-i] LT Db_Tabanalysis.Tab_FragmentCount THEN
	    r-max-fragcount[fathom-i] = Db_Tabanalysis.Tab_FragmentCount.
	IF r-min-fragcount[fathom-i] GT Db_Tabanalysis.Tab_FragmentCount THEN
	    r-min-fragcount[fathom-i] = Db_Tabanalysis.Tab_FragmentCount.

	IF r-max-scatter[fathom-i] LT Db_Tabanalysis.Tab_Scatterfactor THEN
	    r-max-scatter[fathom-i] = Db_Tabanalysis.Tab_Scatterfactor.
	IF r-min-scatter[fathom-i] GT Db_Tabanalysis.Tab_Scatterfactor THEN
	    r-min-scatter[fathom-i] = Db_Tabanalysis.Tab_Scatterfactor.

END. /* of FOR EACH DB_Tabanalysis */

pgm-name = "dbtabanalysis.p".
sec-name = "Finished gathering table samples".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }

RUN xml-dbtabanalysis.p.

pgm-name = "dbtabanalysis.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** dbtablestat.p
** This program will present a trend report for table statistics.  This is 
** based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Define temp tables to store results
*/

DEF NEW GLOBAL SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS CHARACTER
   FIELD name2 AS CHARACTER FORMAT "X(28)"
   FIELD Type AS CHARACTER 
   FIELD reads AS DECIMAL EXTENT 366
   FIELD updates AS DECIMAL  EXTENT 366
   FIELD creates AS DECIMAL  EXTENT 366
   FIELD deletes AS DECIMAL EXTENT 366
   INDEX three NAME2
   INDEX one Type name2.

DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.

/* 
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}

/*
** Read the resource record for resource ID
*/
{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/

sec-name = "Processing Samples".
pgm-name = "Dbtablestat.p".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

{include/sample-query.i}

{include/setup-i.i}
      
/*
** Increment Reporting Counters
*/
    /* See 2003 09 11-030. */
    /*{include/fathom-counters.i}*/
    FIND FIRST DB_TableStat
        WHERE cf_sample.sample_id = DB_TableStat.sample_id NO-LOCK NO-ERROR.
    IF AVAILABLE DB_TableStat THEN
    DO:
              Fathom-Rec-Count = Fathom-Rec-Count + 1.
       Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Cf_Sample.Sample_Len.
       Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Cf_Sample.Sample_Trans.
    END.
 
      FOR EACH db_TableStat
          WHERE
          cf_sample.sample_id = DB_TableStat.sample_id:

          FIND FIRST data_store
              WHERE
              data_store.name = STRING (Db_TableStat.TableStat_TableID)
              NO-ERROR.
          IF NOT AVAILABLE data_store THEN 
          DO:
              CREATE data_store.
              ASSIGN 
                  data_store.name = STRING (DB_TableStat.TableStat_TableID)
                  data_store.name2 = Db_TableStat.TableStat_TableName.
          END.
          ASSIGN
              data_store.reads[Fathom-i] = data_store.reads[Fathom-i] + Db_TableStat.TableStat_Read
              data_store.updates[Fathom-i] = data_store.updates[Fathom-i] + Db_TableStat.TableStat_Update
              data_store.creates[Fathom-i] = data_store.creates[Fathom-i] + Db_TableStat.TableStat_Create
              data_store.deletes[Fathom-i] = data_store.deletes[Fathom-i] + Db_TableStat.TableStat_Delete
              Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

      END. /* of FOR EACH DB_ActServ */
            
      IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
      ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).

   END. /* of assignment of FOR EACH */
   
/*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "dbtablestat.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "dbtablestat.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    /*
    ** We need to make sure certain counters only get incremented once
    ** per day or hour, depending on the report type.
    */
    DEFINE TEMP-TABLE counterTester
        FIELD startTime AS INTEGER
        FIELD startDate AS DATE.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_TableStat:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_TableStat WHERE " +
                     "Ar_TableStat.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_TableStat.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_TableStat.TableStat_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_TableStat.TableStat_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_TableStat.TableStat_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_TableStat.TableStat_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_TableStat.TableStat_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.
    
        /*
        ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
        */
        CASE Fathom-i-intervaltype:
            WHEN "R" THEN fathom-store-value = tablestat_Recordcount.
            WHEN "S" THEN fathom-store-value = tablestat_length.
            WHEN "M" THEN fathom-store-value = tablestat_length / 60.
            WHEN "H" THEN fathom-store-value = tablestat_length / 60 / 60.
            WHEN "T" THEN fathom-store-value = tablestat_transactions.
            OTHERWISE fathom-store-value = 1.
        END CASE.
    
        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        Fathom-i = 0.
    
        /* 
        ** Determine which date column the record falls into
        */
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_TableStat.TableStat_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_TableStat.TableStat_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
                IF Ar_TableStat.TableStat_starttime GE Fathom-t-beg-time[Fathom-i] AND
                    Ar_TableStat.TableStat_starttime LE Fathom-t-end-time[Fathom-i] THEN
                    LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.
        
        FIND FIRST counterTester WHERE
            startDate EQ Ar_TableStat.TableStat_StartDate AND
            startTime EQ Ar_TableStat.TableStat_StartTime NO-ERROR.

        IF NOT AVAILABLE counterTester THEN
        DO:
            Fathom-Rec-Count = Fathom-Rec-Count + ar_tablestat.tablestat_RecordCount.
            Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + ar_tablestat.tablestat_Length.
            Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + ar_tablestat.tablestat_Transactions.
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.
            CREATE counterTester.
            ASSIGN
                startDate = Ar_TableStat.TableStat_StartDate
                startTime = Ar_TableStat.TableStat_StartTime.
        END.

        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store
            WHERE
            data_store.name = STRING (Ar_TableStat.TableStat_TableID)
            NO-ERROR.
        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.name = STRING (Ar_TableStat.TableStat_TableID)
                data_store.name2 = Ar_TableStat.TableStat_TableName.
        END.
        ASSIGN
            data_store.reads[Fathom-i] = 
                data_store.reads[Fathom-i] + Ar_TableStat.TableStat_Read 
            data_store.updates[Fathom-i] = 
                data_store.updates[Fathom-i] + Ar_TableStat.TableStat_Update 
            data_store.creates[Fathom-i] = 
                data_store.creates[Fathom-i] + Ar_TableStat.TableStat_Create 
            data_store.deletes[Fathom-i] = 
                data_store.deletes[Fathom-i] + Ar_TableStat.TableStat_Delete.

    END. /* of REPEAT. */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

    pgm-name = "dbtablestat.p".
    sec-name = "Completed accessing archive information".
    {include/debug.i "pgm-name" "sec-name"}.

END. /* of date testing */

/*
** Print Section
*/
sec-name = "Printing Output".
pgm-name = "dbtablestat.p".
{include/debug.i "pgm-name" "sec-name"}.

{ include/report-name.i }.

RUN xml-dbtablestat.p.

sec-name = "Exiting Program".
pgm-name = "dbtablestat.p".
{include/debug.i "pgm-name" "sec-name"}


QUIT.

/* Program delete-hist.p
**
** This program will purge the archive history files based on the date provided.  It also has the capability to 
** do it specifically for each set of data (H,D,W).
**
** The following values are parsed from the -param command line:
**
** 1 - Date to purge older than.
** 2 - Action Code to be performed - possible codes are (H)ourly, (D)aily, (W)eekly. OPTIONAL!
** 
*/

{include/ar-definitions.i}

/* sec-name = "Starting Program".
{include/ar-debug.i "sec-name"} */

/*
** Main processing
**
** Start parsing the data and combining it based on compression type
**
*/
Case Fathom-i-ActionCode:
    WHEN "H" THEN
    DO:
        Fathom-t-ActionCode = "H".
        run purge-data.
    END.
    WHEN "D" THEN
    DO:
        Fathom-t-ActionCode = "W".
        run purge-data.
    END.
    WHEN "W" THEN
    DO:
        Fathom-t-ActionCode = "W".
        run purge-data.
    END.
    OTHERWISE
    DO:
        Fathom-t-ActionCode = "H".
        run purge-data.
        Fathom-t-ActionCode = "D".
        run purge-data.
        Fathom-t-ActionCode = "W".
        run purge-data.
    END.
END.

PROCEDURE purge-data.

        DO TRANSACTION:
           FOR EACH Ar_ActAPW WHERE
               Ar_ActAPW.ActAPW_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActAPW.ActAPW_StartDate LE Fathom-purgedate:
               DELETE Ar_ActAPW.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActBuf WHERE
               Ar_ActBuf.ActBuf_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActBuf.ActBuf_StartDate LE Fathom-purgedate:
               DELETE Ar_ActBuf.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActIdx WHERE
               Ar_ActIdx.ActIdx_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActIdx.ActIdx_StartDate LE Fathom-purgedate:
               DELETE Ar_ActIdx.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActIOFile WHERE
               Ar_ActIOFile.ActIOFile_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActIOFile.ActIOFile_StartDate LE Fathom-purgedate:
               DELETE Ar_ActIOFile.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActIOType WHERE
               Ar_ActIOType.ActIOType_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActIOType.ActIOType_StartDate LE Fathom-purgedate:
               DELETE Ar_ActIOType.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActLock WHERE
               Ar_ActLock.ActLock_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActLock.ActLock_StartDate LE Fathom-purgedate:
               DELETE Ar_ActLock.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActLog WHERE
               Ar_ActLog.ActLog_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActLog.ActLog_StartDate LE Fathom-purgedate:
               DELETE Ar_ActLog.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActRec WHERE
               Ar_ActRec.ActRec_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActRec.ActRec_StartDate LE Fathom-purgedate:
               DELETE Ar_ActRec.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActServ WHERE
               Ar_ActServ.ActServ_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActServ.ActServ_StartDate LE Fathom-purgedate:
               DELETE Ar_ActServ.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_ActSum WHERE
               Ar_ActSum.ActSum_ArchiveType = Fathom-t-ActionCode AND
               Ar_ActSum.ActSum_StartDate LE Fathom-purgedate:
               DELETE Ar_ActSum.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_AreaStatus WHERE
               Ar_AreaStatus.AreaStatus_ArchiveType = Fathom-t-ActionCode AND
               Ar_AreaStatus.AreaStatus_StartDate LE Fathom-purgedate:
               DELETE Ar_AreaStatus.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_Checkpoint WHERE
               Ar_Checkpoint.Checkpoint_ArchiveType = Fathom-t-ActionCode AND
               Ar_Checkpoint.Checkpoint_StartDate LE Fathom-purgedate:
               DELETE Ar_Checkpoint.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_CPU WHERE
               Ar_CPU.CPU_ArchiveType = Fathom-t-ActionCode AND
               Ar_CPU.CPU_StartDate LE Fathom-purgedate:
               DELETE Ar_CPU.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_Dev WHERE
               Ar_Dev.Dev_ArchiveType = Fathom-t-ActionCode AND
               Ar_Dev.Dev_StartDate LE Fathom-purgedate:
               DELETE Ar_Dev.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_FileSize WHERE
               Ar_FileSize.FileSize_ArchiveType = Fathom-t-ActionCode AND
               Ar_FileSize.FileSize_StartDate LE Fathom-purgedate:
               DELETE Ar_FileSize.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_FileSys WHERE
               Ar_FileSys.FileSys_ArchiveType = Fathom-t-ActionCode AND
               Ar_FileSys.FileSys_StartDate LE Fathom-purgedate:
               DELETE Ar_FileSys.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_IndexStat WHERE
               Ar_IndexStat.IndexStat_ArchiveType = Fathom-t-ActionCode AND
               Ar_IndexStat.IndexStat_StartDate LE Fathom-purgedate:
               DELETE Ar_IndexStat.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_Mem WHERE
               Ar_Mem.Mem_ArchiveType = Fathom-t-ActionCode AND
               Ar_Mem.Mem_StartDate LE Fathom-purgedate:
               DELETE Ar_Mem.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_Net_Data WHERE
               Ar_Net_Data.Net_ArchiveType = Fathom-t-ActionCode AND
               Ar_Net_Data.Net_StartDate LE Fathom-purgedate:
               DELETE Ar_Net_Data.
               hist-deleted = hist-deleted + 1.
           END.
        END.
        DO TRANSACTION:
           FOR EACH Ar_TableStat WHERE
               Ar_TableStat.TableStat_ArchiveType = Fathom-t-ActionCode AND
               Ar_TableStat.TableStat_StartDate LE Fathom-purgedate:
               DELETE Ar_TableStat.
               hist-deleted = hist-deleted + 1.
           END.
        END.
END PROCEDURE.
/* This program will drive the delete process for the following tables.  
**
** Cf_Alert_Detail
** Cf_Log
** Cf_Status
** Cf_Task_Detail
** Db_IdxAnalysis
** Db_TabAnalysis
**
** The following values are parsed from the -param command line:
**
** 1 - Time to archive older than (used only for hourly).
** 2 - Date to archive older than (used for daily and weekly).
** 3 - Site ID to archive (If no site ID then all sites are done).
** 4 - Resrc Name to delete (Only for idxanalysis and tabanalysis data)
** 5 - Table Name to delete or "ALL".  If nothing is provided then nothing is deleted.
** 
*/

{include/dd-setupdefs.i}
{include/dd-pass-input.i}

sec-name = "Starting Program".
{include/ar-debug.i "sec-name"}

/*
** Main processing
**
** Start parsing the data and combining it based on compression type
**
*/

IF Fathom-i-time NE ? THEN
DO:
    IF fathom-i-date NE ? THEN
    DO:
        If Fathom-i-Site-ID NE "" THEN
        DO:
            If Fathom-i-tablename NE "" THEN
            DO:
                CASE Fathom-i-tablename:
                    WHEN "ALL" THEN
                    DO:
                        Fathom-t-tablename = "Cf_Alert_Detail". 
                        RUN delete-cf_alert_detail.
                        Fathom-t-tablename = "Cf_Log". 
                        RUN delete-cf_log.
                        Fathom-t-tablename = "Cf_Status". 
                        RUN delete-cf_status.
                        Fathom-t-tablename = "Cf_Task_Detail". 
                        RUN delete-cf_task_detail.
                        
                        IF fathom-i-resrc-id NE -1 THEN
                        DO:
                            Fathom-t-tablename = "Db_IdxAnalysis". 
                            RUN delete-db_idxanalysis.
                            Fathom-t-tablename = "Db_TabAnalysis". 
                            RUN delete-db_tabanalysis.
                        END.
                    END.
                    OTHERWISE
                    DO:
                        IF fathom-t-tablename = "db_idxanalysis" OR
                            fathom-t-tablename = "db_tabanalysis" THEN
                        DO:
                            IF fathom-i-resrc-id = -1 THEN LEAVE.
                        END.
                        Fathom-t-tablename = Fathom-i-tablename. 
                        RUN VALUE ("delete-" + fathom-t-tablename).
                    END.
                END CASE.
                
                /*
                ** Log details of purge to database log file.
                */

                Fathom-t-msg1 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "Begin Data Purge.  Purging data older than " + 
                                STRING (Fathom-i-date).

                Fathom-t-msg2 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "Deleting Data - Status Records Deleted : " + 
                                STRING (Fathom-status-count).

                Fathom-t-msg3 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "Deleting Data - Log Records Deleted : " + 
                                STRING (Fathom-log-count).

                Fathom-t-msg4 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "Deleting Data - Alert Detail Records Deleted : " + 
                                STRING (Fathom-alertdetail-count).

                {include/ar-log-msgs.i}
                
                Fathom-t-msg1 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "Deleting Data - Alert Detail Records Deleted : " + 
                                STRING (Fathom-alertdetail-count).

                Fathom-t-msg2 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "Deleting Data - Index Analysis Records Deleted : " + 
                                STRING (Fathom-idxanalysis-count).

                Fathom-t-msg3 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "Deleting Data - Table Analysis Records Deleted : " + 
                                STRING (Fathom-tabanalysis-count).

                Fathom-t-msg4 = STRING (TIME, "HH:MM:SS") +
                                " ARCHIVE " + 
                                "   " +
                                "End Data Purge Process.  ".
                
                {include/ar-log-msgs.i}

            END.
            ELSE
            DO:
                PUT SKIP "ERROR - No table name information provided : ".
            END.
        END.
        ELSE
        DO:
            PUT SKIP "ERROR - No Site information available".
        END.
    END.
    ELSE
    DO:
        PUT SKIP "ERROR - No Date Information available".
    END.
END.

/*
** Begin Procedures
*/

PROCEDURE delete-cf_alert_detail.
    sec-name = "Deleting Cf_Alert_Detail".
    {include/ar-debug.i "sec-name"}
    DO TRANSACTION:
       FOR EACH cf_alert_detail WHERE
           cf_alert_detail.site_id = fathom-i-site-id AND
           cf_alert_detail.alert_date LE fathom-i-date:
           IF alert_date LT fathom-i-date THEN
           DO:
               DELETE cf_alert_detail.
           END.
           ELSE
           DO:
               IF cf_alert_detail.alert_time LE fathom-i-time THEN
               DO:
                   DELETE cf_alert_detail.
               END.
           END.
           Fathom-alertdetail-count = Fathom-alertdetail-count + 1.
       END.
    END.
END PROCEDURE.

PROCEDURE delete-cf_log.
    sec-name = "Deleting Cf_Log".
    {include/ar-debug.i "sec-name"}
    DO TRANSACTION:
       FOR EACH cf_log WHERE
           cf_log.site_id = fathom-i-site-id AND
           cf_log.log_date LE fathom-i-date:
           IF cf_log.log_date LT fathom-i-date THEN
           DO:
               DELETE cf_log.
           END.
           ELSE
           DO:
               IF cf_log.log_time LE fathom-i-time THEN
               DO:
                   DELETE cf_log.
               END.
           END.
           Fathom-log-count = Fathom-log-count + 1.
       END.
    END.
END PROCEDURE.

PROCEDURE delete-cf_status.
    sec-name = "Deleting Cf_Status".
    {include/ar-debug.i "sec-name"}
    DO TRANSACTION:
       FOR EACH cf_status WHERE
           cf_status.site_id = fathom-i-site-id AND
           cf_status.status_date LE fathom-i-date:
           IF cf_status.status_date LT fathom-i-date THEN
           DO:
               DELETE cf_status.
           END.
           ELSE
           DO:
               IF cf_status.status_time LE fathom-i-time THEN
               DO:
                   DELETE cf_status.
               END.
           END.
           Fathom-status-count = Fathom-status-count + 1.
       END.
    END.
END PROCEDURE.

PROCEDURE delete-Cf_task_detail.
    sec-name = "Deleting Cf_Task_Detail".
    {include/ar-debug.i "sec-name"}
    DO TRANSACTION:
       FOR EACH cf_task_detail WHERE
           cf_task_detail.site_id = fathom-i-site-id AND
           cf_task_detail.task_startdate LE fathom-i-date:
           IF cf_task_detail.task_startdate LT fathom-i-date THEN
           DO:
               DELETE cf_task_detail.
           END.
           ELSE
           DO:
               IF cf_task_detail.task_starttime LE fathom-i-time THEN
               DO:
                   DELETE cf_task_detail.
               END.
           END.
           Fathom-taskdetail-count = Fathom-taskdetail-count + 1.
       END.
    END.
END PROCEDURE.

PROCEDURE delete-db_idxanalysis.
    sec-name = "Deleting Db_IdxAnalysis".
    {include/ar-debug.i "sec-name"}
    DO TRANSACTION:
       FOR EACH db_idxanalysis WHERE
           db_idxanalysis.site_id = fathom-i-site-id AND
           db_idxanalysis.idx_date LE fathom-i-date:
           IF db_idxanalysis.idx_date LT fathom-i-date THEN
           DO:
               DELETE db_idxanalysis.
           END.
           ELSE
           DO:
               IF db_idxanalysis.idx_time LE fathom-i-time THEN
               DO:
                   DELETE db_idxanalysis.
               END.
           END.
           Fathom-idxanalysis-count = Fathom-idxanalysis-count + 1.
       END.
    END.
END PROCEDURE.

PROCEDURE delete-db_tabanalysis.
    sec-name = "Deleting Db_TabAnalysis".
    {include/ar-debug.i "sec-name"}
    DO TRANSACTION:
       FOR EACH db_tabanalysis WHERE
           db_tabanalysis.site_id = fathom-i-site-id AND
           db_tabanalysis.tab_date LE fathom-i-date:
           IF db_tabanalysis.tab_date LT fathom-i-date THEN
           DO:
               DELETE db_tabanalysis.
           END.
           ELSE
           DO:
               IF db_tabanalysis.tab_time LE fathom-i-time THEN
               DO:
                   DELETE db_tabanalysis.
               END.
           END.
           Fathom-tabanalysis-count = Fathom-tabanalysis-count + 1.
       END.
    END.
END PROCEDURE.

QUIT.
/*
** fathom-compile.p
** This program will compile code given an input file of sources
** and an output directory to save into.
** This is used for the nightly compiles of Fathom.
** NOTE: This does not deal too well with spaces  in the
** pathname (no surprise!)
*/

DEF VAR Input-file AS CHAR NO-UNDO FORMAT "x(255)".
DEF VAR out-dir AS CHAR NO-UNDO FORMAT "x(255)".
DEF VAR i AS INTEGER NO-UNDO.
DEF VAR input-program AS CHAR NO-UNDO FORMAT "x(255)".
DEF VAR output-program AS CHAR NO-UNDO FORMAT "x(255)".

/* 
** Process input parameter information 
*/

input-file = ENTRY (1, SESSION:PARAMETER) NO-ERROR.
out-dir = ENTRY (2, SESSION:PARAMETER) NO-ERROR.
output-program = ENTRY (3, SESSION:PARAMETER) NO-ERROR.

IF INPUT-file = "" THEN
DO:
    PUT SKIP "ERROR - NO input file provided".
    QUIT.
END.
IF out-dir = "" THEN
DO:
    PUT SKIP "ERROR - No output directory provided".
    QUIT.
END.
IF output-program = "" THEN
DO:
    output-program = "gen-compile.p".
END.

/* 
** Start processing the values and compiling them
*/

INPUT FROM VALUE(input-file).

OUTPUT TO VALUE(output-program).

REPEAT:
    IMPORT UNFORMATTED input-program.
    IF input-program NE "" THEN
    DO:
        input-program = 
            "compile " + 
            TRIM (input-program) + 
            " save into " + 
            out-dir + 
            ".".
        PUT SKIP input-program.
    END.
    ELSE LEAVE.
END.

OUTPUT CLOSE.

RUN VALUE (output-program).

/*
** Clean up after ourselves
*/

IF output-program = "gen-compile.p" THEN
DO:
    OS-DELETE VALUE (output-program).
END.

QUIT.
DROP INDEX "TAB_ID_Bytes" ON "Db_TabAnalysis"

DROP FIELD "TAB_Bytes" OF "Db_TabAnalysis"

.
PSC
cpstream=UTF-8
.
0000000098
ADD INDEX "CompactJob" ON "Ar_ActAPW"
  AREA "Trend_Data"
  INDEX-FIELD "ActAPW_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActAPW_StartDate" ASCENDING
  INDEX-FIELD "ActAPW_StartTime" ASCENDING
  INDEX-FIELD "ActAPW_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActBuf"
  AREA "Trend_Data"
  INDEX-FIELD "ActBuf_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActBuf_StartDate" ASCENDING
  INDEX-FIELD "ActBuf_StartTime" ASCENDING
  INDEX-FIELD "ActBuf_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActIdx"
  AREA "Trend_Data"
  INDEX-FIELD "ActIdx_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActIdx_StartDate" ASCENDING
  INDEX-FIELD "ActIdx_StartTime" ASCENDING
  INDEX-FIELD "ActIdx_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActIOFile"
  AREA "Trend_Data"
  INDEX-FIELD "ActIOFile_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActIOFile_FileName" ASCENDING
  INDEX-FIELD "ActIOFile_StartDate" ASCENDING
  INDEX-FIELD "ActIOFile_StartTime" ASCENDING
  INDEX-FIELD "ActIOFile_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActIOType"
  AREA "Trend_Data"
  INDEX-FIELD "ActIOType_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActIOType_StartDate" ASCENDING
  INDEX-FIELD "ActIOType_StartTime" ASCENDING
  INDEX-FIELD "ActIOType_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActLock"
  AREA "Trend_Data"
  INDEX-FIELD "ActLock_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActLock_StartDate" ASCENDING
  INDEX-FIELD "ActLock_StartTime" ASCENDING
  INDEX-FIELD "ActLock_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActLog"
  AREA "Trend_Data"
  INDEX-FIELD "ActLog_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActLog_StartDate" ASCENDING
  INDEX-FIELD "ActLog_StartTime" ASCENDING
  INDEX-FIELD "ActLog_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActRec"
  AREA "Trend_Data"
  INDEX-FIELD "ActRec_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActRec_StartDate" ASCENDING
  INDEX-FIELD "ActRec_StartTime" ASCENDING
  INDEX-FIELD "ActRec_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActServ"
  AREA "Trend_Data"
  INDEX-FIELD "ActServ_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActServ_Num" ASCENDING
  INDEX-FIELD "ActServ_StartDate" ASCENDING
  INDEX-FIELD "ActServ_StartTime" ASCENDING
  INDEX-FIELD "ActServ_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_ActSum"
  AREA "Trend_Data"
  INDEX-FIELD "ActSum_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActSum_StartDate" ASCENDING
  INDEX-FIELD "ActSum_StartTime" ASCENDING
  INDEX-FIELD "ActSum_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_AreaStatus"
  AREA "Trend_Data"
  INDEX-FIELD "AreaStatus_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "AreaStatus_Areanum" ASCENDING
  INDEX-FIELD "AreaStatus_StartDate" ASCENDING
  INDEX-FIELD "AreaStatus_StartTime" ASCENDING
  INDEX-FIELD "AreaStatus_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_Checkpoint"
  AREA "Trend_Data"
  INDEX-FIELD "Checkpoint_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "Checkpoint_StartDate" ASCENDING
  INDEX-FIELD "Checkpoint_StartTime" ASCENDING
  INDEX-FIELD "Checkpoint_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_CPU"
  AREA "Trend_Data"
  INDEX-FIELD "CPU_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "CPU_StartDate" ASCENDING
  INDEX-FIELD "CPU_StartTime" ASCENDING
  INDEX-FIELD "CPU_EndDate" ASCENDING
  INDEX-FIELD "CPU_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_Dev"
  AREA "Trend_Data"
  INDEX-FIELD "Dev_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "Dev_Name" ASCENDING
  INDEX-FIELD "Dev_StartDate" ASCENDING
  INDEX-FIELD "Dev_StartTime" ASCENDING
  INDEX-FIELD "Dev_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_FileSize"
  AREA "Trend_Data"
  INDEX-FIELD "FileSize_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "FileSize_Name" ASCENDING
  INDEX-FIELD "FileSize_StartDate" ASCENDING
  INDEX-FIELD "FileSize_StartTime" ASCENDING
  INDEX-FIELD "FileSize_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_FileSys"
  AREA "Trend_Data"
  INDEX-FIELD "FileSys_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "FileSys_Mount" ASCENDING
  INDEX-FIELD "FileSys_StartDate" ASCENDING
  INDEX-FIELD "FileSys_StartTime" ASCENDING
  INDEX-FIELD "FileSys_EndTime" ASCENDING

ADD INDEX "CreateJob" ON "Ar_IndexStat"
  AREA "Trend_Data"
  INDEX-FIELD "IndexStat_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "IndexStat_IdxNum" ASCENDING
  INDEX-FIELD "IndexStat_StartDate" ASCENDING
  INDEX-FIELD "IndexStat_StartTime" ASCENDING
  INDEX-FIELD "IndexStat_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_Mem"
  AREA "Trend_Data"
  INDEX-FIELD "Mem_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "Mem_StartDate" ASCENDING
  INDEX-FIELD "Mem_StartTime" ASCENDING
  INDEX-FIELD "Mem_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_Net_Data"
  AREA "Trend_Data"
  INDEX-FIELD "Net_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "Net_Status" ASCENDING
  INDEX-FIELD "Net_StartDate" ASCENDING
  INDEX-FIELD "Net_StartTime" ASCENDING
  INDEX-FIELD "Net_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_OE_ActASProc"
  AREA "Trend_Data"
  INDEX-FIELD "ActASProc_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActASProc_StartDate" ASCENDING
  INDEX-FIELD "ActASProc_EndDate" ASCENDING
  INDEX-FIELD "ActBrk_UUID" ASCENDING
  INDEX-FIELD "ActBrk_PID" ASCENDING
  INDEX-FIELD "ActASProc_Name" ASCENDING

ADD INDEX "CompactJob" ON "Ar_OE_ActBrk"
  AREA "Trend_Data"
  INDEX-FIELD "ActBrk_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActBrk_UUID" ASCENDING
  INDEX-FIELD "ActBrk_PID" ASCENDING
  INDEX-FIELD "ActBrk_StartDate" ASCENDING
  INDEX-FIELD "ActBrk_StartTime" ASCENDING
  INDEX-FIELD "ActBrk_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_OE_ActServ"
  AREA "Trend_Data"
  INDEX-FIELD "ActServ_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActBrk_UUID" ASCENDING
  INDEX-FIELD "ActServ_PID" ASCENDING
  INDEX-FIELD "ActServ_Status" ASCENDING
  INDEX-FIELD "ActServ_StartDate" ASCENDING
  INDEX-FIELD "ActServ_StartTime" ASCENDING
  INDEX-FIELD "ActServ_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_OE_ActWSProc"
  AREA "Trend_Data"
  INDEX-FIELD "ActWSProc_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "ActBrk_UUID" ASCENDING
  INDEX-FIELD "ActBrk_PID" ASCENDING
  INDEX-FIELD "ActWSProc_Name" ASCENDING
  INDEX-FIELD "ActWSProc_StartDate" ASCENDING
  INDEX-FIELD "ActWSProc_StartTime" ASCENDING
  INDEX-FIELD "ActWSProc_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_OE_AppService"
  AREA "Trend_Data"
  INDEX-FIELD "ActBrk_UUID" ASCENDING
  INDEX-FIELD "APPS_ServiceName" ASCENDING

ADD INDEX "CompactJob" ON "Ar_Process"
  AREA "Trend_Data"
  INDEX-FIELD "Process_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "Process_PID" ASCENDING
  INDEX-FIELD "Process_StartDate" ASCENDING
  INDEX-FIELD "Process_StartTime" ASCENDING
  INDEX-FIELD "Process_EndTime" ASCENDING

ADD INDEX "CompactJob" ON "Ar_TableStat"
  AREA "Trend_Data"
  INDEX-FIELD "TableStat_ArchiveType" ASCENDING
  INDEX-FIELD "Site_ID" ASCENDING
  INDEX-FIELD "Resrc_ID" ASCENDING
  INDEX-FIELD "TableStat_TableID" ASCENDING
  INDEX-FIELD "TableStat_StartDate" ASCENDING
  INDEX-FIELD "TableStat_StartTime" ASCENDING
  INDEX-FIELD "TableStat_EndTime" ASCENDING

ADD INDEX "Cf_Control" ON "Cf_Control"
  AREA "Trend_Data"
  INDEX-FIELD "ID" ASCENDING

UPDATE PRIMARY INDEX "Cf_Control" ON "Cf_Control"

.
PSC
cpstream=ISO8859-1
.
0000008989

ADD FIELD "TAB_BytesUsed" OF "Db_TabAnalysis" AS decimal
  DESCRIPTION "Number of bytes in table"
  FORMAT "->>,>>>,>>>,>>9"
  FORMAT-SA ?
  POSITION 18
  INITIAL "0"
  INITIAL-SA ?
  HELP "Number of Bytes"
  HELP-SA ""
  LABEL "Bytes"
  LABEL-SA ?
  COLUMN-LABEL ?
  COLUMN-LABEL-SA ?
  CAN-READ "*"
  CAN-WRITE "*"
  VALEXP ?
  VALMSG ""
  VALMSG-SA ""
  VIEW-AS ?
  EXTENT 0
  DECIMALS ?
  ORDER 170
  NULL-ALLOWED
  NOT-CASE-SENSITIVE
  MAX-WIDTH 16

.
PSC
cpstream=UTF-8
.
0000000484
RENAME FIELD "TAB_BytesUsed" OF "Db_TabAnalysis" TO "TAB_Bytes"

UPDATE FIELD "TAB_Bytes" OF "Db_TabAnalysis"
  POSITION 5
  ORDER 40

ADD INDEX "TAB_ID_Bytes" ON "Db_TabAnalysis"
  AREA "Trend_Data"
  INDEX-FIELD "TAB_ID" ASCENDING
  INDEX-FIELD "TAB_Bytes" DESCENDING

.
PSC
cpstream=UTF-8
.
0000000285
/*
** gen-alert.p
**
** This program will generate a Command-line alert based on the information 
** passed to it.  Six fields must be passed to the program.  Depending on the
** alert some or all of the fields will be used.
**
** The first field is always the type of alert to generate.
** The second field is always the site_ID.
** The third field is always the resource name.
** The Fourth field is an action to run (if appropriate)
**
** The rest of the fields are dependant on the alert.
*/
/* 
** llaubach 20140124 - 10.2B+ has merged binaries, so fathomcmd has to be built out of DLC and not OEM
*/

{include/alert-definitions.i "SHARED"}
    
sec-name = "Starting Program".
{include/ar-debug.i "sec-name"}

DEF VAR cmdline AS CHARACTER NO-UNDO.
DEF VAR cmd2line AS CHARACTER NO-UNDO INITIAL "1 -msg '".
DEF VAR fathomcmd AS CHARACTER NO-UNDO.
DEF VAR fathomcmd2 AS CHARACTER NO-UNDO.

/*
** Validate the environment
*/

fathomcmd = OS-GETENV ("progressInstallDirShort").

IF fathomcmd = "" OR fathomcmd = ? THEN
DO:
     fathomcmd = OS-GETENV ("DLC").
     IF fathomcmd = "" OR fathomcmd = ? THEN
     DO:
         PUT SKIP "ERROR - DLC environment variable not set!".
         QUIT.
     END.
END.

/*
** Begin building the common command line
*/
                              
sec-name = "Building Command Line".
{include/ar-debug.i "sec-name"}

/*
** Build the fathom command
*/

cmdline = fathomcmd + 
          CHR(47) + 
          "bin" + 
          CHR(47) +
	  "fathom ".

sec-name = "command line starting : " + cmdline.
{include/ar-debug.i "sec-name"}
/*
** Adding the httpport
*/

Alert-httpport = OS-GETENV ("FM_HTTPPORT").

IF Alert-httpport = ? THEN
DO:
    PUT SKIP "ERROR - HttpPort environment variable not set!".
    QUIT.
END.
cmdline = cmdline +
          "-httpport " +
          Alert-httpport.

sec-name = "HTTP Port : " + Alert-httpport.
{include/ar-debug.i "sec-name"}

/*
** Adding the alerttype to fire
*/

cmdline = cmdline +
          " -firealert " +
          alert-alert_type.

/*
** Adding the resource to the command line
*/

Alert-Resourcekey = OS-GETENV ("RESRC_NAME").
IF Alert-Resourcekey = ? THEN
DO:
    PUT SKIP "ERROR - Resourcekey environment variable not set!".
    QUIT.
END.

sec-name = "Resourcekey : " + Alert-Resourcekey.
{include/ar-debug.i "sec-name"}

cmdline = cmdline +
          " -resource " +
          Alert-Resourcekey.

/*
** Adding the severity
*/

cmdline = cmdline +
          " -severity " +
	  Alert-Severity +
	  " ".

sec-name = "Severity : " + Alert-severity.
{include/ar-debug.i "sec-name"}
/*
** Put the command line and Alert-Detail together and run the process
*/

cmdline = cmdline + "-msg " + Alert-Detail.

sec-name = "Command Line 1 : " + SUBSTRING (cmdline,1,212).
{include/ar-debug.i "sec-name"}
sec-name = "Command Line 2 : " + SUBSTRING (cmdline,212).
{include/ar-debug.i "sec-name"}

    Fathomcmd = OS-GETENV ("fathomWorkDir").
    IF Fathomcmd NE ? THEN
    DO:
        IF OPSYS = "WIN32" THEN
        DO:
            Fathomcmd = chr(34) + Fathomcmd + chr(92) + "runalert.bat" + chr(34).
	    OUTPUT TO value(Fathomcmd).
	    PUT UNFORMATTED cmdline.
            OUTPUT CLOSE.
        END.
        ELSE
        DO:
            Fathomcmd = Fathomcmd + chr(47) + "runalert".
	    OUTPUT TO value(Fathomcmd).
	    PUT UNFORMATTED cmdline.
            OUTPUT CLOSE.
            Fathomcmd2 = "chmod 777 " + fathomcmd.
            sec-name = "Changing Permissions for external command.".
            {include/ar-debug.i "sec-name"}
	    OS-COMMAND NO-CONSOLE VALUE (Fathomcmd2).
        END.

        sec-name = "Beginning running external command.".
        {include/ar-debug.i "sec-name"}
        
	OS-COMMAND NO-CONSOLE VALUE (Fathomcmd) NO-ERROR.
    
        sec-name = "External Command complete.".
        {include/ar-debug.i "sec-name"}

        IF OS-ERROR NE 0 THEN
        DO:
            sec-name = "Alert generation exit code : " + STRING (OS-ERROR).
            {include/ar-debug.i "sec-name"}
        END.
        
        OS-DELETE VALUE (Fathomcmd).

        IF OS-ERROR NE 0 THEN
        DO:
            sec-name = "Alert script deletion exit code : " + STRING (OS-ERROR).
            {include/ar-debug.i "sec-name"}
        END.
        
    END.
    ELSE
    DO:
        PUT SKIP "ERROR - Fathom Working Directory Environment Variable not set!".
    END.
/*
** These definitions are needed for the gen-alert.p program to run
*/

DEFINE {1} VARIABLE Alert-site_id AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-resrc_name AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-alert_type AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-cmd_action AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-Detail AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-Severity AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-httpport AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-Resourcekey AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-field4 AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-field5 AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-field6 AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-field7 AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-field8 AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE Alert-field9 AS CHARACTER NO-UNDO.

/*
** Debugging stuff
*/

DEFINE {1} VARIABLE pgm-name AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE sec-name AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE debug-4gl AS INTEGER NO-UNDO.
/* Def var debug-4gl as int. */
IF debug-4gl = 1 THEN
DO:
    PUT SKIP.
    PUT 
        (STRING (today) + " " +
         STRING (TIME, "HH:MM:SS") +
         " - " +
         " Program : " + PROGRAM-NAME(1) +
         " Section : " + sec-name)  FORMAT "x(255)".
END.
/*
** Ar-definitions.i
** This include file defines the variables needed within the the 
** archive program.  These are the default ones needed. 
*/

/*
llaubach 10/2005
 - now all temp tables are defined with NO-UNDO
 - doHourlyRecords defined as NO-UNDO
 - addded combined index 'four' for w-master table to speed up BY phrase
 
llaubach 08/2006
 - added deleting condition for Db_ActIOFile & Db_AreaStatus, as I've discovered
   couple of records contained invalid UTF-8 characters and when trying to delete
   those we bailed out with error 1422
 - this is VERY VERY VERY DIRTY WORKAROUND, which should not be used !!!
*/

&GLOBAL-DEFINE DAY_END_TIME 86399
&GLOBAL-DEFINE DAY_TIME_LENGTH 86400
&GLOBAL-DEFINE HOUR_TIME_LENGTH 3600

DEF SHARED VAR Fathom-i as INTEGER NO-UNDO.
DEF SHARED VAR Fathom-i-time as INTEGER NO-UNDO.
DEF SHARED VAR Fathom-i-processdate as INTEGER NO-UNDO.
DEF SHARED VAR Fathom-i-date as DATE NO-UNDO.
DEF SHARED VAR Fathom-i-resrc-type as CHARACTER NO-UNDO.
DEF SHARED VAR Fathom-i-resrc-name as CHARACTER NO-UNDO.
DEF SHARED VAR Fathom-i-resrc-id as INTEGER NO-UNDO.
DEF SHARED VAR Fathom-i-site-id as CHARACTER NO-UNDO.
DEF SHARED VAR Fathom-i-ActionCode as CHARACTER NO-UNDO.
DEF SHARED VAR Fathom-i-tablename AS CHARACTER FORMAT "X(255)" NO-UNDO.
SESSION:DATE-FORMAT="mdy".

DEF SHARED VAR Fathom-t-Time AS INTEGER NO-UNDO.
DEF SHARED VAR Fathom-t-Date AS DATE NO-UNDO.
DEF SHARED VAR Fathom-t-BaseDate AS DATE NO-UNDO.
DEF SHARED VAR Fathom-t-msg1 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF SHARED VAR Fathom-t-msg2 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF SHARED VAR Fathom-t-msg3 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF SHARED VAR Fathom-t-msg4 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF SHARED VAR Fathom-log-file AS CHARACTER FORMAT "X(255)" NO-UNDO.
DEF SHARED VAR Fathom-t-ActionCode as CHARACTER NO-UNDO.
DEF SHARED VAR s-beg-week AS DATE NO-UNDO.
DEF SHARED VAR s-end-week AS DATE NO-UNDO.
DEF SHARED VAR s-day AS DATE NO-UNDO.
DEF SHARED VAR s-beg-time AS INT NO-UNDO.
DEF SHARED VAR s-end-time AS INT NO-UNDO.
DEF SHARED VAR s-len as INT NO-UNDO.
DEF SHARED VAR s-comp-count AS INT NO-UNDO.
DEF SHARED VAR recs-compressed AS INT NO-UNDO.
DEF SHARED VAR recs-kept AS INT INITIAL 0 NO-UNDO.
DEF SHARED VAR new-recs AS INTEGER NO-UNDO.
DEF SHARED VAR write-count AS INTEGER NO-UNDO.
DEF SHARED VAR rec-count AS INT INITIAL 0 NO-UNDO.
DEF SHARED VAR hist-deleted AS INT INITIAL 0 NO-UNDO.
DEF SHARED VAR Fathom-t-tablename AS CHARACTER FORMAT "X(20)" NO-UNDO.
DEF SHARED VAR Fathom-runpgm AS CHARACTER NO-UNDO.
DEF SHARED VAR Fathom-Purgeflag AS CHARACTER NO-UNDO.
DEF SHARED VAR Fathom-Purgenumber AS INTEGER NO-UNDO.
DEF SHARED VAR Fathom-PurgeDate AS DATE NO-UNDO.     
DEF SHARED VAR qh1 AS WIDGET-HANDLE. 
DEF SHARED VAR Fathom-ERROR AS INTEGER NO-UNDO.
DEF SHARED VAR doHourlyRecords AS LOGICAL INITIAL YES NO-UNDO.

/*
** Debugging stuff
*/
DEF SHARED VAR pgm-name AS CHAR NO-UNDO.
DEF SHARED VAR sec-name AS CHAR NO-UNDO.
DEF SHARED VAR debug-4gl AS INT NO-UNDO.

/*
** Temp Table definitions
*/

DEF SHARED TEMP-TABLE W-table NO-UNDO   
    FIELD W-Rowid AS ROWID      
    FIELD W-Date AS DATE       
    FIELD W-Time AS INTEGER   
    FIELD W-Sample_ID AS INTEGER   
    FIELD W-Start-Date AS DATE
    FIELD W-Start-Time AS INTEGER
    INDEX One W-Rowid
    INDEX TWO W-Time
    INDEX three W-Date
    INDEX four w-time w-date.

DEF SHARED TEMP-TABLE Delete-table NO-UNDO
    FIELD delete-Rowid AS ROWID      
    INDEX One delete-Rowid.

DEF SHARED TEMP-TABLE Hour-table NO-UNDO
    FIELD hour-Rowid AS ROWID      
    INDEX One hour-Rowid.

DEF SHARED TEMP-TABLE W-Master-table  NO-UNDO
    FIELD WM-Rowid AS ROWID
    FIELD WM-Date AS DATE
    FIELD WM-Time AS INTEGER
    FIELD WM-Sample_ID AS INTEGER   
    FIELD WM-Start-Date AS DATE
    FIELD WM-Start-Time AS INTEGER
    INDEX One WM-Rowid.

DEF SHARED TEMP-TABLE H-Sample NO-UNDO
    FIELD Sample_ID AS INTEGER
    FIELD Sample_Len AS INTEGER
    FIELD Sample_Date AS DATE
    FIELD Sample_Time AS INTEGER
    FIELD Resrc_ID AS INTEGER
    FIELD Sample_Trans AS INTEGER
    FIELD Sample_Type AS CHARACTER
    FIELD Site_ID AS CHARACTER
    FIELD Sample_StartDate AS DATE
    FIELD Sample_StartTime AS INTEGER
    FIELD Sample_StartTime2 AS CHARACTER
    FIELD Sample_Time2 AS CHARACTER
    FIELD Sample_CompressType AS CHARACTER
    FIELD Sample_RecordCount AS INTEGER
    INDEX sample_id sample_id
    INDEX sample_date sample_date
    INDEX sample_time Sample_Time
    INDEX Sample_CompressType Sample_CompressType
    INDEX Sample_IDs Site_ID Resrc_ID. 

/* 
** This set of procedures will purge all of the data for that particular
** table.
*/

/*
** Delete Sys_CPU
*/

PROCEDURE delete-Sys_CPU.

{include/ar-delete-loop.i}

   FIND FIRST Sys_CPU WHERE 
        rowid(Sys_CPU) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Sys_CPU THEN
   DO:
      recs-kept = recs-kept + 1.
      DELETE Sys_CPU.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Sys_CPU table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Sys_Dev
*/

PROCEDURE delete-Sys_Dev.

{include/ar-delete-loop.i}
    
   FIND FIRST Sys_Dev WHERE 
        rowid(Sys_Dev) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Sys_Dev THEN
   DO:
      recs-kept = recs-kept + 1.
      DELETE Sys_Dev.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Sys_Dev table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Sys_Mem
*/

PROCEDURE delete-Sys_Mem.

{include/ar-delete-loop.i}

   FIND FIRST Sys_Mem WHERE 
        rowid(Sys_Mem) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Sys_Mem THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Sys_Mem.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Sys_Mem table : " recs-kept.
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 


END PROCEDURE.

/*
** Delete Sys_FileSize
*/

PROCEDURE delete-Sys_FileSize.

{include/ar-delete-loop.i}

   FIND FIRST Sys_FileSize WHERE 
        rowid(Sys_FileSize) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Sys_FileSize THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Sys_FileSize.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Sys_FileSize table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Sys_FileSys
*/

PROCEDURE delete-Sys_FileSys.

{include/ar-delete-loop.i}

   FIND FIRST Sys_FileSys WHERE 
        rowid(Sys_FileSys) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Sys_FileSys THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Sys_FileSys.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Sys_FileSys table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_ActAPW
*/

PROCEDURE delete-Db_ActAPW.

{include/ar-delete-loop.i}

   FIND FIRST Db_ActAPW WHERE 
        rowid(Db_ActAPW) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActAPW THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActAPW.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from DB_ActAPW table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_ActBuf
*/

PROCEDURE delete-Db_ActBuf.

{include/ar-delete-loop.i}
   
   FIND FIRST Db_ActBuf WHERE 
        rowid(Db_ActBuf) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActBuf THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActBuf.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActBuf table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete DB_ActIDX
*/

PROCEDURE delete-DB_ActIDX.

{include/ar-delete-loop.i}
   
   FIND FIRST Db_ActIdx WHERE 
        rowid(Db_ActIdx) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActIdx THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActIdx.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActIDX table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete DB_ActIOFile
*/

PROCEDURE delete-DB_ActIOFile.

{include/ar-delete-loop.i}

   FIND FIRST Db_ActIOFile WHERE 
        rowid(Db_ActIOFile) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActIOFile THEN 
   DO:
      recs-kept = recs-kept + 1.
      IF ASC(SUBSTRING(Db_ActIOFile.ActIOFile_FileName,1,1)) > 32 THEN DELETE Db_ActIOFile.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActIOFile table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_ActLock
*/

PROCEDURE delete-Db_ActLock.

{include/ar-delete-loop.i}

   FIND FIRST Db_ActLock WHERE 
        rowid(Db_ActLock) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActLock THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActLock.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActLock table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete DB_ActREc
*/

PROCEDURE delete-DB_ActREc.

{include/ar-delete-loop.i}

   FIND FIRST Db_ActRec WHERE 
        rowid(Db_ActRec) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActRec THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActRec.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActRec table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_Actsum
*/

PROCEDURE delete-Db_Actsum.

{include/ar-delete-loop.i}

   FIND FIRST Db_ActSum WHERE 
        rowid(Db_ActSum) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActSum THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActSum.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActSum table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_Checkpoint
*/

PROCEDURE delete-Db_Checkpoint.

{include/ar-delete-loop.i}
   
   FIND FIRST Db_Checkpoint WHERE 
        rowid(Db_Checkpoint) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_Checkpoint THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_Checkpoint.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_Checkpoint table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_TableStat
*/

PROCEDURE delete-Db_TableStat.

{include/ar-delete-loop.i}
   
   FIND FIRST Db_TableStat WHERE 
        rowid(Db_TableStat) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_TableStat THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_TableStat.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_TableStat table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_IndexStat
*/

PROCEDURE delete-Db_IndexStat.

{include/ar-delete-loop.i}
   
   FIND FIRST Db_IndexStat WHERE 
        rowid(Db_IndexStat) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_IndexStat THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_IndexStat.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_IndexStat table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_ActServ
*/

PROCEDURE delete-Db_ActServ.

{include/ar-delete-loop.i}

   FIND FIRST Db_ActServ WHERE 
        rowid(Db_ActServ) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActServ THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActServ.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActServ table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete DB_ActLog
*/

PROCEDURE delete-DB_ActLog.

{include/ar-delete-loop.i}

   FIND FIRST Db_ActLog WHERE 
        rowid(Db_ActLog) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActLog THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActLog.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActLog table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_ActIOType
*/

PROCEDURE delete-Db_ActIOType.

{include/ar-delete-loop.i}
   FIND FIRST Db_ActIOType WHERE 
        rowid(Db_ActIOType) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_ActIOType THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Db_ActIOType.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_ActIOType table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Net_Data
*/

PROCEDURE delete-Net_Data.


{include/ar-delete-loop.i}

   FIND FIRST Net_Data WHERE 
        rowid(Net_Data) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Net_Data THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Net_Data.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Net_Data table : " recs-kept.

   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Db_AreaStatus
*/

PROCEDURE delete-Db_AreaStatus.


{include/ar-delete-loop.i}
   
   FIND FIRST Db_AreaStatus WHERE 
        rowid(Db_AreaStatus) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Db_AreaStatus THEN 
   DO:
      recs-kept = recs-kept + 1.
      IF ASC(SUBSTRING(Db_AreaStatus.AreaStatus_Areaname,1,1)) > 32 THEN DELETE Db_AreaStatus.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Records deleted from Db_AreaStatus table : " recs-kept SKIP.
            
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete OE_ActASProc
*/

PROCEDURE delete-OE_ActASProc.

{include/ar-delete-loop.i}

   FIND FIRST OE_ActASProc WHERE 
        rowid(OE_ActASProc) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE OE_ActASProc THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE OE_ActASProc.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN 
      PUT SKIP TODAY " " 
      STRING(TIME, "HH:MM:SS") 
      " Records deleted from OE_ActASProc table : " 
      recs-kept 
      SKIP.
            
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete OE_ActWSProc
*/

PROCEDURE delete-OE_ActWSProc.

{include/ar-delete-loop.i}

   FIND FIRST OE_ActWSProc WHERE 
        rowid(OE_ActWSProc) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE OE_ActWSProc THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE OE_ActWSProc.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN 
      PUT SKIP TODAY " " 
      STRING(TIME, "HH:MM:SS") 
      " Records deleted from OE_ActWSProc table : " 
      recs-kept SKIP.
            
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete OE_ActSrv
*/

PROCEDURE delete-OE_ActSrv.


{include/ar-delete-loop.i}

   FIND FIRST OE_ActSrv WHERE 
        rowid(OE_ActSrv) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE OE_ActSrv THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE OE_ActSrv.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN 
      PUT SKIP TODAY " " 
      STRING(TIME, "HH:MM:SS") 
      " Records deleted from OE_ActSrv table : " 
      recs-kept SKIP.
            
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete OE_ActBrk
*/

PROCEDURE delete-OE_ActBrk.

{include/ar-delete-loop.i}

   FIND FIRST OE_ActBrk WHERE 
        rowid(OE_ActBrk) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE OE_ActBrk THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE OE_ActBrk.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN 
      PUT SKIP TODAY " " 
      STRING(TIME, "HH:MM:SS") 
      " Records deleted from OE_ActBrk table : " 
      recs-kept SKIP.
            
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.
/*
** Delete OE_ActBrk
*/

PROCEDURE delete-oe_appservice.

{include/ar-delete-loop.i}

   FIND FIRST OE_AppService WHERE 
        rowid(OE_AppService) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE OE_AppService THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE OE_AppService.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN 
      PUT SKIP TODAY " " 
      STRING(TIME, "HH:MM:SS") 
      " Records deleted from OE_AppService table : " 
      recs-kept SKIP.
            
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/*
** Delete Sys_Process
*/

PROCEDURE delete-Sys_Process.

{include/ar-delete-loop.i}

   FIND FIRST Sys_Process WHERE 
        rowid(Sys_Process) = delete-rowid EXCLUSIVE-LOCK NO-ERROR.
   IF AVAILABLE Sys_Process THEN 
   DO:
      recs-kept = recs-kept + 1.
      DELETE Sys_Process.
   END.

{include/ar-delete-loop2.i}

   IF Fathom-i-ActionCode = "H" THEN 
      PUT SKIP TODAY " " 
      STRING(TIME, "HH:MM:SS") 
      " Records deleted from Sys_Process table : " 
      recs-kept SKIP.
            
   /*
   ** Empty out the temp table for the next process
   */	
   EMPTY TEMP-TABLE delete-table NO-ERROR. 

END PROCEDURE.

/* sec-name = "Ending Program".
{include/ar-debug.i "sec-name"} */
DEFINE VARIABLE i AS INTEGER NO-UNDO.

recs-kept = 0.

/*
** Find the first record outside the loop to make sure we can
** find the record and to seed the record.
*/

FIND FIRST delete-table NO-LOCK NO-ERROR.
IF Available delete-table THEN
DO:
   repeat-loop:
   REPEAT:
      DO TRANSACTION:
         DO i = 1 to 500:
            /*
            ** Find the next rowid to delete
            ** If it doesn't exist then exit the whole loop
            */

            FIND NEXT delete-table NO-LOCK NO-ERROR.
            IF NOT AVAILABLE delete-table THEN LEAVE repeat-loop.

         END. /* DO I = 1 to 500 */

      END. /* DO TRANSACTION */

   END. /* REPEAT LOOP */

END. /*Outside read of delete-table */
CREATE delete-table.
ASSIGN delete-rowid = rowid({1}).
RELEASE delete-table.
/*
** include to log messages to the standard output log.
*/

PUT SKIP.
PUT SKIP Fathom-t-msg1 FORMAT "x(160)".
PUT SKIP Fathom-t-msg2 FORMAT "x(160)".
PUT SKIP Fathom-t-msg3 FORMAT "x(160)".
PUT SKIP Fathom-t-msg4 FORMAT "x(160)".

/* ar-pass-input.i
** This input validates the input data for the archiving / purge process
** The fields passed in are:  
**         Hour to begin
**         Hourly Date
**         Daily Date
**         Weekly Date
**         Hour to Purge
**         Hour Purge Date
**         Daily Purge Date
**         Weekly Purge Date
**         Resource Type (optional)
**         Site ID (optional)
**         Resource Name (optional)
**         
*/
DEF VAR Fathom-pass-info AS CHARACTER.
DEF VAR Fathom-pass-tmp AS CHARACTER.

Fathom-pass-info = SESSION:PARAMETER.

IF Fathom-pass-info = "" THEN
DO:
                                                            
    Fathom-pass-tmp = OS-GETENV ("FM_DBCCOMPACTDAYS") NO-ERROR.
    sec-name = "FM_DBCCOMPACTDAYS:" + Fathom-pass-tmp.
    {include/ar-debug.i "sec-name"}
    Fathom-pass-info = Fathom-pass-tmp + ",".
    
    Fathom-pass-tmp = OS-GETENV ("FM_DBHOST") NO-ERROR.
    IF Fathom-pass-tmp = "localhost" THEN
    Fathom-pass-tmp = OS-GETENV ("FM_SITEID") NO-ERROR.
    sec-name = "FM_SITEID/DBHOST:" + Fathom-pass-tmp.
    {include/ar-debug.i "sec-name"}
    Fathom-pass-info = Fathom-pass-info + Fathom-pass-tmp + ",".
    
    Fathom-pass-tmp = OS-GETENV ("FM_DBCPURGEDAYS") NO-ERROR.
    IF Fathom-pass-tmp NE ? THEN
    DO:
        Fathom-pass-info = Fathom-pass-info + Fathom-pass-tmp + ",".
        sec-name = "FM_DBCPURGEDAYS:" + Fathom-pass-tmp.
        {include/ar-debug.i "sec-name"}
    END.
    ELSE 
    DO:
        Fathom-pass-info = Fathom-pass-info + ",".
        sec-name = "FM_DBCPURGEDAYS Empty.".
        {include/ar-debug.i "sec-name"}
    END.

    Fathom-pass-info = Fathom-pass-info + ",,A".
    
    If Fathom-pass-info = "" or Fathom-pass-info = ? THEN
    DO:
        MESSAGE "Fathom-pass-info empty in Archive setup!!!" VIEW-AS ALERT-BOX.
        MESSAGE "Fathom-pass-info: " Fathom-pass-info VIEW-AS ALERT-BOX.
        QUIT.
    END.
    ELSE
    DO:
        sec-name = "Fathom Input Setup:" + Fathom-pass-info.
        {include/ar-debug.i "sec-name"}
    END.

END.
sec-name = "Running Program".
{include/ar-debug.i "sec-name"}
    Fathom-i-processdate = INTEGER (ENTRY (1, Fathom-pass-info)) NO-ERROR.
    Fathom-i-site-id = ENTRY (2, Fathom-pass-info) NO-ERROR.
    Fathom-i-time = INTEGER (ENTRY (3, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc-type = TRIM (ENTRY (4, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc-name = ENTRY (5, Fathom-pass-info) NO-ERROR.
    Fathom-i-ActionCode = ENTRY (6, Fathom-pass-info) NO-ERROR.
    
    IF Fathom-i-processdate GT 0 THEN Fathom-i-date = TODAY - Fathom-i-processdate.


/*
** Log the strings passed 
*/

/*
** If the site and resource are there then we need to find the resource row to populate
** the resource ID.  If then are not there then we are not dealing with a specific resource
** and we need to work with everything for the site and resource type identified.
*/

IF Fathom-i-resrc-name NE "" THEN 
DO:
    FIND FIRST Cf_Resrc WHERE 
        Cf_Resrc.Resrc_Name = Fathom-i-resrc-name AND 
        Cf_Resrc.Site_ID = Fathom-i-site-id
        NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Resrc THEN
    DO:
        MESSAGE "FAILED - NO RESOURCE!!!" + Fathom-i-resrc-name + fathom-i-site-id VIEW-AS ALERT-BOX.
        QUIT.
    END.  /* of not avail resrc loop */
    ELSE 
    DO:
        Fathom-i-resrc-id = Cf_Resrc.Resrc_ID.
    END.  /* of else loop */
END.  /* of if site-id NE "" AND resrc NE ""*/
ELSE
DO:
    IF Fathom-i-site-id NE "" THEN
    DO:
        FIND FIRST Cf_Site WHERE
            Cf_Site.Site_ID = Fathom-i-site-id
            NO-LOCK NO-ERROR.
        IF AVAILABLE Cf_Site THEN
        DO:
            Fathom-i-resrc-id = 0.
        END.
        ELSE
        DO:
            If Fathom-i-resrc-type NE "" THEN
            DO:
                Fathom-i-resrc-id = 0.
            END.
            ELSE
            DO:
                PUT SKIP "WARNING - NO RESOURCES FOUND!!".
                /* QUIT. */
                Fathom-i-resrc-id = 0.
            END. /* of else loop */
        END. /* of available site loop */
    END. /* of Site-id NE "" */
    ELSE
    DO:
        PUT SKIP "ERROR - Site ID and Resrc Name Not Specified!".
        QUIT.
    END.
END. /* of else loop */

/*
** Process the date and set up the base date
*/

Fathom-t-BaseDate = Fathom-i-Date.
/*
** Move the base date such that archiving ends on Saturday.
** This allows weekly records to be processed properly.
*/
Fathom-i-date = Fathom-t-BaseDate - (WEEKDAY(Fathom-t-BaseDate) - 1). 

PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Compacting data older than " Fathom-i-date ".".
/*
** Determine if we purge history or not
*/

Fathom-purgeflag = OS-GETENV("FM_DBCPURGEDAYS") NO-ERROR.

IF Fathom-purgeflag NE "0" AND 
   Fathom-purgeflag NE "?" AND 
   Fathom-purgeflag NE "" THEN
DO:
   Fathom-purgenumber = INTEGER (Fathom-purgeflag).
   Fathom-purgedate = TODAY - Fathom-purgenumber.
END.
ELSE
DO:
   Fathom-purgenumber = -1.
END.
Fathom-purgeflag = "TRUE".
/* 
** ar-reset.i
**
** This resets the variables. 
*/
    recs-kept = 0.
    Fathom-i = 0.
    s-beg-time = 0.
    s-end-time = 0.
    s-day = ?.
    EMPTY Temp-Table H-sample NO-ERROR.
    EMPTY Temp-Table W-Table NO-ERROR.
    FOR EACH W-Master-Table NO-LOCK:
        CREATE W-Table.
        ASSIGN
            W-Rowid = WM-rowid
            W-Date = WM-start-date
            W-Time = WM-Time
            W-Start-Date = WM-Start-Date
            W-Start-Time = WM-Start-Time.
    END.

/* Debugging stuff for work table counts */

    fathom-i = 0.
    IF debug-4gl = 1 THEN
    DO:
        for each w-table:
            fathom-i = fathom-i + 1.
        end.
    END.        
    sec-name = " Work table has " + string (Fathom-i) + " Rows.".
    {include/ar-debug.i "sec-name"}
    
    IF debug-4gl = 1 THEN
    DO:
        fathom-i = 0.            
        for each w-master-table:
            fathom-i = fathom-i + 1.
        end.
    END.        
    sec-name = " Work MASTER has " + string (Fathom-i) + " Rows.".
    {include/ar-debug.i "sec-name"}
/*  ar-select-criteria.i
**
**  This include does the select of rows to be processed from the raw data
**  based on the action code and the dates chosen.
**  The rowid's are placed into a temp table and then we work with that temp table
**  to sort out the correct data to work with.
**
**  NOTE:  This include only works for selecting the data.  It doesn't work for dealing
**         with archiving hourly into daily into weekly.
*/

/*
llaubach 10/2005
 - added NO-LOCK to all 4 QUERY-PREPARE() statements
 - removed BY phrase from QUERY-PREPARE() as any further action with w-table temp-table does BY BY anyway
*/

FIND FIRST W-Master-Table NO-LOCK NO-ERROR.

IF NOT AVAILABLE W-Master-Table THEN
DO:

    CREATE QUERY qh1.
    qh1:SET-BUFFERS(BUFFER Cf_Sample:HANDLE).
    /*
    ** Set up constants for query.
    */
    
    Fathom-t-Time = {&DAY_TIME_LENGTH}.

    CASE Fathom-i-ActionCode:
        WHEN "H" THEN
        DO:
/*            Fathom-t-Date = TODAY.  */
           qh1:QUERY-PREPARE("FOR EACH Cf_Sample NO-LOCK
                                  WHERE Cf_sample.Sample_Date LT " + string (Fathom-i-Date) + 
                                  " AND Cf_Sample.Sample_Time LT " + STRING (Fathom-t-Time + 1)
                             ).
        END.
        WHEN "D" THEN
        DO:
/*            Fathom-t-Date = TODAY - 1.  */
           qh1:QUERY-PREPARE("FOR EACH Cf_Sample NO-LOCK
                                  WHERE Cf_Sample.Sample_Date LE " + string (Fathom-i-Date)
                             ).
        END.
        WHEN "W" THEN
        DO:
/*            Fathom-t-Date = TODAY - 7.  */
           qh1:QUERY-PREPARE("FOR EACH Cf_Sample NO-LOCK
                                  WHERE Cf_Sample.Sample_Date LE " + string (Fathom-i-Date)
                             ).
        END.
        OTHERWISE
        DO:
/*            Fathom-t-Date = fathom-i-date.  */
           qh1:QUERY-PREPARE("FOR EACH Cf_Sample NO-LOCK 
                                  WHERE Cf_sample.Sample_Date LE " + string (Fathom-i-Date) + 
                                  " AND Cf_Sample.Sample_Time LE " + STRING (Fathom-t-Time)
                            ).
        END.
    END CASE.
    
    qh1:QUERY-OPEN().
    
    REPEAT:
        qh1:GET-NEXT.
    
        IF qh1:QUERY-OFF-END THEN LEAVE.
        CREATE W-Table.
        ASSIGN
             W-rowid = ROWID(cf_sample)
             W-Sample_id = cf_Sample.Sample_ID
             W-date = cf_sample.Sample_Date
             W-time = cf_sample.Sample_Time 
             W-Start-Time = Fathom-t-Time
             W-Start-Date = Fathom-t-Date.
    END.
    
    /* 
    ** Creating master table to work from to rebuild data for multiple tables
    **
    */
    Fathom-i = 0.
    FOR EACH W-Table NO-LOCK:
        CREATE W-Master-Table.
    
        fathom-i = fathom-i + 1.
        ASSIGN
            WM-Rowid = W-rowid
            WM-Sample_id = W-Sample_ID
            WM-Date = W-start-date
            WM-Time = W-Time
            WM-Start-Date = W-Start-Date
            WM-Start-Time = W-Start-Time.
    END.
END. /* of Finding a Master Record */
/*
** include/Ar-setupdefs.i
** This include file defines the variables needed within the the 
** archive program.  These are the default ones needed. 
*/

/*
llaubach 10/2005
 - now all temp tables are defined with NO-UNDO
 - doHourlyRecords defined as NO-UNDO
 - addded combined index 'four' for w-master table to speed up BY phrase
*/

DEF NEW GLOBAL SHARED VAR Fathom-i as INTEGER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-time as INTEGER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-processdate as INTEGER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-date as DATE NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-resrc-type as CHARACTER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-resrc-name as CHARACTER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-resrc-id as INTEGER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-site-id as CHARACTER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-ActionCode as CHARACTER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-i-tablename AS CHARACTER FORMAT "X(255)" NO-UNDO.
SESSION:DATE-FORMAT="mdy".

DEF NEW GLOBAL SHARED VAR Fathom-t-Time AS INTEGER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-Date AS DATE NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-BaseDate AS DATE NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-msg1 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-msg2 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-msg3 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-msg4 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-log-file AS CHARACTER FORMAT "X(255)" NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-ActionCode as CHARACTER NO-UNDO.
DEF NEW GLOBAL SHARED VAR s-beg-week AS DATE NO-UNDO.
DEF NEW GLOBAL SHARED VAR s-end-week AS DATE NO-UNDO.
DEF NEW GLOBAL SHARED VAR s-day AS DATE NO-UNDO.
DEF NEW GLOBAL SHARED VAR s-beg-time AS INT NO-UNDO.
DEF NEW GLOBAL SHARED VAR s-end-time AS INT NO-UNDO.
DEF NEW GLOBAL SHARED VAR s-len as INT NO-UNDO.
DEF NEW GLOBAL SHARED VAR s-comp-count AS INT NO-UNDO.
DEF NEW GLOBAL SHARED VAR recs-compressed AS INT NO-UNDO.
DEF NEW GLOBAL SHARED VAR recs-kept AS INT INITIAL 0 NO-UNDO.
DEF NEW GLOBAL SHARED VAR new-recs AS INTEGER NO-UNDO.
DEF NEW GLOBAL SHARED VAR write-count AS INTEGER NO-UNDO.
DEF NEW GLOBAL SHARED VAR rec-count AS INT INITIAL 0 NO-UNDO.
DEF NEW GLOBAL SHARED VAR hist-deleted AS INT INITIAL 0 NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-t-tablename AS CHARACTER FORMAT "X(20)" NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-runpgm AS CHARACTER NO-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-Purgeflag AS CHARACTER No-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-Purgenumber AS INTEGER No-UNDO.
DEF NEW GLOBAL SHARED VAR Fathom-PurgeDate AS DATE No-UNDO.
DEF NEW GLOBAL SHARED VAR qh1 AS WIDGET-HANDLE. 
DEF NEW GLOBAL SHARED VAR Fathom-ERROR AS INTEGER NO-UNDO Initial 0.
DEF NEW GLOBAL SHARED VAR doHourlyRecords AS LOGICAL INITIAL YES NO-UNDO.

/*
** Debugging stuff
*/
DEF NEW GLOBAL SHARED VAR pgm-name AS CHAR NO-UNDO.
DEF NEW GLOBAL SHARED VAR sec-name AS CHAR NO-UNDO.
DEF NEW GLOBAL SHARED VAR debug-4gl AS INT NO-UNDO.

/*
** Temp Table definitions
*/

DEF NEW GLOBAL SHARED TEMP-TABLE W-table NO-UNDO
    FIELD W-Rowid AS ROWID
    FIELD W-Date AS DATE
    FIELD W-Time AS INTEGER
    FIELD W-Sample_ID AS INTEGER
    FIELD W-Start-Date AS DATE
    FIELD W-Start-Time AS INTEGER
    INDEX One W-Rowid
    INDEX TWO W-Time 
    INDEX three W-Date
    INDEX four w-time w-date.

DEF NEW GLOBAL SHARED TEMP-TABLE Delete-table NO-UNDO
    FIELD delete-Rowid AS ROWID
    INDEX One delete-Rowid.

DEF NEW GLOBAL SHARED TEMP-TABLE Hour-table NO-UNDO
    FIELD Hour-Rowid AS ROWID
    INDEX One Hour-Rowid.

DEF NEW GLOBAL SHARED TEMP-TABLE W-Master-table NO-UNDO
    FIELD WM-Rowid AS ROWID
    FIELD WM-Date AS DATE
    FIELD WM-Time AS INTEGER
    FIELD WM-Sample_ID AS INTEGER
    FIELD WM-Start-Date AS DATE
    FIELD WM-Start-Time AS INTEGER
    INDEX One WM-Rowid.

DEF NEW GLOBAL SHARED TEMP-TABLE H-Sample NO-UNDO
    FIELD Sample_ID AS INTEGER
    FIELD Sample_Len AS INTEGER
    FIELD Sample_Date AS DATE
    FIELD Sample_Time AS INTEGER
    FIELD Resrc_ID AS INTEGER
    FIELD Sample_Trans AS INTEGER
    FIELD Sample_Type AS CHARACTER
    FIELD Site_ID AS CHARACTER
    FIELD Sample_StartDate AS DATE
    FIELD Sample_StartTime AS INTEGER
    FIELD Sample_StartTime2 AS CHARACTER
    FIELD Sample_Time2 AS CHARACTER
    FIELD Sample_CompressType AS CHARACTER
    FIELD Sample_RecordCount AS INTEGER
    INDEX sample_id sample_id
    INDEX sample_date sample_date
    INDEX sample_time Sample_Time
    INDEX Sample_CompressType Sample_CompressType
    INDEX Sample_IDs Site_ID Resrc_ID. 

PROPATH = os-getenv("fathomInstallDir") + "/src," + os-getenv("fathomInstallDir") + "," + PROPATH.

/* 
** ar-setuptimes.i
**
** This include will set up the time frame for the specific sample.
*/

/*
llaubach 10/2005
- grouped multiple assignements to one ASSIGN
*/

ASSIGN
 s-beg-time = INTEGER(Cf_Sample.Sample_Time - (Cf_Sample.Sample_Time MODULO {&HOUR_TIME_LENGTH}))
 Fathom-i = INTEGER(s-beg-time / {&HOUR_TIME_LENGTH})
 s-end-time = s-beg-time + ({&HOUR_TIME_LENGTH} - 1).


/*
sec-name = " NEW start Time:" + STRING (s-beg-time) + " end Time:" + STRING (s-end-time).
{include/ar-debug.i "sec-name"}

sec-name = " SAMPLE Time:" + STRING (Cf_Sample.Sample_Time) + " Date:" + STRING (Cf_Sample.Sample_Date).
{include/ar-debug.i "sec-name"}
*/
DEFINE VARIABLE archiveType AS CHARACTER INITIAL "D".

IF Fathom-i-reportcode = "hh" OR
   Fathom-i-reportcode = "hi" OR
   Fathom-i-reportcode = "dh" THEN
    archiveType = "H".

/*
** data-header.i
** This include defines the header frame that is used for all data output.
**
*/

/*
** Main Processing
*/

/* 
** Column-header
** This section will display the column headers in the appropriate
** spacing to display the rest of the data.
*/
    IF Fathom-t-beg-date[1] NE ? THEN
    DO:

        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT "Period," Fathom-j ",". 
        END.

        PUT SKIP.
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT "BeginDate," Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" ",".
        END.
        PUT SKIP.
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT "EndDate," Fathom-t-end-date[Fathom-j] FORMAT "99/99/9999" ",".
        END.
        PUT SKIP.
/* 
** Time heading
**
*/
        IF Fathom-t-beg-time[1] GT 1 AND Fathom-t-end-time[Fathom-i-periods] LT 86400 THEN
        DO:
            DO Fathom-j = 1 TO Fathom-i-periods:
            PUT "BeginTime," STRING (Fathom-t-beg-Time[Fathom-j], "HH:MM:SS") ",".
        END.

        PUT SKIP.
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT "EndTime," STRING (Fathom-t-end-Time[Fathom-j], "HH:MM:SS") ",".
        END.
    END.
END.
PUT SKIP.
include-list = "
ActLog_AIBBufWaits,
ActLog_AIByteWrites,
ActLog_AINoBufAvail,
ActLog_AIPartialWrites,
ActLog_AIRecWrites,
ActLog_AITotWrites,
ActLog_AIWWrites
".
FIND FIRST Db_ActLog WHERE 
   cf_sample.sample_id = Db_ActLog.sample_ID NO-LOCK NO-ERROR. 

IF AVAILABLE Db_ActLog THEN
DO:

   FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" NO-LOCK NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIBBufWaits.

   FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" NO-LOCK NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIByteWrites.

   FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" NO-LOCK NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AINoBufAvail. 

   FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" NO-LOCK NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIPartialWrites.

   FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" NO-LOCK NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIRecWrites. 

   FIND FIRST data_store WHERE name = "ActLog_AITotWrites" NO-LOCK NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AITotWrites.

   FIND FIRST data_store WHERE name = "ActLog_AIWWrites" NO-LOCK NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIWWrites.                                         
END.
include-list = "
ActLog_BITotReads,
ActLog_BITotWrites,
ActLog_BIWWrites,
ActSum_BiReads,
ActSum_BiWrites,
ActLog_BIBBufWaits,
ActLog_BIByteReads,
ActLog_BIByteWrites,
ActLog_BIEBufWaits,
ActLog_BIPartialWrites,
ActLog_BIRecReads,
ActLog_BIRecWrites
".
FIND FIRST Db_ActIOFile WHERE cf_sample.sample_id = 
    Db_ActIOFile.sample_ID NO-LOCK NO-ERROR.

IF AVAILABLE Db_ActIOFile THEN
DO:

   FIND FIRST data_store WHERE name = "ActIOFile_BufReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufReads.

   FIND FIRST data_store WHERE name = "ActIOFile_BufWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufWrites.                                   
   FIND FIRST data_store WHERE name = "ActIOFile_Extends" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Extends.
   
   FIND FIRST data_store WHERE name = "ActIOFile_Reads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Reads. 
   
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufReads. 
   
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufWrites.
   
   FIND FIRST data_store WHERE name = "ActIOFile_Writes" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Writes.
END.

FIND FIRST Db_ActSum WHERE cf_sample.sample_id = 
   Db_ActSum.sample_ID NO-LOCK NO-ERROR.                        

IF AVAILABLE Db_ActSum THEN
DO:
   
   FIND FIRST data_store WHERE name = "ActSum_AllocNewRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_AllocNewRm.
   
   FIND FIRST data_store WHERE name = "ActSum_BytesAlloc" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BytesAlloc.
   
   FIND FIRST data_store WHERE name = "ActSum_Examined" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Examined.
   
   FIND FIRST data_store WHERE name = "ActSum_FromFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_FromFree.
   
   FIND FIRST data_store WHERE name = "ActSum_FromRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_FromRm.
   
   FIND FIRST data_store WHERE name = "ActSum_Removed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Removed.
   
   FIND FIRST data_store WHERE name = "ActSum_RetFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_RetFree.
   
   FIND FIRST data_store WHERE name = "ActSum_TakeFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_TakeFree.
   
   FIND FIRST data_store WHERE name = "ActSum_AiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_AiWrites. 
   
   FIND FIRST data_store WHERE name = "ActSum_BiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BiReads.
   
   FIND FIRST data_store WHERE name = "ActSum_BiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BiWrites.
   
   FIND FIRST data_store WHERE name = "ActSum_Commits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Commits.
   
   FIND FIRST data_store WHERE name = "ActSum_DbAccesses" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbAccesses.
   
   FIND FIRST data_store WHERE name = "ActSum_DbExtend" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbExtend.
   
   FIND FIRST data_store WHERE name = "ActSum_DbReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbReads.
   
   FIND FIRST data_store WHERE name = "ActSum_DbWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbWrites.
   
   FIND FIRST data_store WHERE name = "ActSum_Undos" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Undos.
END.

FIND FIRST Db_ActLog WHERE cf_sample.sample_id = 
   Db_ActLog.sample_ID NO-LOCK NO-ERROR.                        
IF AVAILABLE Db_ActLog THEN
DO:
   FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIBBufWaits.
   
   FIND FIRST data_store WHERE name = "ActLog_BIByteReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteReads.
   
   FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteWrites.
   
   FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIEBufWaits.
   
   FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIPartialWrites.
   
   FIND FIRST data_store WHERE name = "ActLog_BIRecReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecReads.
   
   FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecWrites.
   
   FIND FIRST data_store WHERE name = "ActLog_BITotReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotReads.
   
   FIND FIRST data_store WHERE name = "ActLog_BITotWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotWrites.
   
   FIND FIRST data_store WHERE name = "ActLog_BIWWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIWWrites.
END.
include-list = "
ActSum_DbReads,
ActSum_DbWrites,
ActAPW_DBWrites,
ActAPW_TotDBWrites,
ActSum_DbAccesses,
ActSum_DbExtend,
ActIOType_AiReads,
ActIOType_AiWrites,
ActIOType_BiReads,
ActIOType_BiWrites,
ActIOType_DataReads,
ActIOType_DataWrites,
ActIOType_IdxReads,
ActIOType_IdxWrites".
FIND FIRST Db_ActAPW WHERE cf_sample.sample_id = 
   Db_ActAPW.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActAPW THEN
DO:
   
   FIND FIRST data_store WHERE name = "ActAPW_APWEnq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWEnq.
   
   FIND FIRST data_store WHERE name = "ActAPW_APWQWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWQWrites.
   
   FIND FIRST data_store WHERE name = "ActAPW_BufsCkpt" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsCkpt.
   
   FIND FIRST data_store WHERE name = "ActAPW_BufsScanned" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsScanned.
   
   FIND FIRST data_store WHERE name = "ActAPW_CkptQWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_CkptQWrites.
   
   FIND FIRST data_store WHERE name = "ActAPW_Ckpts" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Ckpts.
   
   FIND FIRST data_store WHERE name = "ActAPW_DBWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_DBWrites.
   
   FIND FIRST data_store WHERE name = "ActAPW_Flushed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Flushed.
   
   FIND FIRST data_store WHERE name = "ActAPW_Marked" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Marked.
   
   FIND FIRST data_store WHERE name = "ActAPW_ScanCycles" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanCycles.
   
   FIND FIRST data_store WHERE name = "ActAPW_ScanWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanWrites.
   
   FIND FIRST data_store WHERE name = "ActAPW_TotDBWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_TotDBWrites.
END.

FIND FIRST Db_ActSum WHERE cf_sample.sample_id = 
   Db_ActSum.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActSum THEN
DO:
   
   FIND FIRST data_store WHERE name = "ActSum_AllocNewRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_AllocNewRm.
   
   FIND FIRST data_store WHERE name = "ActSum_BytesAlloc" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_BytesAlloc.
   
   FIND FIRST data_store WHERE name = "ActSum_Examined" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Examined. 
   
   FIND FIRST data_store WHERE name = "ActSum_FromFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_FromFree.
   
   FIND FIRST data_store WHERE name = "ActSum_FromRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_FromRm.
   
   FIND FIRST data_store WHERE name = "ActSum_Removed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Removed.
   
   FIND FIRST data_store WHERE name = "ActSum_RetFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_RetFree.
   
   FIND FIRST data_store WHERE name = "ActSum_TakeFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_TakeFree.
   
   FIND FIRST data_store WHERE name = "ActSum_AiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_AiWrites.
   
   FIND FIRST data_store WHERE name = "ActSum_BiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_BiReads.
   
   FIND FIRST data_store WHERE name = "ActSum_BiWrites" NO-ERROR.                                        
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_BiWrites.
   
   FIND FIRST data_store WHERE name = "ActSum_Commits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Commits.
   
   FIND FIRST data_store WHERE name = "ActSum_DbAccesses" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbAccesses.
   
   FIND FIRST data_store WHERE name = "ActSum_DbExtend" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbExtend.
   
   FIND FIRST data_store WHERE name = "ActSum_DbReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbReads.
   
   FIND FIRST data_store WHERE name = "ActSum_DbWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbWrites.
   
   FIND FIRST data_store WHERE name = "ActSum_Undos" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Undos.
END.

FIND FIRST Db_ActIOType WHERE cf_sample.sample_id = Db_ActIOType.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActIOType THEN
DO:
   
   FIND FIRST data_store WHERE name = "ActIOType_AiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiReads.
   
   FIND FIRST data_store WHERE name = "ActIOType_AiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiWrites.
   
   FIND FIRST data_store WHERE name = "ActIOType_BiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiReads.
   
   FIND FIRST data_store WHERE name = "ActIOType_BiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiWrites.
   
   FIND FIRST data_store WHERE name = "ActIOType_DataReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataReads.
   
   FIND FIRST data_store WHERE name = "ActIOType_DataWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataWrites.
   
   FIND FIRST data_store WHERE name = "ActIOType_IdxReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxReads.
   
   FIND FIRST data_store WHERE name = "ActIOType_IdxWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxWrites.
END.
include-list = "
ActBuf_Flushed,
ActBuf_LogicReads,
ActBuf_LogicWrites,
ActSum_DbReads,
ActSum_DbWrites,
ActRec_RecRead,
ActLog_BITotWrites,
ActLog_BIWWrites,
ActAPW_APWEnq,
ActAPW_APWQWrites,
ActAPW_BufsCkpt,
ActAPW_BufsScanned,
ActAPW_CkptQWrites,
ActAPW_Ckpts,
ActAPW_DBWrites,
ActAPW_Marked,
ActAPW_ScanCycles,
ActAPW_ScanWrites,
ActAPW_TotDBWrites,
ActBuf_Deferred,
ActBuf_OSReads,
ActBuf_OSWrites,
ActIdx_Create,
ActIdx_Delete,
ActIdx_Find,
ActIdx_Free,
ActIdx_Remove,
ActIdx_Splits,
ActRec_ByteCreate,
ActRec_ByteDel,
ActRec_ByteRead,
ActRec_ByteUpd,
ActRec_FragCreate,
ActRec_FragDel,
ActRec_FragRead,
ActRec_FragUpd,
ActRec_RecCreate,
ActRec_RecDel,
ActRec_RecLock,
ActRec_RecUpd,
ActRec_RecWait,
ActSum_AllocNewRm,
ActSum_BytesAlloc,
ActSum_Examined,
ActSum_FromFree,
ActSum_FromRm,
ActSum_Removed,
ActSum_RetFree,
ActSum_TakeFree,
ActSum_AiWrites,
ActSum_BiReads,
ActSum_BiWrites,
ActSum_Commits,
ActSum_DbAccesses,
ActSum_DbExtend,
ActSum_Undos,
ActLog_AIBBufWaits,
ActLog_AIByteWrites,
ActLog_AINoBufAvail,
ActLog_AIPartialWrites,
ActLog_AIRecWrites,
ActLog_AITotWrites,
ActLog_AIWWrites,
ActLog_BIBBufWaits,
ActLog_BIByteReads,
ActLog_BIByteWrites,
ActLog_BIEBufWaits,
ActLog_BIPartialWrites,
ActLog_BIRecReads,
ActLog_BIRecWrites,
ActLog_BITotReads,
ActIOType_AiReads,
ActIOType_DataReads,
ActIOType_DataWrites,
ActIOType_IdxReads,
ActIOType_IdxWrites".
FIND FIRST Db_ActAPW WHERE cf_sample.sample_id = Db_ActAPW.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ACTAPW THEN
DO:
   FIND FIRST data_store WHERE name = "ActAPW_APWEnq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWEnq.
   FIND FIRST data_store WHERE name = "ActAPW_APWQWrites" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWQWrites.
   FIND FIRST data_store WHERE name = "ActAPW_BufsCkpt" NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsCkpt.
   FIND FIRST data_store WHERE name = "ActAPW_BufsScanned" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsScanned.
   FIND FIRST data_store WHERE name = "ActAPW_CkptQWrites" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_CkptQWrites.
   FIND FIRST data_store WHERE name = "ActAPW_Ckpts" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Ckpts.
   FIND FIRST data_store WHERE name = "ActAPW_DBWrites" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_DBWrites.
   FIND FIRST data_store WHERE name = "ActAPW_Flushed" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Flushed.
   FIND FIRST data_store WHERE name = "ActAPW_Marked" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Marked.
   FIND FIRST data_store WHERE name = "ActAPW_ScanCycles" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanCycles.
   FIND FIRST data_store WHERE name = "ActAPW_ScanWrites" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanWrites.
   FIND FIRST data_store WHERE name = "ActAPW_TotDBWrites" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActAPW.ActAPW_TotDBWrites.
END.

FIND FIRST Db_ActBuf WHERE cf_sample.sample_id = Db_ActBuf.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ACTBuf THEN
DO:
   FIND FIRST data_store WHERE name = "ActBuf_Deferred" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Deferred.
   FIND FIRST data_store WHERE name = "ActBuf_Flushed" NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Flushed.
   FIND FIRST data_store WHERE name = "ActBuf_LogicReads" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicReads.
   FIND FIRST data_store WHERE name = "ActBuf_LogicWrites" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicWrites.
   FIND FIRST data_store WHERE name = "ActBuf_OSReads" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSReads.
   FIND FIRST data_store WHERE name = "ActBuf_OSWrites" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSWrites.
END.

FIND FIRST Db_ActIdx WHERE cf_sample.sample_id = Db_ActIdx.sample_ID NO-LOCK NO-ERROR.                        
IF AVAILABLE Db_ACTIdx THEN
DO:
   FIND FIRST data_store WHERE name = "ActIdx_Create" NO-ERROR. 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Create. 
   FIND FIRST data_store WHERE name = "ActIdx_Delete" NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Delete.
   FIND FIRST data_store WHERE name = "ActIdx_Find" NO-ERROR.                                            
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Find.
   FIND FIRST data_store WHERE name = "ActIdx_Free" NO-ERROR.                                            
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Free.
   FIND FIRST data_store WHERE name = "ActIdx_Remove" NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Remove.
   FIND FIRST data_store WHERE name = "ActIdx_Splits" NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Splits.
END.

FIND FIRST Db_ActIOFile WHERE cf_sample.sample_id = Db_ActIOFile.sample_ID NO-LOCK NO-ERROR.                  
IF AVAILABLE Db_ACTIOFile THEN
DO:
   FIND FIRST data_store WHERE name = "ActIOFile_BufReads" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufReads. 
   FIND FIRST data_store WHERE name = "ActIOFile_BufWrites" NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufWrites.
   FIND FIRST data_store WHERE name = "ActIOFile_Extends" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Extends. 
   FIND FIRST data_store WHERE name = "ActIOFile_Reads" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Reads.  
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufReads" NO-ERROR.                                   
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufReads.
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufWrites" NO-ERROR.                                  
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufWrites.
   FIND FIRST data_store WHERE name = "ActIOFile_Writes" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Writes.
END.

FIND FIRST Db_ActLock WHERE cf_sample.sample_id = Db_ActLock.sample_ID NO-LOCK NO-ERROR.                      
IF AVAILABLE Db_ACTLock THEN
DO:
   FIND FIRST data_store WHERE name = "ActLock_CanclReq" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_CanclReq. 
   FIND FIRST data_store WHERE name = "ActLock_Downgrade" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_Downgrade.
   FIND FIRST data_store WHERE name = "ActLock_ExclFind" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclFind. 
   FIND FIRST data_store WHERE name = "ActLock_ExclLock" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclLock.
   FIND FIRST data_store WHERE name = "ActLock_ExclReq" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclReq. 
   FIND FIRST data_store WHERE name = "ActLock_ExclWait" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclWait.
   FIND FIRST data_store WHERE name = "ActLock_RecGetLock" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetLock.
   FIND FIRST data_store WHERE name = "ActLock_RecGetReq" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetReq.
   FIND FIRST data_store WHERE name = "ActLock_RecGetWait" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetWait.
   FIND FIRST data_store WHERE name = "ActLock_ShrFind" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrFind.  
   FIND FIRST data_store WHERE name = "ActLock_ShrLock" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrLock.                                   
   FIND FIRST data_store WHERE name = "ActLock_ShrReq" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrReq.                                    
   FIND FIRST data_store WHERE name = "ActLock_ShrWait" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrWait.                                   
   FIND FIRST data_store WHERE name = "ActLock_UpgLock" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgLock.                                   
   FIND FIRST data_store WHERE name = "ActLock_UpgReq" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgReq.                                    
   FIND FIRST data_store WHERE name = "ActLock_UpgWait" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgWait.                                   
 END.

FIND FIRST Db_ActRec WHERE cf_sample.sample_id = Db_ActRec.sample_ID NO-LOCK NO-ERROR.                        
IF AVAILABLE Db_ACTRec THEN
DO:
   FIND FIRST data_store WHERE name = "ActRec_ByteCreate" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteCreate.                                  
   FIND FIRST data_store WHERE name = "ActRec_ByteDel" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteDel.                                     
   FIND FIRST data_store WHERE name = "ActRec_ByteRead" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteRead.                                    
   FIND FIRST data_store WHERE name = "ActRec_ByteUpd" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteUpd.                                     
   FIND FIRST data_store WHERE name = "ActRec_FragCreate" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_FragCreate.                                  
   FIND FIRST data_store WHERE name = "ActRec_FragDel" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_FragDel.                                     
   FIND FIRST data_store WHERE name = "ActRec_FragRead" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_FragRead.                                    
   FIND FIRST data_store WHERE name = "ActRec_FragUpd" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_FragUpd.                                     
   FIND FIRST data_store WHERE name = "ActRec_RecCreate" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_RecCreate.                                   
   FIND FIRST data_store WHERE name = "ActRec_RecDel" NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_RecDel.                                      
   FIND FIRST data_store WHERE name = "ActRec_RecLock" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_RecLock.                                     
   FIND FIRST data_store WHERE name = "ActRec_RecRead" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_RecRead.                                     
   FIND FIRST data_store WHERE name = "ActRec_RecUpd" NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_RecUpd.                                      
   FIND FIRST data_store WHERE name = "ActRec_RecWait" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActRec.ActRec_RecWait.                                     
 END.

FIND FIRST Db_ActSum WHERE cf_sample.sample_id = Db_ActSum.sample_ID NO-LOCK NO-ERROR.                        
IF AVAILABLE Db_ACTSum THEN
DO:
   FIND FIRST data_store WHERE name = "ActSum_AllocNewRm" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_AllocNewRm.                                  
   FIND FIRST data_store WHERE name = "ActSum_BytesAlloc" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_BytesAlloc.                                  
   FIND FIRST data_store WHERE name = "ActSum_Examined" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Examined.                                    
   FIND FIRST data_store WHERE name = "ActSum_FromFree" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_FromFree.                                    
   FIND FIRST data_store WHERE name = "ActSum_FromRm" NO-ERROR.                                          
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_FromRm.                                      
   FIND FIRST data_store WHERE name = "ActSum_Removed" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Removed.                                     
   FIND FIRST data_store WHERE name = "ActSum_RetFree" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_RetFree.                                     
   FIND FIRST data_store WHERE name = "ActSum_TakeFree" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_TakeFree.                                    
   FIND FIRST data_store WHERE name = "ActSum_AiWrites" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_AiWrites.                                    
   FIND FIRST data_store WHERE name = "ActSum_BiReads" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_BiReads.                                     
   FIND FIRST data_store WHERE name = "ActSum_BiWrites" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_BiWrites.                                    
   FIND FIRST data_store WHERE name = "ActSum_Commits" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Commits.                                     
   FIND FIRST data_store WHERE name = "ActSum_DbAccesses" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbAccesses.                                  
   FIND FIRST data_store WHERE name = "ActSum_DbExtend" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbExtend.                                    
   FIND FIRST data_store WHERE name = "ActSum_DbReads" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbReads.                                     
   FIND FIRST data_store WHERE name = "ActSum_DbWrites" NO-ERROR.                                        
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_DbWrites.                                    
   FIND FIRST data_store WHERE name = "ActSum_Undos" NO-ERROR.                                           
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActSum.ActSum_Undos.                                       
 END.

FIND FIRST Db_TableStat WHERE cf_sample.sample_id = Db_TableStat.sample_ID NO-LOCK NO-ERROR.                  
IF AVAILABLE Db_TableStat THEN
DO:
   FIND FIRST data_store WHERE name = "TableStat_Create" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_TableStat.TableStat_Create.                                
   FIND FIRST data_store WHERE name = "TableStat_Delete" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_TableStat.TableStat_Delete.                                
   FIND FIRST data_store WHERE name = "TableStat_Read" NO-ERROR.                                         
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_TableStat.TableStat_Read.                                  
   FIND FIRST data_store WHERE name = "TableStat_Update" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_TableStat.TableStat_Update.                                
 END.

FIND FIRST Db_ActLog WHERE cf_sample.sample_id = Db_ActLog.sample_ID NO-LOCK NO-ERROR.                        
IF AVAILABLE Db_ACTLog THEN
DO:
   FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_AIBBufWaits.                                 
   FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_AIByteWrites.                                
   FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_AINoBufAvail.                                
   FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" NO-ERROR.                                 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_AIPartialWrites.                             
   FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_AIRecWrites.                                 
   FIND FIRST data_store WHERE name = "ActLog_AITotWrites" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_AITotWrites.                                 
   FIND FIRST data_store WHERE name = "ActLog_AIWWrites" NO-ERROR.                                       
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_AIWWrites.                                   
   FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_BIBBufWaits.                                 
   FIND FIRST data_store WHERE name = "ActLog_BIByteReads" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteReads.                                 
   FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" NO-ERROR.                                    
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteWrites.                                
   FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" NO-ERROR.                                     
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_BIEBufWaits.                                 
   FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" NO-ERROR.                                 
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_BIPartialWrites.                             
   FIND FIRST data_store WHERE name = "ActLog_BIRecReads" NO-ERROR.                                      
    IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
       data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecReads.                                  
   FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecWrites.                                 
   FIND FIRST data_store WHERE name = "ActLog_BITotReads" NO-ERROR.                                      
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotReads.                                  
   FIND FIRST data_store WHERE name = "ActLog_BITotWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotWrites.                                 
   FIND FIRST data_store WHERE name = "ActLog_BIWWrites" NO-ERROR.                                       
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIWWrites.                                   
 END.

FIND FIRST Db_ActIOType WHERE cf_sample.sample_id = Db_ActIOType.sample_ID NO-LOCK NO-ERROR.                  
IF AVAILABLE Db_ACTIOType THEN
DO:
   FIND FIRST data_store WHERE name = "ActIOType_AiReads" NO-ERROR.                                      
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiReads.                               
   FIND FIRST data_store WHERE name = "ActIOType_AiWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiWrites.                              
   FIND FIRST data_store WHERE name = "ActIOType_BiReads" NO-ERROR.                                      
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiReads.                               
   FIND FIRST data_store WHERE name = "ActIOType_BiWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiWrites.                              
   FIND FIRST data_store WHERE name = "ActIOType_DataReads" NO-ERROR.                                    
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataReads.                             
   FIND FIRST data_store WHERE name = "ActIOType_DataWrites" NO-ERROR.                                   
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataWrites.                            
   FIND FIRST data_store WHERE name = "ActIOType_IdxReads" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxReads.                              
   FIND FIRST data_store WHERE name = "ActIOType_IdxWrites" NO-ERROR.                                    
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxWrites.                             
 END.
include-list = "
ActLock_CanclReq,
ActLock_Downgrade,
ActLock_ExclFind,
ActLock_ExclLock,
ActLock_ExclReq,
ActLock_ExclWait,
ActLock_RecGetLock,
ActLock_RecGetReq,
ActLock_RecGetWait,
ActLock_ShrFind,
ActLock_ShrLock,
ActLock_ShrReq,
ActLock_ShrWait,
ActLock_UpgLock,
ActLock_UpgReq,
ActLock_UpgWait,
".
FIND FIRST Db_ActLock WHERE cf_sample.sample_id = Db_ActLock.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActLock THEN
DO:
   FIND FIRST data_store WHERE name = "ActLock_CanclReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_CanclReq.
   FIND FIRST data_store WHERE name = "ActLock_Downgrade" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_Downgrade.
   FIND FIRST data_store WHERE name = "ActLock_ExclFind" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclFind.
   FIND FIRST data_store WHERE name = "ActLock_ExclLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclLock.
   FIND FIRST data_store WHERE name = "ActLock_ExclReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclReq.
   FIND FIRST data_store WHERE name = "ActLock_ExclWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclWait.
   FIND FIRST data_store WHERE name = "ActLock_RecGetLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetLock.
   FIND FIRST data_store WHERE name = "ActLock_RecGetReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetReq.
   FIND FIRST data_store WHERE name = "ActLock_RecGetWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetWait.
   FIND FIRST data_store WHERE name = "ActLock_ShrFind" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrFind.
   FIND FIRST data_store WHERE name = "ActLock_ShrLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrLock.
   FIND FIRST data_store WHERE name = "ActLock_ShrReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrReq.
   FIND FIRST data_store WHERE name = "ActLock_ShrWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrWait.
   FIND FIRST data_store WHERE name = "ActLock_UpgLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgLock.
   FIND FIRST data_store WHERE name = "ActLock_UpgReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgReq.
   FIND FIRST data_store WHERE name = "ActLock_UpgWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgWait.
END.
include-list = "
ActBuf_Flushed,
ActBuf_LogicReads,
ActBuf_LogicWrites,
ActBuf_Deferred,
ActBuf_OSReads,
ActLog_AIBBufWaits,
ActLog_AINoBufAvail,
ActLog_AIPartialWrites,
ActLog_BIBBufWaits,
ActLog_BIEBufWaits,
ActLog_BIPartialWrites
".
FIND FIRST Db_ActBuf WHERE cf_sample.sample_id = Db_ActBuf.sample_ID NO-LOCK NO-ERROR.                        
IF AVAILABLE Db_ActBuf THEN
DO:
   FIND FIRST data_store WHERE name = "ActBuf_Deferred" NO-ERROR.                                        
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Deferred.
   FIND FIRST data_store WHERE name = "ActBuf_Flushed" NO-ERROR.                                         
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Flushed.  
   FIND FIRST data_store WHERE name = "ActBuf_LogicReads" NO-ERROR.                                      
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicReads.
   FIND FIRST data_store WHERE name = "ActBuf_LogicWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicWrites.
   FIND FIRST data_store WHERE name = "ActBuf_OSReads" NO-ERROR.                                         
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSReads.  
   FIND FIRST data_store WHERE name = "ActBuf_OSWrites" NO-ERROR.                                        
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSWrites.  
END.

FIND FIRST Db_ActLog WHERE cf_sample.sample_id = Db_ActLog.sample_ID NO-LOCK NO-ERROR.                        
IF AVAILABLE Db_ActBuf THEN
DO:
   FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIBBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" NO-ERROR.                                    
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIByteWrites.
   FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" NO-ERROR.                                    
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AINoBufAvail.  
   FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" NO-ERROR.                                 
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIPartialWrites.
   FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIRecWrites.
   FIND FIRST data_store WHERE name = "ActLog_AITotWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AITotWrites.
   FIND FIRST data_store WHERE name = "ActLog_AIWWrites" NO-ERROR.                                       
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIWWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIBBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_BIByteReads" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteReads.
   FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" NO-ERROR.                                    
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIEBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" NO-ERROR.                                 
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIPartialWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIRecReads" NO-ERROR.                                      
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecReads.
   FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecWrites.
   FIND FIRST data_store WHERE name = "ActLog_BITotReads" NO-ERROR.                                      
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotReads.
   FIND FIRST data_store WHERE name = "ActLog_BITotWrites" NO-ERROR.                                     
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIWWrites" NO-ERROR.                                       
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIWWrites.
END.
include-list = "
ActRec_RecRead,
ActRec_ByteCreate,
ActRec_ByteDel,
ActRec_ByteRead,
ActRec_ByteUpd,
ActRec_FragCreate,
ActRec_FragDel,
ActRec_FragRead,
ActRec_FragUpd,
ActRec_RecCreate,
ActRec_RecDel,
ActRec_RecLock,
ActRec_RecUpd,
ActRec_RecWait
".
FIND FIRST Db_ActRec WHERE cf_sample.sample_id = Db_ActRec.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActRec THEN
DO:
   FIND FIRST data_store WHERE name = "ActRec_ByteCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteCreate.
   FIND FIRST data_store WHERE name = "ActRec_ByteDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteDel.
   FIND FIRST data_store WHERE name = "ActRec_ByteRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteRead.
   FIND FIRST data_store WHERE name = "ActRec_ByteUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteUpd.
   FIND FIRST data_store WHERE name = "ActRec_FragCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragCreate.
   FIND FIRST data_store WHERE name = "ActRec_FragDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragDel.
   FIND FIRST data_store WHERE name = "ActRec_FragRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragRead.
   FIND FIRST data_store WHERE name = "ActRec_FragUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragUpd.
   FIND FIRST data_store WHERE name = "ActRec_RecCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecCreate.
   FIND FIRST data_store WHERE name = "ActRec_RecDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecDel.
   FIND FIRST data_store WHERE name = "ActRec_RecLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecLock.
   FIND FIRST data_store WHERE name = "ActRec_RecRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecRead.
   FIND FIRST data_store WHERE name = "ActRec_RecUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecUpd.
   FIND FIRST data_store WHERE name = "ActRec_RecWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecWait.
END.
FIND FIRST Db_ActAPW WHERE cf_sample.sample_id = Db_ActAPW.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActAPW THEN
DO:
   FIND FIRST data_store WHERE name = "ActAPW_APWEnq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWEnq.
   FIND FIRST data_store WHERE name = "ActAPW_APWQWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWQWrites.
   FIND FIRST data_store WHERE name = "ActAPW_BufsCkpt" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsCkpt.
   FIND FIRST data_store WHERE name = "ActAPW_BufsScanned" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsScanned.
   FIND FIRST data_store WHERE name = "ActAPW_CkptQWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_CkptQWrites.
   FIND FIRST data_store WHERE name = "ActAPW_Ckpts" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Ckpts.
   FIND FIRST data_store WHERE name = "ActAPW_DBWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_DBWrites.
   FIND FIRST data_store WHERE name = "ActAPW_Flushed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Flushed.
   FIND FIRST data_store WHERE name = "ActAPW_Marked" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Marked.
   FIND FIRST data_store WHERE name = "ActAPW_ScanCycles" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanCycles.
   FIND FIRST data_store WHERE name = "ActAPW_ScanWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanWrites.
   FIND FIRST data_store WHERE name = "ActAPW_TotDBWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_TotDBWrites.
END.

FIND FIRST Db_ActBuf WHERE cf_sample.sample_id = Db_ActBuf.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActBuf THEN
DO:
   FIND FIRST data_store WHERE name = "ActBuf_Deferred" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Deferred.
   FIND FIRST data_store WHERE name = "ActBuf_Flushed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Flushed.
   FIND FIRST data_store WHERE name = "ActBuf_LogicReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicReads.
   FIND FIRST data_store WHERE name = "ActBuf_LogicWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicWrites.
   FIND FIRST data_store WHERE name = "ActBuf_OSReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSReads.
   FIND FIRST data_store WHERE name = "ActBuf_OSWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSWrites.
END.

FIND FIRST Db_ActIdx WHERE cf_sample.sample_id = Db_ActIdx.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActIdx THEN
DO:
   FIND FIRST data_store WHERE name = "ActIdx_Create" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Create.
   FIND FIRST data_store WHERE name = "ActIdx_Delete" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Delete.
   FIND FIRST data_store WHERE name = "ActIdx_Find" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Find.
   FIND FIRST data_store WHERE name = "ActIdx_Free" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Free.
   FIND FIRST data_store WHERE name = "ActIdx_Remove" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Remove.
   FIND FIRST data_store WHERE name = "ActIdx_Splits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Splits.
END.

FIND FIRST Db_ActIOFile WHERE cf_sample.sample_id = Db_ActIOFile.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActIOFile THEN
DO:
   FIND FIRST data_store WHERE name = "ActIOFile_BufReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufReads.
   FIND FIRST data_store WHERE name = "ActIOFile_BufWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufWrites.
   FIND FIRST data_store WHERE name = "ActIOFile_Extends" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Extends.
   FIND FIRST data_store WHERE name = "ActIOFile_Reads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Reads.
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufReads.
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufWrites.
   FIND FIRST data_store WHERE name = "ActIOFile_Writes" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Writes.
END.

FIND FIRST Db_ActLock WHERE cf_sample.sample_id = Db_ActLock.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActLock THEN
DO:
   FIND FIRST data_store WHERE name = "ActLock_CanclReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_CanclReq.
   FIND FIRST data_store WHERE name = "ActLock_Downgrade" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_Downgrade.
   FIND FIRST data_store WHERE name = "ActLock_ExclFind" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclFind.
   FIND FIRST data_store WHERE name = "ActLock_ExclLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclLock.
   FIND FIRST data_store WHERE name = "ActLock_ExclReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclReq.
   FIND FIRST data_store WHERE name = "ActLock_ExclWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclWait.
   FIND FIRST data_store WHERE name = "ActLock_RecGetLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetLock.
   FIND FIRST data_store WHERE name = "ActLock_RecGetReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetReq.
   FIND FIRST data_store WHERE name = "ActLock_RecGetWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetWait.
   FIND FIRST data_store WHERE name = "ActLock_ShrFind" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrFind.
   FIND FIRST data_store WHERE name = "ActLock_ShrLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrLock.
   FIND FIRST data_store WHERE name = "ActLock_ShrReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrReq.
   FIND FIRST data_store WHERE name = "ActLock_ShrWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrWait.
   FIND FIRST data_store WHERE name = "ActLock_UpgLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgLock.
   FIND FIRST data_store WHERE name = "ActLock_UpgReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgReq.
   FIND FIRST data_store WHERE name = "ActLock_UpgWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgWait.
END.

FIND FIRST Db_ActRec WHERE cf_sample.sample_id = Db_ActRec.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActRec THEN
DO:
   FIND FIRST data_store WHERE name = "ActRec_ByteCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteCreate.
   FIND FIRST data_store WHERE name = "ActRec_ByteDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteDel.
   FIND FIRST data_store WHERE name = "ActRec_ByteRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteRead.
   FIND FIRST data_store WHERE name = "ActRec_ByteUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteUpd.
   FIND FIRST data_store WHERE name = "ActRec_FragCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragCreate.
   FIND FIRST data_store WHERE name = "ActRec_FragDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragDel.
   FIND FIRST data_store WHERE name = "ActRec_FragRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragRead.
   FIND FIRST data_store WHERE name = "ActRec_FragUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragUpd.
   FIND FIRST data_store WHERE name = "ActRec_RecCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecCreate.
   FIND FIRST data_store WHERE name = "ActRec_RecDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecDel.
   FIND FIRST data_store WHERE name = "ActRec_RecLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecLock.
   FIND FIRST data_store WHERE name = "ActRec_RecRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecRead.
   FIND FIRST data_store WHERE name = "ActRec_RecUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecUpd.
   FIND FIRST data_store WHERE name = "ActRec_RecWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecWait.
END.

FIND FIRST Db_ActSum WHERE cf_sample.sample_id = Db_ActSum.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActSum THEN
DO:
   FIND FIRST data_store WHERE name = "ActSum_AllocNewRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_AllocNewRm.
   FIND FIRST data_store WHERE name = "ActSum_BytesAlloc" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BytesAlloc.
   FIND FIRST data_store WHERE name = "ActSum_Examined" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Examined.
   FIND FIRST data_store WHERE name = "ActSum_FromFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_FromFree.
   FIND FIRST data_store WHERE name = "ActSum_FromRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_FromRm.
   FIND FIRST data_store WHERE name = "ActSum_Removed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Removed.
   FIND FIRST data_store WHERE name = "ActSum_RetFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_RetFree.
   FIND FIRST data_store WHERE name = "ActSum_TakeFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_TakeFree.
   FIND FIRST data_store WHERE name = "ActSum_AiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_AiWrites.
   FIND FIRST data_store WHERE name = "ActSum_BiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BiReads.
   FIND FIRST data_store WHERE name = "ActSum_BiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BiWrites.
   FIND FIRST data_store WHERE name = "ActSum_Commits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Commits.
   FIND FIRST data_store WHERE name = "ActSum_DbAccesses" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbAccesses.
   FIND FIRST data_store WHERE name = "ActSum_DbExtend" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbExtend.
   FIND FIRST data_store WHERE name = "ActSum_DbReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbReads.
   FIND FIRST data_store WHERE name = "ActSum_DbWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbWrites.
   FIND FIRST data_store WHERE name = "ActSum_Undos" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Undos.
END.

FIND FIRST Db_TableStat WHERE cf_sample.sample_id = Db_TableStat.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_TableStat THEN
DO:
   FIND FIRST data_store WHERE name = "TableStat_Create" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Create.
   FIND FIRST data_store WHERE name = "TableStat_Delete" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Delete.
   FIND FIRST data_store WHERE name = "TableStat_Read" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Read.
   FIND FIRST data_store WHERE name = "TableStat_Table_ID" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Table_ID.
   FIND FIRST data_store WHERE name = "TableStat_Update" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Update.
END.

FIND FIRST Db_ActLog WHERE cf_sample.sample_id = Db_ActLog.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActLog THEN
DO:
   FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIBBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIByteWrites.
   FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AINoBufAvail.
   FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIPartialWrites.
   FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIRecWrites.
   FIND FIRST data_store WHERE name = "ActLog_AITotWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AITotWrites.
   FIND FIRST data_store WHERE name = "ActLog_AIWWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIWWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIBBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_BIByteReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteReads.
   FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIEBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIPartialWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIRecReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecReads.
   FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecWrites.
   FIND FIRST data_store WHERE name = "ActLog_BITotReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotReads.
   FIND FIRST data_store WHERE name = "ActLog_BITotWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIWWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIWWrites.
END.

FIND FIRST Db_ActIOType WHERE cf_sample.sample_id = Db_ActIOType.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActIOType THEN
DO:
   FIND FIRST data_store WHERE name = "ActIOType_AiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiReads.
   FIND FIRST data_store WHERE name = "ActIOType_AiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiWrites.
   FIND FIRST data_store WHERE name = "ActIOType_BiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiReads.
   FIND FIRST data_store WHERE name = "ActIOType_BiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiWrites.
   FIND FIRST data_store WHERE name = "ActIOType_DataReads" NO-ERROR.
   IF AVAILABLE data_store THEN 
      data_store.data[Fathom-i] = data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataReads.
   FIND FIRST data_store WHERE name = "ActIOType_DataWrites" NO-ERROR.
   IF AVAILABLE data_store THEN 
      data_store.data[Fathom-i] = data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataWrites.
   FIND FIRST data_store WHERE name = "ActIOType_IdxReads" NO-ERROR.
   IF AVAILABLE data_store THEN 
      data_store.data[Fathom-i] = data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxReads.
   FIND FIRST data_store WHERE name = "ActIOType_IdxWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxWrites.
END.
include-list = "
ActBuf_Flushed,
ActBuf_LogicReads,
ActBuf_LogicWrites,
ActSum_DbReads,
ActSum_DbWrites,
ActRec_RecRead,
ActLog_BITotWrites,
ActLog_BIWWrites,
ActAPW_BufsCkpt,
ActBuf_OSReads,
ActBuf_OSWrites,
ActIdx_Create,
ActIdx_Delete,
ActIdx_Find,
ActIdx_Free,
ActIdx_Remove,
ActIdx_Splits,
ActSum_Commits,
ActSum_DbAccesses,
ActSum_DbExtend,
ActIOType_DataReads,
ActIOType_IdxReads,
ActIOType_IdxWrites
".
FIND FIRST Db_ActAPW WHERE cf_sample.sample_id = Db_ActAPW.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActAPW THEN
DO:
   FIND FIRST data_store WHERE name = "ActAPW_APWEnq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWEnq.
   FIND FIRST data_store WHERE name = "ActAPW_APWQWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_APWQWrites.
   FIND FIRST data_store WHERE name = "ActAPW_BufsCkpt" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsCkpt.
   FIND FIRST data_store WHERE name = "ActAPW_BufsScanned" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_BufsScanned.
   FIND FIRST data_store WHERE name = "ActAPW_CkptQWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_CkptQWrites.
   FIND FIRST data_store WHERE name = "ActAPW_Ckpts" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Ckpts.
   FIND FIRST data_store WHERE name = "ActAPW_DBWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_DBWrites.
   FIND FIRST data_store WHERE name = "ActAPW_Flushed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Flushed.
   FIND FIRST data_store WHERE name = "ActAPW_Marked" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_Marked.
   FIND FIRST data_store WHERE name = "ActAPW_ScanCycles" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanCycles.
   FIND FIRST data_store WHERE name = "ActAPW_ScanWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_ScanWrites.
   FIND FIRST data_store WHERE name = "ActAPW_TotDBWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActAPW.ActAPW_TotDBWrites.
END.

FIND FIRST Db_ActBuf WHERE cf_sample.sample_id = Db_ActBuf.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActBuf THEN
DO:
   FIND FIRST data_store WHERE name = "ActBuf_Deferred" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Deferred.
   FIND FIRST data_store WHERE name = "ActBuf_Flushed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_Flushed.
   FIND FIRST data_store WHERE name = "ActBuf_LogicReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicReads.
   FIND FIRST data_store WHERE name = "ActBuf_LogicWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_LogicWrites.
   FIND FIRST data_store WHERE name = "ActBuf_OSReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSReads.
   FIND FIRST data_store WHERE name = "ActBuf_OSWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActBuf.ActBuf_OSWrites.
END.

FIND FIRST Db_ActIdx WHERE cf_sample.sample_id = Db_ActIdx.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActIdx THEN
DO:
   FIND FIRST data_store WHERE name = "ActIdx_Create" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Create.
   FIND FIRST data_store WHERE name = "ActIdx_Delete" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Delete.
   FIND FIRST data_store WHERE name = "ActIdx_Find" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Find.
   FIND FIRST data_store WHERE name = "ActIdx_Free" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Free.
   FIND FIRST data_store WHERE name = "ActIdx_Remove" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Remove.
   FIND FIRST data_store WHERE name = "ActIdx_Splits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIdx.ActIdx_Splits.
END.

FIND FIRST Db_ActIOFile WHERE cf_sample.sample_id = Db_ActIOFile.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActIOFile THEN
DO:
   FIND FIRST data_store WHERE name = "ActIOFile_BufReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufReads.
   FIND FIRST data_store WHERE name = "ActIOFile_BufWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_BufWrites.
   FIND FIRST data_store WHERE name = "ActIOFile_Extends" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Extends.
   FIND FIRST data_store WHERE name = "ActIOFile_Reads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Reads.
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufReads.
   FIND FIRST data_store WHERE name = "ActIOFile_UnbufWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_UnbufWrites.
   FIND FIRST data_store WHERE name = "ActIOFile_Writes" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOFile.ActIOFile_Writes.
END.

FIND FIRST Db_ActLock WHERE cf_sample.sample_id = Db_ActLock.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActLock THEN
DO:
   FIND FIRST data_store WHERE name = "ActLock_CanclReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_CanclReq.
   FIND FIRST data_store WHERE name = "ActLock_Downgrade" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_Downgrade.
   FIND FIRST data_store WHERE name = "ActLock_ExclFind" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclFind.
   FIND FIRST data_store WHERE name = "ActLock_ExclLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclLock.
   FIND FIRST data_store WHERE name = "ActLock_ExclReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclReq.
   FIND FIRST data_store WHERE name = "ActLock_ExclWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ExclWait.
   FIND FIRST data_store WHERE name = "ActLock_RecGetLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetLock.
   FIND FIRST data_store WHERE name = "ActLock_RecGetReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetReq.
   FIND FIRST data_store WHERE name = "ActLock_RecGetWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_RecGetWait.
   FIND FIRST data_store WHERE name = "ActLock_ShrFind" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrFind.
   FIND FIRST data_store WHERE name = "ActLock_ShrLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrLock.
   FIND FIRST data_store WHERE name = "ActLock_ShrReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrReq.
   FIND FIRST data_store WHERE name = "ActLock_ShrWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_ShrWait.
   FIND FIRST data_store WHERE name = "ActLock_UpgLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgLock.
   FIND FIRST data_store WHERE name = "ActLock_UpgReq" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgReq.
   FIND FIRST data_store WHERE name = "ActLock_UpgWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLock.ActLock_UpgWait.
END.

FIND FIRST Db_ActRec WHERE cf_sample.sample_id = Db_ActRec.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActRec THEN
DO:
   FIND FIRST data_store WHERE name = "ActRec_ByteCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteCreate.
   FIND FIRST data_store WHERE name = "ActRec_ByteDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteDel.
   FIND FIRST data_store WHERE name = "ActRec_ByteRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteRead.
   FIND FIRST data_store WHERE name = "ActRec_ByteUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_ByteUpd.
   FIND FIRST data_store WHERE name = "ActRec_FragCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragCreate.
   FIND FIRST data_store WHERE name = "ActRec_FragDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragDel.
   FIND FIRST data_store WHERE name = "ActRec_FragRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragRead.
   FIND FIRST data_store WHERE name = "ActRec_FragUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_FragUpd.
   FIND FIRST data_store WHERE name = "ActRec_RecCreate" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecCreate.
   FIND FIRST data_store WHERE name = "ActRec_RecDel" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecDel.
   FIND FIRST data_store WHERE name = "ActRec_RecLock" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecLock.
   FIND FIRST data_store WHERE name = "ActRec_RecRead" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecRead.
   FIND FIRST data_store WHERE name = "ActRec_RecUpd" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecUpd.
   FIND FIRST data_store WHERE name = "ActRec_RecWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActRec.ActRec_RecWait.
END.

FIND FIRST Db_ActSum WHERE cf_sample.sample_id = Db_ActSum.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActSum THEN
DO:
   FIND FIRST data_store WHERE name = "ActSum_AllocNewRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_AllocNewRm.
   FIND FIRST data_store WHERE name = "ActSum_BytesAlloc" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BytesAlloc.
   FIND FIRST data_store WHERE name = "ActSum_Examined" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Examined.
   FIND FIRST data_store WHERE name = "ActSum_FromFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_FromFree.
   FIND FIRST data_store WHERE name = "ActSum_FromRm" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_FromRm.
   FIND FIRST data_store WHERE name = "ActSum_Removed" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Removed.
   FIND FIRST data_store WHERE name = "ActSum_RetFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_RetFree.
   FIND FIRST data_store WHERE name = "ActSum_TakeFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_TakeFree.
   FIND FIRST data_store WHERE name = "ActSum_AiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_AiWrites.
   FIND FIRST data_store WHERE name = "ActSum_BiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BiReads.
   FIND FIRST data_store WHERE name = "ActSum_BiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_BiWrites.
   FIND FIRST data_store WHERE name = "ActSum_Commits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Commits.
   FIND FIRST data_store WHERE name = "ActSum_DbAccesses" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbAccesses.
   FIND FIRST data_store WHERE name = "ActSum_DbExtend" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbExtend.
   FIND FIRST data_store WHERE name = "ActSum_DbReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbReads.
   FIND FIRST data_store WHERE name = "ActSum_DbWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_DbWrites.
   FIND FIRST data_store WHERE name = "ActSum_Undos" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActSum.ActSum_Undos.
END.

FIND FIRST Db_TableStat WHERE cf_sample.sample_id = Db_TableStat.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_TableStat THEN
DO:
   FIND FIRST data_store WHERE name = "TableStat_Create" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Create.
   FIND FIRST data_store WHERE name = "TableStat_Delete" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Delete.
   FIND FIRST data_store WHERE name = "TableStat_Read" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Read.
   FIND FIRST data_store WHERE name = "TableStat_Table_ID" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_TableID.
   FIND FIRST data_store WHERE name = "TableStat_Update" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_TableStat.TableStat_Update.
END.

FIND FIRST Db_ActLog WHERE cf_sample.sample_id = Db_ActLog.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActLog THEN
DO:
   FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIBBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIByteWrites.
   FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AINoBufAvail.
   FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIPartialWrites.
   FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIRecWrites.
   FIND FIRST data_store WHERE name = "ActLog_AITotWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AITotWrites.
   FIND FIRST data_store WHERE name = "ActLog_AIWWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_AIWWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIBBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_BIByteReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteReads.
   FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIByteWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIEBufWaits.
   FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIPartialWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIRecReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecReads.
   FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIRecWrites.
   FIND FIRST data_store WHERE name = "ActLog_BITotReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotReads.
   FIND FIRST data_store WHERE name = "ActLog_BITotWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BITotWrites.
   FIND FIRST data_store WHERE name = "ActLog_BIWWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActLog.ActLog_BIWWrites.
END.

FIND FIRST Db_ActIOType WHERE cf_sample.sample_id = Db_ActIOType.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Db_ActIOType THEN
DO:
   FIND FIRST data_store WHERE name = "ActIOType_AiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiReads.
   FIND FIRST data_store WHERE name = "ActIOType_AiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_AiWrites.
   FIND FIRST data_store WHERE name = "ActIOType_BiReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiReads.
   FIND FIRST data_store WHERE name = "ActIOType_BiWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_BiWrites.
   FIND FIRST data_store WHERE name = "ActIOType_DataReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataReads.
   FIND FIRST data_store WHERE name = "ActIOType_DataWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_DataWrites.
   FIND FIRST data_store WHERE name = "ActIOType_IdxReads" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxReads.
   FIND FIRST data_store WHERE name = "ActIOType_IdxWrites" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Db_ActIOType.ActIOType_IdxWrites.
END.
/*
** db_status.i
**
** This include will figure out the database status
** All that is needed is the full path to the database and
** the progressInstallDirShort (or DLC) environment variable be set.  
** It will error out and return
** a unknown if either of these is not valid.
**
** Other possible statuses:
**    multi - database is in use in multi-user mode.
**    single - database is in use in single user mode or a utility is running.
**    available - database is not in use.
**
** Variables used in this include:
**    fathom-t-dbname = full path to the database
**    Fathom-t-dbstatus = This will end up being the status of the database
**    fathom-t-dlc = This will house the progressInstallDirShort directory location
**    fathom-t-separator = This is the directory separator
**    Fathom-t-test[9] = THis is the input file for testing.
*/

DEF VAR status-cmd as CHAR NO-UNDO.

if fathom-t-dbname = "" THEN
DO:
    Fathom-t-dbstatus = "unknown - cannot determine db name".
END.
ELSE
DO:
    fathom-t-dlc = OS-GETENV("progressInstallDirShort") NO-ERROR.
    If fathom-t-dlc EQ "" or Fathom-t-dlc = ? THEN
    DO:
        fathom-t-dlc = OS-GETENV("DLC") NO-ERROR.
    END.
        
    If fathom-t-dlc EQ "" or Fathom-t-dlc = ? THEN
    DO:
            Fathom-t-dbstatus = "unknown - DLC not set!".
    END.
    ELSE
    DO:
        IF OPSYS = "UNIX" THEN
        DO:
                Fathom-t-separator = chr(47).
        END.
        ELSE
        DO:
                Fathom-t-separator = chr(92).
        END.
    
        status-cmd = Fathom-t-dlc + 
                 fathom-t-separator + 
                 "bin" + 
                 fathom-t-separator + 
                 "_proutil " + 
                 chr(34) + fathom-t-dbname + chr(34) +
                 " -C holder".
        sec-name = "Command executed: " + status-cmd.
        {include/ar-debug.i "sec-name"}
        INPUT THROUGH VALUE(status-cmd).

        IMPORT Fathom-t-test.
    
        INPUT CLOSE.

        DO Fathom-d = 1 to 10:
            sec-name = "Database status [" + 
	           STRING (Fathom-d) + 
		   "]: " + 
		   Fathom-t-test[Fathom-d].
            {include/ar-debug.i "sec-name"}
            Case Fathom-t-test[Fathom-d]:
                WHEN "Multi-user" THEN
                DO:
                    Fathom-t-dbstatus = "multi".
		    LEAVE.
                END.
                WHEN "Single-user" THEN
                DO:
                    Fathom-t-dbstatus = "single".
		    LEAVE.
                END.
                WHEN "" THEN
                DO:
                    Fathom-t-dbstatus = "available".
		    LEAVE.
                END.
            END CASE.
        END.
        If Fathom-t-dbstatus = "" or Fathom-t-dbstatus = ? THEN
            Fathom-t-dbstatus = "Unknown - cannot determine status".
    END.
END.
/*
** These definitions are needed for the db-status.i include
*/
DEFINE {1} SHARED VARIABLE fathom-t-dbname as CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-dbstatus as CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-dlc as CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-separator as CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-test as CHARACTER EXTENT 20 NO-UNDO.

DEFINE {1} SHARED VARIABLE Fathom-t-IndexNames as CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-TableNames as CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-IndexFailed as CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-IndexBlocks as CHARACTER NO-UNDO.

DEFINE {1} SHARED VARIABLE Fathom-i-tmpfile AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-dbname AS CHAR NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-dbpath AS CHAR NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-resrc-ID AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-site-ID AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-resrc-name AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-utilization AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-blocks AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-RunCompaction AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-i-CompactionPCT AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE fathom-d AS INTEGER NO-UNDO.

DEFINE {1} SHARED VARIABLE nSampleNo    AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE szTmpFile    AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE runcmd AS CHARACTER NO-UNDO INITIAL "".
DEFINE {1} SHARED VARIABLE fathom-t-time AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE fathom-t-date AS DATE INITIAL TODAY.
DEFINE {1} SHARED VARIABLE fathom-w-date AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE fathom-t-id AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-ValidateFile AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE HoldTableName AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE HoldIndexName AS CHARACTER NO-UNDO.
DEFINE {1} SHARED VARIABLE ReadAgain AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE ThreeLineIndex AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE TwoLineIndex AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE fathom-indexline AS CHARACTER EXTENT 9 NO-UNDO.
DEFINE {1} SHARED VARIABLE ValidFile AS INTEGER NO-UNDO.
DEFINE {1} SHARED VARIABLE TempDir AS CHARACTER FORMAT "X(255)" NO-UNDO INITIAL "".
DEFINE {1} SHARED VARIABLE Fathom-t-utilization AS DECIMAL NO-UNDO.
DEFINE {1} SHARED VARIABLE Fathom-t-blocks AS INTEGER NO-UNDO.
/* ar-pass-input.i
** This input validates the input data for the archiving / purge process
** The fields passed in are:  
**         Time
**         Date
**         Site ID
**         Resource Name (optional)
**         Table Name (optional)
**         
*/

DEF VAR Fathom-pass-info AS CHARACTER.

Fathom-pass-info = SESSION:PARAMETER.

IF Fathom-pass-info = "" THEN
DO:
                                                         
    MESSAGE "Fathom-pass-info empty in delete data!!!" VIEW-AS ALERT-BOX.
    QUIT.
END.
ELSE DO:
    Fathom-i-time = INTEGER (ENTRY (1, Fathom-pass-info)) NO-ERROR.
    Fathom-i-date = DATE (ENTRY (2, Fathom-pass-info)) NO-ERROR.
    Fathom-i-site-id = ENTRY (3, Fathom-pass-info) NO-ERROR.
    Fathom-i-resrc-name = ENTRY (4, Fathom-pass-info) NO-ERROR. /* OPTIONAL */
    Fathom-i-tablename = ENTRY (5, Fathom-pass-info) NO-ERROR. /* OPTIONAL */
END.

IF fathom-i-time LT 1 THEN Fathom-i-time = 86400.

IF Fathom-i-tablename = "" THEN Fathom-i-Tablename = "all".
/*
** Log the strings passed 
*/

IF Fathom-i-resrc-name NE "" THEN 
DO:
    FIND FIRST Cf_Resrc WHERE 
        Cf_Resrc.Site_ID = Fathom-i-site-id AND
        Cf_Resrc.Resrc_Name = Fathom-i-resrc-name
        NO-LOCK NO-ERROR.
    IF NOT AVAILABLE Cf_Resrc THEN
    DO:
        fathom-i-resrc-id = -1.
    END.
    ELSE 
    DO:
        Fathom-i-resrc-id = Cf_Resrc.Resrc_ID.
    END.
END.
ELSE fathom-i-resrc-id = -1.
/*
** include/Ar-setupdefs.i
** This include file defines the variables needed within the the 
** archive program.  These are the default ones needed. 
*/

DEF VAR Fathom-i as INTEGER NO-UNDO.
DEF VAR Fathom-i-time as INTEGER NO-UNDO.
DEF VAR Fathom-i-date as DATE NO-UNDO.
DEF VAR Fathom-i-tablename as CHARACTER NO-UNDO.
DEF VAR Fathom-i-site-id as CHARACTER NO-UNDO.
DEF VAR Fathom-i-resrc-name as CHARACTER NO-UNDO.
DEF VAR Fathom-i-resrc-id as INTEGER NO-UNDO.
SESSION:DATE-FORMAT="mdy".

DEF VAR Fathom-t-Time AS INTEGER NO-UNDO.
DEF VAR Fathom-t-Date AS DATE NO-UNDO.
DEF VAR Fathom-t-BaseDate AS DATE NO-UNDO.
DEF VAR Fathom-t-resrc-id as INTEGER NO-UNDO.
DEF VAR Fathom-t-msg1 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF VAR Fathom-t-msg2 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF VAR Fathom-t-msg3 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF VAR Fathom-t-msg4 AS CHARACTER FORMAT "X(76)" NO-UNDO.
DEF VAR Fathom-log-file AS CHARACTER FORMAT "X(255)" NO-UNDO.
DEF VAR rec-count AS INT INITIAL 0 NO-UNDO.
DEF VAR Fathom-t-tablename AS CHARACTER FORMAT "X(20)" NO-UNDO.
DEF VAR Fathom-runpgm AS CHARACTER NO-UNDO.
DEF VAR Fathom-Purgeflag AS CHARACTER No-UNDO.
DEF VAR Fathom-log-count AS INTEGER INITIAL 0 NO-UNDO.
DEF VAR Fathom-alertdetail-count AS INTEGER INITIAL 0 NO-UNDO.
DEF VAR Fathom-status-count AS INTEGER INITIAL 0 NO-UNDO.
DEF VAR Fathom-taskdetail-count AS INTEGER INITIAL 0 NO-UNDO.
DEF VAR Fathom-idxanalysis-count AS INTEGER INITIAL 0 NO-UNDO.
DEF VAR Fathom-tabanalysis-count AS INTEGER INITIAL 0 NO-UNDO.

/*
** Debugging stuff
*/
DEF VAR pgm-name AS CHAR NO-UNDO.
DEF VAR sec-name AS CHAR NO-UNDO.
DEF VAR debug-4gl AS INT NO-UNDO.
IF Fathom-i-OutputType = "R" THEN
DO:
   IF debug-4gl = 1 THEN
   DO:
       PUT skip.
       PUT
           (STRING (today) + " " + 
            STRING (TIME, "HH:MM:SS") + 
            " - " +
            " Program : " + {1} +
            " Section : " + {2}) format "x(255)".
       PUT Skip.
   END.
END.
/*
** definitions.i
** This include file defines the variables needed within the programs.  These
** are the default ones needed.  Anything specific to the report are defined within
** the report.
**
*/

/*
** We need to make sure the numbers that go into the xml output
** file have no commas, and use the period for the decimal.
** This is so the xml file will have no formatted number in it
** and so the xslt engine can do any math it may want before
** formatting.  In order to be able to format properly later,
** we need an xml tag (or tags) that describe the formatting,
** so set variables before stepping on the format.
*/
DEFINE {1} VARIABLE numberSeparator AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE decimalPoint    AS CHARACTER NO-UNDO.
numberSeparator        = SESSION:NUMERIC-SEPARATOR.
decimalPoint           = SESSION:NUMERIC-DECIMAL-POINT.
SESSION:NUMERIC-FORMAT = "American".

def {1} var Fathom-t-Start_date as char.
def {1} var Fathom-t-end_date as char.
def {1} var t-beg-day as char.
def {1} var t-beg-month as char.
def {1} var t-beg-year as char.
def {1} var t-end-day as char.
def {1} var t-end-month as char.
def {1} var t-end-year as char.
def {1} var t-resrc_name as char format "X(32)".
def {1} var t-length as int.
def {1} var twork1 as int.
def {1} var twork2 as int.
def {1} var Fathom-i-Site_ID            AS CHARACTER FORMAT "x(32)" NO-UNDO.
def {1} var Fathom-i-Rep_Name           AS CHARACTER FORMAT "x(32)" NO-UNDO.
def {1} var Fathom-i-Resrc_Name         AS CHARACTER FORMAT "x(32)" NO-UNDO.
def {1} var Fathom-i-Rep_Type           AS CHARACTER FORMAT "x(32)" NO-UNDO.
def {1} var Fathom-i-Resrc_ID           AS INTEGER NO-UNDO.
def {1} var Fathom-i-Start_date         AS DATE NO-UNDO INITIAL "08/01/2001".
def {1} var Fathom-i-Start_time         AS INTEGER NO-UNDO INITIAL 00000.
def {1} var Fathom-i-End_date           AS DATE NO-UNDO INITIAL "08/30/2001".
def {1} var Fathom-i-End_time           AS INTEGER NO-UNDO INITIAL 86399.
def {1} var Fathom-i-periods            AS INTEGER NO-UNDO INITIAL 365.
def {1} var Fathom-i-reportcode         AS CHARACTER NO-UNDO INITIAL "hh".
def {1} var Fathom-i-filename           AS CHARACTER format "x(255)" NO-UNDO.
def {1} var Fathom-i-program            AS CHARACTER FORMAT "X(255)" NO-UNDO.
def {1} var Fathom-i-Title              AS CHARACTER FORMAT "X(255)" NO-UNDO.
def {1} var Fathom-i-IntervalType       AS CHARACTER NO-UNDO.
def {1} var Fathom-i-OutputType         AS CHARACTER NO-UNDO.
def {1} var Fathom-i-OutputDir          AS CHARACTER FORMAT "x(255)" NO-UNDO.
def {1} var Fathom-i-ResrcStatus        AS CHARACTER NO-UNDO.
def {1} var Fathom-i-Resrc_type         AS CHARACTER NO-UNDO.

def {1} var Fathom-t-HRincrement        AS INTEGER NO-UNDO INITIAL 3599.
def {1} var Fathom-t-DYincrement        AS INTEGER NO-UNDO INITIAL 1.
def {1} var Fathom-t-program            AS CHARACTER FORMAT "X(255)" NO-UNDO.
def {1} var Fathom-t-reportcode         AS CHARACTER NO-UNDO.
def {1} var Fathom-t-periods            AS CHARACTER NO-UNDO.
def {1} var Fathom-t-periods-day        AS INTEGER NO-UNDO.
def {1} var Fathom-t-Rep_Name           AS CHARACTER FORMAT "x(255)" NO-UNDO.
def {1} var Fathom-t-data_Name          AS CHARACTER FORMAT "x(255)" NO-UNDO.
def {1} var Fathom-t-beg-date           AS DATE NO-UNDO EXTENT 366.
def {1} var Fathom-t-end-date           AS DATE NO-UNDO EXTENT 366.
def {1} var Fathom-t-beg-time           AS INTEGER NO-UNDO EXTENT 366.
def {1} var Fathom-t-end-time           AS INTEGER NO-UNDO EXTENT 366.
def {1} var Fathom-beg-val              AS DECIMAL NO-UNDO.
def {1} var Fathom-end-val              AS DECIMAL NO-UNDO.
def {1} var Fathom-change-pct           AS DECIMAL INITIAL 20 NO-UNDO.
def {1} var Fathom-change-val           AS DECIMAL NO-UNDO.
def {1} var Fathom-PassInput            AS INTEGER NO-UNDO.
def {1} var Fathom-numsamples           AS DECIMAL NO-UNDO EXTENT 366.
def {1} var Fathom-display-value        AS CHARACTER NO-UNDO FORMAT "x(12)".

def {1} var Fathom-d-rep_name           AS CHARACTER FORMAT "x(64)" LABEL "Report Name" NO-UNDO.
def {1} var Fathom-t-rep_dir            AS CHARACTER FORMAT "x(64)" NO-UNDO.
def {1} var Fathom-t-colon-name         AS CHARACTER FORMAT "x(64)" NO-UNDO. /* Report-name.i */
def {1} var Fathom-t-x1                 AS DATE FORMAT "99-99-9999" NO-UNDO. /* report-name.i */
def {1} var Fathom-t-x2                 AS INTEGER NO-UNDO. /* report-name.i */
def {1} var Fathom-t-x3                 AS INTEGER NO-UNDO. /* report-name.i */
def {1} var Fathom-t-x4                 AS INTEGER NO-UNDO. /* report-name.i */
def {1} var Fathom-t-rep_type_name      AS CHARACTER FORMAT "x(64)" NO-UNDO. /* report-name.i */
def {1} var Fathom-err-status           AS INTEGER NO-UNDO. /* report-name.i */
def {1} var Fathom-t-seperator          AS CHARACTER NO-UNDO. /* report-name.i */
def {1} var Fathom-t-date               AS CHARACTER NO-UNDO. /* report-name.i */
def {1} var Fathom-t-time               AS CHARACTER NO-UNDO. /* report-name.i */
def {1} var Fathom-Rec-Count            AS INTEGER NO-UNDO.
def {1} var Fathom-Interval-recs        AS INTEGER NO-UNDO EXTENT 366.
def {1} var Fathom-Interval-Count       AS INTEGER NO-UNDO EXTENT 366.
def {1} var Fathom-Transaction-Count    AS INTEGER NO-UNDO EXTENT 366.
def {1} var Fathom-i                    AS INTEGER NO-UNDO.
def {1} var Fathom-j                    AS INTEGER NO-UNDO.
def {1} var Fathom-k                    AS INTEGER NO-UNDO.
def {1} var Fathom-Store-name           AS CHARACTER NO-UNDO. /* trendfilesys.p */
def {1} var Fathom-pass-info            AS CHARACTER format "x(255)" NO-UNDO.
def {1} var Fathom-report-title         AS CHARACTER FORMAT "x(255)" NO-UNDO.
def {1} var Fathom-t-rep_type           AS CHARACTER NO-UNDO.

/* Multiple resource variables */

def {1} var x-i as int initial 0.
def {1} var work-siteid as char format "x(64)".
def {1} var work-resrcname as char format "x(64)".
def {1} var work-resrctype as char format "x(64)".

/* The max number of resources that can fit on a single graph. */
DEFINE {1} VARIABLE defaultNumGraphResources AS INTEGER INITIAL 5.
DEFINE {1} VARIABLE numGraphResources AS INTEGER.

/* Report name variables */

def {1} var Fathom-t-errrep1            AS CHARACTER NO-UNDO.  /* Report-error.i */
def {1} var Fathom-t-errrep2            AS CHARACTER NO-UNDO.  /* Report-error.i */
def {1} var Fathom-t-errrep3            AS CHARACTER NO-UNDO.  /* Report-error.i */
def {1} var Fathom-t-errrep4            AS CHARACTER NO-UNDO.  /* Report-error.i */
def {1} var Fathom-t-errreplength       AS INTEGER NO-UNDO.  /* Report-error.i */
def {1} var Fathom-t-rep1               AS CHARACTER NO-UNDO. 
def {1} var Fathom-t-rep2               AS CHARACTER NO-UNDO.
def {1} var Fathom-t-rep3               AS CHARACTER NO-UNDO.
def {1} var Fathom-t-rep4               AS CHARACTER NO-UNDO. 
def {1} var Fathom-t-replength          AS INTEGER NO-UNDO.
def {1} var Fathom-tfs-rep1             AS CHARACTER NO-UNDO.
def {1} var Fathom-tfs-rep2             AS CHARACTER NO-UNDO.
def {1} var Fathom-tfs-rep3             AS CHARACTER NO-UNDO.
def {1} var Fathom-tfs-rep4             AS CHARACTER NO-UNDO.
def {1} var Fathom-tfs-replength        AS INTEGER NO-UNDO.
def {1} var Fathom-t-IntervalTitle      AS CHARACTER NO-UNDO INITIAL " ". 
def {1} var Fathom-breakdown AS CHAR EXTENT 366 FORMAT "x(32)".

/* Archive Reporting Variables */

DEF {1} VAR Fathom-ar-Date AS DATE NO-UNDO.
DEF {1} VAR Fathom-ar-Count AS INTEGER EXTENT 366 NO-UNDO.

/*
** This variable is for the database archiving.  We may only
** want to increment the sample count, etc. once when calling
** the many database archive add programs (ex. ar-report-add-actsum).
*/
DEFINE {1} VARIABLE doCounters AS LOGICAL NO-UNDO INITIAL NO.

/* Temp table for multiple resources */

DEF {1} TEMP-TABLE tmp-resrc
   FIELD tSiteID AS character 
   FIELD tResrcName AS character 
   FIELD tResrcID AS INTEGER 
   FIELD tResrcType AS character
   INDEX one tSiteID 
   INDEX two tResrcName 
   INDEX three tResrcType
   INDEX four tResrcID.

   /*
   ** Environment variable assignments
   */
   DEFINE {1} VARIABLE fathom-t-fathomReportDir AS CHARACTER NO-UNDO FORMAT "X(128)".
   DEFINE {1} VARIABLE fathom-t-fathomInstallDir AS CHARACTER NO-UNDO FORMAT "X(128)".
   DEFINE {1} VARIABLE fathom-t-GraphList AS CHARACTER NO-UNDO FORMAT "X(128)".

/* Debugging Code */

def {1} var debug-4gl                   AS INTEGER initial 0.
def {1} var pgm-name                    AS CHARACTER.
def {1} var sec-name                    AS CHARACTER.

/*
** Debugging stuff for 4GL
*/
debug-4gl = INTEGER(OS-GETENV("fathomDebug4gl")).

if debug-4gl = ? then debug-4gl = 0.

/*
** Internal Procedures
*/

PROCEDURE create-directory.
pgm-name = "Creating first directory".
sec-name = Fathom-t-rep_name.
{include/debug.i "pgm-name" "sec-name"}

OS-CREATE-DIR VALUE(Fathom-t-rep_name).
Fathom-err-status = OS-ERROR.

IF OS-ERROR NE 0 AND OS-ERROR NE 10 AND OS-ERROR NE 13 THEN
DO:
    PUT SKIP " Errors reported when creating directories! Error Number: ".
    PUT Fathom-err-status FORMAT "-999999".
    PUT SKIP "Report Name failed on : ".
    PUT Fathom-t-rep_name format "X(78)".
    QUIT.
END.
END PROCEDURE.
/* dh-pass-input.i
** This input validates the input data for the History purge process
** The fields passed in are:  
**         Date
**         Action Code to be purged (Optional).
**         
*/
DEF VAR Fathom-pass-info AS CHARACTER.

Fathom-pass-info = SESSION:PARAMETER.

IF Fathom-pass-info = "" THEN
DO:
    MESSAGE "Fathom-pass-info empty in delete history!!!" VIEW-AS ALERT-BOX.
    QUIT.
END.
ELSE DO:
    Fathom-i-date = DATE (ENTRY (1, Fathom-pass-info)) NO-ERROR.
    Fathom-i-ActionCode = ENTRY (2, Fathom-pass-info) NO-ERROR.
END.
Fathom-Rec-Count = Fathom-Rec-Count + 1.
Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Cf_Sample.Sample_Len.
Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Cf_Sample.Sample_Trans.
Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.
DEF VAR fathom-dir AS CHARACTER NO-UNDO.
fathom-dir = OS-GETENV("fathomInstallDir").
IF fathom-dir = ? THEN fathom-dir = ".".

PROPATH = fathom-dir + 
          "," + 
          fathom-dir + 
          "/src" +
          "," + 
          fathom-dir + 
          "/src/fathom4gl-r.pl" +
          "," + 
          PROPATH.

IF debug-4gl = 1 THEN
DO:
    PUT SKIP.
    PUT
        (STRING (TODAY) + " " + 
        STRING (TIME, "HH:MM:SS") + 
        " - " +
        " Program : Displaying PROPATH") FORMAT "x(255)".
    PUT SKIP.
    PUT UNFORMATTED PROPATH.
END.
/*
** This include gets environment variables for Fathom Management
*/

Fathom-t-fathomReportDir = OS-GETENV("fathomReportDir").
IF fathom-t-fathomReportDir = "" or Fathom-t-fathomReportDir = ? THEN
DO:
    fathom-t-fathomReportDir = ".".
END.
Fathom-t-fathomInstallDir = OS-GETENV("fathomInstallDir").
IF fathom-t-fathomInstallDir = "" or Fathom-t-fathomInstallDir = ? THEN
DO:
    fathom-t-fathomInstallDir = ".".
END.
/* Passinput.i
** This input validates the input data and attempts to find the
** appropriate definition file and resource file.
** the variable pass-info should contain the following comma-delimited fields:
** Report Name, Resource ID, Site ID, and Report Type.
** 
*/

Fathom-pass-info = SESSION:PARAMETER.

Fathom-passinput = 1.

pgm-name = "genpassinput.i".
sec-name = "Parsing Input Strings".
{include/debug.i "pgm-name" "sec-name"}

t-length = length(Fathom-pass-info) - 2.

if substring(Fathom-pass-info,1,1) = chr(34) THEN
DO:
   Fathom-pass-info = substring(Fathom-pass-info,2, t-length).
END.

IF Fathom-pass-info = "" THEN
DO:
    PUT SKIP "ERROR!!! Parameters not passed to Report!".
    QUIT.
END.
ELSE DO:
    Fathom-i-rep_name = TRIM(ENTRY (1, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc_name = TRIM(ENTRY (2, Fathom-pass-info)) NO-ERROR.
    Fathom-i-site_id = TRIM(ENTRY (3, Fathom-pass-info)) NO-ERROR.
    Fathom-i-rep_type = TRIM(ENTRY (4, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc_type = TRIM(ENTRY (4, Fathom-pass-info)) NO-ERROR.
    Fathom-t-Start_date = TRIM((ENTRY (5, Fathom-pass-info))) NO-ERROR.
    Fathom-t-End_date = TRIM((ENTRY (6, Fathom-pass-info))) NO-ERROR.
    Fathom-i-start_time = INTEGER (ENTRY (7, Fathom-pass-info)) NO-ERROR.
    Fathom-i-end_time = INTEGER (ENTRY (8, Fathom-pass-info)) NO-ERROR.
    Fathom-i-periods = INTEGER (ENTRY (9, Fathom-pass-info)) NO-ERROR.
    Fathom-i-OutputType = ENTRY (10, Fathom-pass-info) NO-ERROR.
    Fathom-i-program = ENTRY (11, Fathom-pass-info) NO-ERROR.
    Fathom-i-Title = ENTRY (12, Fathom-pass-info) NO-ERROR.
    Fathom-i-IntervalType = ENTRY (13, Fathom-pass-info) NO-ERROR.
    Fathom-i-OutputDir = ENTRY (14, Fathom-pass-info) NO-ERROR.
    Fathom-i-ResrcStatus = ENTRY (15, Fathom-pass-info) NO-ERROR.
END.

If Fathom-i-IntervalType = "" then Fathom-i-IntervalType = "R".

If Fathom-i-OutputType = "" THEN Fathom-i-OutputType = "R".

pgm-name = "genpassinput.i".
sec-name = "Rep Type : " + Fathom-i-rep_type.
{include/debug.i "pgm-name" "sec-name"}

/*
** Start processing date stuff
*/

IF Fathom-t-start_date = ? OR Fathom-t-end_date = ? THEN
DO:
    PUT SKIP "ERROR! Begin Date of " 
             Fathom-t-start_date 
             " is invalid or greater than end date".
    QUIT.
END.

IF Fathom-i-end_date = ? THEN
DO:
    PUT SKIP "ERROR! End Date of " Fathom-t-end_date " is invalid.".
    QUIT.
END.

pgm-name = "Outputting data".
sec-name = Fathom-i-rep_name + ":" +
           Fathom-i-resrc_name + ":" +
           Fathom-i-site_id + ":" +
           Fathom-i-rep_type + ":" +
           string(Fathom-t-Start_date) + ":" +
           string(Fathom-t-End_date) + ":" +
           string(Fathom-i-start_time) + ":" +
           string(Fathom-i-end_time) + ":" +
           string(Fathom-i-periods) + ":" + 
           Fathom-i-OutputType + ":" +
           Fathom-i-program + ":" +
           Fathom-i-title + ":" +
           Fathom-i-IntervalType + ":" +  
           Fathom-i-OutputDir + ":" +
           Fathom-i-filename.
{include/debug.i "pgm-name" "sec-name"}

pgm-name = "genpassinput.i".
sec-name = "Parsing dates".
{include/debug.i "pgm-name" "sec-name"}

twork1 = index(Fathom-t-Start_date,"/").
twork2 = r-index(Fathom-t-Start_date,"/").

t-beg-day = substr(Fathom-t-Start_date,(twork1 + 1),(twork2 - twork1 - 1)).
t-beg-month = substr(Fathom-t-Start_date,1,(twork1 - 1)).
t-beg-year = substr(Fathom-t-Start_date,(twork2 + 1),4).

twork1 = index(Fathom-t-end_date,"/").
twork2 = r-index(Fathom-t-end_date,"/").

t-end-day = substr(Fathom-t-end_date,(twork1 + 1),(twork2 - twork1 - 1)).
t-end-month = substr(Fathom-t-end_date,1,(twork1 - 1)).
t-end-year = substr(Fathom-t-end_date,(twork2 + 1),4).

CASE SESSION:DATE-FORMAT:
   when "mdy" THEN
      DO:
         sec-name = "Date Output Format: mdy".
         {include/debug.i "pgm-name" "sec-name"}
         Fathom-i-Start_Date = Date(Fathom-t-start_date).
         Fathom-i-End_Date = Date(Fathom-t-End_date).
      END.
   when "myd" THEN
      DO:
         sec-name = "Date Output Format: myd".
         {include/debug.i "pgm-name" "sec-name"}
         Fathom-i-start_date = DATE (t-beg-month + "/" + 
                               t-beg-year + "/" + t-beg-day). 
         Fathom-i-end_date = DATE (t-end-month + "/" + 
                             t-end-year + "/" + t-end-day). 
      END. 
   when "dmy" THEN
      DO:
         sec-name = "Date Output Format: dmy".
         {include/debug.i "pgm-name" "sec-name"}
         Fathom-i-start_date = DATE (t-beg-day + "/" + 
                               t-beg-month + "/" + t-beg-year). 
         Fathom-i-end_date = DATE (t-end-day + "/" + 
                             t-end-month + "/" + t-end-year). 
      END. 
   when "dym" THEN
      DO:
         sec-name = "Date Output Format: dym".
         {include/debug.i "pgm-name" "sec-name"}
         Fathom-i-start_date = DATE (t-beg-day + "/" + 
                               t-beg-year + "/" + t-beg-month). 
         Fathom-i-end_date = DATE (t-end-day + "/" + 
                             t-end-year + "/" + t-end-month). 
      END. 
   when "ymd" THEN
      DO:
         sec-name = "Date Output Format: ymd".
         {include/debug.i "pgm-name" "sec-name"}
         Fathom-i-start_date = DATE (t-beg-year + "/" + 
                               t-beg-month + "/" + t-beg-day). 
         Fathom-i-end_date = DATE (t-end-year + "/" + 
                             t-end-month + "/" + t-end-day). 
      END. 
   when "ydm" THEN
      DO:
         sec-name = "Date Output Format: ydm".
         {include/debug.i "pgm-name" "sec-name"}
         Fathom-i-start_date = DATE (t-beg-year + "/" + 
                               t-beg-day + "/" + t-beg-month). 
         Fathom-i-end_date = DATE (t-end-year + "/" + 
                             t-end-day + "/" + t-end-month). 
      END. 
END CASE.

IF Fathom-i-start_time LT 1 THEN Fathom-i-start_time = 00001.
IF Fathom-i-end_time LT 1 THEN Fathom-i-end_time = 86399.
IF Fathom-i-periods LT 1 THEN Fathom-i-periods = 4.

/*
** Set up Report Title Stuff
*/

sec-name = "Creating Appropriate titles ".
{include/debug.i "pgm-name" "sec-name"}

CASE  Fathom-i-program:
    WHEN "src/dbafterimage" THEN DO:
        Fathom-report-title = "Trend After-Image Detail Report ".
        Fathom-t-rep_type_name = "Database_AfterImage".
    END.
    WHEN "src/dbbeforeimage" THEN DO:
        Fathom-report-title =  "Trend Before-Image Detail Report ".
        Fathom-t-rep_type_name = "Database_BeforeImage".
    END.
    WHEN "src/dbdisk" THEN DO:
        Fathom-report-title =  "Trend Database Disk Detail Report ".
        Fathom-t-rep_type_name = "Database_Disk".
    END.
    WHEN "src/dblocks" THEN DO:
        Fathom-report-title =  "Trend Locking Detail Report ".
        Fathom-t-rep_type_name = "Database_Locks".
    END.
    WHEN "src/dbmemory" THEN DO:
        Fathom-report-title =  "Trend Database Memory Detail Report ".
        Fathom-t-rep_type_name = "Database_Memory".
    END.
    WHEN "src/dbrecord" THEN DO:
        Fathom-report-title =  "Trend Record Detail Report ".
        Fathom-t-rep_type_name = "Database_Record".
    END.
    WHEN "src/dbservers" THEN DO:
        Fathom-report-title =  "Trend Server Detail Report ".
        Fathom-t-rep_type_name = "Database_Server".
    END.
    WHEN "src/dbsummary" THEN DO:
        Fathom-report-title =  "Trend Summary Report ".
        Fathom-t-rep_type_name = "Database_Summary".
    END.
    WHEN "src/dbdetail" THEN DO:
        Fathom-report-title =  "Trend Detail Report ".
        Fathom-t-rep_type_name = "Database_Detail".
    END.
    WHEN "src/dbcheckpoint" THEN DO:
        Fathom-report-title =  "Trend Checkpoint Summary Report ".
        Fathom-t-rep_type_name = "Database_Checkpoint".
    END.
    WHEN "src/dbindexstat" THEN DO:
        Fathom-t-rep_type_name = "Database_IndexStat".
    END.
    WHEN "src/dbtablestat" THEN DO:
        Fathom-t-rep_type_name = "Database_TableStat".
    END.
    WHEN "src/systemcpu" THEN DO:
        Fathom-report-title =  "Trend System CPU Report ".
        Fathom-t-rep_type_name = "System_CPU".
    END.
    WHEN "src/systemmemory" THEN DO:
        Fathom-report-title =  "Trend System Memory Report ".
        Fathom-t-rep_type_name = "System_Memory".
    END.
    WHEN "src/systemdevice" THEN DO:
        Fathom-report-title =  "Trend System Device Report ".
        Fathom-t-rep_type_name = "System_Device".
    END.
    WHEN "src/systemfilesystem" THEN DO:
        Fathom-t-rep_type_name = "System_FileSystem".
        Fathom-report-title = "Trend FILE I/O Detail Report ".
    END.
    WHEN "src/alertindividual" THEN DO:
        Fathom-t-rep_type_name = "Alert".
    END.
    WHEN "src/alertgeneral" THEN DO:
        Fathom-t-rep_type_name = "General".
    END.
    WHEN "src/network" THEN DO:
        Fathom-report-title =  "Trend Network Summary Report ".
        Fathom-t-rep_type_name = "Network".
    END.
    WHEN "src/systemfilesize" THEN DO:
        Fathom-report-title =  "Trend System File Size Report ".
        Fathom-t-rep_type_name = "System_FileSize".
    END.
    WHEN "src/trendrecommend" THEN DO:
        Fathom-t-rep_type_name = "Recommend".
    END.
    OTHERWISE DO:
        Fathom-t-rep_type_name = "Custom_Report".
    END.
END CASE.
    
sec-name = "Title set to : " + fathom-i-title.
{include/debug.i "pgm-name" "sec-name"}

IF Fathom-i-Title NE "" THEN 
DO:
    sec-name = "Title passed in : " + fathom-i-title.
    {include/debug.i "pgm-name" "sec-name"}

    Fathom-report-title = Fathom-i-Title.
END.

CASE Fathom-i-IntervalType:
    WHEN "D" THEN Fathom-t-IntervalTitle = "Data Reported is Real Values".
    WHEN "S" THEN Fathom-t-IntervalTitle = "Data Reported is Per Second Values".
    WHEN "M" THEN Fathom-t-IntervalTitle = "Data Reported is Per Minute Values".
    WHEN "H" THEN Fathom-t-IntervalTitle = "Data Reported is Per Hour Values".
    WHEN "R" THEN Fathom-t-IntervalTitle = "Data Reported is Per Record Values".
    WHEN "T" THEN Fathom-t-IntervalTitle = "Data Reported is Per Transaction Values".
    OTHERWISE Fathom-t-IntervalTitle = " ".
END CASE. 

CASE Fathom-i-rep_type:
    WHEN "Alert" THEN Fathom-t-IntervalTitle = "Data Reported can only be in real values ".
    WHEN "general" THEN Fathom-t-IntervalTitle = "Data Reported can only be in real values ".
    WHEN "recommend" THEN Fathom-t-IntervalTitle = "Data Reported can only be in real values".
END CASE.

pgm-name = "genpassinput.i".
sec-name = STRING(Fathom-i-start_date) + " -- " + STRING(fathom-i-end_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}
/*
** no-data.i
**
** This program is run when there is no data found for the time frame.  It attempts to
** point the customer to a point where there is data available to assist them in getting a 
** worthwhile report.
*/

/* 
** Variable assignments
*/

DEFINE VARIABLE t-first-date AS DATE NO-UNDO initial 1/1/01.
DEFINE VARIABLE t-last-date AS DATE NO-UNDO.
DEFINE VARIABLE t-first-time AS INTEGER NO-UNDO.
DEFINE VARIABLE t-last-time AS INTEGER NO-UNDO.

/*
** Find the first sample record for the resource
*/
FOR EACH cf_sample WHERE
    Resrc_ID = Fathom-i-resrc_ID AND 
    site_ID = Fathom-i-Site_ID NO-LOCK:

    IF t-first-date = 1/1/01 THEN
    DO:
        t-first-date = cf_sample.sample_date.
        t-last-date = cf_sample.sample_date.
        t-first-time = cf_sample.sample_time.
        t-last-time = cf_sample.sample_time.
    END.
    ELSE
    DO:
        /* 
        ** Do the first date stuff
        */
        IF cf_sample.Sample_date LT t-first-date THEN
        DO:
            t-first-date = cf_sample.sample_date.
            t-first-time = cf_sample.sample_time.
        END.
        ELSE
        DO:
            IF cf_sample.sample_date = t-first-date THEN
            DO:
                IF cf_sample.sample_time LT t-first-time THEN
                    t-first-time = cf_sample.sample_time.
            END.
        END.

        /*
        ** Do the last date stuff
        */
        IF cf_sample.Sample_date GT t-last-date THEN
        DO:
            t-last-date = cf_sample.sample_date.
            t-last-time = cf_sample.sample_time.
        END.
        ELSE
        DO:
            IF cf_sample.sample_date = t-last-date THEN
            DO:
                IF cf_sample.sample_time GT t-last-time THEN
                    t-last-time = cf_sample.sample_time.
            END.
        END.
    END. /* of first time through process ELSE loop */
END.  /* of for each statement */

/*
** Print the information out
*/
/*
If t-first-date = 1/1/01 THEN
DO:
    PUT STREAM ReportOutput SKIP(1) "This resource has never been trended" FORMAT "X(65)".
END.
ELSE
DO:
    PUT STREAM ReportOutput SKIP(1) "This resource was first trended on " 
       t-first-date FORMAT "99/99/9999"
       " at "
       STRING (t-first-time, "HH:MM:SS") 
       ".".
    PUT STREAM ReportOutput SKIP "This resource was last trended on  " 
       t-last-date FORMAT "99/99/9999"
       " at "
       STRING (t-last-time, "HH:MM:SS")
       ".".
END.
*/
/* Passinput.i
** This input validates the input data and attempts to find the
** appropriate definition file and resource file.
** the variable pass-info should contain the following comma-delimited fields:
** Report Name, Resource ID, Site ID, and Report Type.
** 
*/

Fathom-pass-info = SESSION:PARAMETER.

Fathom-passinput = 1.

pgm-name = "pass-input.i".
sec-name = "Parsing Input Strings".
{include/debug.i "pgm-name" "sec-name"}

t-length = length(Fathom-pass-info) - 2.

Fathom-t-DYincrement = 1.
if substring(Fathom-pass-info,1,1) = chr(34) THEN
DO:
   Fathom-pass-info = substring(Fathom-pass-info,2, t-length).
END.

IF Fathom-pass-info = "" THEN
DO:
    PUT SKIP "ERROR!!! Parameters not passed to Report!".
    QUIT.
END.
ELSE DO:
    Fathom-i-rep_name = TRIM(ENTRY (1, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc_name = TRIM(ENTRY (2, Fathom-pass-info)) NO-ERROR.
    Fathom-i-site_id = TRIM(ENTRY (3, Fathom-pass-info)) NO-ERROR.
    Fathom-i-rep_type = TRIM(ENTRY (4, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc_type = TRIM(ENTRY (4, Fathom-pass-info)) NO-ERROR.
    Fathom-t-Start_date = TRIM((ENTRY (5, Fathom-pass-info))) NO-ERROR.
    Fathom-t-End_date = TRIM((ENTRY (6, Fathom-pass-info))) NO-ERROR.
    Fathom-i-start_time = INTEGER (ENTRY (7, Fathom-pass-info)) NO-ERROR.
    Fathom-i-end_time = INTEGER (ENTRY (8, Fathom-pass-info)) NO-ERROR.
/* 
** This variable is no longer used for 2.0A
    Fathom-i-periods = INTEGER (ENTRY (9, Fathom-pass-info)) NO-ERROR.
*/
    Fathom-i-reportcode = TRIM((ENTRY (9, Fathom-pass-info))) NO-ERROR.
    Fathom-i-OutputType = ENTRY (10, Fathom-pass-info) NO-ERROR.
    Fathom-i-program = ENTRY (11, Fathom-pass-info) NO-ERROR.
    Fathom-i-Title = ENTRY (12, Fathom-pass-info) NO-ERROR.
    Fathom-i-IntervalType = ENTRY (13, Fathom-pass-info) NO-ERROR.
    Fathom-i-OutputDir = ENTRY (14, Fathom-pass-info) NO-ERROR.
    Fathom-i-ResrcStatus = ENTRY (15, Fathom-pass-info) NO-ERROR.
END.


IF Fathom-i-IntervalType = "" THEN Fathom-i-IntervalType = "R".

IF Fathom-i-OutputType = "" THEN Fathom-i-OutputType = "R".

pgm-name = "pass-input.i".
sec-name = "Rep Type : " + Fathom-i-rep_type.
{include/debug.i "pgm-name" "sec-name"}

/*
** Start processing date stuff
*/

IF Fathom-t-start_date = ? OR Fathom-t-end_date = ? THEN
DO:
    PUT SKIP "Begin Date of " 
             Fathom-t-start_date 
             " is invalid or greater than end date".
    QUIT.
END.

IF Fathom-i-end_date = ? THEN
DO:
    PUT SKIP "End Date of " Fathom-t-end_date " is invalid.".
    QUIT.
END.

/* 
** Output data coming in if debugging is on.
*/
pgm-name = "Outputting data".
sec-name = Fathom-i-rep_name + ":" +
           Fathom-i-resrc_name + ":" +
           Fathom-i-site_id + ":" +
           Fathom-i-rep_type + ":" +
           string(Fathom-t-Start_date) + ":" +
           string(Fathom-t-End_date) + ":" +
           string(Fathom-i-start_time) + ":" +
           string(Fathom-i-end_time) + ":" +
           Fathom-i-reportcode + ":" + 
           Fathom-i-OutputType + ":" +
           Fathom-i-program + ":" +
           Fathom-i-title + ":" +
           Fathom-i-IntervalType + ":" +  
           Fathom-i-OutputDir + ":" +
           Fathom-i-filename.
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Parsing dates".
{include/debug.i "pgm-name" "sec-name"}

/*
** Process Report Title appropriately
*/
sec-name = "Title set to : " + fathom-i-title.
{include/debug.i "pgm-name" "sec-name"}

IF Fathom-i-Title NE "" THEN 
DO:
    sec-name = "Title passed in : " + fathom-i-title.
    {include/debug.i "pgm-name" "sec-name"}

    Fathom-report-title = Fathom-i-Title.
END.
ELSE Fathom-report-title = "".
/*
** Process resource names appropriately
*/

DO x-i = 1 TO NUM-ENTRIES(Fathom-i-resrc_name, " "):
   work-siteid = TRIM(ENTRY(x-i, Fathom-i-site_id, " ")) NO-ERROR.
   work-resrcname = TRIM(ENTRY(x-i, Fathom-i-resrc_name, " ")) NO-ERROR.
   work-resrctype = TRIM(ENTRY(x-i, Fathom-i-resrc_type, " ")) NO-ERROR.
   pgm-name = "passinput.i".
   sec-name = "WORK SITEID: " + work-siteid.
   {include/debug.i "pgm-name" "sec-name"}
   sec-name = "WORK Resrc Name: " + work-resrcname.
   {include/debug.i "pgm-name" "sec-name"}
   sec-name = "WORK Resrc Type: " + work-resrctype.
   {include/debug.i "pgm-name" "sec-name"}
  
   FIND FIRST tmp-resrc WHERE
      tSiteID = work-SiteID AND
      tResrcName = work-resrcname AND
      tresrcType = work-resrctype NO-LOCK NO-ERROR.
   IF NOT AVAILABLE tmp-resrc THEN
   DO:
        FIND FIRST Cf_Resrc WHERE
           Cf_Resrc.Site_ID = work-SiteID AND
           Cf_Resrc.Resrc_Name = work-resrcname AND
           Cf_Resrc.Resrc_Type = work-resrctype NO-LOCK NO-ERROR.
        IF AVAILABLE Cf_Resrc THEN
	DO:
	    CREATE tmp-resrc.
	    tSiteID = Cf_Resrc.Site_ID.
	    tResrcName = Cf_Resrc.Resrc_Name.
	    tresrcID = Cf_Resrc.Resrc_ID.
	    tResrcType = Cf_Resrc.Resrc_Type.
	    RELEASE tmp-resrc.
	END.
	ELSE
	DO:
	    PUT SKIP "ERROR - No Resource Record Found for Multiple Resources (SiteID, ResrcName, ResrcType)" work-SiteID ":" work-resrcname ":" work-resrctype.
	END.
   END. 
END.

IF DEBUG-4gl = 1 THEN
DO:
   FOR EACH tmp-resrc:
      pgm-name = "Resource Names".
      sec-name = tSiteID + ":" +
      tResrcName + ":" +
      STRING (tResrcID) + ":" +
      tResrcType.
      {include/debug.i "pgm-name" "sec-name"}
   END.
END.

/*
** Start with the beginning date and pull out the day, month, and year
*/

twork1 = index(Fathom-t-Start_date,"/").
twork2 = r-index(Fathom-t-Start_date,"/").

t-beg-day = substr(Fathom-t-Start_date,(twork1 + 1),(twork2 - twork1 - 1)).
t-beg-month = substr(Fathom-t-Start_date,1,(twork1 - 1)).
t-beg-year = substr(Fathom-t-Start_date,(twork2 + 1),4).

/*
** Ensure that the date is 4 digits.
*/
IF LENGTH (t-beg-year) = 2 then t-beg-year = "20" + t-beg-year.

/*
** Parse apart the ending date into day, month, and year
*/

twork1 = index(Fathom-t-end_date,"/").
twork2 = r-index(Fathom-t-end_date,"/").

t-end-day = substr(Fathom-t-end_date,(twork1 + 1),(twork2 - twork1 - 1)).
t-end-month = substr(Fathom-t-end_date,1,(twork1 - 1)).
t-end-year = substr(Fathom-t-end_date,(twork2 + 1),4).

/*
** Ensure that the date is 4 digits.
*/
IF LENGTH (t-end-year) = 2 then t-end-year = "20" + t-end-year.

/*
** Put the date back together again in the appropirate date format.
** This is due to us always receiving the date in MM/DD/YYYY format.
*/
CASE SESSION:DATE-FORMAT:
   when "mdy" THEN
      DO:
         Fathom-i-Start_Date = Date(Fathom-t-start_date).
         Fathom-i-End_Date = Date(Fathom-t-End_date).
      END.
   when "myd" THEN
      DO:
         Fathom-i-start_date = DATE (t-beg-month + "/" + 
                               t-beg-year + "/" + t-beg-day). 
         Fathom-i-end_date = DATE (t-end-month + "/" + 
                             t-end-year + "/" + t-end-day). 
      END. 
   when "dmy" THEN
      DO:
         Fathom-i-start_date = DATE (t-beg-day + "/" + 
                               t-beg-month + "/" + t-beg-year). 
         Fathom-i-end_date = DATE (t-end-day + "/" + 
                             t-end-month + "/" + t-end-year). 
      END. 
   when "dym" THEN
      DO:
         Fathom-i-start_date = DATE (t-beg-day + "/" + 
                               t-beg-year + "/" + t-beg-month). 
         Fathom-i-end_date = DATE (t-end-day + "/" + 
                             t-end-year + "/" + t-end-month). 
      END. 
   when "ymd" THEN
      DO:
         Fathom-i-start_date = DATE (t-beg-year + "/" + 
                               t-beg-month + "/" + t-beg-day). 
         Fathom-i-end_date = DATE (t-end-year + "/" + 
                             t-end-month + "/" + t-end-day). 
      END. 
   when "ydm" THEN
      DO:
         Fathom-i-start_date = DATE (t-beg-year + "/" + 
                               t-beg-day + "/" + t-beg-month). 
         Fathom-i-end_date = DATE (t-end-year + "/" + 
                             t-end-day + "/" + t-end-month). 
      END. 
END CASE.

/*
** Check the end date to insure that it isn't past today.  If it is
** then set it to today.
*/

IF Fathom-i-end_date GT TODAY THEN Fathom-i-end_date = TODAY.
IF Fathom-i-start_time LT 1 THEN Fathom-i-start_time = 00000.
IF Fathom-i-end_time LT 1 THEN Fathom-i-end_time = 86399.
IF Fathom-i-end_time EQ 86400 then Fathom-i-end_time = 86399.

/*
** Figure out number of periods
** This section will determine, based on the report type and the dates and times provided
** how many report periods we should have.  This is then used in trenddates when we set up
** the buckets for specific dates within each column.
**
** NOTE: The limits below for the number of columns in a report
** must match the Fathom UI.
*/
CASE Fathom-i-reportcode:
    /*
    ** Hourly columns by hour
    */
    WHEN "hh" THEN
    DO:
	    /*
	    ** This is for a report with more than 1 day.
	    ** This is presently not allowed.
	    */
	END.
    /*
    ** Hourly columns by 15 minute interval
    */
    WHEN "hi" THEN
    DO:
	    IF Fathom-i-start_date NE Fathom-i-end_date THEN
	    DO:
	        Fathom-i-periods = ((86400 - fathom-i-start_time) + fathom-i-end_time).
	        Fathom-i-periods = INTEGER ((Fathom-i-periods + 1800) / 60 / 60).
	        IF Fathom-i-periods = 0 THEN Fathom-i-periods = 1.
	    END.
	    ELSE
	    DO:
	        Fathom-i-periods = INTEGER ((Fathom-i-end_time - Fathom-i-start_time + 1800) / 60 / 60).
	        IF Fathom-i-periods = 0 THEN Fathom-i-periods = 1.
	    END.
	    Fathom-i-periods = Fathom-i-periods * 4.
	    Fathom-t-HRincrement = 899.
	    IF Fathom-i-periods GT 288 THEN 
            DO:
	       PUT SKIP 
	       STRING (today) " " 
               STRING (TIME, "HH:MM:SS")
               " - "
	       " Hourly reports can only have 288 columns (3 days)."
	       SKIP
	       " This report will be limited to this number of columns. " .

	       Fathom-i-periods = 288.
	    END.
            sec-name = "Configuring Hour by 15 minute increments periods: " + STRING (Fathom-i-periods).
            {include/debug.i "pgm-name" "sec-name"}
	END.
    /*
    ** Daily columns by day
    */
    WHEN "dd" THEN
    DO:
        Fathom-t-DYincrement = 1.
        /* The "+ 1" here is for date math.  We want to include both dates in the report. */
        Fathom-i-periods = Fathom-i-end_date - Fathom-i-start_date + 1.
        IF Fathom-i-periods = 0 THEN Fathom-i-periods = 1.
        IF Fathom-i-periods GT 365 THEN 
        DO:
            Fathom-i-Start_Date = Fathom-i-End_Date - 365.
            PUT SKIP 
                STRING(TODAY) " " 
                STRING(TIME, "HH:MM:SS")
                " - "
                " Daily reports can only have 365 columns ( 1 year )."
                SKIP
                " Report date has been adjusted to: " 
                Fathom-i-Start_Date.
            Fathom-i-periods = 365.
        END.

        sec-name = "Configuring Day by Day periods: " + STRING(Fathom-i-periods).
        {include/debug.i "pgm-name" "sec-name"}.
    END.
    /*
    ** Daily columns by hour
    */
    WHEN "dh" THEN
    DO:
        Fathom-t-DYincrement = 1.
        Fathom-t-HRincrement = 3599.
        /* The "+ 1" here is for date math.  We want to include both dates in the report. */
        Fathom-i-periods = Fathom-i-end_date - Fathom-i-start_date + 1.
        IF Fathom-i-periods = 0 THEN Fathom-i-periods = 1.
        IF Fathom-i-start_time = 0 AND Fathom-i-end_time = 86399 THEN
        DO:
            Fathom-i-periods = Fathom-i-periods * 24.
            Fathom-t-periods-day = 24.
        END.
        ELSE
        DO:
            Fathom-t-periods-day = INTEGER(((Fathom-i-end_time - Fathom-i-start_time) / Fathom-t-HRincrement)).
            Fathom-i-periods = Fathom-i-periods * Fathom-t-periods-day.
        END.

        IF Fathom-i-periods GT 168 THEN 
        DO:
            /* The "+ 1" here is for date math.  We want to include both dates in the report. */
            Fathom-i-Start_Date = Fathom-i-end_date - (168 / Fathom-t-periods-day) + 1.
            PUT SKIP 
                STRING(TODAY) " " 
                STRING(TIME, "HH:MM:SS")
                " - "
                " Hourly reports can only have 168 columns ("
                STRING(TRUNCATE(168 / Fathom-t-periods-day, 0))
                " days)."
    	        SKIP
                " Report date has been adjusted to: " 
    	        Fathom-i-Start_Date.
            Fathom-i-periods = 168.
        END.

        sec-name = "Configuring Day by Hour periods: " + STRING(Fathom-i-periods).
        {include/debug.i "pgm-name" "sec-name"}.
	END.
    /*
    ** Weekly columns by week
    */
    WHEN "ww" THEN
    DO:
        Fathom-i-periods = INTEGER ((Fathom-i-end_date - Fathom-i-start_date) / 7 + 0.5).
        IF Fathom-i-periods LT 1 THEN Fathom-i-periods = 1.
        Fathom-t-DYincrement = 7.
        IF Fathom-i-periods GT 208 THEN
        DO:
            Fathom-i-Start_Date = Fathom-i-End_Date - 1456 .
            PUT SKIP 
                STRING(TODAY) " " 
                STRING(TIME, "HH:MM:SS")
                " - "
                " Weekly reports can only have 208 columns ( 4 years )."
                SKIP
                " Report date has been adjusted to: " 
                Fathom-i-Start_Date.
            Fathom-i-periods = 208.
        END.

        sec-name = "Configuring Week by Week periods: " + STRING(Fathom-i-periods).
        {include/debug.i "pgm-name" "sec-name"}.
    END.
    /*
    ** Weekly columns by day
    */
    WHEN "wd" THEN
    DO:
        /* The "+ 1" here is for date math.  We want to include both dates in the report. */
        Fathom-i-periods = Fathom-i-end_date - Fathom-i-start_date + 1.
        IF Fathom-i-periods = 0 THEN Fathom-i-periods = 1.
        IF Fathom-i-periods GT 365 THEN 
        DO:
            Fathom-i-Start_Date = Fathom-i-End_Date - 365 .
            PUT SKIP
                STRING(TODAY) " "
                STRING(TIME, "HH:MM:SS")
                " - "
    	        " Daily reports can only have 365 columns ( 1 year )."
                SKIP
                " Report date has been adjusted to: "
                Fathom-i-Start_Date.
            Fathom-i-periods = 365.
        END.

        sec-name = "Configuring Week by Day periods: " + STRING(Fathom-i-periods).
        {include/debug.i "pgm-name" "sec-name"}.
    END.
    /*
    ** Monthly columns by month
    */
    WHEN "mm" THEN
    DO:
        /*
        ** This determines if it falls within the same year or not.
        */
        IF INTEGER(t-end-year) - INTEGER(t-beg-year) = 0 THEN
        DO:
            Fathom-i-periods = Fathom-i-end_date - Fathom-i-start_date.
            Fathom-i-periods = INTEGER (t-end-month) - INTEGER (t-beg-month) + 1.
        END.
        ELSE
        DO:
            Fathom-i-periods = 12 - INTEGER(t-beg-month) + INTEGER(t-end-month) + 1.
        	Fathom-i-periods = ((INTEGER(t-end-year) - INTEGER(t-beg-year) - 1) * 12) + Fathom-i-periods.
        END.
        IF Fathom-i-periods = 0 THEN Fathom-i-periods = 1.
        Fathom-t-DYincrement = 28.
        IF Fathom-i-periods GT 96 THEN 
        DO:
           Fathom-i-Start_Date = Fathom-i-End_Date - 2920 .
           PUT SKIP 
               STRING(TODAY) " " 
               STRING(TIME, "HH:MM:SS")
               " - "
               " Monthly reports can only have 96 columns ( 8 years )."
               SKIP
               " Report date has been adjusted to: " 
               Fathom-i-Start_Date.   
           Fathom-i-periods = 96.
        END.

        sec-name = "Configuring Month by Month periods: " + STRING(Fathom-i-periods).
        {include/debug.i "pgm-name" "sec-name"}.
    END.
    /*
    ** Monthly columns by week
    */
    WHEN "mw" THEN
    DO:
        Fathom-i-periods = INTEGER ((Fathom-i-end_date - Fathom-i-start_date) / 7 + 0.5).
        IF Fathom-i-periods LT 1 THEN Fathom-i-periods = 1.
        Fathom-t-DYincrement = 7.
        IF Fathom-i-periods GT 208 THEN
        DO:
            Fathom-i-Start_Date = Fathom-i-End_Date - 1456 .
            PUT SKIP 
                STRING(TODAY) " " 
                STRING(TIME, "HH:MM:SS")
                " - "
                " Weekly reports can only have 208 columns ( 4 years )."
                SKIP
                " Report date has been adjusted to: " 
                Fathom-i-Start_Date.   
            Fathom-i-periods = 208.
        END.
        sec-name = "Configuring Month by Week periods: " + STRING(Fathom-i-periods).
        {include/debug.i "pgm-name" "sec-name"}.
    END.
    OTHERWISE
    DO:
        Fathom-t-DYincrement = 1.
        Fathom-i-periods = Fathom-i-end_date - Fathom-i-start_date + 1.
        IF Fathom-i-periods = 0 THEN Fathom-i-periods = 1.
        IF Fathom-i-periods GT 365 THEN
        DO:
            Fathom-i-Start_Date = Fathom-i-End_Date - 365 .
            PUT SKIP 
                STRING(TODAY) " " 
                STRING(TIME, "HH:MM:SS")
                " - "
                " Default reports can only have 365 columns ( 1 year )."
                SKIP
                " Report date has been adjusted to: " 
                Fathom-i-Start_Date.
            Fathom-i-periods = 365.
        END.

        Fathom-i-reportcode = "dd".

        sec-name = "Report Code was not passed.  Defaulting to Day by Day Report Format".
        {include/debug.i "pgm-name" "sec-name"}
        sec-name = "Configuring Day by Day periods: " + STRING(Fathom-i-periods).
        {include/debug.i "pgm-name" "sec-name"}
    END.
END CASE.

pgm-name = "passinput.i".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"} 
/*
** Read the resource record for resource ID
*/
find first Cf_resrc where cf_resrc.resrc_name = Fathom-i-resrc_name AND
                          Cf_resrc.site_id = Fathom-i-site_id AND
			  Cf_resrc.resrc_type = Fathom-i-resrc_type NO-ERROR.

IF available Cf_Resrc THEN
DO:
    Fathom-i-Resrc_ID = Cf_resrc.Resrc_ID.
END.
ELSE
DO:
    PUT SKIP "No Resource with the name of " Fathom-i-resrc_name " exists.".
    QUIT.
END.
include-list = "
ActBuf_Flushed,
ActBuf_LogicReads,
ActSum_DbReads,
ActSum_DbWrites,
ActLog_BITotWrites,
ActLog_BIWWrites,
ActLock_ExclWait,
ActLock_RecGetWait,
ActLock_ShrWait,
ActLock_UpgWait,
ActLog_AINoBufAvail,
ActLog_BIBBufWaits,
ActLog_BIEBufWaits,
ActLog_BIPartialWrites,
CPU_Usr,
CPU_System,
CPU_Wait,
CPU_Idle,
Mem_SysTot,
Mem_VirtTot,
Mem_VirtFree,
Mem_SysFree,
Mem_PgIn,
Mem_PgOut
".
FIND FIRST Db_ActBuf WHERE cf_sample.sample_id = Db_ActBuf.sample_ID NO-LOCK NO-ERROR.                        
FIND FIRST data_store WHERE name = "ActBuf_Deferred" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActBuf.ActBuf_Deferred.
FIND FIRST data_store WHERE name = "ActBuf_Flushed" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActBuf.ActBuf_Flushed.
FIND FIRST data_store WHERE name = "ActBuf_LogicReads" NO-LOCK NO-ERROR.                                      
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActBuf.ActBuf_LogicReads.
FIND FIRST data_store WHERE name = "ActBuf_LogicWrites" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActBuf.ActBuf_LogicWrites.
FIND FIRST data_store WHERE name = "ActBuf_OSReads" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActBuf.ActBuf_OSReads.
FIND FIRST data_store WHERE name = "ActBuf_OSWrites" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActBuf.ActBuf_OSWrites.
FIND FIRST Db_ActLock WHERE cf_sample.sample_id = Db_ActLock.sample_ID NO-LOCK NO-ERROR.                      
FIND FIRST data_store WHERE name = "ActLock_CanclReq" NO-LOCK NO-ERROR.                                       
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_CanclReq. 
FIND FIRST data_store WHERE name = "ActLock_Downgrade" NO-LOCK NO-ERROR.                                      
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_Downgrade.
FIND FIRST data_store WHERE name = "ActLock_ExclFind" NO-LOCK NO-ERROR.                                       
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ExclFind. 
FIND FIRST data_store WHERE name = "ActLock_ExclLock" NO-LOCK NO-ERROR.                                       
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ExclLock.
FIND FIRST data_store WHERE name = "ActLock_ExclReq" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ExclReq. 
FIND FIRST data_store WHERE name = "ActLock_ExclWait" NO-LOCK NO-ERROR.                                       
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ExclWait.
FIND FIRST data_store WHERE name = "ActLock_RecGetLock" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_RecGetLock.
FIND FIRST data_store WHERE name = "ActLock_RecGetReq" NO-LOCK NO-ERROR.                                      
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_RecGetReq.
FIND FIRST data_store WHERE name = "ActLock_RecGetWait" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_RecGetWait.
FIND FIRST data_store WHERE name = "ActLock_ShrFind" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ShrFind.  
FIND FIRST data_store WHERE name = "ActLock_ShrLock" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ShrLock.                                   
FIND FIRST data_store WHERE name = "ActLock_ShrReq" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ShrReq.                                    
FIND FIRST data_store WHERE name = "ActLock_ShrWait" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_ShrWait.                                   
FIND FIRST data_store WHERE name = "ActLock_UpgLock" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_UpgLock.                                   
FIND FIRST data_store WHERE name = "ActLock_UpgReq" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_UpgReq.                                    
FIND FIRST data_store WHERE name = "ActLock_UpgWait" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLock.ActLock_UpgWait.                                   
FIND FIRST Db_ActSum WHERE cf_sample.sample_id = Db_ActSum.sample_ID NO-LOCK NO-ERROR.                        
FIND FIRST data_store WHERE name = "ActSum_AllocNewRm" NO-LOCK NO-ERROR.                                      
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_AllocNewRm.                                  
FIND FIRST data_store WHERE name = "ActSum_BytesAlloc" NO-LOCK NO-ERROR.                                      
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_BytesAlloc.                                  
FIND FIRST data_store WHERE name = "ActSum_Examined" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_Examined.                                    
FIND FIRST data_store WHERE name = "ActSum_FromFree" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_FromFree.                                    
FIND FIRST data_store WHERE name = "ActSum_FromRm" NO-LOCK NO-ERROR.                                          
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_FromRm.                                      
FIND FIRST data_store WHERE name = "ActSum_Removed" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_Removed.                                     
FIND FIRST data_store WHERE name = "ActSum_RetFree" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_RetFree.                                     
FIND FIRST data_store WHERE name = "ActSum_TakeFree" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_TakeFree.                                    
FIND FIRST data_store WHERE name = "ActSum_AiWrites" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_AiWrites.                                    
FIND FIRST data_store WHERE name = "ActSum_BiReads" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_BiReads.                                     
FIND FIRST data_store WHERE name = "ActSum_BiWrites" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_BiWrites.                                    
FIND FIRST data_store WHERE name = "ActSum_Commits" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_Commits.                                     
FIND FIRST data_store WHERE name = "ActSum_DbAccesses" NO-LOCK NO-ERROR.                                      
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_DbAccesses.                                  
FIND FIRST data_store WHERE name = "ActSum_DbExtend" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_DbExtend.                                    
FIND FIRST data_store WHERE name = "ActSum_DbReads" NO-LOCK NO-ERROR.                                         
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_DbReads.                                     
FIND FIRST data_store WHERE name = "ActSum_DbWrites" NO-LOCK NO-ERROR.                                        
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_DbWrites.                                    
FIND FIRST data_store WHERE name = "ActSum_Undos" NO-LOCK NO-ERROR.                                           
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActSum.ActSum_Undos.                                       
FIND FIRST Db_ActLog WHERE cf_sample.sample_id = Db_ActLog.sample_ID NO-LOCK NO-ERROR.                        
FIND FIRST data_store WHERE name = "ActLog_AIBBufWaits" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_AIBBufWaits.                                 
FIND FIRST data_store WHERE name = "ActLog_AIByteWrites" NO-LOCK NO-ERROR.                                    
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_AIByteWrites.                                
FIND FIRST data_store WHERE name = "ActLog_AINoBufAvail" NO-LOCK NO-ERROR.                                    
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_AINoBufAvail.                                
FIND FIRST data_store WHERE name = "ActLog_AIPartialWrites" NO-LOCK NO-ERROR.                                 
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_AIPartialWrites.                             
FIND FIRST data_store WHERE name = "ActLog_AIRecWrites" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_AIRecWrites.                                 
FIND FIRST data_store WHERE name = "ActLog_AITotWrites" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_AITotWrites.                                 
FIND FIRST data_store WHERE name = "ActLog_AIWWrites" NO-LOCK NO-ERROR.                                       
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_AIWWrites.                                   
FIND FIRST data_store WHERE name = "ActLog_BIBBufWaits" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIBBufWaits.                                 
FIND FIRST data_store WHERE name = "ActLog_BIByteReads" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIByteReads.                                 
FIND FIRST data_store WHERE name = "ActLog_BIByteWrites" NO-LOCK NO-ERROR.                                    
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIByteWrites.                                
FIND FIRST data_store WHERE name = "ActLog_BIEBufWaits" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIEBufWaits.                                 
FIND FIRST data_store WHERE name = "ActLog_BIPartialWrites" NO-LOCK NO-ERROR.                                 
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIPartialWrites.                             
FIND FIRST data_store WHERE name = "ActLog_BIRecReads" NO-LOCK NO-ERROR.                                      
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIRecReads.                                  
FIND FIRST data_store WHERE name = "ActLog_BIRecWrites" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIRecWrites.                                 
FIND FIRST data_store WHERE name = "ActLog_BITotWrites" NO-LOCK NO-ERROR.                                     
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BITotWrites.                                 
FIND FIRST data_store WHERE name = "ActLog_BIWWrites" NO-LOCK NO-ERROR.                                       
 if available data_store THEN data_store.data[i] = data_store.data[i] + Db_ActLog.ActLog_BIWWrites.                                   
{include/sys/mem-load.i}
{include/sys/cpu-load.i}
/* Report-name.i
**
** This include will generate report names to store the reports in the
** appropriate directories.  If the directories don't exist they will be
** created.
**
*/

/* 
** Main Processing
*/

Fathom-d-rep_name = Fathom-i-rep_name.
Fathom-t-rep_name = OS-GETENV("fathomReportDir").
Fathom-t-rep_dir = OS-GETENV("fathomReportOutputDir").

IF OPSYS = "UNIX" THEN
DO:
   Fathom-t-seperator = CHR(47).
END.
ELSE
DO:
   Fathom-t-seperator = CHR(92).
END.

Fathom-t-rep_name = Fathom-t-rep_name + Fathom-t-seperator + Fathom-t-rep_dir.
Fathom-t-rep_dir = Fathom-t-rep_name.


/*
** Creating file name
*/
IF AVAILABLE cf_resrc THEN Fathom-t-colon-name = Cf_Resrc.Resrc_Name.
ELSE Fathom-t-colon-name = t-resrc_name.

/* Take out the colons and replace them with Underscores */

DO Fathom-j = 1 TO LENGTH(Fathom-t-colon-name):
    IF SUBSTRING(Fathom-t-colon-name, Fathom-j, 1) = ":" THEN
    DO:
        Fathom-t-colon-name = 
            SUBSTRING(Fathom-t-colon-name, 1, (Fathom-j - 1)) + "_" +
            SUBSTRING(Fathom-t-colon-name, Fathom-j + 1).
        Fathom-i = 1.
    END.
END.

/* Ensure there is only 1 underscore */
REPEAT:
    Fathom-i = 0.
    DO Fathom-j = 1 TO LENGTH(Fathom-t-colon-name):
        IF SUBSTRING(Fathom-t-colon-name, Fathom-j, 1) = "_" THEN
        DO:
            IF SUBSTRING(Fathom-t-colon-name, Fathom-j + 1, 1) = "_" THEN
            DO:
                Fathom-t-colon-name = 
                    SUBSTRING(Fathom-t-colon-name, 1, Fathom-j) +
                    SUBSTRING(Fathom-t-colon-name, Fathom-j + 2).
                Fathom-i = 1.
                LEAVE.
            END.
        END.
    END.
    IF Fathom-i = 0 THEN LEAVE.
END.

/*
** Put together the actual report name here
*/

If Fathom-i-Site_ID NE "" THEN Fathom-t-rep_name = 
                               Fathom-t-rep_name +
                               Fathom-i-Site_ID.
IF Fathom-t-colon-name NE "" THEN Fathom-t-rep_name = 
                                  Fathom-t-rep_name + "_" +
                                  Fathom-t-colon-name.

/* 
** Attach file type based on type of data desired
*/

IF Fathom-i-OutputType = "D" THEN
DO:
    Fathom-t-Data_Name = Fathom-t-Rep_Name + ".csv".
END.
ELSE
DO:
    Fathom-t-rep_name = Fathom-t-rep_name + ".txt".
END.


pgm-name = "Exiting Report Name Creation : ".
sec-name = Fathom-t-rep_name.
{include/debug.i "pgm-name" "sec-name"}
/* Standard Sample query used in most programs */
FOR EACH cf_sample  
   WHERE 
   Cf_Sample.Resrc_ID = Fathom-i-Resrc_ID AND
   Cf_Sample.Site_ID = Fathom-i-site_ID AND
   Cf_Sample.Sample_Date GE Fathom-t-beg-date[1] AND      
   Cf_Sample.Sample_Date LE Fathom-t-end-date[Fathom-i-periods] AND  
   Cf_Sample.Sample_Time GE Fathom-t-beg-time[1] AND      
   Cf_Sample.Sample_Time LE Fathom-t-end-time[Fathom-i-periods]
   BY sample_date BY sample_time:
Fathom-i = 0.
REPEAT:
    Fathom-i = Fathom-i + 1.
    IF cf_sample.sample_date GE Fathom-t-beg-date[Fathom-i] AND
       cf_sample.sample_date LE Fathom-t-end-date[Fathom-i] THEN
    DO:
       IF cf_sample.sample_time GE Fathom-t-beg-time[Fathom-i] AND
          cf_sample.sample_time LE Fathom-t-end-time[Fathom-i] THEN
          LEAVE.
    END.
    IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
END.
Fathom-k = 0.
REPEAT:
    Fathom-k = Fathom-k + 1.
    IF cf_sample.sample_date GE Fathom-t-beg-date[Fathom-k] AND
       cf_sample.sample_date LE Fathom-t-end-date[Fathom-k] THEN 
    DO:
       IF cf_sample.sample_time GE Fathom-t-beg-time[Fathom-k] AND
          cf_sample.sample_time LE Fathom-t-end-time[Fathom-k] THEN 
          LEAVE.
    END.
    IF Fathom-k EQ Fathom-i-periods THEN LEAVE.
END.
/*
** header-form.i
** This include defines the header frame that is used for the reports that
** are run from the trenddbsingle program.
**
*/

/*
** Main Processing
*/

Fathom-t-replength = LENGTH(Fathom-t-rep_name).
IF Fathom-t-replength GT 195 THEN
DO:
   Fathom-t-rep4 = SUBSTRING(Fathom-t-rep_name,196).
   Fathom-t-rep3 = SUBSTRING(Fathom-t-rep_name,131,65).
   Fathom-t-rep2 = SUBSTRING(Fathom-t-rep_name,66,65).
   Fathom-t-rep1 = SUBSTRING(Fathom-t-rep_name,1,65).
END.
ELSE
IF Fathom-t-replength GT 130 THEN
DO:
   Fathom-t-rep3 = SUBSTRING(Fathom-t-rep_name,131).
   Fathom-t-rep2 = SUBSTRING(Fathom-t-rep_name,66,65).
   Fathom-t-rep1 = SUBSTRING(Fathom-t-rep_name,1,65).
END.
ELSE
DO:
   IF Fathom-t-replength GT 65 THEN
   DO:
      Fathom-t-rep2 = SUBSTRING(Fathom-t-rep_name,66).
      Fathom-t-rep1 = SUBSTRING(Fathom-t-rep_name,1,65).
   END.
   ELSE
   DO:
      Fathom-t-rep1 = Fathom-t-rep_name.
   END.
END.

PUT STREAM ReportOutput Fathom-report-title FORMAT "X(65)"
    SKIP(1)
    "Report Date       : " TODAY FORMAT "99/99/9999" " at " STRING (TIME, "HH:MM:SS")
    SKIP
    "Report Name       : " Fathom-d-rep_name FORMAT "x(30)"
    SKIP.

If AVAILABLE Cf_Resrc THEN
DO:
    PUT STREAM ReportOutput "Site ID           : " Cf_Resrc.Site_ID FORMAT "x(15)"
        SKIP
        "Resource Name     : " Cf_Resrc.Resrc_Name FORMAT "x(30)"
        SKIP
        "Resource Type     : " Cf_Resrc.Resrc_Type FORMAT "x(30)"
        SKIP(1).
END. 

PUT STREAM ReportOutput
    "Start Date        : "  Fathom-i-start_Date FORMAT "99/99/99" "     "
    "          End Date  : "  Fathom-i-End_Date FORMAT "99/99/99".
IF Fathom-ar-Count[1] GT 0 THEN
DO:
    PUT STREAM ReportOutput SKIP "Archive data used for periods older than " Fathom-ar-date FORMAT "99/99/9999".
END.
/*
** This part is commented out for Fathom 2.0A re-work of the report headers
**
** PUT STREAM ReportOutput
**     SKIP(1)
**     "Number of Periods : " Fathom-i-Periods FORMAT "99" "    ".
*/
IF Fathom-i-rep_type NE "Alert" THEN
DO:
    PUT STREAM ReportOutput SKIP(1) "         Number of Samples : " String (Fathom-Rec-Count +
                                                            Fathom-ar-count[1] , ">>>,>>>,>>9") FORMAT "X(15)".
END.

PUT STREAM ReportOutput SKIP(1).
 
IF Fathom-t-rep1 NE "" THEN
DO:
    PUT STREAM ReportOutput SKIP "Report File Name  : " Fathom-t-rep1 FORMAT "X(80)" SKIP.
END.
IF Fathom-t-rep2 NE "" THEN
DO:
    PUT STREAM ReportOutput "                        " Fathom-t-rep2 FORMAT "X(80)" SKIP.
END.
IF Fathom-t-rep3 NE "" THEN
DO:
    PUT STREAM ReportOutput "                        " Fathom-t-rep3 FORMAT "X(95)" SKIP.
END.
IF Fathom-t-rep4 NE "" THEN
DO:
    PUT STREAM ReportOutput "                        " Fathom-t-rep4 FORMAT "X(95)" SKIP.
END.

PUT STREAM ReportOutput SKIP "Report Date Format: " SESSION:DATE-FORMAT.
PUT STREAM ReportOutput SKIP(1) Fathom-t-IntervalTitle FORMAT "X(95)".
PUT STREAM ReportOutput SKIP(2).

/* 
** Column-header
** This section will display the column headers in the appropriate
** spacing to display the rest of the data.
*/
PUT SKIP "Fathom Report CODE: " Fathom-i-reportcode.
IF Fathom-t-beg-date[1] NE ? THEN
DO:
CASE Fathom-i-reportcode:
    WHEN "wd" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-end-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
    END.
    WHEN "ww" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-end-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
    END.
    WHEN "mm" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-end-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
    END.
    WHEN "mw" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-end-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
    END.
    WHEN "dd" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
    END.
    WHEN "dh" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-beg-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-end-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
    END.
    WHEN "hh" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-beg-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-end-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
    END.
    WHEN "hi" THEN
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-beg-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-end-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
    END.
    OTHERWISE
    DO:
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        IF Fathom-i-periods GT 1 THEN PUT STREAM ReportOutput " Change %".
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " Fathom-t-end-date[Fathom-j] FORMAT "99/99/9999" "     ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-beg-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
        PUT STREAM ReportOutput SKIP " " FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-end-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
    END.
/*
** COmmented out for Fathom 2.0A Report heading re-work
**
** PUT STREAM ReportOutput "Period Number" FORMAT "x(25)".
** DO Fathom-j = 1 TO Fathom-i-periods:
**     PUT STREAM ReportOutput Fathom-j FORMAT "->>>>>>>>>>9".
**     PUT STREAM ReportOutput "" FORMAT "x(5)".
** END.
    PUT STREAM ReportOutput SKIP "Period Start Date" FORMAT "x(28)".
    DO Fathom-j = 1 TO Fathom-i-periods:
        PUT STREAM ReportOutput "  " Fathom-t-beg-date[Fathom-j] FORMAT "99/99/99" "       ".
    END.
    IF Fathom-i-periods GT 1 THEN PUT STREAM ReportOutput " Change".
    PUT STREAM ReportOutput SKIP "Period End Date" FORMAT "x(28)".
    DO Fathom-j = 1 TO Fathom-i-periods:
        PUT STREAM ReportOutput "  " Fathom-t-end-date[Fathom-j] FORMAT "99/99/99" "       ".
    END.
    IF Fathom-i-periods GT 1 THEN PUT STREAM ReportOutput "  Pct.".
/* 
** Time heading
**
*/
    IF Fathom-t-beg-time[1] GT 1 AND Fathom-t-end-time[Fathom-i-periods] LT 86400 THEN
    DO:
        PUT STREAM ReportOutput SKIP "Period Start Time" FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-beg-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
        PUT STREAM ReportOutput SKIP "Period End Time" FORMAT "x(28)".
        DO Fathom-j = 1 TO Fathom-i-periods:
            PUT STREAM ReportOutput "  " STRING (Fathom-t-end-Time[Fathom-j], "HH:MM:SS") "       ".
        END.
    END.
*/
END CASE.
END.
FIND FIRST Sys_CPU WHERE cf_sample.sample_id = Sys_CPU.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Sys_CPU THEN
DO:
   FIND FIRST data_store WHERE name = "CPU_Idle" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_CPU.CPU_Idle.
   FIND FIRST data_store WHERE name = "CPU_System" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_CPU.CPU_System.
   FIND FIRST data_store WHERE name = "CPU_Usr" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_CPU.CPU_Usr.
   FIND FIRST data_store WHERE name = "CPU_Wait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_CPU.CPU_Wait.
END.

FIND FIRST Sys_Dev WHERE cf_sample.sample_id = Sys_Dev.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Sys_Dev THEN
DO:
   FIND FIRST data_store WHERE name = "Dev_AvgQue" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Dev.Dev_AvgQue.
   FIND FIRST data_store WHERE name = "Dev_AvgServ" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Dev.Dev_AvgServ.
   FIND FIRST data_store WHERE name = "Dev_AvgWait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Dev.Dev_AvgWait.
   FIND FIRST data_store WHERE name = "Dev_Pct_Busy" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Dev.Dev_Pct_Busy.
END.

FIND FIRST Sys_Mem WHERE cf_sample.sample_id = Sys_Mem.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Sys_Mem THEN
DO:
   FIND FIRST data_store WHERE name = "Mem_PgIn" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_PgIn.
   FIND FIRST data_store WHERE name = "Mem_PgOut" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_PgOut.
   FIND FIRST data_store WHERE name = "Mem_SysFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_SysFree.
   FIND FIRST data_store WHERE name = "Mem_SysTot" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_SysTot.
   FIND FIRST data_store WHERE name = "Mem_VirtFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_VirtFree.
   FIND FIRST data_store WHERE name = "Mem_VirtTot" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_VirtTot.
END.

FIND FIRST Sys_FileSys WHERE cf_sample.sample_id = Sys_FileSys.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Sys_FileSys THEN
DO:
   FIND FIRST data_store WHERE name = "FileSys_Avail" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_FileSys.FileSys_Avail.
   FIND FIRST data_store WHERE name = "FileSys_Capacity" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_FileSys.FileSys_Capacity.
   FIND FIRST data_store WHERE name = "FileSys_UsedPct" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_FileSys.FileSys_UsedPct.
END.
include-list = "
CPU_Usr,
CPU_System,
CPU_Wait,
CPU_Idle".
FIND FIRST Sys_CPU WHERE cf_sample.sample_id = 
   Sys_CPU.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Sys_CPU THEN
DO:
   FIND FIRST data_store WHERE name = "CPU_System" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + (Sys_CPU.CPU_System * cf_sample.sample_len).
   
   FIND FIRST data_store WHERE name = "CPU_Usr" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + (Sys_CPU.CPU_Usr * cf_sample.sample_len).
  
   FIND FIRST data_store WHERE name = "CPU_Wait" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + (Sys_CPU.CPU_Wait * cf_sample.sample_len).
END.
include-list = "
Mem_SysTot,
Mem_VirtTot,
Mem_VirtFree,
Mem_SysFree,
Mem_PgIn,
Mem_PgOut".
FIND FIRST Sys_Mem WHERE cf_sample.sample_id = 
   Sys_Mem.sample_ID NO-LOCK NO-ERROR.
IF AVAILABLE Sys_Mem THEN
DO:
   
   FIND FIRST data_store WHERE name = "Mem_PgIn" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_PgIn.
   
   FIND FIRST data_store WHERE name = "Mem_PgOut" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_PgOut.
   
   FIND FIRST data_store WHERE name = "Mem_SysFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_SysFree.
   
   FIND FIRST data_store WHERE name = "Mem_SysTot" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_SysTot.
   
   FIND FIRST data_store WHERE name = "Mem_VirtFree" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_VirtFree.
   
   FIND FIRST data_store WHERE name = "Mem_VirtTot" NO-ERROR.
   IF AVAILABLE data_store THEN data_store.data[Fathom-i] = 
      data_store.data[Fathom-i] + Sys_Mem.Mem_VirtTot.
END.
/*
llaubach 10/2005
 - data_store temp-table defined as NO-UNDO
*/


DEF {1} TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD ResrcID AS INTEGER 
   FIELD data AS decimal EXTENT 366
   FIELD txn AS decimal  EXTENT 366
   FIELD Sec AS decimal  EXTENT 366
   FIELD lable AS character 
   FIELD name2 AS character 
   FIELD file AS character 
   FIELD sort-order AS integer 
   INDEX one FILE 
   INDEX two TYPE 
   INDEX three NAME
   INDEX four sort-order
   INDEX five ResrcID.
/*
** Trenddates.i
** This program will present a trend report based on the dates provided to
** the report.  The dates will be defined in the Trend database in the table
** Cf_Rep_Def.  The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

DEF VAR datebucket AS INT INITIAL 0.
DEF VAR workyear AS INT.
DEF VAR timeeven AS INT.
DEF VAR workdate AS DATE.
DEF VAR workmonth AS INT.
DEF VAR hourprocessing AS INT NO-UNDO INITIAL 0.
DEF VAR dayinc AS INT.

/*
** Determine if it is an hourly report
*/
CASE Fathom-i-reportcode:
    WHEN "dh" THEN 
        DO:
            hourprocessing = 1.
        END.
    WHEN "hh" THEN 
        DO:
           Fathom-t-periods-day = Fathom-i-periods.
           hourprocessing = 1.
        END.
    WHEN "hi" THEN
        DO:
	   
           Fathom-t-periods-day = Fathom-i-periods.
           hourprocessing = 1.
        END.
    OTHERWISE
        DO:
           Fathom-t-periods-day = 1.
           hourprocessing = 0.
        END.
END CASE.

IF Debug-4gl = 1 THEN
DO:
    sec-name = "periods: " + STRING(fathom-i-periods).
    {include/debug.i "pgm-name" "sec-name"}
    sec-name = "periods-day: " + STRING(fathom-t-periods-day).
    {include/debug.i "pgm-name" "sec-name"}
    sec-name = "Fathom-t-DYincrement: " + STRING(Fathom-t-DYincrement).
    {include/debug.i "pgm-name" "sec-name"}
    sec-name = "Fathom-t-HRincrement: " + STRING(Fathom-t-HRincrement).
    {include/debug.i "pgm-name" "sec-name"}
END.
/*
** This is the new code to deal with Dates
*/

IF hourprocessing = 1 THEN
DO:

    /*
    ** Only processing one date
    */
    IF Fathom-i-start_date = Fathom-i-end_date THEN
    DO:
        /*
	** Process a single day
	*/
        DO Fathom-i = 1 to Fathom-i-periods:
            Fathom-t-beg-date[Fathom-i] = Fathom-i-start_date.
            Fathom-t-end-date[Fathom-i] = Fathom-i-end_date.
	END. /* Looping through periods */
    END.  /* Dates matching */
    ELSE
    DO:
        /* 
	** Processing multiple dates
	*/
        DO Fathom-i = 0 TO Fathom-i-periods - 1:
	   
	    DO Fathom-j = 0 to Fathom-t-periods-day - 1:
                Fathom-t-beg-date[Fathom-i + Fathom-j + 1] = Fathom-i-start_date + (dayinc * Fathom-t-DYincrement).
	        Fathom-t-end-date[Fathom-i + Fathom-j + 1] = Fathom-t-beg-date[Fathom-i + Fathom-j + 1].
	    END.
	    Fathom-i = Fathom-i + Fathom-j - 1.
	    dayinc = dayinc + 1.
	END. 
    END. /* Of dates NOT matching */

    /*
    ** Process TIMES
    */
    dayinc = 0.
    DO Fathom-i = 0 TO Fathom-i-periods - 1:
	DO Fathom-j = 0 to Fathom-t-periods-day - 1:
	    If Fathom-j = 0 THEN
            DO:
	        Fathom-t-beg-time[Fathom-i + Fathom-j + 1] = Fathom-i-start_time.
	        Fathom-t-end-time[Fathom-i + Fathom-j + 1] = Fathom-t-beg-time[Fathom-i + Fathom-j + 1] + 
		                                             Fathom-t-HRincrement.
            END.
            ELSE
	    DO:
	        Fathom-t-beg-time[Fathom-i + Fathom-j + 1] = Fathom-t-end-time[Fathom-i + Fathom-j] + 1.
		Fathom-t-end-time[Fathom-i + Fathom-j + 1] = Fathom-t-beg-time[Fathom-i + Fathom-j + 1] + 
		                                             Fathom-t-HRincrement.
            END.
        END.
	Fathom-i = Fathom-i + Fathom-j - 1.
	dayinc = dayinc + 1.
    END. 
END.  /* Time only loop */
ELSE
DO:

   IF Fathom-i-start_date = Fathom-i-end_date THEN
   DO:
       DO Fathom-i = 1 to Fathom-i-periods:
           Fathom-t-beg-date[Fathom-i] = Fathom-i-start_date.
           Fathom-t-end-date[Fathom-i] = Fathom-i-end_date.
           Fathom-t-beg-time[Fathom-i] = Fathom-i-start_time.
           Fathom-t-end-time[Fathom-i] = Fathom-i-end_time.
       END.
   END.
   ELSE
   DO:
       DO Fathom-i = 1 to Fathom-i-periods:
	   /*
	   ** First time through we must do special processing
	   */
	   Fathom-t-beg-time[Fathom-i] = fathom-i-start_time.
	   Fathom-t-end-time[Fathom-i] = Fathom-i-end_time.
           IF Fathom-i = 1 THEN
	   DO:
               Fathom-t-beg-date[Fathom-i] = Fathom-i-start_date.
	       /*
	       ** Special case some of the processing
	       */
	       CASE Fathom-i-reportcode:
	           WHEN "ww" THEN Fathom-t-end-date[Fathom-i] = Fathom-i-start_date + Fathom-t-DYincrement - 1.
	           WHEN "mw" THEN Fathom-t-end-date[Fathom-i] = Fathom-i-start_date + Fathom-t-DYincrement - 1.
	           WHEN "mm" THEN 
		       DO:
	                   Fathom-t-beg-date[Fathom-i] = DATE(INTEGER(t-beg-month), 1, INTEGER(t-beg-year)).
		           workmonth = MONTH (Fathom-t-beg-date[Fathom-i]).
		           workyear = YEAR(Fathom-t-beg-date[fathom-i]).
		           IF workmonth = 12 THEN
		           DO:
		              workmonth = 1.
			      workyear = workyear + 1.
		           END.
		           ELSE workmonth = workmonth + 1.
	                   Fathom-t-end-date[Fathom-i] = DATE(workmonth , 1, workyear) - 1. 
		       END.
	           OTHERWISE  Fathom-t-end-date[Fathom-i] = Fathom-i-start_date.
	       END CASE.
	   END.
	   ELSE
	   DO:
	       /*
	       ** Special case some of the processing
	       */
	       CASE Fathom-i-reportcode:
	       WHEN "mm" THEN
	           DO:
	               Fathom-t-beg-date[Fathom-i] = Fathom-t-end-date[Fathom-i - 1] + 1.
		       workmonth = MONTH (Fathom-t-beg-date[Fathom-i]).
		       workyear = YEAR (Fathom-t-beg-date[Fathom-i]).
		       IF workmonth = 12 THEN
		       DO:
		           workmonth = 1.
		           workyear = workyear + 1.
		       END.
		       ELSE workmonth = workmonth + 1.
		       Fathom-t-end-date[fathom-i] = DATE( workmonth, 1, workyear) - 1.
	           END.
               WHEN "dd" THEN
                   DO:
	               Fathom-t-beg-date[Fathom-i] = Fathom-t-end-date[Fathom-i - 1] + 1.
	               Fathom-t-end-date[Fathom-i] = Fathom-t-beg-date[Fathom-i].
                   END.
	       OTHERWISE
	           DO:
	               Fathom-t-beg-date[Fathom-i] = Fathom-t-end-date[Fathom-i - 1] + 1.
	               Fathom-t-end-date[Fathom-i] = Fathom-t-beg-date[Fathom-i] + Fathom-t-DYincrement - 1.
	           END.
	       END CASE.
	   END.
           IF Fathom-t-end-time[Fathom-i] LT 1 THEN Fathom-t-end-time[Fathom-i] = Fathom-i-end_time.
          
       END.  /* of DO loop */
       IF Fathom-t-end-time[Fathom-i] LT 1 THEN Fathom-t-end-time[Fathom-i] = Fathom-i-end_time.
    END. /* Of dates NOT matching */
END.

sec-name = "Date Processing Complete - Matrix Follows".
{include/debug.i "pgm-name" "sec-name"}
IF Debug-4gl = 1 THEN
DO:
    DO Fathom-i = 1 to Fathom-i-periods:
        sec-name = "Column: " + STRING (Fathom-i) + 
	           " Start Date: " + STRING(Fathom-t-beg-date[Fathom-i], "99/99/9999") +
	           " End Date: " + STRING(Fathom-t-end-date[Fathom-i], "99/99/9999") +
	           " Start Time: " + STRING(Fathom-t-beg-time[Fathom-i]) +
	           " End Time: " + STRING(Fathom-t-end-time[Fathom-i]).
        {include/debug.i "pgm-name" "sec-name"}
    END.
END.

sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphSpec").
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
/*
** This include sets the graph columns based on the report type that is set.
**
** This will be replace at some point with environment variables as an option
*/
CASE  Fathom-i-program:
   WHEN "src/dbafterimage" THEN DO:
       xmlGraphColumns = "ActLog_AITotWrites,ActLog_AIWWrites".
   END.
   WHEN "src/dbbeforeimage" THEN DO:
       xmlGraphColumns = "ActLog_BiTotWrites,ActLog_BIWWrites".
   END.
   WHEN "src/dbdisk" THEN DO:
       xmlGraphColumns = "ActSum_DbReads,ActSum_DbWrites,ActSum_DbAccesses".
   END.
   WHEN "src/dblocks" THEN DO:
       xmlGraphColumns = "ActLock_ExclLock,ActLock_ShrLock,ActLock_UpgLock".
   END.
   WHEN "src/dbmemory" THEN DO:
       xmlGraphColumns = "ActBuf_OSReads,ActBuf_LogicReads".
   END.
   WHEN "src/dbrecord" THEN DO:
       xmlGraphColumns = "ActRec_RecCreate,ActRec_RecUpd,ActRec_RecDel,ActRec_RecLock".
   END.
   WHEN "src/dbserver" THEN DO:
       xmlGraphColumns = "Records Received,Records Sent".
   END.
   WHEN "src/dbsummary" THEN DO:
       xmlGraphColumns = "ActSum_DbAccesses,ActBuf_LogicWrites,ActBuf_LogicReads".
   END.
   WHEN "src/dbdetail" THEN DO:
       xmlGraphColumns = "Actsum_DbReads,ActSum_DbWrites,ActBuf_LogicReads,ActBuf_LogicWrites".
   END.
   WHEN "src/dbcheckpoint" THEN DO:
       xmlGraphColumns = "Avg. Checkpoint Length (sec.),Avg. Buffers Flushed".
   END.
   WHEN "src/dbareastatus" THEN DO:
       xmlGraphColumns = "Hi Water Mark,Blocks Available".
   END.
   WHEN "src/dbindexstat" THEN DO:
       xmlGraphColumns = "Index Reads".
   END.
   WHEN "src/dbidxanalysis" THEN DO:
       /* xmlGraphColumns = "Avg Util Percent". */
       xmlGraphColumns = "".
   END.
   WHEN "src/dbtabanalysis" THEN DO:
       /* xmlGraphColumns = "Avg Record Count". */
       xmlGraphColumns = "".
   END.
   WHEN "src/dbtablestat" THEN DO:
       xmlGraphColumns = "Record Reads,Record Updates,Record Creates,Record Deletes".
   END.
   WHEN "src/systemcpu" THEN DO:
       xmlGraphColumns = "CPU_Usr,CPU_System,CPU_Wait".
   END.
   WHEN "src/systemmemory" THEN DO:
       xmlGraphColumns = AVG_PHYS_MEM_USED_PCT.
   END.
   WHEN "src/systemdisk" THEN DO:
       xmlGraphColumns = "Pct. Busy".
   END.
   WHEN "src/systemfilesystem" THEN DO:
       xmlGraphColumns = "Pct. Used".
   END.
   WHEN "src/alertindividual" THEN DO:
       xmlGraphColumns = "Severe Alerts,Error Alerts,Warning Alerts,Information Alerts".
   END.
   WHEN "src/alertgeneral" THEN DO:
       xmlGraphColumns = "Severe Alerts,Error Alerts,Warning Alerts,Information Alerts".
   END.
   WHEN "src/network" THEN DO:
       xmlGraphColumns = AVG_RESPONSE_TIME.
   END.
   WHEN "src/systemfilesize" THEN DO:
       xmlGraphColumns = AVG_FILE_SIZE.
   END.
   WHEN "src/trendrecommend" THEN DO:
       xmlGraphColumns = "".
   END.
   WHEN "src/openedge/asprofile" OR WHEN "src/openedge/wsprofile" THEN DO:
       xmlGraphColumns = RUN_COUNT.
   END.
   WHEN "src/openedge/performance" THEN DO:
       xmlGraphColumns = AVG_BUSY_SERVERS + "," + AVG_ACTIVE_CLIENTS + "," + AVG_REQ_DURATION.
   END.

   OTHERWISE DO:
       xmlGraphColumns = "".
   END.
END CASE.
RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "dataset",
                    INPUT "",
                    INPUT "",
                    INPUT "").

RUN print-tag (INPUT-OUTPUT streamdetail,
               INPUT "datasetlabel",
               INPUT "",
               INPUT "",
               INPUT xmldatalabel).

PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
/*
** DO the labels section 
*/
    
RUN print-starttag (INPUT-OUTPUT streamdetail,
              INPUT "labels",
              INPUT "",
              INPUT "",
              INPUT "").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
              
	  DO fathom-j = 1 to xml-numcolumns:

	     xmldataOutputlabel = xmlcolumnnames[fathom-j].	 
             RUN print-tag (INPUT-OUTPUT streamdetail,
                 INPUT "label",
                 INPUT "",
    	         INPUT "",
    	         INPUT xmldataOutputlabel).
          END.

          RUN print-endtag (INPUT-OUTPUT streamdetail,
                                      INPUT "labels").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
/*
** XML Cleanup include
**
** NOTE: This code was built based on the concepts presented by
** Doug Merrett - Progress Software Corporation
**
****************************************************************
**
** This include should be used to clean up the xml environment.
**
****************************************************************
*/

/* hDoc:SAVE ("STREAM", "xmlstream"). */

/* GhDoc:SAVE ("STREAM", "Gxmlstream"). */

/*
** XML definitions include file
**
** This file contains variables and procedeures needed to build 
** the xml file to be exported to the graphing section of Fathom.
**
*/

/*
** Column output names.
*/
/* Shared. */
DEFINE {1} VARIABLE SAMPLE_COUNT        AS CHARACTER NO-UNDO INITIAL "Sample Count".
DEFINE {1} VARIABLE PASSED_SAMPLE_COUNT AS CHARACTER NO-UNDO INITIAL "Passed Sample Count".
DEFINE {1} VARIABLE FAILED_SAMPLE_COUNT AS CHARACTER NO-UNDO INITIAL "Failed Sample Count".

/* File Size. */
DEFINE {1} VARIABLE AVG_FILE_SIZE       AS CHARACTER NO-UNDO INITIAL "Average File Size (KB)".
DEFINE {1} VARIABLE MIN_FILE_SIZE       AS CHARACTER NO-UNDO INITIAL "Minimum Size (KB)".
DEFINE {1} VARIABLE MAX_FILE_SIZE       AS CHARACTER NO-UNDO INITIAL "Maximum Size (KB)".

/* Open Edge Shared. */
DEFINE {1} VARIABLE AVG_REQ_DURATION    AS CHARACTER NO-UNDO INITIAL "Average Request Duration (ms)".

/* Open Edge Profile. */
DEFINE {1} VARIABLE RUN_COUNT           AS CHARACTER NO-UNDO INITIAL "Run Count".
DEFINE {1} VARIABLE RETURN_CODE_SUCCESS AS CHARACTER NO-UNDO INITIAL "Return Code Success".
DEFINE {1} VARIABLE RETURN_CODE_ERROR   AS CHARACTER NO-UNDO INITIAL "Return Code Error".
DEFINE {1} VARIABLE RETURN_CODE_QUIT    AS CHARACTER NO-UNDO INITIAL "Return Code Quit".
DEFINE {1} VARIABLE RETURN_CODE_STOP    AS CHARACTER NO-UNDO INITIAL "Return Code Stop".

/* Open Edge Performance - Client Activity. */
DEFINE {1} VARIABLE AVG_ACTIVE_CLIENTS  AS CHARACTER NO-UNDO INITIAL "Average Active Clients".
DEFINE {1} VARIABLE MAX_ACTIVE_CLIENTS  AS CHARACTER NO-UNDO INITIAL "Maximum Active Clients".
DEFINE {1} VARIABLE CLIENT_REQUESTS     AS CHARACTER NO-UNDO INITIAL "Client Requests".
DEFINE {1} VARIABLE AVG_CLIENT_REQUESTS AS CHARACTER NO-UNDO INITIAL "Average Client Requests".
DEFINE {1} VARIABLE MAX_CLIENT_REQUESTS AS CHARACTER NO-UNDO INITIAL "Maximum Client Requests".

/* Open Edge Performance - Broker Activity. */
DEFINE {1} VARIABLE REQUESTS_COMPLETED  AS CHARACTER NO-UNDO INITIAL "Requests Completed".
DEFINE {1} VARIABLE REQUESTS_QUEUED     AS CHARACTER NO-UNDO INITIAL "Requests Queued".
DEFINE {1} VARIABLE REQ_QUEUED_PCT      AS CHARACTER NO-UNDO INITIAL "Requests Queued %".
DEFINE {1} VARIABLE AVG_CPU_USAGE_PCT   AS CHARACTER NO-UNDO INITIAL "Average CPU Usage %".
DEFINE {1} VARIABLE MAX_CPU_USAGE_PCT   AS CHARACTER NO-UNDO INITIAL "Maximum CPU Usage %".
DEFINE {1} VARIABLE AVG_MEMORY_USAGE    AS CHARACTER NO-UNDO INITIAL "Average Memory Usage (KB)".
DEFINE {1} VARIABLE MAX_MEMORY_USAGE    AS CHARACTER NO-UNDO INITIAL "Maximum Memory Usage (KB)".

/* Open Edge Performance - Server Activity. */
DEFINE {1} VARIABLE AVG_POOL_CPU_USAGE_PCT AS CHARACTER NO-UNDO INITIAL "Average Pool CPU Usage %".
DEFINE {1} VARIABLE MAX_POOL_CPU_USAGE_PCT AS CHARACTER NO-UNDO INITIAL "Maximum Pool CPU Usage %".
DEFINE {1} VARIABLE AVG_POOL_MEMORY_USAGE  AS CHARACTER NO-UNDO INITIAL "Average Pool Memory Usage (KB)".
DEFINE {1} VARIABLE MAX_POOL_MEMORY_USAGE  AS CHARACTER NO-UNDO INITIAL "Maximum Pool Memory Usage (KB)".
DEFINE {1} VARIABLE AVG_BUSY_SERVERS       AS CHARACTER NO-UNDO INITIAL "Average Busy Server Count".
DEFINE {1} VARIABLE MAX_BUSY_SERVERS       AS CHARACTER NO-UNDO INITIAL "Maximum Busy Server Count".
DEFINE {1} VARIABLE AVG_BUSY_SERVER_TIME   AS CHARACTER NO-UNDO INITIAL "Average Busy Server Time (ms)".
DEFINE {1} VARIABLE AVG_LOCKED_SERVERS     AS CHARACTER NO-UNDO INITIAL "Average Locked Server Count".
DEFINE {1} VARIABLE MAX_LOCKED_SERVERS     AS CHARACTER NO-UNDO INITIAL "Maximum Locked Server Count".
DEFINE {1} VARIABLE AVG_LOCKED_SERVER_TIME AS CHARACTER NO-UNDO INITIAL "Average Locked Server Time (ms)".

/* Memory. */
DEFINE {1} VARIABLE AVG_PHYS_MEM_USED_PCT  AS CHARACTER NO-UNDO INITIAL "Average Physical Memory Used %".
DEFINE {1} VARIABLE AVG_PHYS_MEM_USED      AS CHARACTER NO-UNDO INITIAL "Average Physical Memory Used (MB)".
DEFINE {1} VARIABLE MAX_PHYS_MEM_USED      AS CHARACTER NO-UNDO INITIAL "Maximum Physical Memory Used (MB)".
DEFINE {1} VARIABLE AVG_VIRT_MEM_USED_PCT  AS CHARACTER NO-UNDO INITIAL "Average Virtual Memory Used %".
DEFINE {1} VARIABLE AVG_VIRT_MEM_USED      AS CHARACTER NO-UNDO INITIAL "Average Virtual Memory Used (MB)".
DEFINE {1} VARIABLE MAX_VIRT_MEM_USED      AS CHARACTER NO-UNDO INITIAL "Maximum Virtual Memory Used (MB)".
DEFINE {1} VARIABLE MEM_PAGES_IN           AS CHARACTER NO-UNDO INITIAL "Pages In".
DEFINE {1} VARIABLE MEM_PAGES_OUT          AS CHARACTER NO-UNDO INITIAL "Pages Out".

/* Network. */
DEFINE {1} VARIABLE AVG_RESPONSE_TIME  AS CHARACTER NO-UNDO INITIAL "Average Response Time (ms)".


/*
** General.
*/
DEFINE {1} VARIABLE NOT_AVAILABLE         AS CHARACTER NO-UNDO INITIAL "N/A".
DEFINE {1} VARIABLE xmldatetimestampbeg   AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmldatetimestampend   AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmltimeoutbeg         AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmltimeoutend         AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmldateoutbeg         AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmldateoutend         AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmldayoutbeg          AS CHARACTER NO-UNDO FORMAT "x(9)".
DEFINE {1} VARIABLE xmldayoutend          AS CHARACTER NO-UNDO FORMAT "x(9)".
DEFINE {1} VARIABLE xmlday                AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlmonth              AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlunittype           AS CHARACTER NO-UNDO INITIAL "long".
DEFINE {1} VARIABLE xmldatalabel          AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmldataOutputlabel    AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmldatavalue          AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlsamplelength       AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlsampletransactions AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlsamplecount        AS CHARACTER NO-UNDO INITIAL "1".
DEFINE {1} VARIABLE xmlresourcesite       AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlresourcename       AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlresourcetype       AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlsamplebegdate      AS DATE NO-UNDO.
DEFINE {1} VARIABLE xmlsamplebegtime      AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE xmlsampleenddate      AS DATE NO-UNDO.
DEFINE {1} VARIABLE xmlsampleendtime      AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE xmlreportdate         AS DATE FORMAT 99/99/9999 INITIAL TODAY NO-UNDO.
DEFINE {1} VARIABLE xml-numcolumns AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE samplelimit           AS INTEGER NO-UNDO INITIAL 400.
DEFINE {1} VARIABLE fathom-x              AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE xmlgraphcolumns       AS CHARACTER FORMAT "X(240)" NO-UNDO.
DEFINE {1} VARIABLE xmlcolumnnames AS CHARACTER EXTENT 20 NO-UNDO.
DEFINE {1} VARIABLE streamdetail          AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE tmpdetail             AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE tmp2detail            AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE tmp3detail            AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE graph1detail          AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE graph2detail          AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE graph3detail          AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE graph1formula         AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE graph2formula         AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE graph3formula         AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE graph1data            AS DECIMAL EXTENT 366 NO-UNDO.
DEFINE {1} VARIABLE graph2data            AS DECIMAL EXTENT 366 NO-UNDO.
DEFINE {1} VARIABLE graph3data            AS DECIMAL EXTENT 366 NO-UNDO.
DEFINE {1} VARIABLE dataprecision         AS CHARACTER NO-UNDO INITIAL "2".
DEFINE {1} VARIABLE dateFormatString      AS CHARACTER NO-UNDO.

/* Handles for XML parsing */
DEFINE {1} VARIABLE hDoc             AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRoot            AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRootdatavalues  AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRootresrcname   AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRootlabel       AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRootlabelvalue  AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowdataset      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowdatasetlabel AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowdatavalues   AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hFieldvalues     AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hFielddatum      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hTextlabels      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hTextvalues      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE docname          AS CHARACTER FORMAT "x(128)" NO-UNDO.
DEFINE {1} VARIABLE GhDataSets       AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhLegendDetail   AS HANDLE NO-UNDO.

/* Handles for time section */
DEFINE {1} VARIABLE hRowtimeset        AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowtimesetlabel   AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowtimevalues     AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowtimedetails    AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowtimedetailsBEG AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowtimedetailsEND AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hTimeTextlabels    AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hTimeTextvalues    AS HANDLE NO-UNDO.

/* Handles for label section */
DEFINE {1} VARIABLE hRowlabelset        AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowlabelsetlabel   AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowlabelvalues     AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowlabeldetails    AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowlabeldetailsBEG AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hRowlabeldetailsEND AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hLabelTextlabels    AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE hLabelTextvalues    AS HANDLE NO-UNDO.

/* 
** Graphing details for XML
*/

/* Handles for XML parsing */
DEFINE {1} VARIABLE GhDoc             AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhRoot            AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhsubRoot         AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhInstanceDef     AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhLegend          AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhAttribute       AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhRootdatavalues  AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhRootresrcname   AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhRowdataset      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhRowdatasetlabel AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhRowdatavalues   AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhFieldvalues     AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhFielddatum      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhTextlabels      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE GhTextvalues      AS HANDLE NO-UNDO.
DEFINE {1} VARIABLE Gdocname          AS CHARACTER FORMAT "x(128)" NO-UNDO.

/*
** Variables for XML-encoding
*/

DEFINE {1} VARIABLE xmlen-ascii     AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE xmlen-intext    AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlen-inchar    AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlen-sixteen   AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE xmlen-remainder AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE xmlen-keylabel  AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlen-ten       AS INTEGER NO-UNDO.
DEFINE {1} VARIABLE xmlen-outtext   AS CHARACTER NO-UNDO.
DEFINE {1} VARIABLE xmlen-i         AS INTEGER NO-UNDO.

/*
** Graph Detail lines
** This is set up for 3 graphs 
*/

DEFINE {1} VARIABLE xmlgraph1-columns  AS CHARACTER NO-UNDO FORMAT "x(64)".
DEFINE {1} VARIABLE xmlgraph2-columns  AS CHARACTER NO-UNDO FORMAT "x(64)".
DEFINE {1} VARIABLE xmlgraph3-columns  AS CHARACTER NO-UNDO FORMAT "x(64)".
DEFINE {1} VARIABLE xmlgraph1-filename AS CHARACTER NO-UNDO FORMAT "x(128)".
DEFINE {1} VARIABLE xmlgraph2-filename AS CHARACTER NO-UNDO FORMAT "x(128)".
DEFINE {1} VARIABLE xmlgraph3-filename AS CHARACTER NO-UNDO FORMAT "x(128)".

DEFINE {1} VARIABLE xmlgraph-imagetitle AS CHARACTER NO-UNDO INITIAL "1.png".
DEFINE {1} VARIABLE xmlgraph-imageid    AS CHARACTER NO-UNDO INITIAL "1".

/* Streams */

DEFINE {1} STREAM xmlstream.
DEFINE {1} STREAM Gxmlstream.

/*
** Subroutine procedures
*/

PROCEDURE print-starttag.

/* 
** This prints the start tag for an xml file
*/
    DEFINE INPUT-OUTPUT PARAMETER streamdetail AS CHARACTER FORMAT "x(32)".
    DEFINE INPUT PARAMETER tagname AS CHARACTER FORMAT "x(32)".
    DEFINE INPUT PARAMETER tagformat AS CHARACTER FORMAT "x(32)".
    DEFINE INPUT PARAMETER tagunits AS CHARACTER FORMAT "x(32)".
    DEFINE INPUT PARAMETER data-value AS CHARACTER FORMAT "x(64)".


    streamdetail = streamdetail + "<" + tagname.
    IF tagformat NE "" THEN 
    DO:
       streamdetail = streamdetail + " " + tagformat + ' = "' + tagunits + '"'.
    END.
    streamdetail = streamdetail + ">".
    streamdetail = streamdetail + data-value.

END PROCEDURE.


PROCEDURE print-starttag-graph.
/*
** Print the starting tag for a graph
*/

   DEFINE INPUT-OUTPUT PARAMETER graph1detail AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagname AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagformat AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagunits AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER data-value AS CHARACTER FORMAT "x(64)".
   DEFINE INPUT PARAMETER tag2format AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tag2units AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tag3format AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tag3units AS CHARACTER FORMAT "x(32)".


   graph1detail = graph1detail + "<" + tagname.

   IF tagformat NE "" THEN 
   DO:
      graph1detail = graph1detail + " " + tagformat + ' = "' + tagunits + '"'.
   END.
   IF tag2format NE "" THEN 
   DO:
      graph1detail = graph1detail + " " + tag2format + ' = "' + tag2units + '"'.
   END.
   IF tag3format NE "" THEN 
   DO:
      graph1detail = graph1detail + " " + tag3format + ' = "' + tag3units + '"'.
   END.
   graph1detail = graph1detail + ">" + data-value.

END PROCEDURE.


PROCEDURE print-endtag.

/* 
** This prints the end tag
*/

   DEFINE INPUT-OUTPUT PARAMETER streamdetail AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagname AS CHARACTER FORMAT "x(32)".

   streamdetail = streamdetail + "</" + tagname + ">".

END PROCEDURE.

PROCEDURE print-tag.
/*
** This will print the complete tag for the data (front and back).
*/

   DEFINE INPUT-OUTPUT PARAMETER streamdetail AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagname AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagformat AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagunits AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER data-value AS CHARACTER FORMAT "x(64)".

   RUN print-starttag (INPUT-OUTPUT streamdetail,
                       INPUT tagname, 
                       INPUT tagformat,
                       INPUT tagunits,
                       INPUT data-value).

   RUN print-endtag (INPUT-OUTPUT streamdetail,
                     INPUT tagname).
END PROCEDURE.

PROCEDURE print-tag-graph.
/*
** This will print the complete tag for the graph (front and back).
*/

   DEFINE INPUT-OUTPUT PARAMETER graph1detail AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagname AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagformat AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tagunits AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER data-value AS CHARACTER FORMAT "x(64)".
   DEFINE INPUT PARAMETER tag2format AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tag2units AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tag3format AS CHARACTER FORMAT "x(32)".
   DEFINE INPUT PARAMETER tag3units AS CHARACTER FORMAT "x(32)".

   RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                             INPUT tagname, 
                             INPUT tagformat,
                             INPUT tagunits,
                             INPUT data-value,
                             INPUT tag2format,
                             INPUT tag2units,
                             INPUT tag3format,
                             INPUT tag3units).

   RUN print-endtag (INPUT-OUTPUT graph1detail,
                     INPUT tagname).
   
END PROCEDURE.


PROCEDURE xml-document-header.

    /* 
    ** This header set up the information for the different data sets
    ** in the process.  It is required to be run before any other XML 
    ** processing can be done
    */
     
    pgm-name = "xml-document-header".
    sec-name = "Adding top level - reportDataSets".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT '?xml version="1.0" encoding="ISO-8859-1"?',
                        INPUT "", INPUT "", INPUT "").

    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "reportDataSets",
                        INPUT "", INPUT "", INPUT "").

    /* Version info. */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "reportversion",
                        INPUT "", INPUT "", INPUT "").

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "majorversion",
                   INPUT "", INPUT "",
                   INPUT "2").

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "minorversion",
                   INPUT "", INPUT "",
                   INPUT "1").

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "revision",
                   INPUT "", INPUT "",
                   INPUT "1").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportversion").

    /* Number format info. */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "numberformat",
                        INPUT "", INPUT "", INPUT "").

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "numsep",
                   INPUT "", INPUT "",
                   INPUT numberSeparator).

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "numdec",
                   INPUT "", INPUT "",
                   INPUT decimalPoint).

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "numberformat").

    /* Graph Headers */
    pgm-name = "xml-document-header".
    sec-name = "Adding top level - graphRequest".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT '?xml version="1.0" encoding="ISO-8859-1"?',
                              INPUT "", INPUT "", INPUT "", INPUT "",
                              INPUT "", INPUT "", INPUT "").
    xmlen-intext = fathom-t-rep_dir + "processed.xml".
    RUN xml-encode. 
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "graphRequest",
                              INPUT "filespec",
                              INPUT xmlen-outtext,
                              INPUT "", INPUT "",
                              INPUT "", INPUT "", INPUT "").

    /* Version info. */
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "reportversion",
                              INPUT "", INPUT "",
                              INPUT "", INPUT "",
                              INPUT "", INPUT "", INPUT "").

    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "majorversion",
                         INPUT "", INPUT "",
                         INPUT "2",
                         INPUT "", INPUT "",
                         INPUT "", INPUT "").

    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "minorversion",
                         INPUT "", INPUT "",
                         INPUT "1",
                         INPUT "", INPUT "",
                         INPUT "", INPUT "").

    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "revision",
                         INPUT "", INPUT "",
                         INPUT "1",
                         INPUT "", INPUT "",
                         INPUT "", INPUT "").

    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "reportversion").

    /* Number format info. */
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "numberformat",
                              INPUT "", INPUT "",
                              INPUT "", INPUT "",
                              INPUT "", INPUT "", INPUT "").

    xmlen-intext = numberSeparator.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "numsep",
                         INPUT "", INPUT "",
                         INPUT xmlen-outtext,
                         INPUT "", INPUT "",
                         INPUT "", INPUT "").

    xmlen-intext = decimalPoint.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "numdec",
                         INPUT "", INPUT "",
                         INPUT xmlen-outtext,
                         INPUT "", INPUT "",
                         INPUT "", INPUT "").

    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "numberformat").

END PROCEDURE.


PROCEDURE xml-graphspec.

    /* Graph specification part */
    pgm-name = "xml-graphspec".
    sec-name = "Adding graph information - graphSpec".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "graphSpec",
                              INPUT "", INPUT "", INPUT "",
                              INPUT "", INPUT "", INPUT "", INPUT "").

    /* Graph definition part */
    pgm-name = "xml-graphspec".
    sec-name = "Adding graph information - graphInstanceDef".
    {include/debug.i "pgm-name" "sec-name"}

    xmlen-intext = xmlgraph-imageid.
    RUN xml-encode.
    tmpdetail = xmlen-outtext.

    xmlen-intext = fathom-t-rep_dir.
    RUN xml-encode.
    tmp2detail = xmlen-outtext.
    xmlen-intext = xmlgraph-imagetitle.
    RUN xml-encode.
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "graphInstanceDef",
                              INPUT "id",
                              INPUT tmpdetail,
                              INPUT "",
                              INPUT "imagepathspec",
                              INPUT tmp2detail,
                              INPUT "imagefilename",
                              INPUT xmlen-outtext).
			
    /* Graph definition part */
    pgm-name = "xml-graphspec".
    sec-name = "Adding graph information - graphLegend".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "graphLegend",
                              INPUT "", INPUT "", INPUT "",
                              INPUT "", INPUT "", INPUT "", INPUT "").

    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "noDataXmlTemplate",
                         INPUT "", INPUT "", INPUT "",
                         INPUT "", INPUT "", INPUT "", INPUT "").

    RUN print-endtag (INPUT-OUTPUT graph1detail,
                        INPUT "graphLegend").

    /* Graph Instance Setup */
    IF Fathom-i-periods > 1 THEN
        RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                             INPUT "graphAttribute",
                             INPUT "attr",
                             INPUT "type",
                             INPUT "time.line",
                             INPUT "", INPUT "", INPUT "", INPUT "").
    ELSE
        RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                             INPUT "graphAttribute",
                             INPUT "attr",
                             INPUT "type",
                             INPUT "time.column",
                             INPUT "", INPUT "", INPUT "", INPUT "").
    /*RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "graphAttribute",
                         INPUT "attr",
                         INPUT "background",
                         INPUT "white",
                         INPUT "", INPUT "", INPUT "", INPUT "").*/
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "graphAttribute",
                         INPUT "attr",
                         INPUT "grid",
                         INPUT "true",
                         INPUT "", INPUT "", INPUT "", INPUT "").
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "graphAttribute",
                         INPUT "attr",
                         INPUT "dimension",
                         INPUT "3d",
                         INPUT "", INPUT "", INPUT "", INPUT "").
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "graphAttribute",
                         INPUT "attr",
                         INPUT "size",
                         INPUT "small",
                         INPUT "", INPUT "", INPUT "", INPUT "").  
    xmlen-intext = Fathom-report-title.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "graphAttribute",
                         INPUT "attr",
                         INPUT "title",
                         INPUT xmlen-outtext,
                         INPUT "", INPUT "", INPUT "", INPUT "").  
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphInstanceDef").
    
    /* 
    ** This procedure will process resource based information and put it
    ** into the XML file.
    */
    
    pgm-name = "xml-document-header".
    sec-name = "Adding graphical resource information".
    {include/debug.i "pgm-name" "sec-name"}
    /* Add resource name */
    xmlen-intext = xmlresourcesite.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "response",
                         INPUT "attr",
                         INPUT "resourcesite",
                         INPUT xmlen-outtext,
                         INPUT "", INPUT "", INPUT "", INPUT "").

    /* Add resource name */
    xmlen-intext = xmlresourcename.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "response",
                         INPUT "attr",
                         INPUT "resourcename",
                         INPUT xmlen-outtext,
                         INPUT "", INPUT "", INPUT "", INPUT "").

    /* Add resource type */
    xmlen-intext = xmlresourcetype.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "response",
                         INPUT "attr",
                         INPUT "resourcetype",
                         INPUT xmlen-outtext,
                         INPUT "", INPUT "", INPUT "", INPUT "").

    pgm-name = "xml-graphspec".
    sec-name = "Done adding graphical resource information".
    {include/debug.i "pgm-name" "sec-name"}
END PROCEDURE.


PROCEDURE xml-root-header.

    /* Add resource Site */
    pgm-name = "xml-root-header".
    sec-name = "Adding Site".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "resourcesite",
                   INPUT "",
                   INPUT "",
                   INPUT xmlresourcesite).

    /* Add resource name */
    sec-name = "Adding resource name".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "resourcename",
                   INPUT "",
                   INPUT "",
                   INPUT xmlresourcename).

    /* Add resource type */
    sec-name = "Adding resource type".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "resourcetype",
                   INPUT "",
                   INPUT "",
                   INPUT xmlresourcetype).

END PROCEDURE.


PROCEDURE xml-graphDataSets-header.

    /* Graph data part */
    pgm-name = "xml-root-header".
    sec-name = "Adding first sub-level - graphDataSets".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "graphDataSets",
                              INPUT "", INPUT "", INPUT "",
                              INPUT "", INPUT "", INPUT "", INPUT "").

END PROCEDURE.


PROCEDURE xml-graphspec-end.

    /* Close the graphspec tags. */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphSpec").

END PROCEDURE.


PROCEDURE xml-report-header.

    /*
    ** Adding in report header information.
    ** NOTE: This is not resource specific.
    */

    /* Add Report name */
    pgm-name = "xml-report-header".
    sec-name = "Adding report name".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "reportname",
                   INPUT "",
                   INPUT "",
                   INPUT fathom-d-rep_name).
    
    /* Add Report title */
    sec-name = "Adding Report Title".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "reporttitle",
                   INPUT "",
                   INPUT "",
                   INPUT fathom-report-title).

    /* Add Report Date */
    sec-name = "Adding Report date".
    {include/debug.i "pgm-name" "sec-name"}
    xmlen-intext = STRING (TODAY, "99/99/9999") + " "  + STRING (TIME, "HH:MM").
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "reportdate",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /* Add Report Interval Title */
    sec-name = "Adding Report Interval".
    {include/debug.i "pgm-name" "sec-name"}
    xmlen-intext = 
	STRING (Fathom-i-start_Date, "99/99/9999") +
	" - " + 
	STRING (Fathom-i-End_Date, "99/99/9999") +
        " " +
	STRING (Fathom-i-Start_Time, "HH:MM") + 
	" - " +
	STRING (Fathom-i-End_Time, "HH:MM")
	.
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "reportinterval",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /* Add Report Start Date */
    sec-name = "Adding Report Begin Date".
    {include/debug.i "pgm-name" "sec-name"}
    xmlen-intext = STRING (Fathom-i-start_Date, "99/99/9999").
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "reportbegindate",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /* Add Report End Date */
    sec-name = "Adding Report End Date".
    {include/debug.i "pgm-name" "sec-name"}
    xmlen-intext = STRING (Fathom-i-End_Date, "99/99/9999").
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "reportenddate",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /* Add Report Total Sample Count */
    sec-name = "Adding Report Total Sample Count".
    {include/debug.i "pgm-name" "sec-name"}
    xmlen-intext = STRING (Fathom-Rec-Count).
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "reporttotalsamplecount",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    CASE Fathom-i-intervaltype:
        WHEN "R" THEN xmlen-intext = "Per Record".
        WHEN "S" THEN xmlen-intext = "Per Second".
        WHEN "M" THEN xmlen-intext = "Per Minute".
        WHEN "H" THEN xmlen-intext = "Per Hour".
        WHEN "T" THEN xmlen-intext = "Per Transaction".
        OTHERWISE xmlen-intext = "Raw Data".
    END CASE.

    /* Add Report Display Units. */
    sec-name = "Adding Report Display Units".
    {include/debug.i "pgm-name" "sec-name"}.
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "displayunits",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /* Add Report Date Format. */
    sec-name = "Adding Report Date Format".
    {include/debug.i "pgm-name" "sec-name"}.
    xmlen-intext = STRING (SESSION:DATE-FORMAT).
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "dateformat",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

END PROCEDURE.


PROCEDURE xml-row-header.

    /*
    ** This is only for the graphs...
    */
     
        pgm-name = "procedure: xml-row-header".
        sec-name = "data value included: " + xmldatalabel .
        {include/debug.i "pgm-name" "sec-name"}
     
        xmlen-intext = xmldataOutputlabel.
        RUN xml-encode.
        RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset",
                                  INPUT "label",
                                  INPUT xmlen-outtext,
                                  INPUT "",
                                  INPUT "", INPUT "", INPUT "", INPUT "").
        
        xmlen-intext = dateFormatString + " - HH:mm".
        RUN xml-encode.
        RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues",
                                  INPUT "timeformat",
                                  INPUT xmlen-outtext,
                                  INPUT "",
                                  INPUT "", INPUT "", INPUT "", INPUT "").
END PROCEDURE.


PROCEDURE xml-row-end.

    /* Only for graphs, ends tags in xml-row-header. */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "dataValues").
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "dataset").

END PROCEDURE.


PROCEDURE xml-add-data.

    /* 
    ** This procedure adds the data level information to the XML file
    ** for each data value that should be added to the file.
    ** This is only for the data portion - NOT the graphing.
    **
    ** NOTE: This is split up in case procedures need to add other
    **  tags or info under this tag.
    */

    RUN xml-add-data-starttag.
    RUN xml-add-data-tags.
    RUN xml-add-data-endtag.

END PROCEDURE.


PROCEDURE xml-add-data-summary.

    /* 
    ** This procedure adds the data level information to the XML file
    ** for each data value that should be added to the file.
    ** This is only for the data portion - NOT the graphing.
    **
    ** NOTE: This is split up in case procedures need to add other
    **  tags or info under this tag.
    */

    RUN xml-add-data-starttag.
    RUN xml-add-data-tags-summary.
    RUN xml-add-data-endtag.

END PROCEDURE.


PROCEDURE xml-add-data-starttag.

    /*
    ** Starts the data section.  See xml-add-data.
    */

    pgm-name = "xml-add-data".
    sec-name = "Adding resource information to data set".
    {include/debug.i "pgm-name" "sec-name"}

    /* Create the datum heading */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "data",
                        INPUT "",
                        INPUT "",
                        INPUT "").
    
END PROCEDURE.


PROCEDURE xml-add-data-tags.

    /*
    ** Adds the meat of the data section.  See xml-add-data.
    */

    /* Add Field information (field name) */
    sec-name = "Add Field Information" + xmldatalabel.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "fieldname",
                   INPUT "",
                   INPUT "",
                   INPUT xmldatalabel).
    
    /* Add label information */
    sec-name = "Add Label Information" + xmldataOutputlabel.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "label",
                   INPUT "",
                   INPUT "",
                   INPUT xmldataOutputlabel).

    /* Add timestamp format and value */
    sec-name = "Add Timestamp: " + xmldateoutbeg + " - " + xmldateoutend.
    {include/debug.i "pgm-name" "sec-name"}
    IF xmldateoutbeg = xmldateoutend THEN
    DO:
       xmlen-intext = xmldayoutbeg + " " + xmldateoutbeg.
       IF xmlsamplebegtime GT 1 OR xmlsampleendtime LT 86399 THEN
       DO:
           xmlen-intext = xmlen-intext + " " +
	                  xmltimeoutbeg + 
			  " - " + 
			  xmltimeoutend.
       END.
    END.
    ELSE
    DO:
       xmlen-intext = xmldateoutbeg + " - " + xmldateoutend.
       IF xmlsamplebegtime GT 1 OR xmlsampleendtime LT 86399 THEN
       DO:
           xmlen-intext = xmlen-intext + " " +
	                  xmltimeoutbeg + 
			  " - " + 
			  xmltimeoutend.
       END.
    END.
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "timename",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /* Add duration format and value */
    sec-name = "Add Sample Length: " + xmlsamplelength.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "duration",
                   INPUT "",
                   INPUT "",
                   INPUT xmlsamplelength).
   
    /* Add samples format and value */
    sec-name = "Add Sample Counts: " + xmlsamplecount.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "samplecount",
                   INPUT "",
                   INPUT "",
                   INPUT xmlsamplecount).
  
    /* Add transactions format and value */
    sec-name = "Add transaction Counts: " + xmlsampletransactions.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "transactions",
                   INPUT "",
                   INPUT "",
                   INPUT xmlsampletransactions).

    /* Add data precision format and value */
    sec-name = "Add data precision: " + dataprecision.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "precision",
                   INPUT "",
                   INPUT "",
                   INPUT dataprecision).
    
    /* Add the data value for that record */
    sec-name = "Add data value: " + xmldatavalue.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "value",
                   INPUT "units",
                   INPUT xmlunittype,
                   INPUT xmldatavalue).

END PROCEDURE.


PROCEDURE xml-add-data-tags-summary.

    /*
    ** Adds the meat of the data section.  See xml-add-data.
    */

    /* Add Field information (field name) */
    sec-name = "Add Field Information" + xmldatalabel.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "fieldname",
                   INPUT "",
                   INPUT "",
                   INPUT xmldatalabel).
    
    /* Add label information */
    sec-name = "Add Label Information" + xmldataOutputlabel.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "label",
                   INPUT "",
                   INPUT "",
                   INPUT xmldataOutputlabel).

    /* Add timestamp format and value */
    sec-name = "Add Timestamp: Summary".
    {include/debug.i "pgm-name" "sec-name"}
    xmlen-intext = "Summary".
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "timename",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /* Add duration format and value */
    sec-name = "Add Sample Length: " + xmlsamplelength.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "duration",
                   INPUT "",
                   INPUT "",
                   INPUT xmlsamplelength).
   
    /* Add samples format and value */
    sec-name = "Add Sample Counts: " + xmlsamplecount.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "samplecount",
                   INPUT "",
                   INPUT "",
                   INPUT xmlsamplecount).
  
    /* Add transactions format and value */
    sec-name = "Add transaction Counts: " + xmlsampletransactions.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "transactions",
                   INPUT "",
                   INPUT "",
                   INPUT xmlsampletransactions).

    /* Add data precision format and value */
    sec-name = "Add data precision: " + dataprecision.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "precision",
                   INPUT "",
                   INPUT "",
                   INPUT dataprecision).
    
    /* Add the data value for that record */
    sec-name = "Add data value: " + xmldatavalue.
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "value",
                   INPUT "units",
                   INPUT xmlunittype,
                   INPUT xmldatavalue).

END PROCEDURE.


PROCEDURE xml-add-data-endtag.

    /*
    ** Ends the data section.  See xml-add-data.
    */

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "data").

END PROCEDURE.

PROCEDURE xml-add-data-graph.

    /* 
    ** This procedure adds the data level information to the XML file
    ** for each data value that should be added to the file.
    ** This is only for the graph section.
    */

    pgm-name = "xml-add-data-graph".
    sec-name = "Adding resource information to data set".
    {include/debug.i "pgm-name" "sec-name"}

    /* Add timestamp format and value */
    sec-name = "Add Timestamp: " + xmldateoutbeg + " - " + xmldateoutend.
    {include/debug.i "pgm-name" "sec-name"}
    IF xmldateoutbeg = xmldateoutend THEN
    DO:
       xmlen-intext = xmldayoutbeg + " " + xmldateoutbeg.
       IF xmlsamplebegtime GT 1 OR xmlsampleendtime LT 86399 THEN
       DO:
           xmlen-intext = xmlen-intext + " " +
	                  xmltimeoutbeg + 
			  " - " + 
			  xmltimeoutend.
       END.
    END.
    ELSE
    DO:
       xmlen-intext = xmldateoutbeg + " - " + xmldateoutend.
       IF xmlsamplebegtime GT 1 OR xmlsampleendtime LT 86399 THEN
       DO:
           xmlen-intext = xmlen-intext + " " +
	                  xmltimeoutbeg + 
			  " - " + 
			  xmltimeoutend.
       END.
    END.
    /* RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "timename",
		   INPUT "",
		   INPUT "",
		   INPUT xmlen-intext). */
    
    /* Create the datum heading */
    RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "datum",
			      INPUT "", INPUT "", INPUT "", 
			      INPUT "", INPUT "", INPUT "", INPUT "").
   
    /* Add beginning timestamp format and value */
    xmlen-intext = xmldateoutbeg + " - " + xmltimeoutbeg.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "begintimestamp",
			 INPUT "",
			 INPUT "",
			 INPUT xmlen-outtext,
			 INPUT "", INPUT "", INPUT "", INPUT "").
    
    /* Add ending timestamp format and value */
    xmlen-intext = xmldateoutend + " - " + xmltimeoutend.
    RUN xml-encode.
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "endtimestamp",
			 INPUT "",
			 INPUT "",
			 INPUT xmlen-outtext,
			 INPUT "", INPUT "", INPUT "", INPUT "").
     
    /* Add duration format and value */
    /* Commented out due to us adding begin and end time */
    /* Add duration format and value */
    /* Add samples format and value */
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                         INPUT "samplecount",
			 INPUT "",
			 INPUT "",
			 INPUT xmlsamplecount,
			 INPUT "", INPUT "", INPUT "", INPUT "").
       
    /* Add transactions format and value */
    /* RUN print-starttag-graph (INPUT-OUTPUT graph1detail,
                              INPUT "transactions",
			      INPUT "", INPUT "", INPUT "", 
			      INPUT "", INPUT "", INPUT "", INPUT "").  */

    /* Add the data value for that record */
    RUN print-tag-graph (INPUT-OUTPUT graph1detail,
                        INPUT "yValue",
			INPUT "",
			INPUT "",
			INPUT xmldatavalue,
			INPUT "", INPUT "", INPUT "", INPUT "").

    /* RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "transactions").*/
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "datum").
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END PROCEDURE.

PROCEDURE xml-add-data-timetable.

    /*
    ** This procedure adds the data time level information to the XML file
    ** for each data value that should be added to the file.
    ** This is only for the data section, NOT the graphing.
    */

    /*
    ** This creates the time sub-level under times
    */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "time",
                        INPUT "",
                        INPUT "",
                        INPUT "").

    IF xmldateoutbeg = xmldateoutend THEN
    DO:
       xmlen-intext = xmldayoutbeg + " " + xmldateoutbeg.
       IF xmlsamplebegtime GT 1 OR xmlsampleendtime LT 86399 THEN
       DO:
           xmlen-intext = xmlen-intext + " " + 
                          xmltimeoutbeg + " - " + xmltimeoutend.
       END.
    END.
    ELSE
    DO:
       xmlen-intext = xmldateoutbeg + " - " + xmldateoutend.
       IF xmlsamplebegtime GT 1 OR xmlsampleendtime LT 86399 THEN
       DO:
           xmlen-intext = xmlen-intext + " " +  
                          xmltimeoutbeg + " - " + xmltimeoutend.
       END.
    END.
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "name",
                   INPUT "",
                   INPUT "",
                   INPUT xmlen-intext).

    /*
    ** This creates the begin and end sub-levels under time
    */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "begin",
                        INPUT "",
                        INPUT "",
                        INPUT "").

    /* Add Begin Day Name */
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "dayname",
                   INPUT "",
                   INPUT "",
                   INPUT xmldayoutbeg).

    /* Add begin date */
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "date",
                   INPUT "format",
                   INPUT dateFormatString,
                   INPUT xmldateoutbeg).
    
    /* Add begin time */

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "time",
                   INPUT "format",
                   INPUT "HH:mm",
                   INPUT xmltimeoutbeg).
    
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "begin").

    /* Add End Day Name */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "end",
                        INPUT "",
                        INPUT "",
                        INPUT "").

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "dayname",
                   INPUT "",
                   INPUT "",
                   INPUT xmldayoutend).
    
    /* Add end date */
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "date",
                   INPUT "format",
                   INPUT dateFormatString,
                   INPUT xmldateoutend).
    
    /* Add end time */

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "time",
                   INPUT "format",
                   INPUT "HH:mm",
                   INPUT xmltimeoutend).
   
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "end").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "time").
END PROCEDURE.

PROCEDURE xml-add-data-labels.

    /*
    ** This procedure adds the data label level information to the XML file
    ** for each data value that should be added to the file.
    */

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "label",
                   INPUT "",
                   INPUT "",
                   INPUT xmldataOutputlabel).

END PROCEDURE.

PROCEDURE xml-process-date. 

    /* 
    ** This procedure processes the incoming date and formats it in the
    ** java standard format.
    */

    /*xmlday = STRING (DAY(xmlsamplebegdate)).
    IF LENGTH (xmlday) = 1 THEN xmlday = "0" + xmlday.        
    xmlmonth = STRING (MONTH(xmlsamplebegdate)).
    IF LENGTH (xmlmonth) = 1 THEN xmlmonth = "0" + xmlmonth.
    xmldateoutbeg = STRING (YEAR(xmlsamplebegdate)) + "." +
                          xmlmonth + "." +
                          xmlday.*/
    xmldateoutbeg = STRING (xmlsamplebegdate, "99/99/9999").

    xmltimeoutbeg = STRING (xmlsamplebegtime, "HH:MM").


    xmlday = STRING (WEEKDAY (xmlsamplebegdate)).
    CASE xmlday:
       WHEN "1" THEN xmldayoutbeg = "Sunday".
       WHEN "2" THEN xmldayoutbeg = "Monday".
       WHEN "3" THEN xmldayoutbeg = "Tuesday".
       WHEN "4" THEN xmldayoutbeg = "Wednesday".
       WHEN "5" THEN xmldayoutbeg = "Thursday".
       WHEN "6" THEN xmldayoutbeg = "Friday".
       WHEN "7" THEN xmldayoutbeg = "Saturday".
       OTHERWISE xmldayoutbeg = "".
    END CASE.

    /*xmlday = STRING (DAY(xmlsampleenddate)).
    IF LENGTH (xmlday) = 1 THEN xmlday = "0" + xmlday.     
    xmlmonth = STRING (MONTH(xmlsampleenddate)).
    IF LENGTH (xmlmonth) = 1 THEN xmlmonth = "0" + xmlmonth.
    xmldateoutend = STRING (YEAR(xmlsampleenddate)) + "." +
                          xmlmonth + "." +
                          xmlday.*/
    xmldateoutend = STRING (xmlsampleenddate, "99/99/9999").
                          
    xmltimeoutend = STRING (xmlsampleendtime, "HH:MM").

    xmlday = STRING (WEEKDAY (xmlsamplebegdate)).
    CASE xmlday:
       WHEN "1" THEN xmldayoutend = "Sunday".
       WHEN "2" THEN xmldayoutend = "Monday".
       WHEN "3" THEN xmldayoutend = "Tuesday".
       WHEN "4" THEN xmldayoutend = "Wednesday".
       WHEN "5" THEN xmldayoutend = "Thursday".
       WHEN "6" THEN xmldayoutend = "Friday".
       WHEN "7" THEN xmldayoutend = "Saturday".
       OTHERWISE xmldayoutend = "".
    END CASE.

END PROCEDURE.

PROCEDURE xml-encode.
/* 
** This procedure will encode characters for transfer across the wire. 
*/

xmlen-outtext = "".
xmlen-inchar = "".

DO xmlen-i = 1 TO LENGTH (xmlen-intext):

   xmlen-inchar = SUBSTRING (xmlen-intext, xmlen-i, 1).
   xmlen-ascii = ASC(xmlen-inchar).
   IF (xmlen-ascii GT 47 AND xmlen-ascii LT 58) OR 
      (xmlen-ascii GT 64 AND xmlen-ascii LT 91) OR
      (xmlen-ascii GT 96 AND xmlen-ascii LT 123) THEN
   DO:
      xmlen-outtext = xmlen-outtext + xmlen-inchar.
   END.
   ELSE
   DO:
      xmlen-remainder = xmlen-ascii MODULO 16.
      xmlen-sixteen = ( xmlen-ascii - xmlen-remainder ) / 16.
      IF xmlen-remainder GE 10 THEN DO:
         xmlen-ten = xmlen-remainder MODULO 10.
         xmlen-keylabel = KEYLABEL(KEYCODE("A") + xmlen-ten).
      END.
      ELSE 
      DO: 
          xmlen-keylabel = STRING(xmlen-remainder).
      END.
      xmlen-outtext = xmlen-outtext + 
                      "%" + STRING(xmlen-sixteen) + 
		      xmlen-keylabel.
   END.
END.
/* xmlen-outtext = xmlen-intext. */

END PROCEDURE.
/*
** XML Handles include
**
** This include should be used to create and delete the xml handles to
** be written out. It must be included after the xmldefinitions.i
**
****************************************************************
*/

{2} hDoc.  
{1} hRoot.
/* Data handles */
{1} hRootdatavalues.
{1} hRootresrcname.
{1} hRootlabel.
{1} hRootlabelvalue.
{1} hRowdataset.  
{1} hRowdatasetlabel.  
{1} hRowdatavalues.  
/* Time handles */
{1} hRowtimeset.  
{1} hRowtimesetlabel.  
{1} hRowtimevalues.  
{1} hRowtimedetails.  
{1} hRowtimedetailsBEG.  
{1} hRowtimedetailsEND.  
/* Label handles */
{1} hRowlabelset.  
{1} hRowlabelsetlabel.  
{1} hRowlabelvalues.  
{1} hRowlabeldetails.  
{1} hFielddatum. 
{1} hFieldvalues. 
{1} hTextlabels.
{1} hTextvalues.
{1} hTimeTextlabels.
{1} hTimeTextvalues.
{1} hLabelTextlabels.
{1} hLabelTextvalues.

/*Graph Stuff */
{2} GhDoc.  
{1} GhRoot.
{1} GhsubRoot.
{1} GhInstanceDef.
{1} GhLegend.
{1} GhAttribute.
{1} GhRootdatavalues.
{1} GhRootresrcname.
{1} GhRowdataset.  
{1} GhRowdatasetlabel.  
{1} GhRowdatavalues.  
{1} GhFielddatum. 
{1} GhFieldvalues. 
{1} GhTextlabels.
{1} GhTextvalues.

{1} GhDataSets.  
{1} GhLegendDetail.  
/*
** XML Initialization include
**
** NOTE: This code was built based on the concepts presented by
** Doug Merrett - Progress Software Corporation
**
****************************************************************
**
** This include should be used to initialize the xml document to
** be written out. It must be included after the xmldefinitions.i
**
****************************************************************
*/

docname = SUBSTRING (fathom-t-rep_name, 1, LENGTH (Fathom-t-rep_name) - 4) + "_data.xml".
Gdocname = SUBSTRING (fathom-t-rep_name, 1, LENGTH (Fathom-t-rep_name) - 4) + "_graph.xml".
/* docname = "datumblb.xml". */

OUTPUT STREAM xmlstream TO VALUE (docname).
OUTPUT STREAM Gxmlstream TO VALUE (Gdocname).

RUN xml-document-header.

/* Initialize the date format string for the graphing engine. */
dateFormatString = STRING(SESSION:DATE-FORMAT).
CASE dateFormatString:
    WHEN "ymd" THEN dateFormatString = "yyyy/MM/dd".
    WHEN "dmy" THEN dateFormatString = "dd/MM/yyyy".
    OTHERWISE dateFormatString = "MM/dd/yyyy". /* mdy */
END CASE.
PROCEDURE xml-resource-header.
/* 
** This expects that the following is set:
**   xmlresourcename = Cf_Resrc.Resrc_Name 
**   xmlresourcetype = Cf_Resrc.Resrc_Type 
**   xmlresourcesite = Cf_Resrc.Site_ID.
*/
/* Setup the root header and data information */
    
   RUN print-starttag (INPUT-OUTPUT streamdetail,
       INPUT "resource",
       INPUT "",
       INPUT "",
       INPUT "").

   PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
   streamdetail = "".
   PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
   graph1detail = "".
    
   RUN xml-root-header.
   RUN xml-graphDataSets-header.
       
   PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
   streamdetail = "".
   PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
   graph1detail = "".
    
END PROCEDURE. /* resource-header */

/* PROCEDURE xml-print-labels.

/*
** DO the labels section 
*/
    
   RUN print-starttag (INPUT-OUTPUT streamdetail,
       INPUT "labels",
       INPUT "",
       INPUT "",
       INPUT "").
   PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
   streamdetail = "".
   PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
   graph1detail = "".
       
   FOR EACH data_store WHERE data_store.ResrcID = tResrcID USE-INDEX three:
    
       xmldataOutputlabel = data_store.lable.
       RUN print-tag (INPUT-OUTPUT streamdetail,
           INPUT "label",
           INPUT "",
    	   INPUT "",
    	   INPUT xmldataOutputlabel).
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
       
   END.
   RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "labels").
   PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
   streamdetail = "".
   PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
   graph1detail = "".
   
END PROCEDURE. /* xml-print-labels */ */

PROCEDURE xml-print-dates.

/*
** Dates section
*/
    
    RUN print-starttag (INPUT-OUTPUT streamdetail,
        INPUT "times",
        INPUT "",
        INPUT "",
        INPUT "").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    DO fathom-x = 1 to Fathom-i-periods:
        xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
        xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
        xmlsampleenddate = Fathom-t-end-date[fathom-x].
        xmlsampleendtime = Fathom-t-end-time[fathom-x].
                        
        RUN xml-process-date.  /* subroutine to process the date */
        RUN xml-add-data-timetable. /* subroutine to process the datum */
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
    END.
    RUN print-endtag (INPUT-OUTPUT streamdetail, INPUT "times").
    
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
END PROCEDURE.  /* xml-print-dates */

PROCEDURE xml-format-column-intervaltype.

    /*
    ** Prepare the output based on the Interval Type
    ** (Record, Second, Minute, Hour, Transaction, raw numbers)
    */
    CASE Fathom-i-IntervalType:
        WHEN "R" THEN xmldatavalue = 
            STRING (INT64 (xmldatavalue) / INT64 (xmlsamplecount) ).
        WHEN "S" THEN xmldatavalue = 
            STRING (INT64 (xmldatavalue) / 
            INT64 (xmlsamplelength)).
        WHEN "M" THEN xmldatavalue = 
    	    STRING (INT64 (xmldatavalue) / 
            (INT64 (xmlsamplelength) / 60)).
        WHEN "H" THEN xmldatavalue = 
    	    STRING (INT64 (xmldatavalue) / 
    	    ((INT64 (xmlsamplelength) / 60) / 60)).
        WHEN "T" THEN xmldatavalue = 
    	    STRING (INT64 (xmldatavalue) / 
            INT64 (xmlsampletransactions)).
        OTHERWISE xmldatavalue = STRING (xmldatavalue).
    END CASE.

    IF xmldatavalue = ? then xmldatavalue = "0".

END PROCEDURE.

PROCEDURE xml-setup-outputvars.
    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
    xmlsampleenddate = Fathom-t-end-date[fathom-x].
    xmlsampleendtime = Fathom-t-end-time[fathom-x].
    xmlsamplecount = STRING (Fathom-numsamples[fathom-x]).
    xmlsamplelength = STRING (Fathom-Interval-Count[fathom-x]).
    xmlsampletransactions = STRING (Fathom-Transaction-Count[fathom-x]).
    IF xmlsamplelength = ? then xmlsamplelength = "0".
    IF xmlsampletransactions = ? then xmlsampletransactions = "0".
END PROCEDURE.
/* Procedure to load Fathom Version 2.0A schema into a Fathom Version 1.0A database
**
**  FATHOMINSTALLDIR must exist and point to the Fathom 1.0A Fathom Installation directory where
**  the version 1.0A FathomTrendDatabase resides in the db subdirectory.
*/
DEF VAR df-file AS CHARACTER INITIAL "".
DEF VAR dlc-dir AS CHARACTER INITIAL "".

DO TRANSACTION:

FIND FIRST Cf_Control WHERE Cf_Control.ID = "version" EXCLUSIVE-LOCK NO-ERROR.
IF AVAILABLE Cf_Control THEN
DO:
    PUT SKIP "Updating Definitions - Found Control Table.".

    IF Cf_Control.C1 = "1.0A" THEN
    DO:
 
        PUT SKIP "Updating Definitions - DB Version 1.0A.".

        df-file = OS-GETENV("fathomInstallDir"). 
 
        IF df-file = "" OR df-file = ? THEN  
        DO:
            PUT SKIP "Updating Defintions - ERROR! FathomInstallDir not set! Aborting".
            QUIT.
        END. 
        ELSE df-file = df-file + "/db/fathom20a.df".
 
        dlc-dir = OS-GETENV("DLC").
 
        IF dlc-dir = "" OR dlc-dir = ? THEN 
        DO:      
            PUT SKIP "Updating Definitions - ERROR! DLC not set! Aborting".
            QUIT.
        END.
 
        PUT SKIP "Updating Definitions - Environment Correct - continuing.".
        
        RUN prodict/load_df.p (df-file).
        Cf_Control.c1 = "2.0A".
    END.
    ELSE
    DO:
        PUT SKIP "Updating Definitions - Database already has a version number of 2.0A".
        QUIT.
    END.
END.
ELSE 
DO:
    PUT SKIP "Updating Definitions - ERROR! Could not find Cf_Control Table entry!!!".
    QUIT.
END.
END. /* of DO TRANSACTION: */

PUT SKIP "Updating Definitions - Update Complete!!!".
QUIT.
/* 
** Procedure to load Fathom Version 2.1A schema into a Fathom Version 2.0A 
** database
**
**  FATHOMINSTALLDIR must exist and point to the Fathom 2.0A Fathom 
**  Installation directory where
**  the version 2.0A FathomTrendDatabase resides in the db subdirectory.
*/
DEF VAR df-file AS CHARACTER INITIAL "".
DEF VAR dlc-dir AS CHARACTER INITIAL "".

df-file = OS-GETENV("fathomInstallDir"). 
IF df-file = "" OR df-file = ? THEN  
DO:
   PUT SKIP "Updating Defintions - ERROR! FathomInstallDir not set! Aborting".
   QUIT.
END. 
ELSE df-file = df-file + "/db/fathom21a.df".
 
dlc-dir = OS-GETENV("DLC").

IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
   PUT SKIP "Updating Definitions - ERROR! DLC not set! Aborting".
   QUIT.
END.
 
PUT SKIP "Updating Definitions - Environment Correct - continuing.".
        
RUN prodict/load_df.p (df-file).

PUT SKIP "Updating Definitions - Update Complete!!!".

QUIT.
/*
** Network.p
** This program will present a trend report on a network resource based on the dates 
** provided to the report.  The dates will be defined in the Trend database in the 
** table Cf_Rep_Def.  The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* Define Temp Table to store results */

DEF NEW SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name AS character
    FIELD passedSamples AS DECIMAL EXTENT 366 INITIAL 0
    FIELD failedSamples AS DECIMAL EXTENT 366 INITIAL 0
    FIELD h-values      AS DECIMAL EXTENT 366 INITIAL 0
    INDEX three Name.

DEF VAR poll-total AS INT NO-UNDO EXTENT 366.
DEF VAR save-total AS INT NO-UNDO.
DEF VAR Fathom-calc-value AS DECIMAL NO-UNDO.
/* 
** Begin Main Processing
*/
/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }

/* 
** Set up the date arrays
*/

{ include/trenddates.i }
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
/* 
** Begin Main Processing.
*/

/* sec-name = "Processing Samples".        */
/* pgm-name = "network.p".                */
/* {include/debug.i "pgm-name" "sec-name"} */

{include/sample-query.i}

{include/setup-k.i}

   FIND FIRST net_data WHERE Net_Data.Sample_ID = Cf_Sample.Sample_ID NO-ERROR.
   IF AVAILABLE Net_Data THEN
   DO:

/*
** Increment counters
*/
    {include/fathom-counters.i}

      find first Data_Store where Name = Fathom-i-Resrc_Name NO-ERROR.
      if not available Data_Store then
      DO:
         Create Data_Store.
         Data_Store.Name = Fathom-i-Resrc_Name.
      END.
      IF Net_Data.Net_Status = "Passed" THEN
      DO:
          Data_Store.passedSamples[Fathom-k] = Data_Store.passedSamples[Fathom-k] + 1.
          Data_Store.h-values[Fathom-k] = Data_Store.h-values[Fathom-k] + Net_Data.Net_time.
      END.
      ELSE DO:
          Data_Store.failedSamples[Fathom-k] = Data_Store.failedSamples[Fathom-k] + 1.
      END.
   END.

   IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
   ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = cf_sample.sample_date.

END. /* of assignment of for each */

/*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "network.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date GE fathom-i-start_date THEN
DO:
    pgm-name = "network.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.
    DEFINE VARIABLE qh                 AS WIDGET-HANDLE.
        
    pgm-name = "ar-report-add-actsum.p".
    sec-name = "Running procedure add-actsum".
    {include/debug.i "pgm-name" "sec-name"}.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_Net_Data:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_Net_Data WHERE " +
                     "Ar_Net_Data.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_Net_Data.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_Net_Data.Net_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_Net_Data.Net_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_Net_Data.Net_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_Net_Data.Net_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_Net_Data.Net_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().

    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.
    
        /* 
        ** Determine which date column the record falls into
        */
        Fathom-i = 0.
    
        REPEAT:
            Fathom-i = Fathom-i + 1.
            IF Ar_Net_Data.Net_startdate GE Fathom-t-beg-date[Fathom-i] AND
                Ar_Net_Data.Net_startdate LE Fathom-t-end-date[Fathom-i] THEN
            DO:
               IF Ar_Net_Data.Net_starttime GE Fathom-t-beg-time[Fathom-i] AND
                   Ar_Net_Data.Net_starttime LE Fathom-t-end-time[Fathom-i] THEN
                   LEAVE.
            END.
            IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.
        
        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        fathom-rec-count = fathom-rec-count + Ar_Net_Data.net_RecordCount.
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_Net_Data.net_Length.
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_Net_Data.net_RecordCount. 
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1. 
       
        /*
        ** Process each field that is on the report
        */
        FIND FIRST Data_Store WHERE Name = Fathom-i-Resrc_Name NO-ERROR.
        IF NOT AVAILABLE Data_Store THEN
        DO:
            CREATE Data_Store.
            ASSIGN
                Data_Store.Name = Fathom-i-Resrc_Name.
        END.
        IF Ar_Net_Data.Net_Status = "Passed" THEN
        DO:
            Data_Store.passedSamples[Fathom-i] = Data_Store.passedSamples[Fathom-i] + Ar_Net_Data.Net_RecordCount.
            Data_Store.h-values[Fathom-i] = Data_Store.h-values[Fathom-i] +
                                            (Ar_Net_data.Net_time *
                                             Ar_Net_Data.Net_RecordCount).
        END.
        ELSE DO:
            Data_Store.failedSamples[Fathom-i] = Data_Store.failedSamples[Fathom-i] + Ar_Net_Data.Net_RecordCount.
        END.
        
    END.

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}.
END.


/*
** Print Section
*/
sec-name = "Printing Report".
pgm-name = "network.p".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }

RUN xml-network.p.

sec-name = "Exiting Program".
pgm-name = "network.p".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** asprofile.p
**
** This program will gather data on procedures that brokers have run.
**
*/

{include/definitions.i "NEW SHARED"}.

DEFINE NEW SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name                     AS CHARACTER
    FIELD brokerName               AS CHARACTER
    FIELD brokerPID                AS INTEGER
    FIELD brokerUUID               AS CHARACTER
    FIELD procedureType            AS CHARACTER
    FIELD numSamples               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD numSeconds               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD runCount                 AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqTotTime               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqDurationAvg           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeSuccess        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeError          AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeQuit           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeStop           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryNumSamples        AS DECIMAL
    FIELD summaryRunCount          AS DECIMAL
    FIELD summaryReqDurationAvg    AS DECIMAL
    FIELD summaryReturnCodeSuccess AS DECIMAL
    FIELD summaryReturnCodeError   AS DECIMAL
    FIELD summaryReturnCodeQuit    AS DECIMAL
    FIELD summaryReturnCodeStop    AS DECIMAL
    INDEX one Name.


pgm-name = "asprofile.p".
sec-name = "Starting program.".
{include/debug.i "pgm-name" "sec-name"}.


IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}.

    {include/passinput.i}.
END.

/* Set up date buckets in the temp table. */
{include/trenddates.i}.

{include/report-name.i}.

/*
** Read samples and process them into the report table.
*/
pgm-name = "asprofile.p".
sec-name = "Processing Samples".

{include/debug.i "pgm-name" "sec-name"}.

sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}.


/* For use in determining which procedures to report on. */
DEFINE VARIABLE Procedure-filter AS CHARACTER NO-UNDO.
Procedure-filter = OS-GETENV("fathomReportProcedureFilter").

DEFINE VARIABLE Procedure-filter-type AS CHARACTER NO-UNDO.
Procedure-filter-type = OS-GETENV("fathomReportProcedureFilterType").

/* For 'matches'. */
DEFINE VARIABLE subprocfilter AS CHARACTER NO-UNDO.
DEFINE VARIABLE procfilter-index AS INTEGER NO-UNDO.

/* For query. */
DEFINE VARIABLE qh          AS WIDGET-HANDLE.
DEFINE VARIABLE matchstring AS CHARACTER NO-UNDO.


/*
** Get data from trend database.
*/
pgm-name = "asprofile.p".
sec-name = "Starting data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** Set up the query expression.
*/
CASE Procedure-filter-type:

    WHEN "begins" THEN
    DO:
        pgm-name = "asprofile.p".
        sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
        {include/debug.i "pgm-name" "sec-name"}.

        matchstring = "OE_ActASProc.ActASProc_Name BEGINS ~"" + Procedure-filter + "~" ".

    END. /* WHEN "begins" */

    WHEN "matches" THEN
    DO:
        pgm-name = "asprofile.p".
        sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
        {include/debug.i "pgm-name" "sec-name"}.

        matchstring = "(".
        
        DO procfilter-index = 1 TO NUM-ENTRIES(Procedure-filter, "|"):
            subprocfilter = TRIM(ENTRY(procfilter-index, Procedure-filter, "|")) NO-ERROR.
            matchstring = matchstring + "OE_ActASProc.ActASProc_Name MATCHES ~"" + subprocfilter + "~" OR ".
        END.

        IF LENGTH(matchstring) GT 4 THEN
            matchstring = SUBSTRING(matchstring, 1, LENGTH(matchstring) - 4) + ") ".
        ELSE
            matchstring = "".

    END. /* WHEN "matches" */

    OTHERWISE
    DO:
        /* Literal is the default if the value isn't set. */
        IF Procedure-filter-type NE "literal" THEN
        DO:
            pgm-name = "asprofile.p".
            sec-name = "fathomReportProcedureFilterType not set, defaulting to literal.".
            {include/debug.i "pgm-name" "sec-name"}.
        END.
        ELSE
        DO:
            pgm-name = "asprofile.p".
            sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
            {include/debug.i "pgm-name" "sec-name"}.
        END.

        matchstring = "OE_ActASProc.ActASProc_Name EQ ~"" + Procedure-filter + "~" ".

    END. /* OTHERWISE */

END CASE.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER OE_ActASProc:HANDLE).


/*
** Get the data.
*/
FOR EACH tmp-resrc:

    pgm-name = "asprofile.p".
    sec-name = "Gathering data for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    Fathom-i-Resrc_ID = tmp-resrc.tresrcID.
           
    {include/sample-query.i}
                        
        {include/setup-i.i}.

        qh:QUERY-PREPARE("FOR EACH OE_ActASProc WHERE " +
                         STRING(Cf_Sample.Sample_ID) + " EQ OE_ActASProc.Sample_ID " + " AND " +
                         matchstring).
        qh:QUERY-OPEN().

        REPEAT:
            qh:GET-NEXT.
            IF qh:QUERY-OFF-END THEN LEAVE.
                
            {include/fathom-counters.i}.
               
            FIND FIRST data_store WHERE data_store.brokerUUID = OE_ActASProc.ActBrk_UUID AND
                                        data_store.Name = OE_ActASProc.ActASProc_Name NO-ERROR. /* AND
                                        data_store.brokerName = tmp-resrc.tResrcName NO-ERROR. */
                            
            IF NOT AVAILABLE data_store THEN
            DO:
                CREATE data_store.
                ASSIGN
                    data_store.Name = OE_ActASProc.ActASProc_Name
                    data_store.brokerName = tmp-resrc.tResrcName
                    data_store.brokerPID = OE_ActASProc.ActBrk_PID
                    data_store.brokerUUID = OE_ActASProc.ActBrk_UUID
                    data_store.procedureType = OE_ActASProc.ActASProc_ProcType.
            END.
                        
            /* Run Count, Average Request Duration, and Return Codes. */
            ASSIGN
                data_store.runCount[Fathom-i] = data_store.runCount[Fathom-i] +
                                                OE_ActASProc.ActASProc_Calls
                data_store.reqTotTime[Fathom-i] = data_store.reqTotTime[Fathom-i] +
                                                  OE_ActASProc.ActASProc_TotTime
                data_store.returnCodeSuccess[Fathom-i] = data_store.returnCodeSuccess[Fathom-i] +
                                                         OE_ActASProc.ActASProc_SuccessCount
                data_store.returnCodeError[Fathom-i] = data_store.returnCodeError[Fathom-i] +
                                                       OE_ActASProc.ActASProc_ErrorCount
                data_store.returnCodeQuit[Fathom-i] = data_store.returnCodeQuit[Fathom-i] +
                                                      OE_ActASProc.ActASProc_QuitCount
                data_store.returnCodeStop[Fathom-i] = data_store.returnCodeStop[Fathom-i] +
                                                      OE_ActASProc.ActASProc_StopCount
                data_store.numSeconds[Fathom-i] = data_store.numSeconds[Fathom-i] +
                                                  Cf_Sample.Sample_len
                data_store.numSamples[Fathom-i] = data_store.numSamples[Fathom-i] + 1.
               
        END. /* of REPEAT. */

        IF Fathom-ar-date = ? THEN Fathom-ar-date = cf_sample.sample_date.
        ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN Fathom-ar-date = cf_sample.sample_date.
            
    END. /* {include/sample-query.i} => FOR EACH Cf_Sample */

END. /* FOR EACH tmp-resrc */

qh:QUERY-CLOSE().
DELETE OBJECT qh.

pgm-name = "asprofile.p".
sec-name = "Exiting data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** Process archive records if the need arises to do so.
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "asprofile.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}.

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}.

IF Fathom-ar-date GT Fathom-i-start_date THEN
DO:
    pgm-name = "asprofile.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    /*
    ** Set up the query expression.
    */
    CASE Procedure-filter-type:
        WHEN "begins" THEN
        DO:
            pgm-name = "asprofile.p".
            sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
            {include/debug.i "pgm-name" "sec-name"}.

            matchstring = "Ar_OE_ActASProc.ActASProc_Name BEGINS ~"" + Procedure-filter + "~" ".

        END. /* WHEN "begins" */
    
        WHEN "matches" THEN
        DO:
            pgm-name = "asprofile.p".
            sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
            {include/debug.i "pgm-name" "sec-name"}.

            matchstring = "(".
        
            DO procfilter-index = 1 TO NUM-ENTRIES(Procedure-filter, "|"):
                subprocfilter = TRIM(ENTRY(procfilter-index, Procedure-filter, "|")) NO-ERROR.
                matchstring = matchstring + "Ar_OE_ActASProc.ActASProc_Name MATCHES ~"" + subprocfilter + "~" OR ".
            END.

            IF LENGTH(matchstring) GT 4 THEN
                matchstring = SUBSTRING(matchstring, 1, LENGTH(matchstring) - 4) + ") ".
            ELSE
                matchstring = "".

        END. /* WHEN "matches" */

        OTHERWISE
        DO:
            /* Literal is the default if the value isn't set. */
            IF Procedure-filter-type NE "literal" THEN
            DO:
                pgm-name = "asprofile.p".
                sec-name = "fathomReportProcedureFilterType not set, defaulting to literal.".
                {include/debug.i "pgm-name" "sec-name"}.
            END.
            ELSE
            DO:
                pgm-name = "asprofile.p".
                sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
                {include/debug.i "pgm-name" "sec-name"}.
            END.

            matchstring = "Ar_OE_ActASProc.ActASProc_Name EQ ~"" + Procedure-filter + "~" ".

        END. /* OTHERWISE */

    END CASE.

    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_OE_ActASProc:HANDLE).

    /*
    ** Get the data.
    */
    FOR EACH tmp-resrc:

        pgm-name = "asprofile.p".
        sec-name = "Gathering archive data for resource: " + tmp-resrc.tResrcName + ".".
        {include/debug.i "pgm-name" "sec-name"}.

        qh:QUERY-PREPARE("FOR EACH Ar_OE_ActASProc WHERE " +
                         "Ar_OE_ActASProc.Resrc_ID EQ " + STRING(tmp-resrc.tResrcID) + " AND " +
                         "Ar_OE_ActASProc.Site_ID EQ ~"" + tmp-resrc.tSiteID + "~" AND " +
                         "Ar_OE_ActASProc.ActASProc_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                         "Ar_OE_ActASProc.ActASProc_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                         "Ar_OE_ActASProc.ActASProc_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                         "Ar_OE_ActASProc.ActASProc_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                         "Ar_OE_ActASProc.ActASProc_ArchiveType EQ ~"" + archiveType + "~" " + " AND " +
                         matchstring).
        qh:QUERY-OPEN().

        REPEAT:
            qh:GET-NEXT.
            IF qh:QUERY-OFF-END THEN LEAVE.

            Fathom-i = 0.
            REPEAT:
                Fathom-i = Fathom-i + 1.
                IF Ar_OE_ActASProc.ActASProc_StartDate GE Fathom-t-beg-date[Fathom-i] AND
                    Ar_OE_ActASProc.ActASProc_StartDate LE Fathom-t-end-date[Fathom-i] THEN
                DO:
                    IF Ar_OE_ActASProc.ActASProc_starttime GE Fathom-t-beg-time[Fathom-i] AND
                        Ar_OE_ActASProc.ActASProc_starttime LE Fathom-t-end-time[Fathom-i] THEN
                        LEAVE.
                END.
                IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
            END.
        
            FIND FIRST data_store WHERE data_store.brokerUUID = Ar_OE_ActASProc.ActBrk_UUID AND
                                        data_store.Name = Ar_OE_ActASProc.ActASProc_Name NO-ERROR. /* AND
                                        data_store.brokerName = tmp-resrc.tResrcName NO-ERROR. */
                    
            IF NOT AVAILABLE data_store THEN
            DO:
                CREATE data_store.
                ASSIGN
                    data_store.Name = Ar_OE_ActASProc.ActASProc_Name
                    data_store.brokerName = tmp-resrc.tResrcName
                    data_store.brokerPID = Ar_OE_ActASProc.ActBrk_PID
                    data_store.brokerUUID = Ar_OE_ActASProc.ActBrk_UUID
                    data_store.procedureType = Ar_OE_ActASProc.ActASProc_ProcType.
            END.
                
            /* Run Count, Average Request Duration, and Return Codes. */
            ASSIGN
                data_store.runCount[Fathom-i] = data_store.runCount[Fathom-i] +
                                                Ar_OE_ActASProc.ActASProc_Calls
                data_store.reqTotTime[Fathom-i] = data_store.reqTotTime[Fathom-i] +
                                                  Ar_OE_ActASProc.ActASProc_TotTime
                data_store.returnCodeSuccess[Fathom-i] = data_store.returnCodeSuccess[Fathom-i] +
                                                         Ar_OE_ActASProc.ActASProc_SuccessCount
                data_store.returnCodeError[Fathom-i] = data_store.returnCodeError[Fathom-i] +
                                                       Ar_OE_ActASProc.ActASProc_ErrorCount
                data_store.returnCodeQuit[Fathom-i] = data_store.returnCodeQuit[Fathom-i] +
                                                      Ar_OE_ActASProc.ActASProc_QuitCount
                data_store.returnCodeStop[Fathom-i] = data_store.returnCodeStop[Fathom-i] +
                                                      Ar_OE_ActASProc.ActASProc_StopCount
                data_store.numSeconds[Fathom-i] = data_store.numSeconds[Fathom-i] +
                                                  Ar_OE_ActASProc.ActASProc_Length
                data_store.numSamples[Fathom-i] = data_store.numSamples[Fathom-i] +
                                                  Ar_OE_ActASProc.ActASProc_RecordCount
                Fathom-Rec-Count = Fathom-Rec-Count + Ar_OE_ActASProc.ActASProc_RecordCount
                Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] +
                                                 Ar_OE_ActASProc.ActASProc_RecordCount.

        END. /* FOR EACH Ar_OE_ActASProc */

    END. /* FOR EACH tmp-resrc: */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

END. /* IF fathom-ar-date GT fathom-i-start_date */

pgm-name = "asprofile.p".
sec-name = "Exiting archive data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** Print to xml files.
*/
RUN openedge/xml-asprofile.p.


pgm-name = "asprofile.p".
sec-name = "Exiting program.".
{include/debug.i "pgm-name" "sec-name"}.
/*
** brokeractivity.p
**
** This program will present a broker activity report for AppServer
**  or WebSpeed based on the dates provided to the report.  
**
** The performance report is actually three reports combined into one.
**  There is a broker, client, and server report.  It is possible to use
**  any one, two, or all parts of the report.  This program is the
**  broker part.
**
*/

{include/definitions.i "SHARED"}.

DEFINE TEMP-TABLE data_store_broker NO-UNDO
    FIELD Name                        AS CHARACTER
    FIELD resID                       AS INTEGER
    FIELD operatingMode               AS CHARACTER
    FIELD numSeconds                  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryNumSeconds           AS DECIMAL INITIAL 0
    FIELD numSamples                  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryNumSamples           AS DECIMAL
    FIELD numSystemSamples            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD totSystemSamples            AS DECIMAL
    FIELD numDurationSamples          AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryNumDurationSamples   AS DECIMAL
    FIELD CPUUsageAvg                 AS DECIMAL EXTENT 366 INITIAL 0
    FIELD CPUUsageTime                AS DECIMAL EXTENT 366 INITIAL 0
    FIELD CPUUsageMax                 AS DECIMAL EXTENT 366 INITIAL 0
    FIELD memoryUsageAvg              AS DECIMAL EXTENT 366 INITIAL 0
    FIELD memoryUsageMax              AS DECIMAL EXTENT 366 INITIAL 0
    FIELD requestDurationTime         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD requestDurationCalls        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD requestDurationTotTime      AS DECIMAL
    FIELD requestDurationTotCalls     AS DECIMAL
    FIELD requestDurationAvg          AS DECIMAL EXTENT 366 INITIAL 0
    FIELD totRequestsQueued           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD totRequestsCompleted        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD requestsQueuedPct           AS DECIMAL EXTENT 366 INITIAL 0
    /* Need these four for maximum values--not available for archived records. */
    FIELD printMaxArray               AS LOGICAL EXTENT 366 INITIAL NO
    FIELD haveArchivedRecArray        AS LOGICAL EXTENT 366 INITIAL NO
    FIELD printMax                    AS LOGICAL INITIAL NO
    FIELD haveArchivedRec             AS LOGICAL INITIAL NO
    FIELD summaryCPUUsageAvg          AS DECIMAL
    FIELD summaryCPUUsageTime         AS DECIMAL
    FIELD summaryCPUUsageMax          AS DECIMAL
    FIELD summaryMemoryUsageAvg       AS DECIMAL
    FIELD summaryMemoryUsageMax       AS DECIMAL
    FIELD summaryNumSystemSamples     AS DECIMAL
    FIELD summaryRequestDurationAvg   AS DECIMAL
    FIELD summaryTotRequestsQueued    AS DECIMAL
    FIELD summaryTotRequestsCompleted AS DECIMAL
    FIELD summaryRequestsQueuedPct    AS DECIMAL
    INDEX one Name
    INDEX two resID.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.

/* List-by-service will define if we are to list output by broker or service name. */
DEFINE SHARED VARIABLE List-by-service AS LOGICAL NO-UNDO.

    
pgm-name = "brokeractivity.p".
sec-name = "Starting Program.".
{include/debug.i "pgm-name" "sec-name"}.

/* Reset the record counter for each section of the performance report. */
Fathom-Rec-Count = 0.


/*
** Get data from trend database.
*/
FOR EACH tmp-resrc:

    pgm-name = "brokeractivity.p".
    sec-name = "Gathering data for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    Fathom-i-Resrc_ID = tmp-resrc.tresrcID.

    {include/sample-query.i}
        
        {include/setup-i.i}
    
        {include/fathom-counters.i}
    
        FOR EACH OE_ActBrk WHERE Cf_Sample.Sample_ID = OE_ActBrk.Sample_ID:
    
            FIND FIRST data_store_broker WHERE data_store_broker.Name = tmp-resrc.tResrcName NO-ERROR.
    
            IF NOT AVAILABLE data_store_broker THEN
            DO:
                CREATE data_store_broker.
                ASSIGN
                    /*
                    ** data_store_broker.Name = OE_ActBrk.ActBrk_Name 
                    ** Make this Fathom's resource name, not the broker name
                    **  in case we ever decide to let users change the
                    **  name of a broker resource in Fathom:
                    */
                    data_store_broker.Name = tmp-resrc.tResrcName
                    data_store_broker.resID = tmp-resrc.tresrcID
                    data_store_broker.operatingMode = OE_ActBrk.ActBrk_Mode.
            END.
    
            /* Total Requests Queued and Received. */
            ASSIGN
                data_store_broker.totRequestsQueued[Fathom-i] = data_store_broker.totRequestsQueued[Fathom-i] +
                                                                OE_ActBrk.ActBrk_ReqQueued
                data_store_broker.totRequestsCompleted[Fathom-i] = data_store_broker.totRequestsCompleted[Fathom-i] +
                                                                   OE_ActBrk.ActBrk_ReqComp
                data_store_broker.numSeconds[Fathom-i] = data_store_broker.numSeconds[Fathom-i] +
                                                         Cf_Sample.Sample_len
                data_store_broker.summaryNumSeconds = data_store_broker.summaryNumSeconds +
                                                         Cf_Sample.Sample_len
                data_store_broker.numSamples[Fathom-i] = data_store_broker.numSamples[Fathom-i] + 1.

            /* System metrics. */
            FOR EACH Sys_Process WHERE OE_ActBrk.Sample_ID = Sys_Process.Sample_ID AND
                                       OE_ActBrk.ActBrk_PID = Sys_Process.Process_PID:
                ASSIGN
                    data_store_broker.CPUUsageAvg[Fathom-i] = data_store_broker.CPUUsageAvg[Fathom-i] +
                                                              Sys_Process.Process_CPUUser +
                                                              Sys_Process.Process_CPUSystem
                    data_store_broker.summaryCPUUsageAvg = data_store_broker.summaryCPUUsageAvg +
                                                           Sys_Process.Process_CPUUser +
                                                           Sys_Process.Process_CPUSystem
                    data_store_broker.CPUUsageTime[Fathom-i] = data_store_broker.CPUUsageTime[Fathom-i] +
                                                               Sys_Process.Process_ElapsedTime
                    data_store_broker.summaryCPUUsageTime = data_store_broker.summaryCPUUsageTime +
                                                            Sys_Process.Process_ElapsedTime
                    data_store_broker.memoryUsageAvg[Fathom-i] = data_store_broker.memoryUsageAvg[Fathom-i] +
                                                                 Sys_Process.Process_ResMemory
                    data_store_broker.numSystemSamples[Fathom-i] = data_store_broker.numSystemSamples[Fathom-i] + 1
                    data_store_broker.totSystemSamples = data_store_broker.totSystemSamples + 1.
    
                /* Max CPU Usage. */
                IF data_store_broker.CPUUsageMax[Fathom-i] LT 1 THEN
                DO:
                    ASSIGN data_store_broker.CPUUsageMax[Fathom-i] = Sys_Process.Process_CPUPct.
                END.
                ELSE IF Sys_Process.Process_CPUPct GT 0 AND
                        Sys_Process.Process_CPUPct GT data_store_broker.CPUUsageMax[Fathom-i] THEN 
                DO:
                    ASSIGN data_store_broker.CPUUsageMax[Fathom-i] = Sys_Process.Process_CPUPct.
                END.
    
                /* Max Memory Usage. */
                IF data_store_broker.memoryUsageMax[Fathom-i] LT 1 THEN 
                DO:
                    ASSIGN data_store_broker.memoryUsageMax[Fathom-i] = Sys_Process.Process_ResMemory.
                END.
                ELSE IF Sys_Process.Process_ResMemory GT 0 AND
                        Sys_Process.Process_ResMemory GT data_store_broker.memoryUsageMax[Fathom-i] THEN 
                DO:
                    ASSIGN data_store_broker.memoryUsageMax[Fathom-i] = Sys_Process.Process_ResMemory.
                END.
            END.
    
            /*
            ** Request duration must be retrieved from each procedure in the procedure table.
            **  Avg duration will be the total time / number of times called, regardless of
            **  sample time.
            */
            IF tmp-resrc.tResrcType = "APPSERVER" THEN
            DO:
                FOR EACH OE_ActASProc WHERE OE_ActBrk.Sample_ID = OE_ActASProc.Sample_ID AND
                                            OE_ActBrk.ActBrk_UUID = OE_ActASProc.ActBrk_UUID:
                    ASSIGN
                        data_store_broker.requestDurationTime[Fathom-i] = data_store_broker.requestDurationTime[Fathom-i] +
                                                                          OE_ActASProc.ActASProc_TotTime
                        data_store_broker.requestDurationCalls[Fathom-i] = data_store_broker.requestDurationCalls[Fathom-i] +
                                                                           OE_ActASProc.ActASProc_Calls
                        data_store_broker.numDurationSamples[Fathom-i] = data_store_broker.numDurationSamples[Fathom-i] + 1.
                END.
            END.
            ELSE DO:
                FOR EACH OE_ActWSProc WHERE OE_ActBrk.Sample_ID = OE_ActWSProc.Sample_ID AND
                                            OE_ActBrk.ActBrk_UUID = OE_ActWSProc.ActBrk_UUID:
                    ASSIGN
                        data_store_broker.requestDurationTime[Fathom-i] = data_store_broker.requestDurationTime[Fathom-i] +
                                                                          OE_ActWSProc.ActWSProc_TotTime
                        data_store_broker.requestDurationCalls[Fathom-i] = data_store_broker.requestDurationCalls[Fathom-i] +
                                                                           OE_ActWSProc.ActWSProc_Calls
                        data_store_broker.numDurationSamples[Fathom-i] = data_store_broker.numDurationSamples[Fathom-i] + 1.
                END.
            END.

            printMaxArray[fathom-i] = YES.
            printMax = YES.
    
        END. /* FOR EACH OE_ActBrk */

        IF Fathom-ar-date = ? THEN Fathom-ar-date = cf_sample.sample_date.
        ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN Fathom-ar-date = cf_sample.sample_date.
    
    END. /* {include/sample-query.i} => FOR EACH Cf_Sample */

END. /* FOR EACH tmp-resrc */




/*
** Process archive records if the need arises to do so.
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "brokeractivity.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}.

sec-name = "Testing Archive Dates - Archive Date :" + STRING(Fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}.

IF Fathom-ar-date GT Fathom-i-start_date THEN
DO:
    pgm-name = "brokeractivity.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    DEFINE VARIABLE brokerQuery AS WIDGET-HANDLE.
    CREATE QUERY brokerQuery.
    brokerQuery:SET-BUFFERS(BUFFER Ar_OE_ActBrk:HANDLE).

    DEFINE VARIABLE processQuery AS WIDGET-HANDLE.
    CREATE QUERY processQuery.
    processQuery:SET-BUFFERS(BUFFER Ar_Process:HANDLE).

    DEFINE VARIABLE procedureQueryAS AS WIDGET-HANDLE.
    CREATE QUERY procedureQueryAS.
    procedureQueryAS:SET-BUFFERS(BUFFER Ar_OE_ActASProc:HANDLE).

    DEFINE VARIABLE procedureQueryWS AS WIDGET-HANDLE.
    CREATE QUERY procedureQueryWS.
    procedureQueryWS:SET-BUFFERS(BUFFER Ar_OE_ActWSProc:HANDLE).

    /*
    ** If we have broker pids different, we get multiple archive
    ** records with the same UUID, thus a potential to go through the
    ** same procedure records more than once.
    */
    DEFINE TEMP-TABLE brokeruuid
        FIELD uuid      AS CHARACTER
        FIELD starttime AS INTEGER
        FIELD startdate AS DATE.

    FOR EACH tmp-resrc:

        pgm-name = "brokeractivity.p".
        sec-name = "Gathering archive data for resource: " + tmp-resrc.tResrcName + ".".
        {include/debug.i "pgm-name" "sec-name"}.
        
        brokerQuery:QUERY-PREPARE("FOR EACH Ar_OE_ActBrk WHERE " +
                                  "Ar_OE_ActBrk.Resrc_ID EQ " + STRING(tmp-resrc.tResrcID) + " AND " +
                                  "Ar_OE_ActBrk.Site_ID EQ ~"" + tmp-resrc.tSiteID + "~" AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartDate GE " + STRING(Fathom-i-Start_date) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_ArchiveType EQ ~"" + archiveType + "~"").
        brokerQuery:QUERY-OPEN().
        
        REPEAT:
            brokerQuery:GET-NEXT.
            IF brokerQuery:QUERY-OFF-END THEN LEAVE.

            Fathom-i = 0.
            REPEAT:
                Fathom-i = Fathom-i + 1.
                IF Ar_OE_ActBrk.ActBrk_StartDate GE Fathom-t-beg-date[Fathom-i] AND
                    Ar_OE_ActBrk.ActBrk_StartDate LE Fathom-t-end-date[Fathom-i] THEN
                DO:
                    IF Ar_OE_ActBrk.ActBrk_starttime GE Fathom-t-beg-time[Fathom-i] AND
                        Ar_OE_ActBrk.ActBrk_starttime LE Fathom-t-end-time[Fathom-i] THEN
                        LEAVE.
                END.
                IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
            END.

            FIND FIRST data_store_broker WHERE data_store_broker.Name = tmp-resrc.tResrcName NO-ERROR.
    
            IF NOT AVAILABLE data_store_broker THEN
            DO:
                CREATE data_store_broker.
                ASSIGN
                    /*
                    ** data_store_broker.Name = OE_ActBrk.ActBrk_Name 
                    ** Make this Fathom's resource name, not the broker name
                    **  in case we ever decide to let users change the
                    **  name of a broker resource in Fathom:
                    */
                    data_store_broker.Name = tmp-resrc.tResrcName
                    data_store_broker.resID = tmp-resrc.tresrcID
                    data_store_broker.operatingMode = Ar_OE_ActBrk.ActBrk_Mode.
            END.
    
            /* Total Requests Queued and Received. */
            ASSIGN
                data_store_broker.totRequestsQueued[Fathom-i] = data_store_broker.totRequestsQueued[Fathom-i] +
                                                                Ar_OE_ActBrk.ActBrk_ReqQueued
                data_store_broker.totRequestsCompleted[Fathom-i] = data_store_broker.totRequestsCompleted[Fathom-i] +
                                                                   Ar_OE_ActBrk.ActBrk_ReqComp
                data_store_broker.numSeconds[Fathom-i] = data_store_broker.numSeconds[Fathom-i] +
                                                         Ar_OE_ActBrk.ActBrk_Length
                data_store_broker.summaryNumSeconds = data_store_broker.summaryNumSeconds +
                                                      Ar_OE_ActBrk.ActBrk_Length
                data_store_broker.numSamples[Fathom-i] = data_store_broker.numSamples[Fathom-i] +
                                                         Ar_OE_ActBrk.ActBrk_RecordCount
                Fathom-Rec-Count = Fathom-Rec-Count + Ar_OE_ActBrk.ActBrk_RecordCount
                Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] +
                                                 Ar_OE_ActBrk.ActBrk_RecordCount.

            /* System metrics. */
            processQuery:QUERY-PREPARE("FOR EACH Ar_Process WHERE " +
                                       "Ar_Process.Process_StartDate EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartDate) + " AND " +
                                       "Ar_Process.Process_StartTime EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartTime) + " AND " +
                                       "Ar_Process.Process_PID EQ " + STRING(Ar_OE_ActBrk.ActBrk_PID) + " AND " +
                                       "Ar_Process.Process_ArchiveType EQ ~"" + archiveType + "~"").
            processQuery:QUERY-OPEN().

            REPEAT:
                processQuery:GET-NEXT.
                IF processQuery:QUERY-OFF-END THEN LEAVE.

                ASSIGN
                    data_store_broker.CPUUsageAvg[Fathom-i] = data_store_broker.CPUUsageAvg[Fathom-i] +
                                                              Ar_Process.Process_CPUUser +
                                                              Ar_Process.Process_CPUSystem
                    data_store_broker.summaryCPUUsageAvg = data_store_broker.summaryCPUUsageAvg +
                                                           Ar_Process.Process_CPUUser +
                                                           Ar_Process.Process_CPUSystem
                    data_store_broker.CPUUsageTime[Fathom-i] = data_store_broker.CPUUsageTime[Fathom-i] +
                                                               Ar_Process.Process_ElapsedTime
                    data_store_broker.summaryCPUUsageTime = data_store_broker.summaryCPUUsageTime +
                                                            Ar_Process.Process_ElapsedTime
                    data_store_broker.memoryUsageAvg[Fathom-i] = data_store_broker.memoryUsageAvg[Fathom-i] +
                                                                 (Ar_Process.Process_ResMemory *
                                                                  Ar_Process.Process_RecordCount)
                    data_store_broker.numSystemSamples[Fathom-i] = data_store_broker.numSystemSamples[Fathom-i] +
                                                                   Ar_Process.Process_RecordCount
                    data_store_broker.totSystemSamples = data_store_broker.totSystemSamples +
                                                         Ar_Process.Process_RecordCount.
    
                /*
                ** Max CPU Usage and Max Memory Usage.
                ** NOTE: Archived data does not exist for this field.
                */
            END.
    
            /*
            ** Request duration must be retrieved from each procedure in the procedure table.
            **  Avg duration will be the total time / number of times called, regardless of
            **  sample time.
            */
            IF tmp-resrc.tResrcType = "APPSERVER" THEN
            DO:
                procedureQueryAS:QUERY-PREPARE("FOR EACH Ar_OE_ActASProc WHERE " +
                                               "Ar_OE_ActASProc.ActASProc_StartDate EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartDate) + " AND " +
                                               "Ar_OE_ActASProc.ActASProc_StartTime EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartTime) + " AND " +
                                               "Ar_OE_ActASProc.ActBrk_UUID EQ ~"" + Ar_OE_ActBrk.ActBrk_UUID + "~" AND " +
                                               "Ar_OE_ActASProc.ActASProc_ArchiveType EQ ~"" + archiveType + "~"").
                procedureQueryAS:QUERY-OPEN().

                REPEAT:
                    procedureQueryAS:GET-NEXT.
                    IF procedureQueryAS:QUERY-OFF-END THEN LEAVE.

                    FIND FIRST brokeruuid WHERE
                        uuid EQ Ar_OE_ActBrk.ActBrk_UUID AND
                        startDate EQ Ar_OE_ActBrk.ActBrk_StartDate AND
                        startTime EQ Ar_OE_ActBrk.ActBrk_StartTime NO-ERROR.
            
                    IF AVAILABLE brokeruuid THEN
                        LEAVE.

                    ASSIGN
                        data_store_broker.requestDurationTime[Fathom-i] = data_store_broker.requestDurationTime[Fathom-i] +
                                                                          Ar_OE_ActASProc.ActASProc_TotTime
                        data_store_broker.requestDurationCalls[Fathom-i] = data_store_broker.requestDurationCalls[Fathom-i] +
                                                                           Ar_OE_ActASProc.ActASProc_Calls
                        data_store_broker.numDurationSamples[Fathom-i] = data_store_broker.numDurationSamples[Fathom-i] +
                                                                         Ar_OE_ActASProc.ActASProc_RecordCount.
                END. /* of REPEAT. */

            END.
            ELSE DO:
                procedureQueryWS:QUERY-PREPARE("FOR EACH Ar_OE_ActWSProc WHERE " +
                                               "Ar_OE_ActWSProc.ActWSProc_StartDate EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartDate) + " AND " +
                                               "Ar_OE_ActWSProc.ActWSProc_StartTime EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartTime) + " AND " +
                                               "Ar_OE_ActWSProc.ActBrk_UUID EQ ~"" + Ar_OE_ActBrk.ActBrk_UUID + "~" AND " +
                                               "Ar_OE_ActWSProc.ActWSProc_ArchiveType EQ ~"" + archiveType + "~"").
                procedureQueryWS:QUERY-OPEN().
                
                REPEAT:
                    procedureQueryWS:GET-NEXT.
                    IF procedureQueryWS:QUERY-OFF-END THEN LEAVE.

                    FIND FIRST brokeruuid WHERE
                        uuid EQ Ar_OE_ActBrk.ActBrk_UUID AND
                        startDate EQ Ar_OE_ActBrk.ActBrk_StartDate AND
                        startTime EQ Ar_OE_ActBrk.ActBrk_StartTime NO-ERROR.
                    
                    IF AVAILABLE brokeruuid THEN
                        LEAVE.

                    ASSIGN
                        data_store_broker.requestDurationTime[Fathom-i] = data_store_broker.requestDurationTime[Fathom-i] +
                                                                          Ar_OE_ActWSProc.ActWSProc_TotTime
                        data_store_broker.requestDurationCalls[Fathom-i] = data_store_broker.requestDurationCalls[Fathom-i] +
                                                                           Ar_OE_ActWSProc.ActWSProc_Calls
                        data_store_broker.numDurationSamples[Fathom-i] = data_store_broker.numDurationSamples[Fathom-i] +
                                                                         Ar_OE_ActWSProc.ActWSProc_RecordCount.
                END. /* of REPEAT. */

            END.

            haveArchivedRecArray[fathom-i] = YES.
            haveArchivedRec = YES.

            FIND FIRST brokeruuid WHERE
                uuid EQ Ar_OE_ActBrk.ActBrk_UUID AND
                startDate EQ Ar_OE_ActBrk.ActBrk_StartDate AND
                startTime EQ Ar_OE_ActBrk.ActBrk_StartTime NO-ERROR.

            IF NOT AVAILABLE brokeruuid THEN
            DO:
                CREATE brokeruuid.
                ASSIGN
                    uuid = Ar_OE_ActBrk.ActBrk_UUID
                    startDate = Ar_OE_ActBrk.ActBrk_StartDate
                    startTime = Ar_OE_ActBrk.ActBrk_StartTime.
            END.
    
        END. /* of REPEAT. */

        EMPTY TEMP-TABLE brokeruuid.

    END. /* FOR EACH tmp-resrc */

    brokerQuery:QUERY-CLOSE().
    DELETE OBJECT brokerQuery.
    processQuery:QUERY-CLOSE().
    DELETE OBJECT processQuery.
    procedureQueryAS:QUERY-CLOSE().
    DELETE OBJECT procedureQueryAS.
    procedureQueryWS:QUERY-CLOSE().
    DELETE OBJECT procedureQueryWS.

END.


pgm-name = "brokeractivity.p".
sec-name = "Exiting archive data collection.".
{include/debug.i "pgm-name" "sec-name"}.





/*
** Print to xml file.
**
** NOTE: The initialization has already been done in performance.p.
*/
{include/xmldefinitions.i "SHARED"}.

IF Fathom-Rec-Count lt 1 THEN
DO:
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for the broker activity report.").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    pgm-name = "brokeractivity.p".
    sec-name = "No samples - finishing XML files.".
    {include/debug.i "pgm-name" "sec-name"}.

    RETURN.
END.

DEFINE VARIABLE datalabels AS CHARACTER EXTENT 9.
ASSIGN
    datalabels[1] = REQUESTS_COMPLETED
    datalabels[2] = REQUESTS_QUEUED
    datalabels[3] = REQ_QUEUED_PCT
    datalabels[4] = AVG_REQ_DURATION
    datalabels[5] = AVG_CPU_USAGE_PCT
    datalabels[6] = MAX_CPU_USAGE_PCT
    datalabels[7] = AVG_MEMORY_USAGE
    datalabels[8] = MAX_MEMORY_USAGE
    datalabels[9] = SAMPLE_COUNT.
DEFINE VARIABLE i AS INTEGER.


Fathom-report-title = "Broker Activity".
RUN xml-report-header.
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


FOR EACH tmp-resrc:

    pgm-name = "brokeractivity.p".
    sec-name = "Printing data to XML file for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    FIND FIRST Cf_Resrc WHERE tmp-resrc.tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.

    IF AVAILABLE Cf_Resrc THEN
    DO:
        ASSIGN
            xmlresourcename = Cf_Resrc.Resrc_Name 
            xmlresourcetype = Cf_Resrc.Resrc_Type 
            xmlresourcesite = Cf_Resrc.Site_ID.

        /* Setup the root header and data information. */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "resource",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        sec-name = "Writing out Root header - Label :" + 
                   xmlresourcename + ":" +
                   xmlresourcetype + ":" +
                   xmlresourcesite.
        {include/debug.i "pgm-name" "sec-name"}.

        RUN xml-root-header.

        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Labels section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "labels",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        DO i = 1 TO EXTENT(datalabels):

            xmldataOutputlabel = datalabels[i].

                RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "label",
                           INPUT "",
                           INPUT "",
                           INPUT xmldataOutputlabel).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        END.

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "labels").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Dates section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "times",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        DO fathom-x = 1 to Fathom-i-periods:

            xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
            xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
            xmlsampleenddate = Fathom-t-end-date[fathom-x].
            xmlsampleendtime = Fathom-t-end-time[fathom-x].
                
            RUN xml-process-date.       /* Subroutine to process the date. */
            RUN xml-add-data-timetable. /* Subroutine to process the datum. */
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".

        END.

        IF Fathom-i-periods > 1 THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "time",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "name",
                           INPUT "",
                           INPUT "",
                           INPUT "Summary").
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "time").
        END.

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "times").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /* 
        ** Data Section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        FOR EACH data_store_broker WHERE data_store_broker.resID = tmp-resrc.tResrcID:

            DO i = 1 TO EXTENT(datalabels):

                xmldataOutputlabel = datalabels[i].
                xmldatalabel = datalabels[i].

                sec-name = "Writing out row header - Label :" + xmldatalabel.
                {include/debug.i "pgm-name" "sec-name"}.

                DO fathom-x = 1 to Fathom-i-periods:

                    /* For display units. */
                    CASE Fathom-i-intervaltype:
                        WHEN "S" THEN Fathom-store-value = data_store_broker.numSeconds[Fathom-x].
                        WHEN "M" THEN Fathom-store-value = data_store_broker.numSeconds[Fathom-x] / 60.
                        WHEN "H" THEN Fathom-store-value = data_store_broker.numSeconds[Fathom-x] / 60 / 60.
                        OTHERWISE Fathom-store-value = 1.
                    END CASE.

                    /*
                    ** This preserves summary info when there are no samples in a period.
                    ** See 2003 08 13-018.
                    */
                    IF Fathom-store-value = 0 THEN Fathom-store-value = 1.

                    xmlsamplelength = STRING (data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING (data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    /* xmlsamplecount = STRING (Fathom-numsamples[fathom-x]). */
                    xmlsamplecount = STRING (data_store_broker.numSamples[fathom-x]).

                    CASE datalabels[i]:

                        WHEN REQUESTS_COMPLETED THEN
                        DO:
                            dataprecision = "0".
                            data_store_broker.summaryTotRequestsCompleted = data_store_broker.summaryTotRequestsCompleted +
                                                                            data_store_broker.totRequestsCompleted[fathom-x].
                            data_store_broker.totRequestsCompleted[fathom-x] = data_store_broker.totRequestsCompleted[fathom-x] /
                                                                               Fathom-store-value.
                            IF data_store_broker.totRequestsCompleted[fathom-x] = ? THEN
                                data_store_broker.totRequestsCompleted[fathom-x] = 0.
                            IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_broker.totRequestsCompleted[fathom-x]).
                            END.
                        END.
                        WHEN REQUESTS_QUEUED THEN
                        DO:
                            dataprecision = "0".
                            data_store_broker.summaryTotRequestsQueued = data_store_broker.summaryTotRequestsQueued +
                                                                         data_store_broker.totRequestsQueued[fathom-x].
                            data_store_broker.totRequestsQueued[fathom-x] = data_store_broker.totRequestsQueued[fathom-x] /
                                                                            Fathom-store-value.
                            IF data_store_broker.totRequestsQueued[fathom-x] = ? THEN
                                data_store_broker.totRequestsQueued[fathom-x] = 0.
                            IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_broker.totRequestsQueued[fathom-x]).
                            END.
                        END.
                        WHEN REQ_QUEUED_PCT THEN
                        DO:
                            dataprecision = "2".
                            data_store_broker.requestsQueuedPct[fathom-x] = (data_store_broker.totRequestsQueued[fathom-x] /
                                                                             data_store_broker.totRequestsCompleted[fathom-x]) *
                                                                            100.
                            IF data_store_broker.requestsQueuedPct[fathom-x] = ? THEN
                                data_store_broker.requestsQueuedPct[fathom-x] = 0.
                            IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_broker.requestsQueuedPct[fathom-x]).
                            END.
                        END.
                        WHEN AVG_REQ_DURATION THEN
                        DO:
                            dataprecision = "0".
                            data_store_broker.requestDurationTotTime = data_store_broker.requestDurationTotTime +
                                                                       data_store_broker.requestDurationTime[fathom-x].
                            data_store_broker.requestDurationTotCalls = data_store_broker.requestDurationTotCalls +
                                                                        data_store_broker.requestDurationCalls[fathom-x].
                            data_store_broker.requestDurationAvg[fathom-x] = data_store_broker.requestDurationTime[fathom-x] /
                                                                             data_store_broker.requestDurationCalls[fathom-x].
                            IF data_store_broker.requestDurationAvg[fathom-x] = ? THEN
                                data_store_broker.requestDurationAvg[fathom-x] = 0.
                            IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_broker.requestDurationAvg[fathom-x]).
                            END.
                        END.
                        WHEN AVG_CPU_USAGE_PCT THEN
                        DO:
                            dataprecision = "2".
                            data_store_broker.CPUUsageAvg[fathom-x] = (data_store_broker.CPUUsageAvg[fathom-x] /
                                                                       data_store_broker.CPUUsageTime[fathom-x]) *
                                                                      100.
                            IF data_store_broker.CPUUsageAvg[fathom-x] = ? THEN
                                data_store_broker.CPUUsageAvg[fathom-x] = 0.
                            IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_broker.CPUUsageAvg[fathom-x]).
                            END.
                        END.
                        WHEN MAX_CPU_USAGE_PCT THEN
                        DO:
                            dataprecision = "2".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_broker.CPUUsageMax[fathom-x] GT 0 AND
                                   data_store_broker.CPUUsageMax[fathom-x] GT data_store_broker.summaryCPUUsageMax THEN 
                                DO:
                                    ASSIGN data_store_broker.summaryCPUUsageMax = data_store_broker.CPUUsageMax[fathom-x].
                                END.
                                IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_broker.CPUUsageMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN AVG_MEMORY_USAGE THEN
                        DO:
                            dataprecision = "2".
                            data_store_broker.summaryMemoryUsageAvg = data_store_broker.summaryMemoryUsageAvg +
                                                                      data_store_broker.memoryUsageAvg[fathom-x].
                            data_store_broker.memoryUsageAvg[fathom-x] = data_store_broker.memoryUsageAvg[fathom-x] /
                                                                         data_store_broker.numSystemSamples[fathom-x].
                            IF data_store_broker.memoryUsageAvg[fathom-x] = ? THEN
                                data_store_broker.memoryUsageAvg[fathom-x] = 0.
                            IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_broker.memoryUsageAvg[fathom-x]).
                            END.
                        END.
                        WHEN MAX_MEMORY_USAGE THEN
                        DO:
                            dataprecision = "2".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_broker.memoryUsageMax[fathom-x] GT 0 AND
                                   data_store_broker.memoryUsageMax[fathom-x] GT data_store_broker.summaryMemoryUsageMax THEN 
                                DO:
                                    ASSIGN data_store_broker.summaryMemoryUsageMax = data_store_broker.memoryUsageMax[fathom-x].
                                END.
                                IF data_store_broker.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_broker.memoryUsageMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN SAMPLE_COUNT THEN
                        DO:
                            dataprecision = "0".
                            /* For graph ordering. */
                            data_store_broker.summaryNumSamples = data_store_broker.summaryNumSamples +
                                                                  data_store_broker.numSamples[fathom-x].
                            data_store_broker.summaryNumSystemSamples = data_store_broker.summaryNumSystemSamples +
                                                                        data_store_broker.numSystemSamples[fathom-x].
                            data_store_broker.summaryNumDurationSamples = data_store_broker.summaryNumDurationSamples +
                                                                          data_store_broker.numDurationSamples[fathom-x].
                            xmldatavalue = STRING(data_store_broker.numSamples[Fathom-x]).
                        END.
                        OTHERWISE
                            /* Should not happen as we just defined the array above. */
                            xmldatavalue = "".

                    END CASE.

                    RUN xml-process-date.
                    RUN xml-add-data.
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".

                    IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 THEN
                    DO:
                        /* For display units. */
                        CASE Fathom-i-intervaltype:
                            WHEN "S" THEN Fathom-store-value = data_store_broker.summaryNumSeconds.
                            WHEN "M" THEN Fathom-store-value = data_store_broker.summaryNumSeconds / 60.
                            WHEN "H" THEN Fathom-store-value = data_store_broker.summaryNumSeconds / 60 / 60.
                            OTHERWISE Fathom-store-value = 1.
                        END CASE.

                        CASE datalabels[i]:

                            WHEN REQUESTS_COMPLETED THEN
                            DO:
                                dataprecision = "0".
                                data_store_broker.summaryTotRequestsCompleted = data_store_broker.summaryTotRequestsCompleted /
                                                                                Fathom-store-value.
                                IF data_store_broker.summaryTotRequestsCompleted = ? THEN
                                    data_store_broker.summaryTotRequestsCompleted = 0.
                                xmldatavalue = STRING(data_store_broker.summaryTotRequestsCompleted).
                            END.
                            WHEN REQUESTS_QUEUED THEN
                            DO:
                                dataprecision = "0".
                                data_store_broker.summaryTotRequestsQueued = data_store_broker.summaryTotRequestsQueued /
                                                                             Fathom-store-value.
                                IF data_store_broker.summaryTotRequestsQueued = ? THEN
                                    data_store_broker.summaryTotRequestsQueued = 0.
                                xmldatavalue = STRING(data_store_broker.summaryTotRequestsQueued).
                            END.
                            WHEN REQ_QUEUED_PCT THEN
                            DO:
                                dataprecision = "2".
                                data_store_broker.summaryRequestsQueuedPct = (data_store_broker.summaryTotRequestsQueued /
                                                                              data_store_broker.summaryTotRequestsCompleted) *
                                                                             100.
                                IF data_store_broker.summaryRequestsQueuedPct = ? THEN
                                    data_store_broker.summaryRequestsQueuedPct = 0.
                                xmldatavalue = STRING(data_store_broker.summaryRequestsQueuedPct).
                            END.
                            WHEN AVG_REQ_DURATION THEN
                            DO:
                                dataprecision = "0".
                                data_store_broker.summaryRequestDurationAvg = data_store_broker.requestDurationTotTime /
                                                                              data_store_broker.requestDurationTotCalls.
                                IF data_store_broker.summaryRequestDurationAvg = ? THEN
                                    data_store_broker.summaryRequestDurationAvg = 0.
                                xmldatavalue = STRING(data_store_broker.summaryRequestDurationAvg).
                            END.
                            WHEN AVG_CPU_USAGE_PCT THEN
                            DO:
                                dataprecision = "2".
                                data_store_broker.summaryCPUUsageAvg = (data_store_broker.summaryCPUUsageAvg /
                                                                        data_store_broker.summaryCPUUsageTime) *
                                                                       100.
                                IF data_store_broker.summaryCPUUsageAvg = ? THEN
                                    data_store_broker.summaryCPUUsageAvg = 0.
                                xmldatavalue = STRING(data_store_broker.summaryCPUUsageAvg).
                            END.
                            WHEN MAX_CPU_USAGE_PCT THEN
                            DO:
                                dataprecision = "2".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_broker.summaryCPUUsageMax).
                            END.
                            WHEN AVG_MEMORY_USAGE THEN
                            DO:
                                dataprecision = "2".
                                data_store_broker.summaryMemoryUsageAvg = data_store_broker.summaryMemoryUsageAvg /
                                                                          data_store_broker.totSystemSamples.
                                IF data_store_broker.summaryMemoryUsageAvg = ? THEN
                                    data_store_broker.summaryMemoryUsageAvg = 0.
                                xmldatavalue = STRING(data_store_broker.summaryMemoryUsageAvg).
                            END.
                            WHEN MAX_MEMORY_USAGE THEN
                            DO:
                                dataprecision = "2".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_broker.summaryMemoryUsageMax).
                            END.
                            WHEN SAMPLE_COUNT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store_broker.summaryNumSamples).
                            END.
                            OTHERWISE
                                /* Should not happen as we just defined the array above. */
                                xmldatavalue = "".
    
                        END CASE.

                        RUN xml-add-data-summary.
                        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                        streamdetail = "".

                    END. /* IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 */

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

            END. /* DO i = 1 TO EXTENT(datalabels): */

        END. /* FOR EACH data_store */

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "dataset").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
   
    END. /* IF AVAILABLE Cf_Resrc */

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "resource").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

END. /* FOR EACH tmp-resrc */


pgm-name = "brokeractivity.p".
sec-name = "Finishing data XML file.".
{include/debug.i "pgm-name" "sec-name"}.




/*
** Print out the graph xml file.
**  We do this in a separate loop so that we can limit the
**  number of brokers put on the graph.  We have to know
**  the top x brokers that have the highest average request duration, etc.
*/
numGraphResources = INTEGER(OS-GETENV("fathomResourcesPerGraph")) NO-ERROR.
DEFINE VARIABLE graph AS CHARACTER.
DEFINE VARIABLE isgraphed AS LOGICAL INITIAL NO.

IF numGraphResources = ? THEN
DO:
   numGraphResources = defaultNumGraphResources.
END.


DO x-i = 1 TO NUM-ENTRIES(xmlGraphColumns, ","):
    graph = TRIM(ENTRY(x-i, xmlGraphColumns, ",")) NO-ERROR.

    CASE graph:
        WHEN "none" THEN LEAVE.
        WHEN REQUESTS_COMPLETED THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + REQUESTS_COMPLETED.
            xmlgraph-imagetitle = "requestscompleted.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "1".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryTotRequestsCompleted DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_broker.totRequestsCompleted[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN REQUESTS_QUEUED THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + REQUESTS_QUEUED.
            xmlgraph-imagetitle = "requestsqueued.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "2".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryTotRequestsQueued DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_broker.totRequestsQueued[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN REQ_QUEUED_PCT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + REQ_QUEUED_PCT.
            xmlgraph-imagetitle = "requestsqueuedpct.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "3".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryRequestsQueuedPct DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_broker.requestsQueuedPct[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_REQ_DURATION THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + AVG_REQ_DURATION.
            xmlgraph-imagetitle = "reqdurationavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "4".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryRequestDurationAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_broker.requestDurationAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_CPU_USAGE_PCT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + AVG_CPU_USAGE_PCT.
            xmlgraph-imagetitle = "cpuavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "5".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryCPUUsageAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_broker.CPUUsageAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_CPU_USAGE_PCT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + MAX_CPU_USAGE_PCT.
            xmlgraph-imagetitle = "cpumax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "6".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryCPUUsageMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_broker.CPUUsageMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_MEMORY_USAGE THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + AVG_MEMORY_USAGE.
            xmlgraph-imagetitle = "memoryavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "7".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryMemoryUsageAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_broker.memoryUsageAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_MEMORY_USAGE THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + MAX_MEMORY_USAGE.
            xmlgraph-imagetitle = "memorymax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "8".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryMemoryUsageMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_broker.memoryUsageMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN SAMPLE_COUNT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Broker Activity: " + SAMPLE_COUNT.
            xmlgraph-imagetitle = "samplecount.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "9".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_broker BY summaryNumSamples DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_broker.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_broker.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_broker.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_broker.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_broker.numSamples[Fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

    END CASE.

    IF isgraphed = YES THEN
    DO:
        isgraphed = NO.
        RUN xml-graphspec-end.
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
    END.

END.



pgm-name = "brokeractivity.p".
sec-name = "Finished broker section of graph XML file.".
{include/debug.i "pgm-name" "sec-name"}.



pgm-name = "brokeractivity.p".
sec-name = "Exiting Program.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** clientactivity.p
**
** This program will present a client activity report for AppServer
**  or WebSpeed based on the dates provided to the report.  
**
** The performance report is actually three reports combined into one.
**  There is a broker, client, and server report.  It is possible to use
**  any one, two, or all parts of the report.  This program is the
**  client part.
**
*/

{include/definitions.i "SHARED"}.

DEFINE TEMP-TABLE data_store_client NO-UNDO
    FIELD Name                    AS CHARACTER
    FIELD resID                   AS INTEGER
    FIELD operatingMode           AS CHARACTER
    FIELD numSeconds              AS DECIMAL EXTENT 366 INITIAL 0
    FIELD numSamples              AS DECIMAL EXTENT 366 INITIAL 0
    FIELD currClientTotal         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD activeClientAvg         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD activeClientMax         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD clientRequests          AS DECIMAL EXTENT 366 INITIAL 0
    FIELD clientRequestAvg        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD clientRequestMax        AS DECIMAL EXTENT 366 INITIAL 0
    /* Need these four for maximum values--not available for archived records. */
    FIELD printMaxArray           AS LOGICAL EXTENT 366 INITIAL NO
    FIELD haveArchivedRecArray    AS LOGICAL EXTENT 366 INITIAL NO
    FIELD printMax                AS LOGICAL INITIAL NO
    FIELD haveArchivedRec         AS LOGICAL INITIAL NO
    FIELD summaryNumSamples       AS DECIMAL
    FIELD summaryNumSeconds       AS DECIMAL
    FIELD summaryActiveClientAvg  AS DECIMAL
    FIELD summaryActiveClientMax  AS DECIMAL
    FIELD summaryClientRequests   AS DECIMAL
    FIELD summaryClientRequestAvg AS DECIMAL
    FIELD summaryClientRequestMax AS DECIMAL
    INDEX one Name.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.

/* List-by-service will define if we are to list output by broker or service name. */
DEFINE SHARED VARIABLE List-by-service AS LOGICAL NO-UNDO.

    
pgm-name = "clientactivity.p".
sec-name = "Starting Program.".
{include/debug.i "pgm-name" "sec-name"}.

/* Reset the record counter for each section of the performance report. */
Fathom-Rec-Count = 0.


/*
** Get data from trend database.
*/
pgm-name = "clientactivity.p".
sec-name = "Starting data collection.".
{include/debug.i "pgm-name" "sec-name"}.

FOR EACH tmp-resrc:

    pgm-name = "clientactivity.p".
    sec-name = "Gathering data for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    Fathom-i-Resrc_ID = tmp-resrc.tresrcID.

    {include/sample-query.i}
        
        {include/setup-i.i}.
    
        {include/fathom-counters.i}.
    
        FOR EACH OE_ActBrk WHERE Cf_Sample.Sample_ID = OE_ActBrk.Sample_ID:

            FIND FIRST data_store_client WHERE data_store_client.Name = tmp-resrc.tResrcName NO-ERROR.
    
            IF NOT AVAILABLE data_store_client THEN
            DO:
                CREATE data_store_client.
                ASSIGN
                    /*
                    ** data_store_broker.Name = OE_ActBrk.ActBrk_Name 
                    ** Make this Fathom's resource name, not the broker name
                    **  in case we ever decide to let users change the
                    **  name of a broker resource in Fathom:
                    */
                    data_store_client.Name = tmp-resrc.tResrcName
                    data_store_client.resID = tmp-resrc.tresrcID
                    data_store_client.operatingMode = OE_ActBrk.ActBrk_Mode.
            END.
    
            /* Active Clients and Client Requests. */
            ASSIGN
                data_store_client.currClientTotal[Fathom-i] = data_store_client.currClientTotal[Fathom-i] +
                                                              OE_ActBrk.ActBrk_CurrClients
                data_store_client.clientRequestAvg[Fathom-i] = data_store_client.clientRequestAvg[Fathom-i] +
                                                               OE_ActBrk.ActBrk_ReqRec
                data_store_client.clientRequests[Fathom-i] = data_store_client.clientRequests[Fathom-i] +
                                                             OE_ActBrk.ActBrk_ReqRec
                data_store_client.numSeconds[Fathom-i] = data_store_client.numSeconds[Fathom-i] +
                                                         Cf_Sample.Sample_len
                data_store_client.numSamples[Fathom-i] = data_store_client.numSamples[Fathom-i] + 1
                data_store_client.summaryNumSamples = data_store_client.summaryNumSamples + 1
                data_store_client.summaryNumSeconds = data_store_client.summaryNumSeconds +
                                                      Cf_Sample.Sample_len.
    
            /* Max Active Clients. */
            IF data_store_client.activeClientMax[Fathom-i] LT 1 THEN 
            DO:
                ASSIGN data_store_client.activeClientMax[Fathom-i] = OE_ActBrk.ActBrk_CurrClients.
            END.
            ELSE IF OE_ActBrk.ActBrk_CurrClients GT 0 AND
                    OE_ActBrk.ActBrk_CurrClients GT data_store_client.activeClientMax[Fathom-i] THEN 
            DO:
                ASSIGN data_store_client.activeClientMax[Fathom-i] = OE_ActBrk.ActBrk_CurrClients.
            END.
    
            /* Max Client Requests. */
            IF data_store_client.clientRequestMax[Fathom-i] LT 1 THEN 
            DO:
                ASSIGN data_store_client.clientRequestMax[Fathom-i] = OE_ActBrk.ActBrk_ReqRec.
            END.
            ELSE IF OE_ActBrk.ActBrk_ReqRec GT 0 AND
                    OE_ActBrk.ActBrk_ReqRec GT data_store_client.clientRequestMax[Fathom-i] THEN 
            DO:
                ASSIGN data_store_client.clientRequestMax[Fathom-i] = OE_ActBrk.ActBrk_ReqRec.
            END.

            printMaxArray[fathom-i] = YES.
            printMax = YES.
    
        END. /* FOR EACH OE_ActBrk */

        IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
        ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = cf_sample.sample_date.
    
    END. /* {include/sample-query.i} => FOR EACH Cf_Sample */

END. /* FOR EACH tmp-resrc */

pgm-name = "clientactivity.p".
sec-name = "Exiting data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** Process archive records if the need arises to do so.
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "clientactivity.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}.

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}.

DEFINE VARIABLE reqrecavg AS DECIMAL.

IF Fathom-ar-date GT Fathom-i-start_date THEN
DO:
    pgm-name = "clientactivity.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.

    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_OE_ActBrk:HANDLE).

    FOR EACH tmp-resrc:

        pgm-name = "clientactivity.p".
        sec-name = "Gathering archive data for resource: " + tmp-resrc.tResrcName + ".".
        {include/debug.i "pgm-name" "sec-name"}.

        qh:QUERY-PREPARE("FOR EACH Ar_OE_ActBrk WHERE " +
                         "Ar_OE_ActBrk.Resrc_ID EQ " + STRING(tmp-resrc.tResrcID) + " AND " +
                         "Ar_OE_ActBrk.Site_ID EQ ~"" + tmp-resrc.tSiteID + "~" AND " +
                         "Ar_OE_ActBrk.ActBrk_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                         "Ar_OE_ActBrk.ActBrk_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                         "Ar_OE_ActBrk.ActBrk_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                         "Ar_OE_ActBrk.ActBrk_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                         "Ar_OE_ActBrk.ActBrk_ArchiveType EQ ~"" + archiveType + "~"").
        qh:QUERY-OPEN().
        
        REPEAT:
            qh:GET-NEXT.
            IF qh:QUERY-OFF-END THEN LEAVE.

        /*FOR EACH Ar_OE_ActBrk WHERE
            Ar_OE_ActBrk.Resrc_ID = tmp-resrc.tResrcID AND
            Ar_OE_ActBrk.Site_ID = tmp-resrc.tSiteID AND
            Ar_OE_ActBrk.ActBrk_StartDate LT Fathom-ar-date AND
            Ar_OE_ActBrk.ActBrk_Startdate GE Fathom-i-start_date AND
            Ar_OE_ActBrk.ActBrk_ArchiveType = "D"
            BY Ar_OE_ActBrk.ActBrk_Startdate:*/

            Fathom-i = 0.
            REPEAT:
                Fathom-i = Fathom-i + 1.
                IF Ar_OE_ActBrk.ActBrk_StartDate GE Fathom-t-beg-date[Fathom-i] AND
                    Ar_OE_ActBrk.ActBrk_StartDate LE Fathom-t-end-date[Fathom-i] THEN
                DO:
                    IF Ar_OE_ActBrk.ActBrk_starttime GE Fathom-t-beg-time[Fathom-i] AND
                        Ar_OE_ActBrk.ActBrk_starttime LE Fathom-t-end-time[Fathom-i] THEN
                        LEAVE.
                END.
                IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
            END.

            FIND FIRST data_store_client WHERE data_store_client.Name = tmp-resrc.tResrcName NO-ERROR.
    
            IF NOT AVAILABLE data_store_client THEN
            DO:
                CREATE data_store_client.
                ASSIGN
                    /*
                    ** data_store_broker.Name = OE_ActBrk.ActBrk_Name 
                    ** Make this Fathom's resource name, not the broker name
                    **  in case we ever decide to let users change the
                    **  name of a broker resource in Fathom:
                    */
                    data_store_client.Name = tmp-resrc.tResrcName
                    data_store_client.resID = tmp-resrc.tresrcID
                    data_store_client.operatingMode = Ar_OE_ActBrk.ActBrk_Mode.
            END.
    
            /* Active Clients and Client Requests. */
            ASSIGN
                data_store_client.currClientTotal[Fathom-i] = data_store_client.currClientTotal[Fathom-i] +
                                                              (Ar_OE_ActBrk.ActBrk_CurrClients *
                                                               Ar_OE_ActBrk.ActBrk_RecordCount)
                data_store_client.clientRequestAvg[Fathom-i] = data_store_client.clientRequestAvg[Fathom-i] +
                                                               Ar_OE_ActBrk.ActBrk_ReqRec
                data_store_client.clientRequests[Fathom-i] = data_store_client.clientRequests[Fathom-i] +
                                                             Ar_OE_ActBrk.ActBrk_ReqRec
                data_store_client.numSeconds[Fathom-i] = data_store_client.numSeconds[Fathom-i] +
                                                         Ar_OE_ActBrk.ActBrk_Length
                data_store_client.numSamples[Fathom-i] = data_store_client.numSamples[Fathom-i] +
                                                         Ar_OE_ActBrk.ActBrk_RecordCount
                data_store_client.summaryNumSamples = data_store_client.summaryNumSamples +
                                                      Ar_OE_ActBrk.ActBrk_RecordCount
                Fathom-Rec-Count = Fathom-Rec-Count + Ar_OE_ActBrk.ActBrk_RecordCount
                data_store_client.summaryNumSeconds = data_store_client.summaryNumSeconds +
                                                      Ar_OE_ActBrk.ActBrk_Length.
    
            /*
            ** Max Active Clients and Max Client Requests.
            ** NOTE: Archived data not available for this field.
            */
            haveArchivedRecArray[fathom-i] = YES.
            haveArchivedRec = YES.

        END. /* FOR EACH Ar_OE_ActBrk */

    END. /* FOR EACH tmp-resrc */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

END.

pgm-name = "clientactivity.p".
sec-name = "Exiting archive data collection.".
{include/debug.i "pgm-name" "sec-name"}.



/*
** Print to xml file.
**
** NOTE: The initialization has already been done in performance.p.
*/
{include/xmldefinitions.i "SHARED"}.

IF Fathom-Rec-Count lt 1 THEN
DO:
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for the client activity report.").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    pgm-name = "clientactivity.p".
    sec-name = "No samples - finishing XML files.".
    {include/debug.i "pgm-name" "sec-name"}.

    RETURN.
END.

DEFINE VARIABLE datalabels AS CHARACTER EXTENT 6.
ASSIGN
    datalabels[1] = AVG_ACTIVE_CLIENTS
    datalabels[2] = MAX_ACTIVE_CLIENTS
    datalabels[3] = CLIENT_REQUESTS
    datalabels[4] = AVG_CLIENT_REQUESTS
    datalabels[5] = MAX_CLIENT_REQUESTS
    datalabels[6] = SAMPLE_COUNT.
DEFINE VARIABLE i AS INTEGER.


fathom-report-title = "Client Activity".
RUN xml-report-header.
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


FOR EACH tmp-resrc:

    pgm-name = "clientactivity.p".
    sec-name = "Printing data to XML file for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    FIND FIRST Cf_Resrc WHERE tmp-resrc.tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.

    IF AVAILABLE Cf_Resrc THEN
    DO:
        ASSIGN
            xmlresourcename = Cf_Resrc.Resrc_Name 
            xmlresourcetype = Cf_Resrc.Resrc_Type 
            xmlresourcesite = Cf_Resrc.Site_ID.

        /* Setup the root header and data information. */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "resource",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        sec-name = "Writing out Root header - Label :" + 
                   xmlresourcename + ":" +
                   xmlresourcetype + ":" +
                   xmlresourcesite.
        {include/debug.i "pgm-name" "sec-name"}.

        RUN xml-root-header.
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Labels section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "labels",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        DO i = 1 TO EXTENT(datalabels):

            xmldataOutputlabel = datalabels[i].

                RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "label",
                           INPUT "",
                           INPUT "",
                           INPUT xmldataOutputlabel).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "labels").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Dates section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "times",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        DO fathom-x = 1 to Fathom-i-periods:

            xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
            xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
            xmlsampleenddate = Fathom-t-end-date[fathom-x].
            xmlsampleendtime = Fathom-t-end-time[fathom-x].
                
            RUN xml-process-date.       /* Subroutine to process the date. */
            RUN xml-add-data-timetable. /* Subroutine to process the datum. */
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

        END.

        IF Fathom-i-periods > 1 THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "time",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "name",
                           INPUT "",
                           INPUT "",
                           INPUT "Summary").
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "time").
        END.

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "times").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /* 
        ** Data Section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        FOR EACH data_store_client WHERE data_store_client.resID = tmp-resrc.tResrcID:

            DO i = 1 TO EXTENT(datalabels):

                xmldataOutputlabel = datalabels[i].
                xmldatalabel = datalabels[i].

                sec-name = "Writing out row header - Label :" + xmldatalabel.
                {include/debug.i "pgm-name" "sec-name"}.

                DO fathom-x = 1 to Fathom-i-periods:

                    /* For display units. */
                    CASE Fathom-i-intervaltype:
                        WHEN "S" THEN Fathom-store-value = data_store_client.numSeconds[Fathom-i].
                        WHEN "M" THEN Fathom-store-value = data_store_client.numSeconds[Fathom-i] / 60.
                        WHEN "H" THEN Fathom-store-value = data_store_client.numSeconds[Fathom-i] / 60 / 60.
                        OTHERWISE Fathom-store-value = 1.
                    END CASE.

                    /*
                    ** This preserves summary info when there are no samples in a period.
                    ** See 2003 08 13-018.
                    */
                    IF Fathom-store-value = 0 THEN Fathom-store-value = 1.

                    xmlsamplelength = STRING (data_store_client.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING (data_store_client.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    /* xmlsamplecount = STRING (Fathom-numsamples[fathom-x]). */
                    xmlsamplecount = STRING (data_store_client.numSamples[fathom-x]).

                    CASE datalabels[i]:

                        WHEN AVG_ACTIVE_CLIENTS THEN
                        DO:
                            dataprecision = "2".
                            data_store_client.summaryActiveClientAvg = data_store_client.summaryActiveClientAvg +
                                                                       data_store_client.currClientTotal[fathom-x].
                            data_store_client.activeClientAvg[fathom-x] = data_store_client.currClientTotal[fathom-x] /
                                                                          data_store_client.numSamples[fathom-x].
                            IF data_store_client.activeClientAvg[fathom-x] = ? THEN
                                data_store_client.activeClientAvg[fathom-x] = 0.
                            IF data_store_client.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_client.activeClientAvg[fathom-x]).
                            END.
                        END.
                        WHEN MAX_ACTIVE_CLIENTS THEN
                        DO:
                            dataprecision = "0".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_client.activeClientMax[fathom-x] GT 0 AND
                                   data_store_client.activeClientMax[fathom-x] GT data_store_client.summaryActiveClientMax THEN 
                                DO:
                                    ASSIGN data_store_client.summaryActiveClientMax = data_store_client.activeClientMax[fathom-x].
                                END.
                                IF data_store_client.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_client.activeClientMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN CLIENT_REQUESTS THEN
                        DO:
                            dataprecision = "0".
                            data_store_client.summaryClientRequests = data_store_client.summaryClientRequests +
                                                                      data_store_client.clientRequests[fathom-x].
                            data_store_client.clientRequests[fathom-x] = data_store_client.clientRequests[fathom-x] /
                                                                         Fathom-store-value.
                            IF data_store_client.clientRequests[fathom-x] = ? THEN
                                data_store_client.clientRequests[fathom-x] = 0.
                            IF data_store_client.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_client.clientRequests[fathom-x]).
                            END.
                        END.
                        WHEN AVG_CLIENT_REQUESTS THEN
                        DO:
                            dataprecision = "2".
                            data_store_client.summaryClientRequestAvg = data_store_client.summaryClientRequestAvg +
                                                                        data_store_client.clientRequestAvg[fathom-x].
                            IF Fathom-store-value = 1 THEN
                            DO:
                                /* Average Client Requests doesn't mean anything in raw data mode--requests per what? */
                                data_store_client.clientRequestAvg[fathom-x] = -2.
                                xmldatavalue = STRING(NOT_AVAILABLE).
                            END.
                            ELSE
                            DO:
                                data_store_client.clientRequestAvg[fathom-x] = data_store_client.clientRequestAvg[fathom-x] /
                                                                               Fathom-store-value. /* Num seconds */
                                IF data_store_client.clientRequestAvg[fathom-x] = ? THEN
                                    data_store_client.clientRequestAvg[fathom-x] = 0.
                                IF data_store_client.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_client.clientRequestAvg[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN MAX_CLIENT_REQUESTS THEN
                        DO:
                            dataprecision = "0".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_client.clientRequestMax[fathom-x] GT 0 AND
                                   data_store_client.clientRequestMax[fathom-x] GT data_store_client.summaryClientRequestMax THEN 
                                DO:
                                    ASSIGN data_store_client.summaryClientRequestMax = data_store_client.clientRequestMax[fathom-x].
                                END.
                                IF data_store_client.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_client.clientRequestMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN SAMPLE_COUNT THEN
                        DO:
                            dataprecision = "0".
                            xmldatavalue = STRING(data_store_client.numSamples[fathom-x]).
                        END.
                        OTHERWISE
                            /* Should not happen as we just defined the array above. */
                            xmldatavalue = "".

                    END CASE.

                    RUN xml-process-date.
                    RUN xml-add-data.
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".

                    IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 THEN
                    DO:

                        /* For display units. */
                        CASE Fathom-i-intervaltype:
                            WHEN "S" THEN Fathom-store-value = data_store_client.summaryNumSeconds.
                            WHEN "M" THEN Fathom-store-value = data_store_client.summaryNumSeconds / 60.
                            WHEN "H" THEN Fathom-store-value = data_store_client.summaryNumSeconds / 60 / 60.
                            OTHERWISE Fathom-store-value = 1.
                        END CASE.

                        CASE datalabels[i]:
    
                            WHEN AVG_ACTIVE_CLIENTS THEN
                            DO:
                                dataprecision = "2".
                                data_store_client.summaryActiveClientAvg = data_store_client.summaryActiveClientAvg /
                                                                           data_store_client.summaryNumSamples.
                                IF data_store_client.summaryActiveClientAvg = ? THEN
                                    data_store_client.summaryActiveClientAvg = 0.
                                xmldatavalue = STRING(data_store_client.summaryActiveClientAvg).
                            END.
                            WHEN MAX_ACTIVE_CLIENTS THEN
                            DO:
                                dataprecision = "0".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_client.summaryActiveClientMax).
                            END.
                            WHEN CLIENT_REQUESTS THEN
                            DO:
                                dataprecision = "0".
                                data_store_client.summaryClientRequests = data_store_client.summaryClientRequests /
                                                                          Fathom-store-value.
                                xmldatavalue = STRING(data_store_client.summaryClientRequests).
                            END.
                            WHEN AVG_CLIENT_REQUESTS THEN
                            DO:
                                dataprecision = "2".
                                IF Fathom-store-value = 1 THEN
                                    xmldatavalue = STRING("N/A").
                                ELSE
                                DO:
                                    data_store_client.summaryClientRequestAvg = data_store_client.summaryClientRequestAvg /
                                                                                Fathom-store-value. /* Num seconds */
                                    IF data_store_client.summaryClientRequestAvg = ? THEN
                                        data_store_client.summaryClientRequestAvg = 0.
                                    xmldatavalue = STRING(data_store_client.summaryClientRequestAvg).
                                END.
                            END.
                            WHEN MAX_CLIENT_REQUESTS THEN
                            DO:
                                dataprecision = "0".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_client.summaryClientRequestMax).
                            END.
                            WHEN SAMPLE_COUNT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store_client.summaryNumSamples).
                            END.
                            OTHERWISE
                                /* Should not happen as we just defined the array above. */
                                xmldatavalue = "".
    
                        END CASE.

                        RUN xml-add-data-summary.
                        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                        streamdetail = "".

                    END. /* IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 */

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

            END. /* DO i = 1 TO EXTENT(datalabels): */

        END. /* FOR EACH data_store */

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "dataset").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
   
    END. /* IF AVAILABLE Cf_Resrc */

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "resource").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

END. /* FOR EACH tmp-resrc */


pgm-name = "clientactivity.p".
sec-name = "Finishing data XML file.".
{include/debug.i "pgm-name" "sec-name"}.




/*
** Print out the graph xml file.
**  We do this in a separate loop so that we can limit the
**  number of brokers put on the graph.  We have to know
**  the top x brokers that have the highest average active clients, etc.
*/
numGraphResources = INTEGER(OS-GETENV("fathomResourcesPerGraph")) NO-ERROR.
DEFINE VARIABLE graph AS CHARACTER.
DEFINE VARIABLE isgraphed AS LOGICAL INITIAL NO.

IF numGraphResources = ? THEN
DO:
   numGraphResources = defaultNumGraphResources.
END.


DO x-i = 1 TO NUM-ENTRIES(xmlGraphColumns, ","):
    graph = TRIM(ENTRY(x-i, xmlGraphColumns, ",")) NO-ERROR.

    CASE graph:
        WHEN "none" THEN LEAVE.
        WHEN AVG_ACTIVE_CLIENTS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Client Activity: " + AVG_ACTIVE_CLIENTS.
            xmlgraph-imagetitle = "activeclientsavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "1".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_client BY summaryActiveClientAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_client.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_client.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_client.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_client.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_client.activeClientAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_ACTIVE_CLIENTS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Client Activity: " + MAX_ACTIVE_CLIENTS.
            xmlgraph-imagetitle = "activeclientsmax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "2".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_client BY summaryActiveClientMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_client.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_client.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_client.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_client.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_client.activeClientMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN CLIENT_REQUESTS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Client Activity: " + CLIENT_REQUESTS.
            xmlgraph-imagetitle = "clientrequests.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "3".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_client BY summaryClientRequests DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_client.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_client.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_client.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_client.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_client.clientRequests[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_CLIENT_REQUESTS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Client Activity: " + AVG_CLIENT_REQUESTS.
            xmlgraph-imagetitle = "clientrequestsavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "4".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_client BY summaryClientRequestAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_client.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_client.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_client.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_client.numSamples[fathom-x]).
                    IF data_store_client.clientRequestAvg[fathom-x] = -2 THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_client.clientRequestAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_CLIENT_REQUESTS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Client Activity: " + MAX_CLIENT_REQUESTS.
            xmlgraph-imagetitle = "clientrequestsmax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "5".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_client BY summaryClientRequestMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_client.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_client.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_client.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_client.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_client.clientRequestMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN SAMPLE_COUNT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Client Activity: " + SAMPLE_COUNT.
            xmlgraph-imagetitle = "samplecount.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "6".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_client BY summaryNumSamples DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_client.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_client.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_client.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_client.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_client.numSamples[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

    END CASE.

    IF isgraphed = YES THEN
    DO:
        isgraphed = NO.
        RUN xml-graphspec-end.
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
    END.

END.



pgm-name = "clientactivity.p".
sec-name = "Finished client section of graph XML file.".
{include/debug.i "pgm-name" "sec-name"}.



pgm-name = "clientactivity.p".
sec-name = "Exiting Program.".
{include/debug.i "pgm-name" "sec-name"}.
/*
** performance.p
**
** This program will present a performance report for AppServer or WebSpeed
**  based on the dates provided to the report.  
**
** The performance report is actually three reports combined into one.
**  There is a broker, client, and server report.  It is possible to use
**  any one, two, or all parts of the report.
**
** The program is given a list of AppServer or WebSpeed resources and
**  the type or types of reports to generate (broker, client, or server).
**  The list of resources comes with the arguments in the -param argument,
**  and the report type ends up in the environment variable
**  "fathomReportSubTypes".
**
*/

{include/definitions.i "NEW SHARED"}.


pgm-name = "performance.p".
sec-name = "Starting Program.".
{include/debug.i "pgm-name" "sec-name"}.


IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}.

    {include/passinput.i}.
END.



/* 
** Begin Main Processing.
*/


/*
** The performance report can be listed by brokers or by service names.
**  If the report specifies listing by service name, we have no resources
**  at the moment!  We need to change the service name list into a
**  list of resources so the reports can look by resource, as there is no
**  lookup by service name.  Populate the tmp-resrc temp-table.
**
** List-by-service will define if we are to list output by broker or service name.
**
** NOTE: Order is important.  We need to ensure that the order in is the order in
**  the xml file.
*/
/* Temporarily commenting out to get this working with just resources first.
DEFINE NEW SHARED VARIABLE List-by-service AS LOGICAL INITIAL NO NO-UNDO.
DEFINE VARIABLE Service-name-list AS CHARACTER.
Service-name-list = OS-GETENV("fathomReportServiceName").

IF Service-name-list NE ? THEN
DO:
    List-by-service = YES.

END.*/

/* Set up date buckets in the temp tables. */
{include/trenddates.i}.

{include/report-name.i}.


/*
** Read samples and process them into the report table.
*/
pgm-name = "performance.p".
sec-name = "Processing Samples".

{include/debug.i "pgm-name" "sec-name"}.

sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}.


pgm-name = "performance.p".
sec-name = "Initializing XML file.".
{include/debug.i "pgm-name" "sec-name"}.

{include/xmldefinitions.i "NEW SHARED"}.
{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}.
{include/xmlinitialize.i}. 
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
  
pgm-name = "performance.p".
sec-name = "Completed initialization of XML files.".
{include/debug.i "pgm-name" "sec-name"}.

xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.

IF xmlGraphColumns = ? THEN
DO:
   {include/xml-graphcolumns.i}.
END.


/*
** The performance report has three possible subtypes: client activity,
**  broker activity, and/or server/agent activity.  We can get one, two,
**  or all three of them.  So we can have up to three reports on one page.
**  If this is not set, or junk, default to the client activity only.
**
** This will come in the form:
**  client,broker,server
** or:
**  broker,server
**
** NOTE: Order is important.  We need to ensure that the order in is the order in
**  the xml file.
*/
DEFINE VARIABLE Fathom-report-data-list AS CHARACTER NO-UNDO.
Fathom-report-data-list = OS-GETENV("fathomReportDataList").

pgm-name = "performance.p".
sec-name = "Fathom-report-data-list : " + Fathom-report-data-list.
{include/debug.i "pgm-name" "sec-name"}.

DEFINE VARIABLE subtyp AS CHARACTER.
DEFINE VARIABLE reportHasRun AS LOGICAL INITIAL NO.
DEFINE VARIABLE performance-loop-index AS INTEGER.

DO performance-loop-index = 1 TO NUM-ENTRIES(Fathom-report-data-list, ","):
    subtyp = TRIM(ENTRY(performance-loop-index, Fathom-report-data-list, ",")) NO-ERROR.

    CASE subtyp:

        WHEN "broker" THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "report",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

            RUN openedge/brokeractivity.p.
            reportHasRun = YES.

            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "report").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        END.

        WHEN "client" THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "report",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

            RUN openedge/clientactivity.p.
            reportHasRun = YES.

            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "report").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        END.

        WHEN "server" THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "report",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

            RUN openedge/serveractivity.p.
            reportHasRun = YES.

            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "report").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        END.

    END CASE.
END.

/* No subtype, use default. */
IF reportHasRun = NO THEN DO:
    pgm-name = "performance.p".
    sec-name = "No subtype specified: defaulting to clientactivity.".
    {include/debug.i "pgm-name" "sec-name"}.
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "report",
                        INPUT "",
                        INPUT "",
                        INPUT "").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    RUN openedge/clientactivity.p.

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
END.


pgm-name = "performance.p".
sec-name = "Finishing XML files.".
{include/debug.i "pgm-name" "sec-name"}.

/* Every sub-report has put data into the xml file, close. */
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/* Close up the graphing stuff. */
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}.
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}.

pgm-name = "performance.p".
sec-name = "XML files complete.".
{include/debug.i "pgm-name" "sec-name"}.


pgm-name = "performance.p".
sec-name = "Exiting Program.".
{include/debug.i "pgm-name" "sec-name"}.

/*
** serveractivity.p
**
** This program will present a server activity report for AppServer
**  or WebSpeed based on the dates provided to the report.  
**
** The performance report is actually three reports combined into one.
**  There is a broker, client, and server report.  It is possible to use
**  any one, two, or all parts of the report.  This program is the
**  server part.
**
*/

{include/definitions.i "SHARED"}.

DEFINE TEMP-TABLE data_store_server NO-UNDO
    FIELD Name                     AS CHARACTER
    FIELD resID                    AS INTEGER
    FIELD operatingMode            AS CHARACTER
    FIELD numSeconds               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD numSamples               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD numServerSamples         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD totServerSamples         AS DECIMAL
    FIELD busyServersAvg           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD busyServersMax           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryBusyServersAvg    AS DECIMAL
    FIELD summaryBusyServersMax    AS DECIMAL
    /*
    ** The "...State" fields are how many times a server went into that state
    ** during the poll, not the count of how many servers were in that state.
    */
    FIELD busyServerState          AS DECIMAL EXTENT 366 INITIAL 0
    FIELD busyServerTime           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryBusyServerState   AS DECIMAL
    FIELD summaryBusyServerTime    AS DECIMAL
    FIELD lockedServersAvg         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD lockedServersMax         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryLockedServersAvg  AS DECIMAL
    FIELD summaryLockedServersMax  AS DECIMAL
    FIELD lockedServerState        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD lockedServerTime         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryLockedServerState AS DECIMAL
    FIELD summaryLockedServerTime  AS DECIMAL
    /* Running servers info removed.
    FIELD runningServersAvg         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD runningServersMax         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryRunningServersAvg  AS DECIMAL
    FIELD summaryRunningServersMax  AS DECIMAL*/
    FIELD numSystemSamples         AS DECIMAL EXTENT 366 INITIAL 0
    FIELD totSystemSamples         AS DECIMAL
    FIELD poolCPUAvg               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD poolCPUTime              AS DECIMAL EXTENT 366 INITIAL 0
    FIELD poolCPUMax               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD poolMemoryAvg            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD poolMemoryMax            AS DECIMAL EXTENT 366 INITIAL 0
    /* Need these four for maximum values--not available for archived records. */
    FIELD printMaxArray            AS LOGICAL EXTENT 366 INITIAL NO
    FIELD haveArchivedRecArray     AS LOGICAL EXTENT 366 INITIAL NO
    FIELD printMax                 AS LOGICAL INITIAL NO
    FIELD haveArchivedRec          AS LOGICAL INITIAL NO
    FIELD summaryPoolCPUAvg        AS DECIMAL
    FIELD summaryPoolCPUTime       AS DECIMAL
    FIELD summaryPoolCPUMax        AS DECIMAL
    FIELD summaryPoolMemoryAvg     AS DECIMAL
    FIELD summaryPoolMemoryMax     AS DECIMAL
    FIELD summaryNumSamples        AS DECIMAL
    INDEX one NAME
    INDEX two resID.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.

/* List-by-service will define if we are to list output by broker or service name. */
DEFINE SHARED VARIABLE List-by-service AS LOGICAL NO-UNDO.

/* Keep track of servers busy and servers locked. */
DEFINE VARIABLE serversbusy   AS INTEGER INITIAL 0.
DEFINE VARIABLE serverslocked AS INTEGER INITIAL 0.


pgm-name = "serveractivity.p".
sec-name = "Starting Program.".
{include/debug.i "pgm-name" "sec-name"}.

/* Reset the record counter for each section of the performance report. */
Fathom-Rec-Count = 0.


/*
** Get data from trend database.
*/
FOR EACH tmp-resrc:

    pgm-name = "serveractivity.p".
    sec-name = "Gathering data for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    Fathom-i-Resrc_ID = tmp-resrc.tresrcID. /* need this? todo-try without */

    {include/sample-query.i}
        
        {include/setup-i.i}
    
        {include/fathom-counters.i}
    
        FOR EACH OE_ActBrk WHERE Cf_Sample.Sample_ID = OE_ActBrk.Sample_ID:
    
            FIND FIRST data_store_server WHERE data_store_server.Name = tmp-resrc.tResrcName NO-ERROR.
    
            IF NOT AVAILABLE data_store_server THEN
            DO:
                CREATE data_store_server.
                ASSIGN
                    /*
                    ** data_store_broker.Name = OE_ActBrk.ActBrk_Name 
                    ** Make this Fathom's resource name, not the broker name
                    **  in case we ever decide to let users change the
                    **  name of a broker resource in Fathom:
                    */
                    data_store_server.Name = tmp-resrc.tResrcName
                    data_store_server.resID = tmp-resrc.tresrcID
                    data_store_server.operatingMode = OE_ActBrk.ActBrk_Mode.
            END.
    
            /* Number of Servers/Agents Running -- omitted. */
            ASSIGN
                /*data_store_server.runningServersAvg[Fathom-i] = data_store_server.runningServersAvg[Fathom-i] +
                                                                OE_ActBrk.ActBrk_CurrServers*/
                data_store_server.numSeconds[Fathom-i] = data_store_server.numSeconds[Fathom-i] +
                                                         Cf_Sample.Sample_len
                data_store_server.numSamples[Fathom-i] = data_store_server.numSamples[Fathom-i] + 1
                data_store_server.summaryNumSamples = data_store_server.summaryNumSamples + 1.
    
            /* Max Running Servers/Agents. */
            /*IF data_store_server.runningServersMax[Fathom-i] LT 1 THEN 
            DO:
                ASSIGN data_store_server.runningServersMax[Fathom-i] = OE_ActBrk.ActBrk_CurrServers.
            END.
            ELSE IF OE_ActBrk.ActBrk_CurrServers GT 0 AND
                    OE_ActBrk.ActBrk_CurrServers GT data_store_server.runningServersMax[Fathom-i] THEN 
            DO:
                ASSIGN data_store_server.runningServersMax[Fathom-i] = OE_ActBrk.ActBrk_CurrServers.
            END.*/
    
            /*
            ** Retrieve server-specific info.
            */
            FOR EACH OE_ActSrv WHERE OE_ActBrk.Sample_ID = OE_ActSrv.Sample_ID AND
                                     OE_ActBrk.ActBrk_UUID = OE_ActSrv.ActBrk_UUID:
                ASSIGN
                    data_store_server.busyServerState[Fathom-i] = data_store_server.busyServerState[Fathom-i] +
                                                                  OE_ActSrv.ActSrv_BusyCount
                    data_store_server.busyServerTime[Fathom-i] = data_store_server.busyServerTime[Fathom-i] +
                                                                 OE_ActSrv.ActSrv_BusyTime
                    data_store_server.lockedServerState[Fathom-i] = data_store_server.lockedServerState[Fathom-i] +
                                                                    OE_ActSrv.ActSrv_LockedCount
                    data_store_server.lockedServerTime[Fathom-i] = data_store_server.lockedServerTime[Fathom-i] +
                                                                   OE_ActSrv.ActSrv_LockedTime
                    data_store_server.numServerSamples[Fathom-i] = data_store_server.numServerSamples[Fathom-i] + 1
                    data_store_server.totServerSamples = data_store_server.totServerSamples + 1.
    
                /* 0 = Idle, 1 = Busy, 2 = Locked, 3 = Other. */
                CASE OE_ActSrv.ActSrv_Status:
                    WHEN "1" THEN serversbusy = serversbusy + 1.
                    WHEN "2" THEN serverslocked = serverslocked + 1.
                END CASE.
    
                /* System metrics--should only be one record per server/agent. */
                FOR EACH Sys_Process WHERE OE_ActSrv.Sample_ID = Sys_Process.Sample_ID AND
                                           OE_ActSrv.ActSrv_PID = Sys_Process.Process_PID:
                    ASSIGN
                        data_store_server.poolCPUAvg[Fathom-i] = data_store_server.poolCPUAvg[Fathom-i] +
                                                                 Sys_Process.Process_CPUUser +
                                                                 Sys_Process.Process_CPUSystem
                        data_store_server.summaryPoolCPUAvg = data_store_server.summaryPoolCPUAvg +
                                                              Sys_Process.Process_CPUUser +
                                                              Sys_Process.Process_CPUSystem
                        data_store_server.poolCPUTime[Fathom-i] = data_store_server.poolCPUTime[Fathom-i] +
                                                                  Sys_Process.Process_ElapsedTime
                        data_store_server.summaryPoolCPUTime = data_store_server.summaryPoolCPUTime +
                                                               Sys_Process.Process_ElapsedTime
                        data_store_server.poolMemoryAvg[Fathom-i] = data_store_server.poolMemoryAvg[Fathom-i] +
                                                                    Sys_Process.Process_ResMemory
                        data_store_server.numSystemSamples[Fathom-i] = data_store_server.numSystemSamples[Fathom-i] + 1
                        data_store_server.totSystemSamples = data_store_server.totSystemSamples + 1.
    
                    /* Max Pool CPU. */
                    IF data_store_server.poolCPUMax[Fathom-i] LT 1 THEN 
                    DO:
                        ASSIGN data_store_server.poolCPUMax[Fathom-i] = Sys_Process.Process_CPUPct.
                    END.
                    ELSE IF Sys_Process.Process_CPUPct GT 0 AND
                            Sys_Process.Process_CPUPct GT data_store_server.poolCPUMax[Fathom-i] THEN 
                    DO:
                        ASSIGN data_store_server.poolCPUMax[Fathom-i] = Sys_Process.Process_CPUPct.
                    END.
    
                    /* Max Pool Memory. */
                    IF data_store_server.poolMemoryMax[Fathom-i] LT 1 THEN 
                    DO:
                        ASSIGN data_store_server.poolMemoryMax[Fathom-i] = Sys_Process.Process_ResMemory.
                    END.
                    ELSE IF Sys_Process.Process_ResMemory GT 0 AND
                            Sys_Process.Process_ResMemory GT data_store_server.poolMemoryMax[Fathom-i] THEN 
                    DO:
                        ASSIGN data_store_server.poolMemoryMax[Fathom-i] = Sys_Process.Process_ResMemory.
                    END.

                END. /* FOR EACH Sys_Process */
    
            END. /* FOR EACH OE_ActSrv */

            /*
            ** Okay, we've gathered the states of each server for this sample on
            ** this broker, get the avg and max.
            */
            ASSIGN
                data_store_server.busyServersAvg[Fathom-i] = data_store_server.busyServersAvg[Fathom-i] +
                                                             serversbusy
                data_store_server.lockedServersAvg[Fathom-i] = data_store_server.lockedServersAvg[Fathom-i] +
                                                               serverslocked.

            /* Max Busy Servers. */
            IF data_store_server.busyServersMax[Fathom-i] LT 1 THEN 
            DO:
                ASSIGN data_store_server.busyServersMax[Fathom-i] = serversbusy.
            END.
            ELSE IF serversbusy GT data_store_server.busyServersMax[Fathom-i] THEN 
            DO:
                ASSIGN data_store_server.busyServersMax[Fathom-i] = serversbusy.
            END.

            /* Max Locked Servers. */
            IF data_store_server.lockedServersMax[Fathom-i] LT 1 THEN 
            DO:
                ASSIGN data_store_server.lockedServersMax[Fathom-i] = serverslocked.
            END.
            ELSE IF serverslocked GT data_store_server.lockedServersMax[Fathom-i] THEN 
            DO:
                ASSIGN data_store_server.lockedServersMax[Fathom-i] = serverslocked.
            END.

            ASSIGN
                serversbusy   = 0
                serverslocked = 0
                printMaxArray[fathom-i] = YES.
                printMax = YES.
    
        END. /* FOR EACH OE_ActBrk */

        IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
        ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = cf_sample.sample_date.
    
    END. /* {include/sample-query.i} => FOR EACH Cf_Sample */

END. /* FOR EACH tmp-resrc */



/*
** Process archive records if the need arises to do so.
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "serveractivity.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}.

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}.

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "serveractivity.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    DEFINE VARIABLE brokerQuery AS WIDGET-HANDLE.
    CREATE QUERY brokerQuery.
    brokerQuery:SET-BUFFERS(BUFFER Ar_OE_ActBrk:HANDLE).

    DEFINE VARIABLE serverQuery AS WIDGET-HANDLE.
    CREATE QUERY serverQuery.
    serverQuery:SET-BUFFERS(BUFFER Ar_OE_ActServ:HANDLE).

    DEFINE VARIABLE processQuery AS WIDGET-HANDLE.
    CREATE QUERY processQuery.
    processQuery:SET-BUFFERS(BUFFER Ar_Process:HANDLE).

    /*
    ** This temp table stores server pids, and gets cleared on every iteration
    ** through the broker loop.  We need to keep track of this because there
    ** are server records separated by both pid AND server status.  This means
    ** we will go through the process loop too many times if we don't check
    ** what pid has already been processed.
    */
    DEFINE TEMP-TABLE serverpid
        FIELD pid AS DECIMAL.
    /*
    ** Same thing here, but if we have broker pids different, we get multiple
    ** archive records with the same UUID, thus a potential to go through the
    ** same server records more than once.
    */
    DEFINE TEMP-TABLE brokeruuid
        FIELD uuid      AS CHARACTER
        FIELD startTime AS INTEGER
        FIELD startDate AS DATE.

    FOR EACH tmp-resrc:

        brokerQuery:QUERY-PREPARE("FOR EACH Ar_OE_ActBrk WHERE " +
                                  "Ar_OE_ActBrk.Resrc_ID EQ " + STRING(tmp-resrc.tResrcID) + " AND " +
                                  "Ar_OE_ActBrk.Site_ID EQ ~"" + tmp-resrc.tSiteID + "~" AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartDate GE " + STRING(Fathom-i-Start_date) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                                  "Ar_OE_ActBrk.ActBrk_ArchiveType EQ ~"" + archiveType + "~"").
        brokerQuery:QUERY-OPEN().
        
        REPEAT:
            brokerQuery:GET-NEXT.
            IF brokerQuery:QUERY-OFF-END THEN LEAVE.

            Fathom-i = 0.
            REPEAT:
                Fathom-i = Fathom-i + 1.
                IF Ar_OE_ActBrk.ActBrk_StartDate GE Fathom-t-beg-date[Fathom-i] AND
                    Ar_OE_ActBrk.ActBrk_StartDate LE Fathom-t-end-date[Fathom-i] THEN
                DO:
                    IF Ar_OE_ActBrk.ActBrk_starttime GE Fathom-t-beg-time[Fathom-i] AND
                        Ar_OE_ActBrk.ActBrk_starttime LE Fathom-t-end-time[Fathom-i] THEN
                        LEAVE.
                END.
                IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
            END.

            Fathom-Rec-Count = Fathom-Rec-Count + Ar_OE_ActBrk.ActBrk_RecordCount.
            Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] +
                                             Ar_OE_ActBrk.ActBrk_RecordCount.
    
            FIND FIRST data_store_server WHERE data_store_server.Name = tmp-resrc.tResrcName NO-ERROR.
    
            IF NOT AVAILABLE data_store_server THEN
            DO:
                CREATE data_store_server.
                ASSIGN
                    /*
                    ** data_store_broker.Name = OE_ActBrk.ActBrk_Name 
                    ** Make this Fathom's resource name, not the broker name
                    **  in case we ever decide to let users change the
                    **  name of a broker resource in Fathom:
                    */
                    data_store_server.Name = tmp-resrc.tResrcName
                    data_store_server.resID = tmp-resrc.tresrcID
                    data_store_server.operatingMode = Ar_OE_ActBrk.ActBrk_Mode.
            END.
    
            /* Number of Servers/Agents Running -- omitted. */
            ASSIGN
                data_store_server.numSeconds[Fathom-i] = data_store_server.numSeconds[Fathom-i] +
                                                         Ar_OE_ActBrk.ActBrk_Length
                data_store_server.numSamples[Fathom-i] = data_store_server.numSamples[Fathom-i] +
                                                         Ar_OE_ActBrk.ActBrk_RecordCount
                data_store_server.summaryNumSamples = data_store_server.summaryNumSamples +
                                                      Ar_OE_ActBrk.ActBrk_RecordCount.

            /*
            ** Retrieve server-specific info.
            */
            serverQuery:QUERY-PREPARE("FOR EACH Ar_OE_ActServ WHERE " +
                                      "Ar_OE_ActServ.ActServ_StartDate EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartDate) + " AND " +
                                      "Ar_OE_ActServ.ActServ_StartTime EQ " + STRING(Ar_OE_ActBrk.ActBrk_StartTime) + " AND " +
                                      "Ar_OE_ActServ.ActBrk_UUID EQ ~"" + Ar_OE_ActBrk.ActBrk_UUID + "~" AND " +
                                      "Ar_OE_ActServ.ActServ_ArchiveType EQ ~"" + archiveType + "~"").
            serverQuery:QUERY-OPEN().

            REPEAT:
                serverQuery:GET-NEXT.
                IF serverQuery:QUERY-OFF-END THEN LEAVE.

                FIND FIRST brokeruuid WHERE
                    uuid EQ Ar_OE_ActBrk.ActBrk_UUID AND
                    startDate EQ Ar_OE_ActBrk.ActBrk_StartDate AND
                    startTime EQ Ar_OE_ActBrk.ActBrk_StartTime NO-ERROR.

                IF AVAILABLE brokeruuid THEN
                    LEAVE.

                ASSIGN
                    data_store_server.busyServerState[Fathom-i] = data_store_server.busyServerState[Fathom-i] +
                                                                  Ar_OE_ActServ.ActServ_BusyCount
                    data_store_server.busyServerTime[Fathom-i] = data_store_server.busyServerTime[Fathom-i] +
                                                                 Ar_OE_ActServ.ActServ_BusyTime
                    data_store_server.lockedServerState[Fathom-i] = data_store_server.lockedServerState[Fathom-i] +
                                                                    Ar_OE_ActServ.ActServ_LockedCount
                    data_store_server.lockedServerTime[Fathom-i] = data_store_server.lockedServerTime[Fathom-i] +
                                                                   Ar_OE_ActServ.ActServ_LockedTime
                    data_store_server.numServerSamples[Fathom-i] = data_store_server.numServerSamples[Fathom-i] +
                                                                   Ar_OE_ActServ.ActServ_RecordCount
                    data_store_server.totServerSamples = data_store_server.totServerSamples +
                                                         Ar_OE_ActServ.ActServ_RecordCount.

                /* 0 = Idle, 1 = Busy, 2 = Locked, 3 = Other. */
                CASE Ar_OE_ActServ.ActServ_Status:
                    WHEN "1" THEN serversbusy = serversbusy + Ar_OE_ActServ.ActServ_RecordCount.
                    WHEN "2" THEN serverslocked = serverslocked + Ar_OE_ActServ.ActServ_RecordCount.
                END CASE.
    
                /* System metrics--should only be one record per server/agent. */
                processQuery:QUERY-PREPARE("FOR EACH Ar_Process WHERE " +
                                           "Ar_Process.Process_StartDate EQ " + STRING(Ar_OE_ActServ.ActServ_StartDate) + " AND " +
                                           "Ar_Process.Process_StartTime EQ " + STRING(Ar_OE_ActServ.ActServ_StartTime) + " AND " +
                                           "Ar_Process.Process_PID EQ " + STRING(Ar_OE_ActServ.ActServ_PID) + " AND " +
                                           "Ar_Process.Process_ArchiveType EQ ~"" + archiveType + "~"").
                processQuery:QUERY-OPEN().
    
                REPEAT:
                    processQuery:GET-NEXT.
                    IF processQuery:QUERY-OFF-END THEN LEAVE.

                    FIND FIRST serverpid WHERE pid EQ Ar_OE_ActServ.ActServ_PID NO-ERROR.

                    IF AVAILABLE serverpid THEN
                        LEAVE.
                    ELSE
                    DO:
                        CREATE serverpid.
                        ASSIGN
                            pid = Ar_OE_ActServ.ActServ_PID.
                    END.

                    ASSIGN
                        data_store_server.poolCPUAvg[Fathom-i] = data_store_server.poolCPUAvg[Fathom-i] +
                                                                 Ar_Process.Process_CPUUser +
                                                                 Ar_Process.Process_CPUSystem
                        data_store_server.summaryPoolCPUAvg = data_store_server.summaryPoolCPUAvg +
                                                              Ar_Process.Process_CPUUser +
                                                              Ar_Process.Process_CPUSystem
                        data_store_server.poolCPUTime[Fathom-i] = data_store_server.poolCPUTime[Fathom-i] +
                                                                  Ar_Process.Process_ElapsedTime
                        data_store_server.summaryPoolCPUTime = data_store_server.summaryPoolCPUTime +
                                                               Ar_Process.Process_ElapsedTime
                        data_store_server.poolMemoryAvg[Fathom-i] = data_store_server.poolMemoryAvg[Fathom-i] +
                                                                    (Ar_Process.Process_ResMemory *
                                                                     Ar_Process.Process_RecordCount)
                        data_store_server.numSystemSamples[Fathom-i] = data_store_server.numSystemSamples[Fathom-i] +
                                                                       Ar_Process.Process_RecordCount
                        data_store_server.totSystemSamples = data_store_server.totSystemSamples +
                                                             Ar_Process.Process_RecordCount.

                    /*
                    ** Max Pool CPU and Max Pool Memory Useage.
                    ** NOTE: Can't get accurate data from the archived records, so skip.
                    */

                END. /* of Process REPEAT. */
    
            END. /* of Server REPEAT. */

            /*
            ** Okay, we've gathered the states of each server for this sample on
            ** this broker, get the avg and max.
            */
            ASSIGN
                data_store_server.busyServersAvg[Fathom-i] = data_store_server.busyServersAvg[Fathom-i] +
                                                             serversbusy
                data_store_server.lockedServersAvg[Fathom-i] = data_store_server.lockedServersAvg[Fathom-i] +
                                                               serverslocked.

            /*
            ** Max Busy Servers and Max Locked Servers.
            ** NOTE: Don't have available for archived data.
            */

            ASSIGN
                serversbusy   = 0
                serverslocked = 0
                haveArchivedRecArray[fathom-i] = YES
                haveArchivedRec = YES.

            EMPTY TEMP-TABLE serverpid.

            FIND FIRST brokeruuid WHERE
                uuid EQ Ar_OE_ActBrk.ActBrk_UUID AND
                startDate EQ Ar_OE_ActBrk.ActBrk_StartDate AND
                startTime EQ Ar_OE_ActBrk.ActBrk_StartTime NO-ERROR.

            IF NOT AVAILABLE brokeruuid THEN
            DO:
                CREATE brokeruuid.
                ASSIGN
                    uuid = Ar_OE_ActBrk.ActBrk_UUID
                    startTime = Ar_OE_ActBrk.ActBrk_StartTime
                    startDate = Ar_OE_ActBrk.ActBrk_StartDate.
            END.

        END. /* of Broker REPEAT. */

        EMPTY TEMP-TABLE brokeruuid.

    END. /* FOR EACH tmp-resrc */

    brokerQuery:QUERY-CLOSE().
    DELETE OBJECT brokerQuery.
    serverQuery:QUERY-CLOSE().
    DELETE OBJECT serverQuery.
    processQuery:QUERY-CLOSE().
    DELETE OBJECT processQuery.

END.

pgm-name = "serveractivity.p".
sec-name = "Exiting archive data collection.".
{include/debug.i "pgm-name" "sec-name"}.



/*
** Print to xml file.
**
** NOTE: The initialization has already been done in performance.p.
*/
{include/xmldefinitions.i "SHARED"}.

IF Fathom-Rec-Count lt 1 THEN
DO:
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for the server activity report.").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    RETURN.
END.

DEFINE VARIABLE datalabels AS CHARACTER EXTENT 11.
ASSIGN
    datalabels[1]  = AVG_POOL_CPU_USAGE_PCT
    datalabels[2]  = MAX_POOL_CPU_USAGE_PCT
    datalabels[3]  = AVG_POOL_MEMORY_USAGE
    datalabels[4]  = MAX_POOL_MEMORY_USAGE
    datalabels[5]  = AVG_BUSY_SERVERS
    datalabels[6]  = MAX_BUSY_SERVERS
    datalabels[7]  = AVG_BUSY_SERVER_TIME
    datalabels[8]  = AVG_LOCKED_SERVERS
    datalabels[9]  = MAX_LOCKED_SERVERS
    datalabels[10] = AVG_LOCKED_SERVER_TIME
    datalabels[11] = SAMPLE_COUNT.
DEFINE VARIABLE i AS INTEGER.


fathom-report-title = "Server Activity".
RUN xml-report-header.
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


FOR EACH tmp-resrc:

    pgm-name = "serveractivity.p".
    sec-name = "Printing data to XML file for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    FIND FIRST Cf_Resrc WHERE tmp-resrc.tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.

    IF AVAILABLE Cf_Resrc THEN
    DO:
        ASSIGN
            xmlresourcename = Cf_Resrc.Resrc_Name 
            xmlresourcetype = Cf_Resrc.Resrc_Type 
            xmlresourcesite = Cf_Resrc.Site_ID.

        /* Setup the root header and data information. */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "resource",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        sec-name = "Writing out Root header - Label :" + 
                   xmlresourcename + ":" +
                   xmlresourcetype + ":" +
                   xmlresourcesite.
        {include/debug.i "pgm-name" "sec-name"}.

        RUN xml-root-header.
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Labels section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "labels",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        DO i = 1 TO EXTENT(datalabels):

            xmldataOutputlabel = datalabels[i].

                RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "label",
                           INPUT "",
                           INPUT "",
                           INPUT xmldataOutputlabel).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

        END.

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "labels").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Dates section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "times",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        DO fathom-x = 1 to Fathom-i-periods:

            xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
            xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
            xmlsampleenddate = Fathom-t-end-date[fathom-x].
            xmlsampleendtime = Fathom-t-end-time[fathom-x].
                
            RUN xml-process-date.
            RUN xml-add-data-timetable.
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

        END.

        IF Fathom-i-periods > 1 THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "time",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "name",
                           INPUT "",
                           INPUT "",
                           INPUT "Summary").
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "time").
        END.

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "times").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /* 
        ** Data Section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        FOR EACH data_store_server WHERE data_store_server.resID = tmp-resrc.tResrcID:

            DO i = 1 TO EXTENT(datalabels):

                xmldataOutputlabel = datalabels[i].
                xmldatalabel = datalabels[i].

                sec-name = "Writing out row header - Label :" + xmldatalabel.
                {include/debug.i "pgm-name" "sec-name"}.

                DO fathom-x = 1 to Fathom-i-periods:

                    /* For display units. */
                    CASE Fathom-i-intervaltype:
                        WHEN "S" THEN Fathom-store-value = data_store_server.numSeconds[Fathom-i].
                        WHEN "M" THEN Fathom-store-value = data_store_server.numSeconds[Fathom-i] / 60.
                        WHEN "H" THEN Fathom-store-value = data_store_server.numSeconds[Fathom-i] / 60 / 60.
                        OTHERWISE Fathom-store-value = 1.
                    END CASE.

                    /*
                    ** This preserves summary info when there are no samples in a period.
                    ** See 2003 08 13-018.
                    */
                    IF Fathom-store-value = 0 THEN Fathom-store-value = 1.

                    xmlsamplelength = STRING (data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING (data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    /* xmlsamplecount = STRING (Fathom-numsamples[fathom-x]). */
                    xmlsamplecount = STRING (data_store_server.numSamples[fathom-x]).

                    CASE datalabels[i]:

                        WHEN AVG_POOL_CPU_USAGE_PCT THEN
                        DO:
                            dataprecision = "2".
                            data_store_server.poolCPUAvg[fathom-x] = (data_store_server.poolCPUAvg[fathom-x] /
                                                                      data_store_server.poolCPUTime[fathom-x]) *
                                                                     100.
                            IF data_store_server.poolCPUAvg[fathom-x] = ? THEN
                                data_store_server.poolCPUAvg[fathom-x] = 0.
                            IF data_store_server.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_server.poolCPUAvg[fathom-x]).
                            END.
                        END.
                        WHEN MAX_POOL_CPU_USAGE_PCT THEN
                        DO:
                            dataprecision = "2".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_server.poolCPUMax[fathom-x] GT 0 AND
                                   data_store_server.poolCPUMax[fathom-x] GT data_store_server.summaryPoolCPUMax THEN 
                                DO:
                                    ASSIGN data_store_server.summaryPoolCPUMax = data_store_server.poolCPUMax[fathom-x].
                                END.
                                IF data_store_server.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_server.poolCPUMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN AVG_POOL_MEMORY_USAGE THEN
                        DO:
                            dataprecision = "2".
                            data_store_server.summaryPoolMemoryAvg = data_store_server.summaryPoolMemoryAvg +
                                                                     data_store_server.poolMemoryAvg[fathom-x].
                            data_store_server.poolMemoryAvg[fathom-x] = data_store_server.poolMemoryAvg[fathom-x] /
                                                                        data_store_server.numSystemSamples[fathom-x].
                            IF data_store_server.poolMemoryAvg[fathom-x] = ? THEN
                                data_store_server.poolMemoryAvg[fathom-x] = 0.
                            IF data_store_server.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_server.poolMemoryAvg[fathom-x]).
                            END.
                        END.
                        WHEN MAX_POOL_MEMORY_USAGE THEN
                        DO:
                            dataprecision = "2".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_server.poolMemoryMax[fathom-x] GT 0 AND
                                   data_store_server.poolMemoryMax[fathom-x] GT data_store_server.summaryPoolMemoryMax THEN 
                                DO:
                                    ASSIGN data_store_server.summaryPoolMemoryMax = data_store_server.poolMemoryMax[fathom-x].
                                END.
                                IF data_store_server.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_server.poolMemoryMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN AVG_BUSY_SERVERS THEN
                        DO:
                            dataprecision = "2".
                            data_store_server.summaryBusyServersAvg = data_store_server.summaryBusyServersAvg +
                                                                      data_store_server.busyServersAvg[fathom-x].
                            data_store_server.busyServersAvg[fathom-x] = data_store_server.busyServersAvg[fathom-x] /
                                                                         data_store_server.numSamples[fathom-x].
                            IF data_store_server.busyServersAvg[fathom-x] = ? THEN
                                data_store_server.busyServersAvg[fathom-x] = 0.
                            IF data_store_server.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_server.busyServersAvg[fathom-x]).
                            END.
                        END.
                        WHEN MAX_BUSY_SERVERS THEN
                        DO:
                            dataprecision = "0".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_server.busyServersMax[fathom-x] GT 0 AND
                                   data_store_server.busyServersMax[fathom-x] GT data_store_server.summaryBusyServersMax THEN 
                                DO:
                                    ASSIGN data_store_server.summaryBusyServersMax = data_store_server.busyServersMax[fathom-x].
                                END.
                                IF data_store_server.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_server.busyServersMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN AVG_BUSY_SERVER_TIME THEN
                        DO:
                            dataprecision = "0".
                            data_store_server.summaryBusyServerTime = data_store_server.summaryBusyServerTime +
                                                                      data_store_server.busyServerTime[fathom-x].
                            data_store_server.summaryBusyServerState = data_store_server.summaryBusyServerState +
                                                                       data_store_server.busyServerState[fathom-x].
                            data_store_server.busyServerTime[fathom-x] = data_store_server.busyServerTime[fathom-x] /
                                                                         data_store_server.busyServerState[fathom-x].
                            IF data_store_server.busyServerTime[fathom-x] = ? THEN
                                data_store_server.busyServerTime[fathom-x] = 0.
                            IF data_store_server.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_server.busyServerTime[fathom-x]).
                            END.
                        END.
                        WHEN AVG_LOCKED_SERVERS THEN
                        DO:
                            dataprecision = "2".
                            data_store_server.summaryLockedServersAvg = data_store_server.summaryLockedServersAvg +
                                                                        data_store_server.lockedServersAvg[fathom-x].
                            data_store_server.lockedServersAvg[fathom-x] = data_store_server.lockedServersAvg[fathom-x] /
                                                                           data_store_server.numSamples[fathom-x].
                            IF data_store_server.lockedServersAvg[fathom-x] = ? THEN
                                data_store_server.lockedServersAvg[fathom-x] = 0.
                            IF data_store_server.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_server.lockedServersAvg[fathom-x]).
                            END.
                        END.
                        WHEN MAX_LOCKED_SERVERS THEN
                        DO:
                            dataprecision = "0".
                            IF printMaxArray[fathom-x] = NO AND haveArchivedRecArray[fathom-x] = YES THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                IF data_store_server.lockedServersMax[fathom-x] GT 0 AND
                                   data_store_server.lockedServersMax[fathom-x] GT data_store_server.summaryLockedServersMax THEN 
                                DO:
                                    ASSIGN data_store_server.summaryLockedServersMax = data_store_server.lockedServersMax[fathom-x].
                                END.
                                IF data_store_server.numSamples[fathom-x] = 0 THEN
                                    xmldatavalue = NOT_AVAILABLE.
                                ELSE
                                DO:
                                    xmldatavalue = STRING(data_store_server.lockedServersMax[fathom-x]).
                                END.
                            END.
                        END.
                        WHEN AVG_LOCKED_SERVER_TIME THEN
                        DO:
                            dataprecision = "0".
                            data_store_server.summaryLockedServerTime = data_store_server.summaryLockedServerTime +
                                                                        data_store_server.lockedServerTime[fathom-x].
                            data_store_server.summaryLockedServerState = data_store_server.summaryLockedServerState +
                                                                         data_store_server.lockedServerState[fathom-x].
                            data_store_server.lockedServerTime[fathom-x] = data_store_server.lockedServerTime[fathom-x] /
                                                                           data_store_server.lockedServerState[fathom-x].
                            IF data_store_server.lockedServerTime[fathom-x] = ? THEN
                                data_store_server.lockedServerTime[fathom-x] = 0.
                            IF data_store_server.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store_server.lockedServerTime[fathom-x]).
                            END.
                        END.
                        WHEN SAMPLE_COUNT THEN
                        DO:
                            dataprecision = "0".
                            xmldatavalue = STRING(data_store_server.numSamples[fathom-x]).
                        END.
                        OTHERWISE
                            /* Should not happen as we just defined the array above. */
                            xmldatavalue = "".

                    END CASE.

                    RUN xml-process-date.  /* Subroutine to process the date. */
                    RUN xml-add-data.      /* Subroutine to process the datum. */
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".

                    IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 THEN
                    DO:

                        CASE datalabels[i]:

                            WHEN AVG_POOL_CPU_USAGE_PCT THEN
                            DO:
                                dataprecision = "2".
                                data_store_server.summaryPoolCPUAvg = (data_store_server.summaryPoolCPUAvg /
                                                                       data_store_server.summaryPoolCPUTime) *
                                                                      100.
                                IF data_store_server.summaryPoolCPUAvg = ? THEN
                                    data_store_server.summaryPoolCPUAvg = 0.
                                xmldatavalue = STRING(summaryPoolCPUAvg).
                            END.
                            WHEN MAX_POOL_CPU_USAGE_PCT THEN
                            DO:
                                dataprecision = "2".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_server.summaryPoolCPUMax).
                            END.
                            WHEN AVG_POOL_MEMORY_USAGE THEN
                            DO:
                                dataprecision = "2".
                                data_store_server.summaryPoolMemoryAvg = data_store_server.summaryPoolMemoryAvg /
                                                                         data_store_server.totSystemSamples.
                                IF data_store_server.summaryPoolMemoryAvg = ? THEN
                                    data_store_server.summaryPoolMemoryAvg = 0.
                                xmldatavalue = STRING(data_store_server.summaryPoolMemoryAvg).
                            END.
                            WHEN MAX_POOL_MEMORY_USAGE THEN
                            DO:
                                dataprecision = "2".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_server.summaryPoolMemoryMax).
                            END.
                            WHEN AVG_BUSY_SERVERS THEN
                            DO:
                                dataprecision = "2".
                                data_store_server.summaryBusyServersAvg = data_store_server.summaryBusyServersAvg /
                                                                          data_store_server.summaryNumSamples.
                                IF data_store_server.summaryBusyServersAvg = ? THEN
                                    data_store_server.summaryBusyServersAvg = 0.
                                xmldatavalue = STRING(data_store_server.summaryBusyServersAvg).
                            END.
                            WHEN MAX_BUSY_SERVERS THEN
                            DO:
                                dataprecision = "0".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_server.summaryBusyServersMax).
                            END.
                            WHEN AVG_BUSY_SERVER_TIME THEN
                            DO:
                                dataprecision = "0".
                                data_store_server.summaryBusyServerTime = data_store_server.summaryBusyServerTime /
                                                                          data_store_server.summaryBusyServerState.
                                IF data_store_server.summaryBusyServerTime = ? THEN
                                    data_store_server.summaryBusyServerTime = 0.
                                xmldatavalue = STRING(data_store_server.summaryBusyServerTime).
                            END.
                            WHEN AVG_LOCKED_SERVERS THEN
                            DO:
                                dataprecision = "2".
                                data_store_server.summaryLockedServersAvg = data_store_server.summaryLockedServersAvg /
                                                                            data_store_server.summaryNumSamples.
                                IF data_store_server.summaryLockedServersAvg = ? THEN
                                    data_store_server.summaryLockedServersAvg = 0.
                                xmldatavalue = STRING(data_store_server.summaryLockedServersAvg).
                            END.
                            WHEN MAX_LOCKED_SERVERS THEN
                            DO:
                                dataprecision = "0".
                                IF printMax = NO AND haveArchivedRec = YES THEN
                                    xmldatavalue = "N/A".
                                ELSE
                                    xmldatavalue = STRING(data_store_server.summaryLockedServersMax).
                            END.
                            WHEN AVG_LOCKED_SERVER_TIME THEN
                            DO:
                                dataprecision = "0".
                                data_store_server.summaryLockedServerTime = data_store_server.summaryLockedServerTime /
                                                                            data_store_server.summaryLockedServerState.
                                IF data_store_server.summaryLockedServerTime = ? THEN
                                    data_store_server.summaryLockedServerTime = 0.
                                xmldatavalue = STRING(data_store_server.summaryLockedServerTime).
                            END.
                            WHEN SAMPLE_COUNT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store_server.summaryNumSamples).
                            END.
                            OTHERWISE
                                /* Should not happen as we just defined the array above. */
                                xmldatavalue = "".
    
                        END CASE.

                        RUN xml-add-data-summary.
                        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                        streamdetail = "".

                    END. /* IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 */

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

            END. /* DO i = 1 TO EXTENT(datalabels): */

        END. /* FOR EACH data_store */

        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "dataset").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
   
    END. /* IF AVAILABLE Cf_Resrc */

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "resource").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

END. /* FOR EACH tmp-resrc */



/*
** Print out the graph xml file.
**  We do this in a separate loop so that we can limit the
**  number of brokers put on the graph.  We have to know
**  the top x brokers that have the highest average busy servers, etc.
*/
numGraphResources = INTEGER(OS-GETENV("fathomResourcesPerGraph")) NO-ERROR.
DEFINE VARIABLE graph AS CHARACTER.
DEFINE VARIABLE isgraphed AS LOGICAL INITIAL NO.

IF numGraphResources = ? THEN
DO:
   numGraphResources = defaultNumGraphResources.
END.


DO x-i = 1 TO NUM-ENTRIES(xmlGraphColumns, ","):
    graph = TRIM(ENTRY(x-i, xmlGraphColumns, ",")) NO-ERROR.

    CASE graph:
        WHEN "none" THEN LEAVE.
        WHEN AVG_POOL_CPU_USAGE_PCT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + AVG_POOL_CPU_USAGE_PCT.
            xmlgraph-imagetitle = "poolcpuavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "1".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryPoolCPUAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_server.poolCPUAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_POOL_CPU_USAGE_PCT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + MAX_POOL_CPU_USAGE_PCT.
            xmlgraph-imagetitle = "poolcpumax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "2".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryPoolCPUMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_server.poolCPUMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_POOL_MEMORY_USAGE THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + AVG_POOL_MEMORY_USAGE.
            xmlgraph-imagetitle = "poolmemoryavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "3".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryPoolMemoryAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_server.poolMemoryAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_POOL_MEMORY_USAGE THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + MAX_POOL_MEMORY_USAGE.
            xmlgraph-imagetitle = "poolmemorymax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "4".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryPoolMemoryMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_server.poolMemoryMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_BUSY_SERVERS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + AVG_BUSY_SERVERS.
            xmlgraph-imagetitle = "busyservercountavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "5".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryBusyServersAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_server.busyServersAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_BUSY_SERVERS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + MAX_BUSY_SERVERS.
            xmlgraph-imagetitle = "busyservercountmax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "6".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryBusyServersMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_server.busyServersMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_BUSY_SERVER_TIME THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: Average Busy Server Time (ms)".
            xmlgraph-imagetitle = "busyservertimeavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "7".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryBusyServerTime DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_server.busyServerTime[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_LOCKED_SERVERS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + AVG_LOCKED_SERVERS.
            xmlgraph-imagetitle = "lockedservercountavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "8".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryLockedServersAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_server.lockedServersAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN MAX_LOCKED_SERVERS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + MAX_LOCKED_SERVERS.
            xmlgraph-imagetitle = "lockedservercountmax.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "9".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryLockedServersMax DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    IF printMaxArray[fathom-x] = NO THEN
                        xmldatavalue = "N/A".
                    ELSE
                        xmldatavalue = STRING(data_store_server.lockedServersMax[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.
        WHEN AVG_LOCKED_SERVER_TIME THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + AVG_LOCKED_SERVER_TIME.
            xmlgraph-imagetitle = "lockedservertimeavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "10".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryLockedServerTime DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_server.lockedServerTime[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN SAMPLE_COUNT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "Server Activity: " + SAMPLE_COUNT.
            xmlgraph-imagetitle = "samplecount.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "11".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store_server BY summaryNumSamples DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store_server.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store_server.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store_server.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store_server.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store_server.numSamples[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

    END CASE.

    IF isgraphed = YES THEN
    DO:
        isgraphed = NO.
        RUN xml-graphspec-end.
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
    END.

END.



pgm-name = "serveractivity.p".
sec-name = "Finished server section of graph XML file.".
{include/debug.i "pgm-name" "sec-name"}.




pgm-name = "serveractivity.p".
sec-name = "Exiting Program.".
{include/debug.i "pgm-name" "sec-name"}.
/*
** wsprofile.p
**
** This program will gather data on procedures that brokers have run.
**
*/

{include/definitions.i "NEW SHARED"}.

DEFINE NEW SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name                  AS CHARACTER
    FIELD brokerName            AS CHARACTER
    FIELD brokerPID             AS INTEGER
    FIELD brokerUUID            AS CHARACTER
    FIELD numSeconds            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD numSamples            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD runCount              AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqTotTime            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqDurationAvg        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryNumSamples     AS DECIMAL
    FIELD summaryRunCount       AS DECIMAL
    FIELD summaryReqDurationAvg AS DECIMAL
    INDEX one Name.


pgm-name = "wsprofile.p".
sec-name = "Starting program.".
{include/debug.i "pgm-name" "sec-name"}.

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}.

    {include/passinput.i}.
END.

/* Set up date buckets in the temp table. */
{include/trenddates.i}.

{include/report-name.i}.

/*
** Read samples and process them into the report table.
*/
pgm-name = "wsprofile.p".
sec-name = "Processing Samples".

{include/debug.i "pgm-name" "sec-name"}.

sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}.
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}.


pgm-name = "wsprofile.p".
sec-name = "Starting data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/* For use in determining which procedures to report on. */
DEFINE VARIABLE Procedure-filter AS CHARACTER NO-UNDO.
Procedure-filter = OS-GETENV("fathomReportProcedureFilter").

DEFINE VARIABLE Procedure-filter-type AS CHARACTER NO-UNDO.
Procedure-filter-type = OS-GETENV("fathomReportProcedureFilterType").

/* For 'matches'. */
DEFINE VARIABLE subprocfilter AS CHARACTER NO-UNDO.
DEFINE VARIABLE procfilter-index AS INTEGER NO-UNDO.

/* For query. */
DEFINE VARIABLE qh          AS WIDGET-HANDLE.
DEFINE VARIABLE matchstring AS CHARACTER NO-UNDO.


/*
** Get data from trend database.
*/
pgm-name = "wsprofile.p".
sec-name = "Starting data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** Set up the query expression.
*/
CASE Procedure-filter-type:

    WHEN "begins" THEN
    DO:
        pgm-name = "wsprofile.p".
        sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
        {include/debug.i "pgm-name" "sec-name"}.

        matchstring = "OE_ActWSProc.ActWSProc_Name BEGINS ~"" + Procedure-filter + "~" ".

    END. /* WHEN "begins" */

    WHEN "matches" THEN
    DO:
        pgm-name = "wsprofile.p".
        sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
        {include/debug.i "pgm-name" "sec-name"}.

        matchstring = "(".
        
        DO procfilter-index = 1 TO NUM-ENTRIES(Procedure-filter, "|"):
            subprocfilter = TRIM(ENTRY(procfilter-index, Procedure-filter, "|")) NO-ERROR.
            matchstring = matchstring + "OE_ActWSProc.ActWSProc_Name MATCHES ~"" + subprocfilter + "~" OR ".
        END.

        IF LENGTH(matchstring) GT 4 THEN
            matchstring = SUBSTRING(matchstring, 1, LENGTH(matchstring) - 4) + ") ".
        ELSE
            matchstring = "".

    END. /* WHEN "matches" */

    OTHERWISE
    DO:
        /* Literal is the default if the value isn't set. */
        IF Procedure-filter-type NE "literal" THEN
        DO:
            pgm-name = "wsprofile.p".
            sec-name = "fathomReportProcedureFilterType not set, defaulting to literal.".
            {include/debug.i "pgm-name" "sec-name"}.
        END.
        ELSE
        DO:
            pgm-name = "wsprofile.p".
            sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
            {include/debug.i "pgm-name" "sec-name"}.
        END.

        matchstring = "OE_ActWSProc.ActWSProc_Name EQ ~"" + Procedure-filter + "~" ".

    END. /* OTHERWISE */

END CASE.

CREATE QUERY qh.
qh:SET-BUFFERS(BUFFER OE_ActWSProc:HANDLE).


/*
** Get the data.
*/
FOR EACH tmp-resrc:

    pgm-name = "wsprofile.p".
    sec-name = "Gathering data for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    Fathom-i-Resrc_ID = tmp-resrc.tresrcID.
        
    {include/sample-query.i}
                    
        {include/setup-i.i}.

        qh:QUERY-PREPARE("FOR EACH OE_ActWSProc WHERE " +
                         STRING(Cf_Sample.Sample_ID) + " EQ OE_ActWSProc.Sample_ID " + " AND " +
                         matchstring).
        qh:QUERY-OPEN().

        REPEAT:
            qh:GET-NEXT.
            IF qh:QUERY-OFF-END THEN LEAVE.
        
            {include/fathom-counters.i}.

            FIND FIRST data_store WHERE data_store.brokerUUID = OE_ActWSProc.ActBrk_UUID AND
                                        data_store.Name = OE_ActWSProc.ActWSProc_Name NO-ERROR. /* AND
                                        data_store.brokerName = tmp-resrc.tResrcName NO-ERROR. */
                    
            IF NOT AVAILABLE data_store THEN
            DO:
                CREATE data_store.
                ASSIGN
                    data_store.Name = OE_ActWSProc.ActWSProc_Name
                    data_store.brokerName = tmp-resrc.tResrcName
                    data_store.brokerPID = OE_ActWSProc.ActBrk_PID
                    data_store.brokerUUID = OE_ActWSProc.ActBrk_UUID.
            END.
                
            /* Run Count, Average Request Duration, and Return Codes. */
            ASSIGN
                data_store.runCount[Fathom-i] = data_store.runCount[Fathom-i] +
                                                OE_ActWSProc.ActWSProc_Calls
                data_store.reqTotTime[Fathom-i] = data_store.reqTotTime[Fathom-i] +
                                                  OE_ActWSProc.ActWSProc_TotTime
                data_store.numSeconds[Fathom-i] = data_store.numSeconds[Fathom-i] +
                                                  Cf_Sample.Sample_len
                data_store.numSamples[Fathom-i] = data_store.numSamples[Fathom-i] + 1.

        END. /* of REPEAT. */

        IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
        ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = cf_sample.sample_date.
        
    END. /* {include/sample-query.i} => FOR EACH Cf_Sample */
        
END. /* FOR EACH tmp-resrc */

qh:QUERY-CLOSE().
DELETE OBJECT qh.

pgm-name = "wsprofile.p".
sec-name = "Exiting data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** Process archive records if the need arises to do so.
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "wsprofile.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}.

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}.

IF Fathom-ar-date GT Fathom-i-start_date THEN
DO:
    pgm-name = "wsprofile.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    /*
    ** Set up the query expression.
    */
    CASE Procedure-filter-type:
        WHEN "begins" THEN
        DO:
            pgm-name = "wsprofile.p".
            sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
            {include/debug.i "pgm-name" "sec-name"}.

            matchstring = "Ar_OE_ActWSProc.ActWSProc_Name BEGINS ~"" + Procedure-filter + "~" ".

        END. /* WHEN "begins" */
    
        WHEN "matches" THEN
        DO:
            pgm-name = "wsprofile.p".
            sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
            {include/debug.i "pgm-name" "sec-name"}.

            matchstring = "(".
        
            DO procfilter-index = 1 TO NUM-ENTRIES(Procedure-filter, "|"):
                subprocfilter = TRIM(ENTRY(procfilter-index, Procedure-filter, "|")) NO-ERROR.
                matchstring = matchstring + "Ar_OE_ActWSProc.ActWSProc_Name MATCHES ~"" + subprocfilter + "~" OR ".
            END.

            IF LENGTH(matchstring) GT 4 THEN
                matchstring = SUBSTRING(matchstring, 1, LENGTH(matchstring) - 4) + ") ".
            ELSE
                matchstring = "".

        END. /* WHEN "matches" */

        OTHERWISE
        DO:
            /* Literal is the default if the value isn't set. */
            IF Procedure-filter-type NE "literal" THEN
            DO:
                pgm-name = "wsprofile.p".
                sec-name = "fathomReportProcedureFilterType not set, defaulting to literal.".
                {include/debug.i "pgm-name" "sec-name"}.
            END.
            ELSE
            DO:
                pgm-name = "wsprofile.p".
                sec-name = "fathomReportProcedureFilterType: " + Procedure-filter-type + ".".
                {include/debug.i "pgm-name" "sec-name"}.
            END.

            matchstring = "Ar_OE_ActWSProc.ActWSProc_Name EQ ~"" + Procedure-filter + "~" ".

        END. /* OTHERWISE */

    END CASE.

    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_OE_ActWSProc:HANDLE).

    /*
    ** Get the data.
    */
    FOR EACH tmp-resrc:

        pgm-name = "wsprofile.p".
        sec-name = "Gathering archive data for resource: " + tmp-resrc.tResrcName + ".".
        {include/debug.i "pgm-name" "sec-name"}.

        qh:QUERY-PREPARE("FOR EACH Ar_OE_ActWSProc WHERE " +
                         "Ar_OE_ActWSProc.Resrc_ID EQ " + STRING(tmp-resrc.tResrcID) + " AND " +
                         "Ar_OE_ActWSProc.Site_ID EQ ~"" + tmp-resrc.tSiteID + "~" AND " +
                         "Ar_OE_ActWSProc.ActWSProc_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                         "Ar_OE_ActWSProc.ActWSProc_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                         "Ar_OE_ActWSProc.ActWSProc_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                         "Ar_OE_ActWSProc.ActWSProc_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                         "Ar_OE_ActWSProc.ActWSProc_ArchiveType EQ ~"" + archiveType + "~" " + " AND " +
                         matchstring).
        qh:QUERY-OPEN().

        REPEAT:
            qh:GET-NEXT.
            IF qh:QUERY-OFF-END THEN LEAVE.

            Fathom-i = 0.
            REPEAT:
                Fathom-i = Fathom-i + 1.
                IF Ar_OE_ActWSProc.ActWSProc_StartDate GE Fathom-t-beg-date[Fathom-i] AND
                    Ar_OE_ActWSProc.ActWSProc_StartDate LE Fathom-t-end-date[Fathom-i] THEN
                DO:
                    IF Ar_OE_ActWSProc.ActWSProc_starttime GE Fathom-t-beg-time[Fathom-i] AND
                        Ar_OE_ActWSProc.ActWSProc_starttime LE Fathom-t-end-time[Fathom-i] THEN
                        LEAVE.
                END.
                IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
            END.
        
            FIND FIRST data_store WHERE data_store.brokerUUID = Ar_OE_ActWSProc.ActBrk_UUID AND
                                        data_store.Name = Ar_OE_ActWSProc.ActWSProc_Name NO-ERROR. /* AND
                                        data_store.brokerName = tmp-resrc.tResrcName NO-ERROR. */
                    
            IF NOT AVAILABLE data_store THEN
            DO:
                CREATE data_store.
                ASSIGN
                    data_store.Name = Ar_OE_ActWSProc.ActWSProc_Name
                    data_store.brokerName = tmp-resrc.tResrcName
                    data_store.brokerPID = Ar_OE_ActWSProc.ActBrk_PID
                    data_store.brokerUUID = Ar_OE_ActWSProc.ActBrk_UUID.
            END.
                
            /* Run Count, Average Request Duration, and Return Codes. */
            ASSIGN
                data_store.runCount[Fathom-i] = data_store.runCount[Fathom-i] +
                                                Ar_OE_ActWSProc.ActWSProc_Calls
                data_store.reqTotTime[Fathom-i] = data_store.reqTotTime[Fathom-i] +
                                                  Ar_OE_ActWSProc.ActWSProc_TotTime
                data_store.numSeconds[Fathom-i] = data_store.numSeconds[Fathom-i] +
                                                  Ar_OE_ActWSProc.ActWSProc_Length
                data_store.numSamples[Fathom-i] = data_store.numSamples[Fathom-i] +
                                                  Ar_OE_ActWSProc.ActWSProc_RecordCount
                Fathom-Rec-Count = Fathom-Rec-Count + Ar_OE_ActWSProc.ActWSProc_RecordCount
                Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] +
                                                 Ar_OE_ActWSProc.ActWSProc_RecordCount.

        END. /* of REPEAT. */

    END. /* FOR EACH tmp-resrc: */

END. /* IF fathom-ar-date GT fathom-i-start_date */

pgm-name = "wsprofile.p".
sec-name = "Exiting archive data collection.".
{include/debug.i "pgm-name" "sec-name"}.


/*
** Print to xml file.
*/
RUN openedge/xml-wsprofile.p.


pgm-name = "wsprofile.p".
sec-name = "Exiting program.".
{include/debug.i "pgm-name" "sec-name"}.
/*
** xml-asprofile.p
**
** Print data to xml files.
**
*/

{include/definitions.i "SHARED"}.
{include/xmldefinitions.i "NEW SHARED"}.
{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}.
{include/xmlinitialize.i}.

DEFINE SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name                     AS CHARACTER
    FIELD brokerName               AS CHARACTER
    FIELD brokerPID                AS INTEGER
    FIELD brokerUUID               AS CHARACTER
    FIELD procedureType            AS CHARACTER
    FIELD numSamples               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD numSeconds               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD runCount                 AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqTotTime               AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqDurationAvg           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeSuccess        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeError          AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeQuit           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD returnCodeStop           AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryNumSamples        AS DECIMAL
    FIELD summaryRunCount          AS DECIMAL
    FIELD summaryReqDurationAvg    AS DECIMAL
    FIELD summaryReturnCodeSuccess AS DECIMAL
    FIELD summaryReturnCodeError   AS DECIMAL
    FIELD summaryReturnCodeQuit    AS DECIMAL
    FIELD summaryReturnCodeStop    AS DECIMAL
    INDEX one Name.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.


pgm-name = "xml-asprofile.p".
sec-name = "Initializing XML files.".
{include/debug.i "pgm-name" "sec-name"}.

Fathom-report-title = "AppServer Profile".
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
  
pgm-name = "xml-asprofile.p".
sec-name = "Completed initialization of XML files.".
{include/debug.i "pgm-name" "sec-name"}.

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

IF Fathom-Rec-Count LT 1 THEN
DO:
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for the AppServer profile report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    pgm-name = "xml-asprofile.p".
    sec-name = "No samples - finishing XML files.".
    {include/debug.i "pgm-name" "sec-name"}.
    
    /* Every sub-report has put data into the xml file, close. */
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /* Close up the graphing stuff. */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
    {include/xmlcleanup.i}.
    {include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}.

    RETURN.
END.


DEFINE VARIABLE datalabels AS CHARACTER EXTENT 7.
ASSIGN
    datalabels[1] = RUN_COUNT
    datalabels[2] = AVG_REQ_DURATION
    datalabels[3] = RETURN_CODE_SUCCESS
    datalabels[4] = RETURN_CODE_ERROR
    datalabels[5] = RETURN_CODE_QUIT
    datalabels[6] = RETURN_CODE_STOP
    datalabels[7] = SAMPLE_COUNT.
DEFINE VARIABLE i AS INTEGER.


/* Setup the root header and data information. */
RUN xml-report-header.
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


FOR EACH tmp-resrc:

    pgm-name = "xml-asprofile.p".
    sec-name = "Printing data to XML file for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    FIND FIRST Cf_Resrc WHERE tmp-resrc.tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.

    IF AVAILABLE Cf_Resrc THEN
    DO:
        ASSIGN
            xmlresourcename = Cf_Resrc.Resrc_Name 
            xmlresourcetype = Cf_Resrc.Resrc_Type 
            xmlresourcesite = Cf_Resrc.Site_ID.

        /* Setup the root header and data information. */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "resource",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        sec-name = "Writing out Root header - Label :" + 
                   xmlresourcename + ":" +
                   xmlresourcetype + ":" +
                   xmlresourcesite.
        {include/debug.i "pgm-name" "sec-name"}.

        RUN xml-root-header.
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Labels section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "labels",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        DO i = 1 TO EXTENT(datalabels):
        
            xmldataOutputlabel = datalabels[i].
        
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "label",
                           INPUT "",
                           INPUT "",
                           INPUT xmldataOutputlabel).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        END.
        
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "labels").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        
        /*
        ** Dates section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "times",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        DO fathom-x = 1 TO Fathom-i-periods:
        
            xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
            xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
            xmlsampleenddate = Fathom-t-end-date[fathom-x].
            xmlsampleendtime = Fathom-t-end-time[fathom-x].
                        
            RUN xml-process-date.
            RUN xml-add-data-timetable.
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
        END.

        IF Fathom-i-periods > 1 THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "time",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "name",
                           INPUT "",
                           INPUT "",
                           INPUT "Summary").
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "time").
        END.
        
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "times").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        
        /* 
        ** Data Section.
        */
        FOR EACH data_store WHERE data_store.brokerName = tmp-resrc.tResrcName:
        
            pgm-name = "xml-asprofile.p".
            sec-name = "Writing procedure info to XML file - Name: " + data_store.Name.
            {include/debug.i "pgm-name" "sec-name"}.
        
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "procedure",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "procedureName",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.Name).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "procedureType",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.procedureType).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "brokerName",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.brokerName).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "brokerPID",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.brokerPID).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "brokerUUID",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.brokerUUID).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
    
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "dataset",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
        
            DO i = 1 TO EXTENT(datalabels):
        
                xmldataOutputlabel = datalabels[i].
                xmldatalabel = data_store.Name.

                DO fathom-x = 1 to Fathom-i-periods:

                    /* For display units. */
                    CASE Fathom-i-intervaltype:
                        WHEN "S" THEN Fathom-store-value = data_store.numSeconds[fathom-x].
                        WHEN "M" THEN Fathom-store-value = data_store.numSeconds[fathom-x] / 60.
                        WHEN "H" THEN Fathom-store-value = data_store.numSeconds[fathom-x] / 60 / 60.
                        OTHERWISE Fathom-store-value = 1.
                    END CASE.

                    /*
                    ** This preserves summary info when there are no samples in a period.
                    ** See 2003 08 13-018.
                    */
                    IF Fathom-store-value = 0 THEN Fathom-store-value = 1.

                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
        
                    CASE datalabels[i]:
        
                        WHEN RUN_COUNT THEN
                        DO:
                            dataprecision = "0".
                            data_store.runCount[fathom-x] = data_store.runCount[fathom-x] /
                                                            Fathom-store-value.
                            IF data_store.runCount[fathom-x] = ? THEN
                                data_store.runCount[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.runCount[fathom-x]).
                                data_store.summaryRunCount = data_store.summaryRunCount +
                                                             data_store.runCount[fathom-x].
                            END.
                        END.
                        WHEN AVG_REQ_DURATION THEN
                        DO:
                            dataprecision = "0".
                            data_store.reqTotTime[fathom-x] = data_store.reqTotTime[fathom-x] /
                                                              Fathom-store-value.
                            data_store.reqDurationAvg[fathom-x] = data_store.reqTotTime[fathom-x] /
                                                                  data_store.runCount[fathom-x].
                            data_store.summaryReqDurationAvg = data_store.summaryReqDurationAvg +
                                                               data_store.reqTotTime[fathom-x].
                            IF data_store.reqDurationAvg[fathom-x] = ? THEN
                                data_store.reqDurationAvg[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.reqDurationAvg[fathom-x]).
                            END.
                        END.
                        WHEN RETURN_CODE_SUCCESS THEN
                        DO:
                            dataprecision = "0".
                            data_store.returnCodeSuccess[fathom-x] = data_store.returnCodeSuccess[fathom-x] /
                                                                     Fathom-store-value.
                            IF data_store.returnCodeSuccess[fathom-x] = ? THEN
                                data_store.returnCodeSuccess[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.returnCodeSuccess[fathom-x]).
                                data_store.summaryReturnCodeSuccess = data_store.summaryReturnCodeSuccess +
                                                                      data_store.returnCodeSuccess[fathom-x].
                            END.
                        END.
                        WHEN RETURN_CODE_ERROR THEN
                        DO:
                            dataprecision = "0".
                            data_store.returnCodeError[fathom-x] = data_store.returnCodeError[fathom-x] /
                                                                   Fathom-store-value.
                            IF data_store.returnCodeError[fathom-x] = ? THEN
                                data_store.returnCodeError[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.returnCodeError[fathom-x]).
                                data_store.summaryReturnCodeError = data_store.summaryReturnCodeError +
                                                                    data_store.returnCodeError[fathom-x].
                            END.
                        END.
                        WHEN RETURN_CODE_QUIT THEN
                        DO:
                            dataprecision = "0".
                            data_store.returnCodeQuit[fathom-x] = data_store.returnCodeQuit[fathom-x] /
                                                                  Fathom-store-value.
                            IF data_store.returnCodeQuit[fathom-x] = ? THEN
                                data_store.returnCodeQuit[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.returnCodeQuit[fathom-x]).
                                data_store.summaryReturnCodeQuit = data_store.summaryReturnCodeQuit +
                                                                   data_store.returnCodeQuit[fathom-x].
                            END.
                        END.
                        WHEN RETURN_CODE_STOP THEN
                        DO:
                            dataprecision = "0".
                            data_store.returnCodeStop[fathom-x] = data_store.returnCodeStop[fathom-x] /
                                                                  Fathom-store-value.
                            IF data_store.returnCodeStop[fathom-x] = ? THEN
                                data_store.returnCodeStop[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.returnCodeStop[fathom-x]).
                                data_store.summaryReturnCodeStop = data_store.summaryReturnCodeStop +
                                                                   data_store.returnCodeStop[fathom-x].
                            END.
                        END.
                        WHEN SAMPLE_COUNT THEN
                        DO:
                            dataprecision = "0".
                            data_store.summaryNumSamples = data_store.summaryNumSamples +
                                                           data_store.numSamples[fathom-x].
                            xmldatavalue = STRING(data_store.numSamples[fathom-x]).
                        END.
                        OTHERWISE
                            /* Should not happen as we just defined the array above. */
                            xmldatavalue = "".
        
                    END CASE.
        
                    RUN xml-process-date.
                    RUN xml-add-data.
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".

                    IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 THEN
                    DO:
                        /* Add summary information to xml file. */
                        CASE datalabels[i]:
            
                            WHEN RUN_COUNT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryRunCount).
                            END.
                            WHEN AVG_REQ_DURATION THEN
                            DO:
                                dataprecision = "0".
                                data_store.summaryReqDurationAvg = data_store.summaryReqDurationAvg /
                                                                   data_store.summaryRunCount.
                                IF data_store.summaryReqDurationAvg = ? THEN
                                    data_store.summaryReqDurationAvg = 0.
                                xmldatavalue = STRING(data_store.summaryReqDurationAvg).
                            END.
                            WHEN RETURN_CODE_SUCCESS THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryReturnCodeSuccess).
                            END.
                            WHEN RETURN_CODE_ERROR THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryReturnCodeError).
                            END.
                            WHEN RETURN_CODE_QUIT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryReturnCodeQuit).
                            END.
                            WHEN RETURN_CODE_STOP THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryReturnCodeStop).
                            END.
                            WHEN SAMPLE_COUNT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryNumSamples).
                            END.
                            OTHERWISE
                                /* Should not happen as we just defined the array above. */
                                xmldatavalue = "".
            
                        END CASE.

                        RUN xml-add-data-summary.
                        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                        streamdetail = "".

                    END. /* IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 */
        
                END. /* DO fathom-x = 1 to Fathom-i-periods: */

            END. /* DO i = 1 TO EXTENT(datalabels): */
        
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "dataset").
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "procedure").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
    
        END. /* FOR EACH data_store */

    END. /* IF AVAILABLE Cf_Resrc */

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "resource").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

END. /* FOR EACH tmp-resrc */


pgm-name = "xml-asprofile.p".
sec-name = "Finishing data XML file.".
{include/debug.i "pgm-name" "sec-name"}.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "report").
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".




/*
** Print out the graph xml file.
**  We do this in a separate loop so that we can limit the
**  number of procedures put on the graph.  We have to know
**  the top x procedures that have the highest run count, etc.
*/
xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
numGraphResources = INTEGER(OS-GETENV("fathomResourcesPerGraph")) NO-ERROR.
DEFINE VARIABLE graph AS CHARACTER.
DEFINE VARIABLE isgraphed AS LOGICAL INITIAL NO.

IF numGraphResources = ? THEN
DO:
   numGraphResources = defaultNumGraphResources.
END.

IF xmlGraphColumns = ? THEN
DO:
   {include/xml-graphcolumns.i}.
END.

DO x-i = 1 TO NUM-ENTRIES(xmlGraphColumns, ","):
    graph = TRIM(ENTRY(x-i, xmlGraphColumns, ",")) NO-ERROR.

    CASE graph:
        WHEN "none" THEN LEAVE.

        WHEN RUN_COUNT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "AppServer Profile: " + RUN_COUNT.
            xmlgraph-imagetitle = "runcount.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "1".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryRunCount DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.runCount[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN AVG_REQ_DURATION THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "AppServer Profile: " + AVG_REQ_DURATION.
            xmlgraph-imagetitle = "reqdurationavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "2".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryReqDurationAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.reqDurationAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN RETURN_CODE_SUCCESS THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "AppServer Profile: " + RETURN_CODE_SUCCESS.
            xmlgraph-imagetitle = "returncodesuccess.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "3".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryReturnCodeSuccess DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.returnCodeSuccess[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN RETURN_CODE_ERROR THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "AppServer Profile: " + RETURN_CODE_ERROR.
            xmlgraph-imagetitle = "returncodeerror.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "4".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryReturnCodeError DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.returnCodeError[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN RETURN_CODE_QUIT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "AppServer Profile: " + RETURN_CODE_QUIT.
            xmlgraph-imagetitle = "returncodequit.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "5".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryReturnCodeQuit DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.returnCodeQuit[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN RETURN_CODE_STOP THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "AppServer Profile: " + RETURN_CODE_STOP.
            xmlgraph-imagetitle = "returncodestop.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "6".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryReturnCodeStop DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.returnCodeStop[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN SAMPLE_COUNT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "AppServer Profile: " + SAMPLE_COUNT.
            xmlgraph-imagetitle = "samplecount.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "7".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryNumSamples DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.numSamples[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

    END CASE.

    IF isgraphed = YES THEN
    DO:
        isgraphed = NO.
        RUN xml-graphspec-end.
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
    END.

END.



pgm-name = "xml-asprofile.p".
sec-name = "Finishing graph XML file.".
{include/debug.i "pgm-name" "sec-name"}.

/* Close up the graphing stuff. */
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}.
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}.

pgm-name = "xml-asprofile.p".
sec-name = "XML files complete.".
{include/debug.i "pgm-name" "sec-name"}.
/*
** xml-wsprofile.p
**
** Print data to xml files.
**
*/

{include/definitions.i "SHARED"}.
{include/xmldefinitions.i "NEW SHARED"}.
{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}.
{include/xmlinitialize.i}.

DEFINE SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name                  AS CHARACTER
    FIELD brokerName            AS CHARACTER
    FIELD brokerPID             AS INTEGER
    FIELD brokerUUID            AS CHARACTER
    FIELD numSeconds            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD numSamples            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD runCount              AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqTotTime            AS DECIMAL EXTENT 366 INITIAL 0
    FIELD reqDurationAvg        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD summaryNumSamples     AS DECIMAL
    FIELD summaryRunCount       AS DECIMAL
    FIELD summaryReqDurationAvg AS DECIMAL
    INDEX one Name.

DEFINE VARIABLE Fathom-store-value AS DECIMAL NO-UNDO.

pgm-name = "xml-wsprofile.p".
sec-name = "Initializing XML files.".
{include/debug.i "pgm-name" "sec-name"}.

Fathom-report-title = "WebSpeed Profile".
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
  
pgm-name = "xml-wsprofile.p".
sec-name = "Completed initialization of XML files.".
{include/debug.i "pgm-name" "sec-name"}.

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

IF Fathom-Rec-Count LT 1 THEN
DO:
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for the WebSpeed profile report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    pgm-name = "xml-wsprofile.p".
    sec-name = "No samples - finishing XML files.".
    {include/debug.i "pgm-name" "sec-name"}.
    
    /* Every sub-report has put data into the xml file, close. */
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /* Close up the graphing stuff. */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
    {include/xmlcleanup.i}.
    {include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}.

    RETURN.
END.


DEFINE VARIABLE datalabels AS CHARACTER EXTENT 3.
ASSIGN
    datalabels[1] = RUN_COUNT
    datalabels[2] = AVG_REQ_DURATION
    datalabels[3] = SAMPLE_COUNT.
DEFINE VARIABLE i AS INTEGER.


/* Setup the root header and data information. */
RUN xml-report-header.
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


FOR EACH tmp-resrc:

    pgm-name = "xml-wsprofile.p".
    sec-name = "Printing data to XML file for resource: " + tmp-resrc.tResrcName + ".".
    {include/debug.i "pgm-name" "sec-name"}.

    FIND FIRST Cf_Resrc WHERE tmp-resrc.tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.

    IF AVAILABLE Cf_Resrc THEN
    DO:
        ASSIGN
            xmlresourcename = Cf_Resrc.Resrc_Name 
            xmlresourcetype = Cf_Resrc.Resrc_Type 
            xmlresourcesite = Cf_Resrc.Site_ID.

        /* Setup the root header and data information. */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "resource",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

        sec-name = "Writing out Root header - Label :" + 
                   xmlresourcename + ":" +
                   xmlresourcetype + ":" +
                   xmlresourcesite.
        {include/debug.i "pgm-name" "sec-name"}.

        RUN xml-root-header.
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".


        /*
        ** Labels section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "labels",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        DO i = 1 TO EXTENT(datalabels):
        
            xmldataOutputlabel = datalabels[i].
        
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "label",
                           INPUT "",
                           INPUT "",
                           INPUT xmldataOutputlabel).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        END.
        
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "labels").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        
        /*
        ** Dates section.
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "times",
                            INPUT "",
                            INPUT "",
                            INPUT "").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        DO fathom-x = 1 to Fathom-i-periods:
        
            xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
            xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
            xmlsampleenddate = Fathom-t-end-date[fathom-x].
            xmlsampleendtime = Fathom-t-end-time[fathom-x].
                        
            RUN xml-process-date.       /* Subroutine to process the date. */
            RUN xml-add-data-timetable. /* Subroutine to process the datum. */
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
        END.

        IF Fathom-i-periods > 1 THEN
        DO:
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "time",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "name",
                           INPUT "",
                           INPUT "",
                           INPUT "Summary").
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "time").
        END.
        
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "times").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        
        
        /* 
        ** Data Section.
        */
        FOR EACH data_store WHERE data_store.brokerName = tmp-resrc.tResrcName:
        
            pgm-name = "xml-wsprofile.p".
            sec-name = "Writing procedure info to XML file - Name: " + data_store.Name.
            {include/debug.i "pgm-name" "sec-name"}.
        
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "procedure",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "procedureName",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.Name).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "brokerName",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.brokerName).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".

            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "brokerPID",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.brokerPID).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
            RUN print-tag (INPUT-OUTPUT streamdetail,
                           INPUT "brokerUUID",
                           INPUT "",
                           INPUT "",
                           INPUT data_store.brokerUUID).
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
    
            RUN print-starttag (INPUT-OUTPUT streamdetail,
                                INPUT "dataset",
                                INPUT "",
                                INPUT "",
                                INPUT "").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
        
        
            DO i = 1 TO EXTENT(datalabels):
        
                xmldataOutputlabel = datalabels[i].
                xmldatalabel = data_store.Name.

                DO fathom-x = 1 to Fathom-i-periods:

                    /* For display units. */
                    CASE Fathom-i-intervaltype:
                        WHEN "S" THEN Fathom-store-value = data_store.numSeconds[fathom-x].
                        WHEN "M" THEN Fathom-store-value = data_store.numSeconds[fathom-x] / 60.
                        WHEN "H" THEN Fathom-store-value = data_store.numSeconds[fathom-x] / 60 / 60.
                        OTHERWISE Fathom-store-value = 1.
                    END CASE.

                    /*
                    ** This preserves summary info when there are no samples in a period.
                    ** See 2003 08 13-018.
                    */
                    IF Fathom-store-value = 0 THEN Fathom-store-value = 1.
        
                    xmlsamplelength = STRING (data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING (data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING (data_store.numSamples[fathom-x]).
        
                    CASE datalabels[i]:
        
                        WHEN RUN_COUNT THEN
                        DO:
                            dataprecision = "0".
                            data_store.runCount[fathom-x] = data_store.runCount[fathom-x] /
                                                            Fathom-store-value.
                            IF data_store.runCount[fathom-x] = ? THEN
                                data_store.runCount[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.runCount[fathom-x]).
                                data_store.summaryRunCount = data_store.summaryRunCount +
                                                             data_store.runCount[fathom-x].
                            END.
                        END.
                        WHEN AVG_REQ_DURATION THEN
                        DO:
                            dataprecision = "0".
                            data_store.reqTotTime[fathom-x] = data_store.reqTotTime[fathom-x] /
                                                              Fathom-store-value.
                            data_store.reqDurationAvg[fathom-x] = data_store.reqTotTime[fathom-x] /
                                                                  data_store.runCount[fathom-x].
                            data_store.summaryReqDurationAvg = data_store.summaryReqDurationAvg +
                                                               data_store.reqTotTime[fathom-x].
                            IF data_store.reqDurationAvg[fathom-x] = ? THEN
                                data_store.reqDurationAvg[fathom-x] = 0.
                            IF data_store.numSamples[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING(data_store.reqDurationAvg[fathom-x]).
                            END.
                        END.
                        WHEN SAMPLE_COUNT THEN
                        DO:
                            dataprecision = "0".
                            data_store.summaryNumSamples = data_store.summaryNumSamples +
                                                           data_store.numSamples[fathom-x].
                            xmldatavalue = STRING(data_store.numSamples[fathom-x]).
                        END.
                        OTHERWISE
                            /* Should not happen as we just defined the array above. */
                            xmldatavalue = "".
        
                    END CASE.
        
                    RUN xml-process-date.
                    RUN xml-add-data.
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".

                    IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 THEN
                    DO:
                        /* Add summary information to xml file. */
                        CASE datalabels[i]:
            
                            WHEN RUN_COUNT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryRunCount).
                            END.
                            WHEN AVG_REQ_DURATION THEN
                            DO:
                                dataprecision = "0".
                                data_store.summaryReqDurationAvg = data_store.summaryReqDurationAvg /
                                                                   data_store.summaryRunCount.
                                IF data_store.summaryReqDurationAvg = ? THEN
                                    data_store.summaryReqDurationAvg = 0.
                                xmldatavalue = STRING(data_store.summaryReqDurationAvg).
                            END.
                            WHEN SAMPLE_COUNT THEN
                            DO:
                                dataprecision = "0".
                                xmldatavalue = STRING(data_store.summaryNumSamples).
                            END.
                            OTHERWISE
                                /* Should not happen as we just defined the array above. */
                                xmldatavalue = "".
            
                        END CASE.

                        RUN xml-add-data-summary.
                        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                        streamdetail = "".

                    END. /* IF fathom-x = Fathom-i-periods AND Fathom-i-periods > 1 */
        
                END. /* DO fathom-x = 1 to Fathom-i-periods: */
        
            END. /* DO i = 1 TO EXTENT(datalabels): */
        
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "dataset").
            RUN print-endtag (INPUT-OUTPUT streamdetail,
                              INPUT "procedure").
            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
            streamdetail = "".
    
        END. /* FOR EACH data_store */

    END. /* IF AVAILABLE Cf_Resrc */

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "resource").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

END. /* FOR EACH tmp-resrc */



pgm-name = "xml-wsprofile.p".
sec-name = "Finishing data XML file.".
{include/debug.i "pgm-name" "sec-name"}.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "report").
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


/*
** Print out the graph xml file.
**  We do this in a separate loop so that we can limit the
**  number of procedures put on the graph.  We have to know
**  the top x procedures that have the highest run count, etc.
*/
xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
numGraphResources = INTEGER(OS-GETENV("fathomResourcesPerGraph")) NO-ERROR.
DEFINE VARIABLE graph AS CHARACTER.
DEFINE VARIABLE isgraphed AS LOGICAL INITIAL NO.

IF numGraphResources = ? THEN
DO:
   numGraphResources = defaultNumGraphResources.
END.

IF xmlGraphColumns = ? THEN
DO:
   {include/xml-graphcolumns.i}.
END.

DO x-i = 1 TO NUM-ENTRIES(xmlGraphColumns, ","):
    graph = TRIM(ENTRY(x-i, xmlGraphColumns, ",")) NO-ERROR.

    CASE graph:
        WHEN "none" THEN LEAVE.

        WHEN RUN_COUNT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "WebSpeed Profile: " + RUN_COUNT.
            xmlgraph-imagetitle = "runcount.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "1".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryRunCount DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.runCount[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN AVG_REQ_DURATION THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "WebSpeed Profile: " + AVG_REQ_DURATION.
            xmlgraph-imagetitle = "reqdurationavg.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "2".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryReqDurationAvg DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.reqDurationAvg[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

        WHEN SAMPLE_COUNT THEN
        DO:
            isgraphed = YES.
            Fathom-report-title = "WebSpeed Profile: " + SAMPLE_COUNT.
            xmlgraph-imagetitle = "samplecount.png".
            xmlresourcesite = "".
            xmlresourcename = "".
            xmlresourcetype = "".
            xmlgraph-imageid = "3".
            RUN xml-graphspec.
            RUN xml-graphDataSets-header.
            i = 0.

            FOR EACH data_store BY summaryNumSamples DESCENDING:

                i = i + 1.

                IF i GT numGraphResources THEN LEAVE.

                xmldataOutputlabel = data_store.brokerName + " : " + data_store.Name.
                RUN xml-row-header.

                DO fathom-x = 1 to Fathom-i-periods:
        
                    xmlsamplelength = STRING(data_store.numSeconds[fathom-x]).
                    xmlsampletransactions = STRING(data_store.numSamples[fathom-x]).
                    xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                    xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                    xmlsampleenddate = Fathom-t-end-date[fathom-x].
                    xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    xmlsamplecount = STRING(data_store.numSamples[fathom-x]).
                    xmldatavalue = STRING(data_store.numSamples[fathom-x]).

                    RUN xml-process-date.
                    RUN xml-add-data-graph.
                    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                    graph1detail = "".

                END. /* DO fathom-x = 1 to Fathom-i-periods: */

                RUN xml-row-end.

            END. /* FOR EACH data_store */

            PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
            graph1detail = "".
        END.

    END CASE.

    IF isgraphed = YES THEN
    DO:
        isgraphed = NO.
        RUN xml-graphspec-end.
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
    END.

END.


pgm-name = "asprofile.p".
sec-name = "Finishing graph XML file.".
{include/debug.i "pgm-name" "sec-name"}.

/* Close up the graphing stuff. */
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}.
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}.


pgm-name = "xml-wsprofile.p".
sec-name = "XML files complete.".
{include/debug.i "pgm-name" "sec-name"}.
/* Orphan.p
**
** This program will search through the fathom trend database and find
** Orphaned information.  THis is based strictly off of the cf_resrc table to
** work to eliminate duplicate entries.
**
** THis should only be run during the migration process between 1.0A and 2.0A.
*/

DEF VAR i AS INT.
DEF VAR j AS INT.
DEF VAR k AS INT.
DEF VAR l AS INT.

DEF VAR t-resrc_name AS CHAR.
DEF VAR t-site_id AS CHAR.
DEF VAR t-resrc_type AS CHAR.
DEF VAR t-resrc_id AS INT.

DEFINE TEMP-TABLE t-resrc LIKE cf_resrc.

PUT SKIP(1) "Beginning resource migration process...".

FOR EACH cf_resrc:
    CASE cf_resrc.resrc_type:
        WHEN "GROUP" THEN j = j + 1.
        WHEN "REPORT" THEN j = j + 1.
        WHEN "JOB" THEN j = j + 1.
        OTHERWISE 
        DO:
            CREATE t-resrc.
            BUFFER-COPY cf_resrc TO t-resrc.
        END.
    END CASE.
END.

FOR EACH t-resrc BY t-resrc.resrc_name:
    PUT SKIP.
    PUT UNFORMATTED "Validating Resource: " 
                    t-resrc.site_id 
                    ":" 
                    t-resrc.resrc_name.
    PUT SKIP.

    FIND FIRST cf_resrc WHERE 
        cf_resrc.resrc_name = t-resrc.resrc_name AND
        cf_resrc.site_id = t-resrc.site_id AND
        cf_resrc.resrc_type = t-resrc.resrc_type NO-LOCK NO-ERROR.
    IF AVAILABLE cf_resrc THEN
    DO:
        t-resrc_name = cf_resrc.resrc_name.
        t-site_id = cf_resrc.site_id.
        t-resrc_type = cf_resrc.resrc_type.
        t-resrc_id = cf_resrc.resrc_id.
        FIND NEXT cf_resrc WHERE       
            cf_resrc.resrc_name = t-resrc.resrc_name AND
            cf_resrc.site_id = t-resrc.site_id AND
            cf_resrc.resrc_type = t-resrc.resrc_type NO-ERROR.
        IF AVAILABLE cf_resrc THEN
        DO:
            RUN cleanup-data.
            RUN cleanup-samples.
            RUN cleanup-resources.
            i = i + 1.
        END.
    END.
END.

PUT SKIP "Found " i " duplicate resources".
PUT SKIP(1) "Finished resource migration routine..." SKIP.
    QUIT.

PROCEDURE cleanup-samples.
    FOR EACH cf_sample WHERE
        cf_sample.Site_id  = t-site_id AND
        cf_sample.resrc_id = t-resrc_id:         
        ASSIGN
            cf_sample.resrc_id = cf_resrc.resrc_id
            cf_sample.site_id = cf_resrc.site_id.
        k = k + 1.
    END.
    PUT SKIP "Found " k " sample records for resource " t-site_id ":" t-resrc_name.
    k = 0.
END PROCEDURE.

PROCEDURE cleanup-data.
    /* Cf_Status, Cf_Alert_Detail */

    DO TRANSACTION:
        FOR EACH cf_alert_detail WHERE
            cf_alert_detail.site_id = t-site_id AND
            cf_alert_detail.resrc_id = t-resrc_id:
            ASSIGN
                cf_alert_detail.site_id = cf_resrc.site_id
                cf_alert_detail.resrc_id = cf_resrc.resrc_id.
            k = k + 1.
        END.
    END.

    DO TRANSACTION:
        FOR EACH cf_Status WHERE
            cf_Status.site_id = t-site_id AND
            cf_Status.resrc_id = t-resrc_id:
            ASSIGN
                cf_Status.site_id = cf_resrc.site_id
                cf_Status.resrc_id = cf_resrc.resrc_id.
            l = l + 1.
        END.
    END.
    
    PUT SKIP "Found " k " alert detail records for resource " t-site_id ":" t-resrc_name.
    PUT SKIP "Found " l " status records for resource " t-site_id ":" t-resrc_name.
    k = 0.
    l = 0.

END PROCEDURE.

PROCEDURE cleanup-resources.
    FIND FIRST cf_resrc WHERE
        cf_resrc.resrc_name = t-resrc_name AND
        cf_resrc.site_id = t-site_id AND
        cf_resrc.resrc_type = t-resrc_type NO-ERROR.
    IF AVAILABLE cf_resrc THEN
    DO:
    
        DO TRANSACTION:
            DELETE cf_resrc.
        END.
        PUT SKIP "deleted resource : " t-site_id ":" t-resrc_name.
    END.
END PROCEDURE.
/* program name purgedb_indexstat.p
   This program is designed to purge all of the data in your~
     FathomTrendDatabase's index-statistics table for all trended~
     databases.
   */
DEF VAR sample_id_temp AS INT.
DEF VAR last_date AS DATE.
DEF VAR run-purge AS LOGICAL.

MESSAGE "This program will purge all index statistics for all databases before and~
 including the date you specify.  You should backup or archive this data before~
 continuing.  Do you wish to continue?"
    VIEW-AS ALERT-BOX QUESTION BUTTONS YES-NO UPDATE run-purge.
    IF NOT run-purge THEN LEAVE.

UPDATE last_date FORMAT "99/99/9999" WITH NO-LABEL WITH TITLE 
    "Delete all table statics before and including this date:" WITH WIDTH 70.

FOR EACH cf_sample WHERE cf_sample.sample_date LE last_date:
    sample_id_temp = sample_id.
    DISPLAY sample_id sample_date.
    PAUSE 0.
FOR EACH db_indexstat WHERE db_indexstat.sample_id = sample_id_temp:
    DISPLAY "Deleting db_indexstat, please wait." WITH 1 DOWN.
    DELETE db_indexstat.
    PAUSE 0.
END.

END.
/* program name purgedb_tablestat.p
   This program is designed to purge all of the data in your~
     FathomTrendDatabase's table-statistics table, for all trended~
     databases.
   */
DEF VAR sample_id_temp AS INT.
DEF VAR last_date AS DATE.
DEF VAR run-purge AS LOGICAL.

MESSAGE "This program will purge all table statistics for all databases before and~
 including the date you specify.  You should backup or archive this data before~
 continuing.  Do you wish to continue?"
    VIEW-AS ALERT-BOX QUESTION BUTTONS YES-NO UPDATE run-purge.
    IF NOT run-purge THEN LEAVE.

UPDATE last_date FORMAT "99/99/9999" WITH NO-LABEL WITH TITLE 
    "Delete all table statics before and including this date:" WITH WIDTH 70.

FOR EACH cf_sample WHERE cf_sample.sample_date LE last_date:
    sample_id_temp = sample_id.
DISPLAY sample_id sample_date.
PAUSE 0.

FOR EACH db_tablestat WHERE db_tablestat.sample_id = sample_id_temp:
    DISPLAY "Deleting db_tablestat, please wait." WITH 1 DOWN.
    DELETE db_tablestat.
    PAUSE 0.
END.

END.
/*
** CfStatus.p
** This program will present a trend report for the status table.  This is 
** based on the dates provided to the report.  
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** NOTE:The header information for the report does not use the standard include.
**
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Define temp table to store data output
*/

DEF NEW SHARED TEMP-TABLE tt-status 
    FIELD xid AS INTEGER
    FIELD xresrc-id AS INTEGER 
    FIELD xsite-id AS CHARACTER
    FIELD xdate AS DATE
    FIELD xstatus AS CHARACTER
    FIELD xtime AS INTEGER
    FIELD xseconds AS INTEGER
    INDEX one xdate
    INDEX two xtime
    INDEX three xresrc-id
                xsite-id.

DEF NEW SHARED TEMP-TABLE tt-desc
    FIELD ystatus AS CHARACTER
    FIELD yorder AS INTEGER
    INDEX one yorder.

DEF VAR hold-time AS INTEGER NO-UNDO.
DEF VAR diff-time AS INTEGER NO-UNDO.
DEF VAR hold-date AS DATE NO-UNDO.
DEF VAR hold-status AS CHARACTER NO-UNDO.
DEF VAR hold-site-id AS CHARACTER NO-UNDO.
DEF VAR hold-resrc-id AS INTEGER NO-UNDO.
DEF VAR first-time AS INTEGER INITIAL 0.
DEF VAR prev-id AS INTEGER INITIAL 0.
DEF VAR top-id AS INTEGER INITIAL 1.
DEF VAR diff-dates AS INTEGER NO-UNDO.
DEF VAR unknown-status AS CHARACTER NO-UNDO INITIAL "Status unknown".
DEF VAR fathom-pct AS DECIMAL NO-UNDO.
DEF VAR time-value AS INTEGER NO-UNDO.

/* 
** Begin Main Processing
*/

/*
** This variable is used to provide correct values for partial times.
*/

CASE Fathom-i-Reportcode:
   WHEN "hh" OR WHEN "dh" OR WHEN "hi" THEN
   DO:      
         PUT SKIP.
        PUT 
            STRING (TODAY, "99/99/9999") " "  
            STRING (TIME, "HH:MM:SS")  
            " Reporting on Hourly or Hour by Increment is not valid with " .
        PUT SKIP.
        PUT 
            STRING (TODAY, "99/99/9999")  " "  
            STRING (TIME, "HH:MM:SS")  
            " the Status Detail report.  You must run a daily report.".
        PUT SKIP.
        QUIT.
   END.
   OTHERWISE time-value = 86400.
END CASE.

{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/
pgm-name = "status.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "Periods: " + STRING(Fathom-i-periods).
{include/debug.i "pgm-name" "sec-name"}

    /*
    ** Loop through all of the appropriate records
    */
    FOR EACH cf_status WHERE
        cf_status.site_id = fathom-i-site_id AND
        cf_status.resrc_id = fathom-i-resrc_id AND
        cf_status.STATUS_date GE (Fathom-i-start_date - 1) AND
        cf_status.STATUS_date LE fathom-i-end_date
        BY cf_status.STATUS_date 
        BY cf_status.STATUS_time:

        /* 
        ** Update the status type temp-table
        ** This will be used in the reporting section
        */

        FIND FIRST tt-desc WHERE
            ystatus = cf_status.STATUS_status NO-ERROR.
        IF NOT AVAILABLE tt-desc THEN
        DO:
            CREATE tt-desc.
            ASSIGN ystatus = cf_status.STATUS_status.
	        CASE Cf_Status.Status_Status:
	            WHEN "passed" THEN yorder = 1.
	            OTHERWISE yorder = 10.
	        END CASE.
        END.

        Fathom-rec-count = fathom-rec-count + 1.

        /*
        ** test for (first time) and create the appropriate data
        */
        
        IF first-time = 0 THEN
        DO:
            ASSIGN
                hold-site-id = cf_status.site_id
                hold-resrc-id = cf_status.resrc_id
                hold-date = cf_status.STATUS_date
                hold-time = cf_status.STATUS_time
                hold-status = unknown-status.

            /*
            ** Create initial seed record with the current status
            */
            prev-id = top-id + 1.
            top-id = top-id + 1.

            CREATE tt-status.

            /* RUN assign-xsite-id. */
	        ASSIGN
                xid = prev-id
                xseconds = 0 
                xsite-id = cf_status.Site_id
                xresrc-id = cf_status.resrc_id
                xdate = cf_status.STATUS_date
                xtime = cf_status.STATUS_time
                xstatus = cf_status.STATUS_status.

            first-time = 1.

            /*
            ** Creating an unknown time for status until the first status
            ** change. 
            */
	        DO Fathom-j = 1 to Fathom-i-Periods:
	           IF Fathom-t-beg-date[fathom-j] LT Cf_Status.Status_Date THEN
	           DO:
                   /*
                   ** Create the unknown status record for the
                   ** dates UNTIL we have our first status
                   */
                   CREATE tt-status.
     
	               ASSIGN
                       xseconds = time-value
                       xsite-id = cf_status.Site_id
                       xresrc-id = cf_status.resrc_id
                       xdate = Fathom-t-beg-date[fathom-j]
                       xtime = Fathom-t-beg-time[fathom-j]
                       xid = 0
                       xstatus = unknown-status.
	           END.
	           ELSE
	           DO:
	               IF Fathom-t-beg-date[fathom-j] = Cf_Status.Status_Date AND
	               Fathom-t-beg-time[fathom-j]  LT Cf_Status.Status_Time 
	               THEN
	               DO:
                       /*
                       ** Create the original unknown status record for the
                       ** date that we have our first status in
                       */
                       CREATE tt-status.
	                   ASSIGN
                           xseconds = Cf_Status.Status_time
                           xsite-id = cf_status.Site_id
                           xresrc-id = cf_status.resrc_id
                           xdate = Fathom-t-beg-date[fathom-j]
                           xtime = (Fathom-t-beg-time[fathom-j] + 1)
                           xid = 0
                           xstatus = unknown-status.
                       LEAVE.
	               END.
	           END.
	        END. /* end of the DO fathom-j loop */
                
            FIND FIRST tt-desc WHERE ystatus = unknown-status NO-ERROR.
            IF NOT AVAILABLE tt-desc THEN
            DO:
                CREATE tt-desc.
                ASSIGN 
                    yorder = 99
                    ystatus = unknown-status.
            END.
            NEXT.
        END. /* OF IF FIRST TIME */

        /*
        ** Processing after the first time
        */

        /*
        ** This processing is for the previous record
        ** We also need to do some processing for the existing record to
        ** make sure it exists.  If it doesn't exist then we need to create
        ** it!
        */
        IF cf_status.STATUS_date = hold-date THEN
        DO:
            /*
            ** This "should" never happen...
            */
            IF Cf_Status.STATUS_status = hold-status THEN NEXT.
            
            diff-time = Cf_status.STATUS_time - hold-time.
            
            IF diff-time LT 0 THEN diff-time = time-value - cf_status.STATUS_time.

            /*
            ** This is the processing of the previous record
            */
            FIND FIRST tt-status WHERE
                xid = prev-id 
		    NO-ERROR.
            IF AVAILABLE tt-status THEN
            DO:
                xseconds = xseconds + cf_Status.status_time - hold-time.
            END.
            ELSE
            DO:
                prev-id = top-id + 1.
                top-id = top-id + 1.
                
                CREATE tt-status.
	            ASSIGN
                    xid = prev-id
                    xseconds = 0
                    xsite-id = cf_status.Site_id
                    xresrc-id = cf_status.resrc_id
                    xdate = cf_status.STATUS_date
                    xtime = cf_status.STATUS_time
                    xstatus = cf_status.STATUS_status.
                    xseconds = cf_Status.status_time - hold-time.
            END.
        END. /* OF IF Status-date = Hold-date */
        ELSE
        DO:
            /*
            ** The date has changed - Do date change processing  
            **
            ** Process counts for more than 1 day's difference
            ** The balance of the first and last days are going to be
            ** accounted for in the next formula.
            */

            IF cf_status.STATUS_date - hold-date GT 1 THEN
            DO:
                diff-dates = cf_status.STATUS_date - hold-date - 1.
                DO fathom-i = 1 TO diff-dates:
                
                    FIND FIRST tt-status WHERE
                        xsite-id = cf_status.site_id AND
                        xresrc-id = cf_status.resrc_id AND
                        xdate = (hold-date + fathom-i) AND
                        xstatus = cf_status.STATUS_status NO-ERROR.
                    IF AVAILABLE tt-status THEN
                    DO:
                         prev-id = xid.
                         xseconds = xseconds + time-value.
                    END.
                    ELSE
                    DO:
                        /*
                        ** Create a record for the next day with the 
                        ** previous day's status in it
                        */
                        CREATE tt-status.
	                    ASSIGN
                            xsite-id = cf_status.Site_id
                            xresrc-id = cf_status.resrc_id
                            xid = 0
                            xdate = hold-date + fathom-i
                            xtime = 0
                            xseconds = time-value
                            xstatus = cf_status.STATUS_status.
                    END.
                END. /* OF Do fathom-i = 1 to DiffDates */
            END. /* OF if the date differences are greater than 1 */
            /*
            ** Update the last record for the previous day
            */
            FIND FIRST tt-status WHERE
                xid = prev-id 
		        NO-ERROR.
            IF AVAILABLE tt-status THEN
            DO:  
                /*
                ** Process the difference for the rest of the time.  For example
                ** If you have something stop at 10PM and the next status change
                ** is at 2AM then next day you have 4 hours to account for.
                */
                
                xseconds = xseconds + time-value - xtime.
                hold-status = xstatus.

                /* 
                ** Create a new record for the balance of the time spent
                ** in the previous status from the previous day
                */
                
                prev-id = top-id + 1.
                top-id = top-id + 1.

                CREATE tt-status.
	            ASSIGN
                    xid = prev-id
                    xsite-id = cf_status.Site_id
                    xseconds = cf_status.STATUS_time
                    xresrc-id = cf_status.resrc_id
                    xdate = cf_status.STATUS_date
                    xtime = cf_status.STATUS_time
                    xstatus = hold-status.
            END.
            ELSE
            DO:

                /*
                ** Create a new record for this day
                */
                prev-id = top-id + 1.
                top-id = top-id + 1.

                CREATE tt-status.
	            ASSIGN
                    xid = prev-id
                    xseconds = 0
                    xsite-id = cf_status.Site_id
                    xresrc-id = cf_status.resrc_id
                    xdate = cf_status.STATUS_date
                    xtime = cf_status.STATUS_time
                    xstatus = cf_status.STATUS_status.
            END.
        END. /* END OF ELSE if status-date */

        /* 
        ** This is the processing for the existing record
        */

        FIND FIRST tt-status WHERE
            xsite-id = cf_status.site_id AND
            xresrc-id = cf_status.resrc_id AND
            xdate = cf_status.STATUS_date AND
            xstatus = cf_status.STATUS_status NO-ERROR.
        IF AVAILABLE tt-status THEN
        DO:
            prev-id = xid.
        END.
        ELSE
        DO:
            /*
            ** The processing for an existing record that doesn't exist
            ** yet in the table
            */

            prev-id = top-id + 1.
            top-id = top-id + 1.

            CREATE tt-status.
	        ASSIGN
                xid = prev-id
                xseconds = 0
                xsite-id = cf_status.Site_id
                xresrc-id = cf_status.resrc_id
                xdate = cf_status.STATUS_date
                xtime = cf_status.STATUS_time
                xstatus = cf_status.STATUS_status.
        END.
        
        ASSIGN
            hold-site-id = cf_status.site_id
            hold-resrc-id = cf_status.resrc_id
            hold-date = cf_status.STATUS_date
            hold-time = cf_status.STATUS_time
            hold-status = cf_status.STATUS_status.
     
    END. /*  FOR EACH cf_status WHERE */

    /*
    ** Clean up days that are BEFORE the date range found
    */
    FOR EACH tt-status WHERE xdate LT fathom-i-start_date:
        DELETE tt-status.
    END.

    /*
    ** Creating an unknown time for the last day
    */
    FIND LAST tt-status WHERE  
        xdate = hold-date AND
        xsite-id = hold-site-id AND
        xresrc-id = hold-resrc-id AND
        xstatus = hold-status 
		NO-ERROR.  
    IF AVAILABLE tt-status THEN
    DO:
        xseconds = xseconds + time-value - hold-time.
    END.
    ELSE
    DO:
         CREATE tt-status.
         ASSIGN
             xid = 0
             xsite-id = hold-site-id
             xresrc-id = hold-resrc-id
             xdate = hold-date
             xtime = hold-time
             xseconds = time-value - hold-time
             xstatus = unknown-status.
    END.

    /*
    ** Fill in the previous status for all of the rest of the periods
    **
    ** Find the last status we used to get the status for going forward
    */
     FIND LAST cf_status WHERE
        cf_status.site_id = fathom-i-site_id AND
        cf_status.resrc_id = fathom-i-resrc_id AND
        cf_status.STATUS_date GE (Fathom-i-start_date - 1) AND
        cf_status.STATUS_date LE fathom-i-end_date NO-LOCK NO-ERROR.
     IF AVAILABLE Cf_Status THEN
     DO:
         /*
         ** save the last status for use in the Temp Table
         */
         hold-site-id = Cf_Status.site_id.
         hold-resrc-id = Cf_Status.resrc_id.
         hold-status = Cf_Status.Status_status.
     END.
     /*
     ** Find the last appropriate temp table row
     */
     FIND LAST tt-status WHERE
	     xsite-id = hold-site-id AND
         xresrc-id = hold-resrc-id AND
         xstatus = hold-status
	     NO-ERROR.  
    IF AVAILABLE tt-status THEN
    DO:
        DO fathom-j = 1 to Fathom-i-periods:
            IF xdate GE Fathom-t-beg-date[fathom-j] AND
	        xdate LE Fathom-t-end-date[fathom-j] AND
	        xtime GE Fathom-t-Beg-time[fathom-j] AND
	        xtime LE Fathom-t-End-time[fathom-j] THEN
            DO:
	        ASSIGN hold-time = fathom-j + 1.
	        LEAVE.
            END.
        END.

        DO fathom-j = hold-time TO Fathom-i-periods:
             CREATE tt-status.
             ASSIGN
                 xid = 5
                 xsite-id = hold-site-id
                 xresrc-id = hold-resrc-id
                 xdate = Fathom-t-beg-date[fathom-j]
                 xtime = Fathom-t-beg-time[fathom-j]
                 xseconds = time-value
                 xstatus = hold-status.
        END.
    END. /* OF if available tt-status */

    /*
    ** Make sure the status times are appropriate
    */
    hold-date = ?.
    hold-time = 0.
    FOR EACH tt-status USE-INDEX one: 
        IF hold-date NE xdate THEN
        DO:
            hold-time = xseconds.
            hold-date = xdate.
        END.
        ELSE
        DO:
            IF hold-time + xseconds GT time-value THEN
            DO:
                xseconds = time-value - hold-time.
                hold-time = xseconds.
            END.
            ELSE hold-time = hold-time + xseconds.
        END.
    END. 

    /*
    ** Debug export the data set
    */
    IF Fathom-i-OutputType = "R" THEN
    DO:
        IF debug-4gl = 1 THEN
        DO:
            PUT SKIP.
            PUT
                (STRING (TODAY) + " " + 
                STRING (TIME, "HH:MM:SS") + 
                " - " +
                " Program : status.p" +
                " Section : Exporting temp table" ) format "x(255)".
            PUT SKIP.
            FOR EACH tt-status:
               EXPORT tt-status.
            END.
        END.
    END. 


/*
** Print Section
*/
sec-name = "Printing Report".
pgm-name = "status.p".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }
Fathom-report-title = Fathom-i-Title.
IF Fathom-report-title = "" then fathom-report-title = "Specific Resource Summary Report".
Fathom-tfs-replength = length(Fathom-t-rep_name).

/*
** Begin the XML output setup and header information
*/
DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

xml-numcolumns = 0.

FOR EACH tt-desc:
   xml-numcolumns = xml-numcolumns + 1.
   xmlcolumnnames[xml-numcolumns] = tt-desc.ystatus.
END.
   
{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbserver.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


/* 
** Start outputting the detail information.
*/
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbserver.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no statuses logged during the dates specified!").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

END.
ELSE
DO:    
    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
     
    pgm-name = "xml-dbserver.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    FIND FIRST tt-status NO-LOCK NO-ERROR.
    IF AVAILABLE tt-status THEN
    DO:
       FIND FIRST Cf_Resrc WHERE
       xresrc-id = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */

          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbserver.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
       END.
    END.
        xmldatalabel = xmlresourcename.
  
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset",
                            INPUT "",
                            INPUT "",
                            INPUT "").
    FOR EACH tt-desc:
        xmldatalabel = tt-desc.ystatus.

        /* 
	    ** Print the data label setting
	    */
      

        CASE Fathom-i-reportcode:
	    WHEN "hh" OR WHEN "hi" OR WHEN "dh" THEN
	    DO:
	        DO Fathom-j = 1 to fathom-i-periods:

	            hold-date = Fathom-t-beg-date[fathom-j].

                FIND FIRST tt-status WHERE
                    tt-status.xstatus = tt-desc.ystatus AND
                    tt-status.xdate = hold-date AND 
		            tt-status.xtime GE Fathom-t-Beg-time[fathom-j] AND
		            tt-status.xtime LE Fathom-t-End-time[fathom-j]
		            NO-LOCK NO-ERROR.

                RUN print-available-tt-status.
                
	        END.
	    END.
	    OTHERWISE
	    DO:
            DO fathom-j = 0 TO (fathom-i-periods - 1):

                fathom-x = fathom-j + 1.

                hold-date = fathom-i-start_date + fathom-j.

                FIND FIRST tt-status WHERE
                    tt-status.xstatus = tt-desc.ystatus AND
                    tt-status.xdate = hold-date 
                    NO-LOCK NO-ERROR.

                RUN print-available-tt-status.

            END.
	    END. /* OF Otherwise statement */
	    END CASE.
    END.
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "dataset").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
     RUN print-endtag (INPUT-OUTPUT streamdetail,
                       INPUT "resource").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
END.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
IF Fathom-Rec-Count GT 0 THEN
DO:
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphDataSets").
END.

RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}


sec-name = "Exiting Program".
pgm-name = "Statusdetail.p".
{include/debug.i "pgm-name" "sec-name"}

/*
** Start Internal Procedures Section
*/

/* 
** Print a dash where there is no data
*/
PROCEDURE Print-status-dash.
    dataprecision = "0".
    xmldataOutputlabel = tt-desc.ystatus.
    xmltestlabel = tt-desc.ystatus.
    RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
    RUN xml-process-date.     /* subroutine to process the date */
	xmldatavalue = "0".
                
	RUN xml-format-column-intervaltype.
    RUN xml-add-data. /* subroutine to process the datum */
	PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    dataprecision = "2".
END PROCEDURE.

/*
** Print the output of the details 
*/
PROCEDURE Print-status-detail.
    fathom-pct = (INTEGER (10000 * (hold-time / time-value)))  / 100.

    xmldataOutputlabel = tt-desc.ystatus.
    xmltestlabel = tt-desc.ystatus.

    RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
    RUN xml-process-date.     /* subroutine to process the date */
	xmldatavalue = STRING (fathom-pct, ">>9.99").
                 
	RUN xml-format-column-intervaltype.
    RUN xml-add-data. /* subroutine to process the datum */
	PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "dataset").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
END PROCEDURE.

PROCEDURE print-available-tt-status.
    IF AVAILABLE tt-status THEN
    DO:
        hold-time = xseconds MODULO time-value.
        diff-time = (xseconds - hold-time) / time-value.
        IF hold-time = 0 AND diff-time = 1 THEN hold-time = time-value.
	    fathom-pct = (INTEGER (10000 * (hold-time / time-value)))  / 100.

        xmldataOutputlabel = tt-desc.ystatus.
        xmltestlabel = tt-desc.ystatus.

        RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
        RUN xml-process-date.     /* subroutine to process the date */

		xmldatavalue = STRING (fathom-pct, ">>9.99").
        
		RUN xml-format-column-intervaltype.
        RUN xml-add-data. /* subroutine to process the datum */

		PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
    
    END.
    ELSE 
    DO:
	    RUN Print-status-dash.
    END.
END PROCEDURE.

QUIT.
/*
** statussummary.p
** This program will present a trend report for the status table.  This is 
** based on the dates provided to the report.  
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** NOTE:The header information for the report does not use the standard include.
**
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Define temp table to store data output
*/

DEF TEMP-TABLE tt-status 
    FIELD xid AS INTEGER
    FIELD xresrc-id AS INTEGER 
    FIELD xsite-id AS CHARACTER
    FIELD xdate AS DATE
    FIELD xstatus AS CHARACTER
    FIELD xtime AS INTEGER
    FIELD xseconds AS INTEGER
    FIELD xorder AS INTEGER
    INDEX one xorder
              xdate
    INDEX two xtime
    INDEX three xresrc-id
                xsite-id.

DEF TEMP-TABLE tt-desc
    FIELD ystatus AS CHARACTER
    FIELD yorder AS INTEGER
    INDEX one yorder.
    
DEF TEMP-TABLE out-status
    FIELD zresrc-id AS INTEGER
    FIELD zsite-id AS CHARACTER
    FIELD zstatus AS CHARACTER
    FIELD zseconds AS INTEGER Extent 366
    index zsite-id
          zresrc-id
	  zstatus.

DEF VAR unknown-seconds as INTEGER extent 366.
DEF VAR hold-time AS INTEGER NO-UNDO.
DEF VAR diff-time AS INTEGER NO-UNDO.
DEF VAR hold-date AS DATE NO-UNDO.
DEF VAR hold-status AS CHARACTER NO-UNDO.
DEF VAR hold-site-id AS CHARACTER NO-UNDO.
DEF VAR hold-resrc-id AS INTEGER NO-UNDO.
DEF VAR first-time AS INTEGER INITIAL 0.
DEF VAR prev-id AS INTEGER INITIAL 0.
DEF VAR top-id AS INTEGER INITIAL 1.
DEF VAR diff-dates AS INTEGER NO-UNDO.
DEF VAR cnt-dates AS INTEGER NO-UNDO.
DEF VAR unknown-status AS CHARACTER NO-UNDO INITIAL "Status unknown".
DEF VAR Time-value AS INTEGER NO-UNDO.

/* 
** Begin Main Processing
*/
/*
** Get the Site ID and Resource ID and read the report definition
*/

{include/trenddates.i}.

/*
** Read samples and process them into the rpt table
*/
pgm-name = "statussummary.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "Increment value: " + STRING(Fathom-t-HRincrement).
{include/debug.i "pgm-name" "sec-name"}

/*
** This variable is used to provide correct values for partial times.
*/

CASE Fathom-i-Reportcode:
   WHEN "hh" OR WHEN "dh" OR WHEN "hi" THEN 
   DO:
        PUT SKIP.
        PUT 
            STRING (TODAY, "99/99/9999") " "  
            STRING (TIME, "HH:MM:SS")  
            " Reporting on Hourly or Hour by Increment is not valid with " .
        PUT SKIP.
        PUT 
            STRING (TODAY, "99/99/9999")  " "  
            STRING (TIME, "HH:MM:SS")  
            " the Status Summary report.  You must run a daily report.".
        PUT SKIP.
        QUIT.
   END.
   OTHERWISE time-value = 86400.
END CASE.

    /*
    ** Loop through all of the appropriate records
    */
    FOR EACH cf_status WHERE
        cf_status.site_id = fathom-i-site_id AND
        cf_status.STATUS_date GE (Fathom-i-start_date - 1) AND
        cf_status.STATUS_date LE fathom-i-end_date
        BY cf_Status.resrc_id
        BY cf_status.STATUS_date 
        BY cf_status.STATUS_time:

	    FIND FIRST cf_resrc WHERE 
            cf_resrc.resrc_id = cf_status.resrc_id NO-ERROR.
	    IF NOT AVAILABLE CF_Resrc THEN NEXT.
	    if Cf_Resrc.resrc_type = "REPORT" OR
	       Cf_Resrc.resrc_type = "JOB" OR
	       Cf_Resrc.resrc_type = "GROUP" OR
	       Cf_Resrc.resrc_type = "" OR
	       Cf_Resrc.resrc_type = ? THEN NEXT.

        /* 
        ** Update the status type temp-table
        ** This will be used in the reporting section
        */

        FIND FIRST tt-desc WHERE
            ystatus = cf_status.STATUS_status NO-ERROR.
        IF NOT AVAILABLE tt-desc THEN
        DO:
            CREATE tt-desc.
            ASSIGN
                yorder = 1
                ystatus = cf_status.STATUS_status.
        END.

        Fathom-rec-count = fathom-rec-count + 1.

        /*
        ** test for (first time) and create the appropriate data
        */
        
        IF first-time = 0 THEN
        DO:
	    /*
	    ** Test if the first date is the date on the report to start with
	    ** if it isn't then we need to create records for those dates.
	    ** with a status of unknown
	    */

	    IF Cf_Status.Status_Date GT Fathom-i-Start_Date THEN
	    DO:
	        cnt-dates = cf_status.Status_Date - Fathom-i-Start_Date - 1.
		    DO fathom-j = 0 to cnt-dates:
		    
               prev-id = top-id + 1.
               top-id = top-id + 1.

               CREATE tt-status.
               ASSIGN
                   xid = prev-id
                   xsite-id = cf_status.Site_id
                   xresrc-id = cf_status.resrc_id
                   xdate = Fathom-i-start_Date + fathom-j
                   xtime = 0
                   xseconds = time-value
                   xorder = 99
                   xstatus = unknown-status.
			   RUN calc-BOM.
		    END.
	     END.

         ASSIGN
             hold-site-id = cf_status.site_id
             hold-resrc-id = cf_status.resrc_id
             hold-date = cf_status.STATUS_date
             hold-time = cf_status.STATUS_time
             hold-status = cf_status.STATUS_status.
         /*
         ** Create initial seed record
         */
         prev-id = top-id + 1.
         top-id = top-id + 1.

         CREATE tt-status.
 
         ASSIGN
             xid = prev-id
             xsite-id = cf_status.Site_id
             xresrc-id = cf_status.resrc_id
             xdate = cf_status.STATUS_date
             xtime = cf_status.STATUS_time
             xseconds = 0
             xorder = 1
             xstatus = cf_status.STATUS_status.
         RUN calc-BOM.
         first-time = 1.

         /*
         ** Creating an unknown time for status until the first status
         ** change. It will be called "no data available".
         */
         CREATE tt-status.
 
         ASSIGN
             xsite-id = cf_status.Site_id
             xresrc-id = cf_status.resrc_id
             xdate = cf_status.STATUS_date
             xtime = cf_status.STATUS_time
             xseconds = Cf_Status.STATUS_time
             xid = 0
             xorder = 99
             xstatus = unknown-status.
		 RUN calc-BOM.
            
         FIND FIRST tt-desc WHERE ystatus = unknown-status NO-ERROR.
         IF NOT AVAILABLE tt-desc THEN
         DO:
             CREATE tt-desc.
             ASSIGN 
                 yorder = 99
                 ystatus = unknown-status.
         END.
         
    END. /*  FOR EACH */

        /*
        ** Processing after the first time
        **
        ** This processing is for the previous record
        ** We also need to do some processing for the existing record to
        ** make sure it exists.  If it doesn't exist then we need to create
        ** it!
        */
        IF cf_status.STATUS_date = hold-date THEN
        DO:
            /*
            ** This "should" never happen...
            */
            IF Cf_Status.STATUS_status = hold-status THEN NEXT.
            
            diff-time = Cf_status.STATUS_time - hold-time.
            
            IF diff-time LT 0 THEN diff-time = time-value - STATUS_time.

            /*
            ** This is the processing of the previous record
            */
            FIND FIRST tt-status WHERE
                xid = prev-id NO-ERROR.
            IF AVAILABLE tt-status THEN
            DO:
                xseconds = xseconds + (cf_Status.status_time - hold-time).
            END.
            ELSE
            DO:
                prev-id = top-id + 1.
                top-id = top-id + 1.
                
                CREATE tt-status.
 
                ASSIGN
                    xid = prev-id
                    xsite-id = cf_status.Site_id
                    xresrc-id = cf_status.resrc_id
                    xdate = cf_status.STATUS_date
                    xtime = cf_status.STATUS_time
                    xseconds = 0
		    xorder = 1
                    xstatus = cf_status.STATUS_status.
		    RUN calc-BOM.
            END.
        END.
        ELSE
        DO:
            /*
            ** The date has changed - Do date change processing  
            **
            ** Process counts for more than 1 day's difference
            ** The balance of the first and last days are going to be
            ** accounted for in the next formula.
            */

            IF cf_status.STATUS_date - hold-date GT 1 THEN
            DO:
                diff-dates = cf_status.STATUS_date - hold-date - 1.
                DO fathom-i = 1 TO diff-dates:
                
                    FIND FIRST tt-status WHERE
                        xsite-id = cf_status.site_id AND
                        xresrc-id = cf_status.resrc_id AND
                        xdate = (hold-date + fathom-i) AND
                        xstatus = cf_status.STATUS_status NO-ERROR.
                    IF AVAILABLE tt-status THEN
                    DO:
                         prev-id = xid.
                         xseconds = xseconds + time-value.
                    END.
                    ELSE
                    DO:
                        CREATE tt-status.
 
                        ASSIGN
                            xsite-id = cf_status.Site_id
                            xresrc-id = cf_status.resrc_id
                            xid = 0
                            xdate = hold-date + fathom-i
                            xtime = 0
                            xseconds = time-value
			                xorder = 1
                            xstatus = hold-status.
			            RUN calc-BOM.
                    END.
                END.
            END.
            /*
            ** Update the last record for the previous day
            */
            FIND FIRST tt-status WHERE
                xid = prev-id NO-ERROR.
            IF AVAILABLE tt-status THEN
            DO:  
                /*
                ** Process the difference for the rest of the time.  For example
                ** If you have something stop at 10PM and the next status change
                ** is at 2AM then next day you have 4 hours to account for.
                */
                
                xseconds = xseconds + (time-value - hold-time).

                /* 
                ** Create a new record for the balance of the time spent
                ** in the previous status from the previous day
                */
                
                prev-id = top-id + 1.
                top-id = top-id + 1.

                CREATE tt-status.
 
                ASSIGN
                    xid = prev-id
                    xsite-id = cf_status.Site_id
                    xresrc-id = cf_status.resrc_id
                    xdate = cf_status.STATUS_date
                    xtime = cf_status.STATUS_time
                    xseconds = Cf_Status.STATUS_time
		            xorder = 1
                    xstatus = hold-status.
		    RUN calc-BOM.
            END.
            ELSE
            DO:

                /*
                ** Create a new record for this day
                */
                prev-id = top-id + 1.
                top-id = top-id + 1.

                CREATE tt-status.
 
                ASSIGN
                    xid = prev-id
                    xsite-id = cf_status.Site_id
                    xresrc-id = cf_status.resrc_id
                    xdate = cf_status.STATUS_date
                    xtime = cf_status.STATUS_time
                    xseconds = 0
		    xorder = 1
                    xstatus = cf_status.STATUS_status.
		    RUN calc-BOM.
            END.
        END.

        /* 
        ** This is the processing for the existing record
        */

        FIND FIRST tt-status WHERE
            xsite-id = cf_status.site_id AND
            xresrc-id = cf_status.resrc_id AND
            xdate = cf_status.STATUS_date AND
            xstatus = cf_status.STATUS_status NO-ERROR.
        IF AVAILABLE tt-status THEN
        DO:
            prev-id = xid.
        END.
        ELSE
        DO:
            /*
            ** The processing for an existing record that doesn't exist
            ** yet in the table
            */

            prev-id = top-id + 1.
            top-id = top-id + 1.

            CREATE tt-status.
 
            ASSIGN
                xid = prev-id
                xsite-id = cf_status.Site_id
                xresrc-id = cf_status.resrc_id
                xdate = cf_status.STATUS_date
                xtime = cf_status.STATUS_time
                xseconds = 0
		        xorder = 1
                xstatus = cf_status.STATUS_status.
		    RUN calc-BOM.
        END.
        
        ASSIGN
            hold-site-id = cf_status.site_id
            hold-resrc-id = cf_status.resrc_id
            hold-date = cf_status.STATUS_date
            hold-time = cf_status.STATUS_time
            hold-status = cf_status.STATUS_status.
     
    END. /*  FOR EACH cf_status WHERE */

    /*
    ** Debug export the data set
    */
    IF debug-4gl = 1 THEN
    DO:
        PUT SKIP.
        PUT
            (STRING (TODAY) + " " + 
            STRING (TIME, "HH:MM:SS") + 
            " - " +
            " Program : statussummary.p" +
            " Section : Exporting temp table" ) format "x(255)".
        PUT SKIP.
        FOR EACH tt-status:
            EXPORT tt-status. 
        END.
    END.

    /*
    ** Clean up days that are outside of the date range (before the
    ** selection dates.
    */
    FOR EACH tt-status WHERE xdate LT fathom-i-start_date:
        DELETE tt-status.
    END.

/*
** Take the accumulated data and push it into an easier output format
*/
sec-name = "2nd Temp Table Creation".
pgm-name = "statussummary.p".
{include/debug.i "pgm-name" "sec-name"}

FOR EACH tt-status:

    diff-dates = 0.
    DO fathom-i = 1 to Fathom-i-periods:
        diff-dates = diff-dates + 1.
	    IF xdate GE Fathom-t-beg-date[fathom-i] THEN
	    IF xdate LE Fathom-t-end-date[Fathom-i] THEN LEAVE.
    END.

    Find first out-status where
       out-status.zresrc-id = xresrc-id and
       out-status.zsite-id = xsite-id and
       out-status.zstatus = xstatus NO-ERROR.
    IF AVAILABLE out-status THEN
    DO:
	 out-status.zseconds[diff-dates] = xseconds.
    END.
    ELSE
    DO:
        create out-status.
	assign
	    out-status.zresrc-id = xresrc-id
	    out-status.zsite-id = xsite-id
	    out-status.zstatus = xstatus
	    out-status.zseconds[diff-dates] = xseconds.
    END.
END.

sec-name = "2nd Temp Table Description Validation".
pgm-name = "statussummary.p".
{include/debug.i "pgm-name" "sec-name"}

/* 
** Description validation for second temp table.
*/
FOR EACH tt-desc:
    FOR EACH tt-status:
    
        FIND FIRST out-status WHERE
           out-status.zresrc-id = xresrc-id and
           out-status.zsite-id = xsite-id and
           out-status.zstatus = ystatus NO-ERROR.
        IF NOT AVAILABLE out-status THEN
        DO:
            diff-dates = 0.
            DO fathom-i = 1 to Fathom-i-periods:
                diff-dates = diff-dates + 1.
	            IF xdate GE Fathom-t-beg-date[fathom-i] THEN
	            IF xdate LE Fathom-t-end-date[Fathom-i] THEN LEAVE.
            END.
            CREATE out-status.
	        ASSIGN
	            out-status.zresrc-id = xresrc-id
	            out-status.zsite-id = xsite-id
	            out-status.zstatus = ystatus
	            out-status.zseconds[diff-dates] = 0.
        END.
    END.
END.

sec-name = "2nd Temp Table Second Calculations".
pgm-name = "statussummary.p".
{include/debug.i "pgm-name" "sec-name"}
IF debug-4gl = 1 THEN
DO:
    PUT SKIP.
    PUT
        (STRING (TODAY) + " " + 
        STRING (TIME, "HH:MM:SS") + 
        " - " +
        " Program : statussummary.p" +
        " Section : Exporting temp table" ) format "x(255)".
    PUT SKIP.
    FOR EACH out-status:
        EXPORT out-status.
    END.
END.
/* 
** Second calculation to make up the 24 hours in a day
** Since we don't know what the "last" status was we can only put the balances
** into the "status unknown" column.
*/
hold-resrc-id = 0.
FOR EACH out-status BY zresrc-id BY zsite-id:
    IF hold-resrc-id = 0 THEN hold-resrc-id = zresrc-id.
    If zstatus = unknown-status THEN
    DO:
       DO Fathom-i = 1 to Fathom-i-periods:
           zseconds[Fathom-i] = time-value - unknown-seconds[Fathom-i].
           unknown-seconds[Fathom-i] = 0. 
       END.
    END.
    ELSE
    DO:
        DO Fathom-i = 1 to Fathom-i-periods:
	    unknown-seconds[Fathom-i] = unknown-seconds[Fathom-i] + zseconds[Fathom-i].
	END.
    END.
END.


/*
** Print Section
*/
sec-name = "Printing Report".
pgm-name = "statussummary.p".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }

Fathom-report-title = Fathom-i-Title.
IF Fathom-report-title = "" then fathom-report-title = "Specific Resource Summary Report".
Fathom-tfs-replength = length(Fathom-t-rep_name).
/*
** Begin the XML output setup and header information
*/
DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

xml-numcolumns = 0.

FOR EACH tt-desc:
   xml-numcolumns = xml-numcolumns + 1.
   xmlcolumnnames[xml-numcolumns] = tt-desc.ystatus.
END.
   
{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbserver.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
/* 
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "". */

  
/* 
** Start outputting the detail information.
**
*/

IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbserver.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no statuses logged during the dates specified!").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    /*
    ** Close up the graphing stuff
    */
    /* 
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "". */
END.
ELSE
DO: 
/* 
    RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
*/
    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    /* 
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
     */ 
    pgm-name = "xml-dbserver.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.

    /*
    ** Do the Resource level tags
    */
   
    ASSIGN
        xmlresourcename = Cf_Resrc.Site_ID
        xmlresourcetype = Cf_Resrc.Resrc_Type 
        xmlresourcesite = Cf_Resrc.Site_ID. 

    RUN xml-resource-header.

    /*
    ** DO the labels section 
    */

    {include/xml-print-labels.i}
   
    /*
    ** Dates section
    */
    
    RUN xml-print-dates.
            
    hold-status = "".
    hold-resrc-id = 0.

    /*
    ** Export the temp table for debugging
    */
    IF debug-4gl = 1 THEN
    DO:
        PUT SKIP.
        PUT
            (STRING (TODAY) + " " + 
            STRING (TIME, "HH:MM:SS") + 
            " - " +
            " Program : statussummary.p" +
            " Section : Exporting temp table" ) format "x(255)".
        PUT SKIP.
        FOR EACH out-status:
            EXPORT out-status.
        END.
    END.

    FOR EACH out-status:
        
       IF hold-status = "" THEN hold-status = zstatus.
       IF hold-resrc-id NE zresrc-id THEN
       DO:
           FIND FIRST Cf_Resrc where cf_resrc.resrc_id = zresrc-id NO-ERROR.
	       IF AVAILABLE Cf_resrc THEN
           DO:
              ASSIGN
                xmlresourcename = Cf_Resrc.Resrc_Name 
                xmlresourcetype = Cf_Resrc.Resrc_Type 
                xmlresourcesite = Cf_Resrc.Site_ID.
           END. /* OF AVAILABLE Resource */
    
           IF hold-resrc-id NE 0 THEN
           DO:
               RUN print-endtag (INPUT-OUTPUT streamdetail,
                                 INPUT "dataset").
               PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
               streamdetail = "".
           END.

           xmldatalabel = xmlresourcename.
           {include/xml-print-dataset.i}
                               
        END. /* Resource Change */

	    DO Fathom-i = 1 to Fathom-i-periods:
       
            Fathom-x = fathom-i.
	        IF zseconds[Fathom-i] = time-value THEN
	        DO:
                hold-time = zseconds[fathom-i].
                hold-status = zstatus.
                RUN print-status-24.
	        END.
	        ELSE
	        DO:
                hold-time = zseconds[fathom-i].
                hold-status = zstatus.
                IF hold-time = 0 THEN dataprecision = "0".
                RUN print-status-normal.
                IF hold-time = 0 THEN dataprecision = "2".
	        END.
        END. 

	    hold-resrc-id = zresrc-id.
    END. /* END OF FOR EACH OUT-status */

END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "dataset").

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "resource").

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "report").

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").

PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/

RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphDataSets").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"} 


sec-name = "Exiting Program".
pgm-name = "statussummary.p".
{include/debug.i "pgm-name" "sec-name"}

PROCEDURE Calc-BOM.
    /*
    ** This procedure will correctly calculate the beginning of the month
    ** for the month by month report
    */
    If Fathom-i-reportcode = "mm" THEN
    DO:
        tt-status.xdate = DATE(INTEGER(MONTH(tt-status.xdate)), 1, INTEGER(YEAR(tt-status.xdate))). 
    END.
END PROCEDURE.

PROCEDURE Print-status-24.
    dataprecision = "0".
    xmldataOutputlabel = hold-status.
    xmltestlabel = hold-status.
    RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
    RUN xml-process-date.     /* subroutine to process the date */
    CASE Fathom-i-Reportcode:
       WHEN "hh" OR WHEN "dh" THEN xmldatavalue = "00:60:00".
       WHEN "hi" THEN xmldatavalue = "00:15:00".
       OTHERWISE xmldatavalue = "24:00:00".
    END CASE.
                
	RUN xml-format-column-intervaltype.
    RUN xml-add-data. /* subroutine to process the datum */
	PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    dataprecision = "2".
END PROCEDURE.

/*
** Print the output of the details 
*/
PROCEDURE Print-status-normal.
    xmldatavalue = STRING (hold-time, "HH:MM:SS").
    IF xmldatavalue = "00:00:00" THEN xmldatavalue = "       0".

    xmldataOutputlabel = hold-status.
    xmltestlabel = hold-status.

    /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
    DO:
        RUN xml-row-header. /* Only for Graphing */
    END. */
    
    RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
    RUN xml-process-date.     /* subroutine to process the date */
                 
	RUN xml-format-column-intervaltype.
    RUN xml-add-data. /* subroutine to process the datum */
	PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
    DO:
        RUN xml-add-data-graph. /* subroutine to process the datum */
    END.
	IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
    DO:
        RUN print-endtag (INPUT-OUTPUT graph1detail,
                          INPUT "dataValues").
        RUN print-endtag (INPUT-OUTPUT graph1detail,
                          INPUT "dataset").
    END. */

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    /* PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "". */

    /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
    DO:
        RUN print-endtag (INPUT-OUTPUT graph1detail,
                          INPUT "dataValues").
        RUN print-endtag (INPUT-OUTPUT graph1detail,
                          INPUT "dataset").
    END. */

END PROCEDURE.
QUIT.
/*
** This program is for System CPU.
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

fathom-t-rep_type = "syscpu".

pgm-name = "systemcpu.p".
sec-name = "Starting".
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Report Type :" + fathom-t-rep_type.
{include/debug.i "pgm-name" "sec-name"}

DEF NEW GLOBAL SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD ResrcID AS INTEGER
   FIELD data AS decimal EXTENT 366 
   FIELD txn AS decimal  EXTENT 366
   FIELD Sec AS decimal  EXTENT 366
   FIELD lable AS character 
   FIELD name2 AS character 
   FIELD file AS character 
   FIELD sort-order AS integer 
   INDEX one FILE 
   INDEX two TYPE 
   INDEX three NAME
   INDEX four sort-order
   INDEX five ResrcID.

DEF VAR include-list AS CHAR NO-UNDO.  
DEF VAR sort-num AS INT NO-UNDO. 
DEF VAR Fathom-total AS DECIMAL EXTENT 366 NO-UNDO INITIAL 0.

/* 
** Begin Main Processing
*/
/*
** Get the Site ID and Resource ID and read the report definition
*/
/* pass-info = SESSION:PARAMETER. */

pgm-name = "SystemCPU.p".
sec-name = "Parse Input".
{include/debug.i "pgm-name" "sec-name"}
IF Fathom-PassInput NE 1 THEN
DO:
    {include/passinput.i}
END.

/* Set up date buckets */
pgm-name = "SystemCPU.p".
sec-name = "Setup Dates".
{include/debug.i "pgm-name" "sec-name"}

{ include/trenddates.i } /* Set up Dates and times in appropriate buckets */

/*
** Here is where we add multiple resource information onto the reports.
**
*/

FOR EACH tmp-resrc:

/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }

pgm-name = "SystemCPU.p".
sec-name = "include listing".
{include/debug.i "pgm-name" "sec-name"}

/* Set up rpt table */

{include/sys/cpu-list.i}. 

/* 
** Load the temp table with the appropriate records
*/
pgm-name = "SystemCPU.p".
sec-name = "Loading Temp Table".
{include/debug.i "pgm-name" "sec-name"}

create data_store.
ASSIGN
   data_store.name = "CPU_System"
   data_store.FILE = "Sys_CPU"
   data_store.sort-order = 2
   data_store.lable = "System Percent"
   data_store.resrcID = Cf_Resrc.Resrc_ID.
release data_store.

create data_store.
ASSIGN
   data_store.name = "CPU_Usr"
   data_store.FILE = "Sys_CPU"
   data_store.sort-order = 1
   data_store.lable = "User Percent"
   data_store.resrcID = Cf_Resrc.Resrc_ID.
release data_store.

create data_store.
ASSIGN
   data_store.name = "CPU_Idle"
   data_store.FILE = "Sys_CPU"
   data_store.sort-order = 3
   data_store.lable = "Idle Percent"
   data_store.resrcID = Cf_Resrc.Resrc_ID.
release data_store.

create data_store.
ASSIGN
   data_store.name = "CPU_Wait"
   data_store.FILE = "Sys_CPU"
   data_store.sort-order = 4
   data_store.lable = "Wait Percent"
   data_store.resrcID = Cf_Resrc.Resrc_ID.
release data_store.

/*
** Read samples and process them into the rpt table
*/
pgm-name = "SystemCPU.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

{include/sample-query.i}.

{include/setup-i.i}.

/*
** Increment appropriate counters
*/
{include/fathom-counters.i}.

/*
** Reading files and loading data into temp table 
*/
{include/sys/cpu-load.i}.

/*
** Add up the number of sample records we are dealing with
*/
Fathom-numsamples[Fathom-i] = Fathom-numsamples[Fathom-i] + 1.

IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).

END. /* of assignment of FOR EACH  - in sample-query.i */

END. /* OF Multiple Resource Entries */

/*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "SystemCPU.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "SystemCPU.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}
      
    RUN archive/ar-report-syscpu.p.
    
    pgm-name = "SystemCPU.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}

END.


/*
** Print Section.
*/
pgm-name = "SystemCPU.p".
sec-name = "Printing Data".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i } /* Set up report directory and names */

/*
** Calculate data before sending to xml-dbsingle,
** as we need raw data there and it processes raw
** data differently than we desire for CPU.
*/
DO Fathom-j = 1 to Fathom-i-periods:
    FOR EACH data_store:
        data_store.data[Fathom-j] = data_store.data[Fathom-j] / Fathom-Interval-Count[Fathom-j].
        Fathom-total[Fathom-j] = Fathom-total[Fathom-j] + data_store.data[Fathom-j].
    END.
    /* Fill in the idle % based on the other fields. */
    FIND FIRST data_store WHERE name = "CPU_Idle" NO-ERROR.
    IF AVAILABLE data_store THEN data_store.data[Fathom-j] = 100 - Fathom-total[Fathom-j].
END.

/* Section for XML file */
pgm-name = "systemcpu.p".
sec-name = "Begin writing XML file".
{include/debug.i "pgm-name" "sec-name"}.

/*
** Interval type is set to "D" (raw data) for all CPU reports
** regardless of what is passed in.
*/
Fathom-i-IntervalType = "D".

RUN xml-dbsingle.p.

pgm-name = "systemcpu.p".
sec-name = "Done with XML file writing.".
{include/debug.i "pgm-name" "sec-name"}.


pgm-name = "SystemCPU.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}.

QUIT.
/*
** systemdisk.p
** This program will present a trend report for disk devices.  This is 
** based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Name, resource ID, site ID, and report type.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.


DEF NEW GLOBAL SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD pct_busy AS DECIMAL EXTENT 366 INITIAL 0
   FIELD avgque AS DECIMAL  EXTENT 366 INITIAL 0
   FIELD avgwait AS DECIMAL  EXTENT 366 INITIAL 0
   FIELD avgserv AS DECIMAL EXTENT 366 INITIAL 0
   FIELD minbusy AS DECIMAL EXTENT 366 INITIAL 0
   FIELD maxbusy AS DECIMAL EXTENT 366 INITIAL 0
   FIELD numseconds AS DECIMAL EXTENT 366 INITIAL 0
   FIELD numsamples AS DECIMAL EXTENT 366 INITIAL 0
   INDEX three NAME.

DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.

/* 
** Begin Main Processing
*/
/* Disk report only outputs raw data. */
Fathom-i-intervaltype = "d".

/* Set up date buckets */

{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }
/*
** Read samples and process them into the rpt table
*/
pgm-name = "systemdisk.p".
sec-name = "Processing Samples".

{include/debug.i "pgm-name" "sec-name"}

sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

{include/sample-query.i}

{include/setup-i.i}

/* 
** Increment counters
*/
    /* Added below, inside Sys_Dev loop.
    {include/fathom-counters.i}*/
      
      FOR EACH Sys_Dev
          WHERE
          cf_sample.sample_id = Sys_Dev.sample_id:

          FIND FIRST data_store
          WHERE
          data_store.NAME = Sys_Dev.Dev_Name
          NO-ERROR.
          IF NOT AVAILABLE data_store THEN 
          DO:
              CREATE data_store.
              ASSIGN 
                  data_store.NAME = Sys_Dev.Dev_Name.
          END.
          ASSIGN
              data_store.pct_busy[Fathom-i]   = data_store.pct_busy[Fathom-i]   + Sys_Dev.Dev_Pct_Busy
              data_store.avgque[Fathom-i]     = data_store.avgque[Fathom-i]     + Sys_Dev.Dev_AvgQue
              data_store.avgwait[Fathom-i]    = data_store.avgwait[Fathom-i]    + Sys_Dev.Dev_AvgWait
              data_store.avgserv[Fathom-i]    = data_store.avgserv[Fathom-i]    + Sys_Dev.Dev_AvgServ
              data_store.numseconds[Fathom-i] = data_store.numseconds[Fathom-i] + Cf_Sample.Sample_len
              data_store.numsamples[Fathom-i] = data_store.numsamples[Fathom-i] + 1
              Fathom-Interval-recs[fathom-i]  = Fathom-Interval-recs[fathom-i] + 1
              Fathom-rec-count                = Fathom-rec-count + 1. 

          /* Min User Counts */
          IF data_store.minbusy[Fathom-i] LT 1 THEN 
              DO:
              data_store.minbusy[Fathom-i] = Sys_Dev.Dev_Pct_Busy.
          END.
          ELSE IF Sys_Dev.Dev_Pct_Busy GT 0 THEN 
              DO:
              IF data_store.minbusy[Fathom-i] GT Sys_Dev.Dev_Pct_Busy THEN 
                  data_store.minbusy[Fathom-i] = Sys_Dev.Dev_Pct_Busy.
          END.
          
          /* Max User Counts */
          IF data_store.maxbusy[Fathom-i] LT 1 THEN 
              DO:
              data_store.maxbusy[Fathom-i] = Sys_Dev.Dev_Pct_Busy.
          END.
          ELSE IF Sys_Dev.Dev_Pct_Busy GT 0 THEN 
              DO:
              IF Sys_Dev.Dev_Pct_Busy GT data_store.maxbusy[Fathom-i] THEN 
                  data_store.maxbusy[Fathom-i] = Sys_Dev.Dev_Pct_Busy.
          END.
      END. /* of FOR EACH DB_ActServ */
      
      IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
      ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).

   END. /* of assignment of FOR EACH */

/*
** Process archive records if the need arises to do so
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "systemdisk.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_Dev:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_Dev WHERE " +
                     "Ar_Dev.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_Dev.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_Dev.Dev_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_Dev.Dev_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_Dev.Dev_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_Dev.Dev_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_Dev.Dev_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.

        /* 
        ** Determine which date column the record falls into
        */
        Fathom-i = 0.
        REPEAT:
           Fathom-i = Fathom-i + 1.
           IF Ar_Dev.Dev_startdate GE Fathom-t-beg-date[Fathom-i] AND
               Ar_Dev.Dev_startdate LE Fathom-t-end-date[Fathom-i] THEN
           DO:
               IF Ar_Dev.Dev_starttime GE Fathom-t-beg-time[Fathom-i] AND
                     Ar_Dev.Dev_starttime LE Fathom-t-end-time[Fathom-i] THEN
                     LEAVE.
           END.
           IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.

        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store
        WHERE
        data_store.NAME = Ar_Dev.Dev_Name
        NO-ERROR.

        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.NAME = Ar_Dev.Dev_Name.
        END.

        ASSIGN
            data_store.pct_busy[Fathom-i]   = data_store.pct_busy[Fathom-i]   +
                                              (Ar_Dev.Dev_Pct_Busy * Ar_Dev.Dev_RecordCount)
            data_store.avgque[Fathom-i]     = data_store.avgque[Fathom-i]     +
                                              (Ar_Dev.Dev_AvgQue * Ar_Dev.Dev_RecordCount)
            data_store.avgwait[Fathom-i]    = data_store.avgwait[Fathom-i]    +
                                              (Ar_Dev.Dev_AvgWait * Ar_Dev.Dev_RecordCount)
            data_store.avgserv[Fathom-i]    = data_store.avgserv[Fathom-i]    +
                                              (Ar_Dev.Dev_AvgServ * Ar_Dev.Dev_RecordCount)
            Fathom-ar-count[1]              = Fathom-ar-count[1] + 1
            data_store.numseconds[Fathom-i] = data_store.numseconds[Fathom-i] + Ar_Dev.Dev_Length
            data_store.numsamples[Fathom-i] = data_store.numsamples[Fathom-i] + Ar_Dev.Dev_RecordCount
            Fathom-Interval-recs[fathom-i]  = Fathom-Interval-recs[fathom-i]  + Ar_Dev.Dev_RecordCount
            Fathom-rec-count                = Fathom-rec-count                + Ar_Dev.Dev_RecordCount. 
         
        /* Min User Counts */
        IF data_store.minbusy[Fathom-i] LT 1 THEN 
        DO:
            data_store.minbusy[Fathom-i] = Ar_Dev.Dev_Pct_Busy.
        END.
        ELSE IF Ar_Dev.Dev_Pct_Busy GT 0 THEN 
        DO:
            IF data_store.minbusy[Fathom-i] GT Ar_Dev.Dev_Pct_Busy THEN 
                data_store.minbusy[Fathom-i] = Ar_Dev.Dev_Pct_Busy.
        END.
      
        /* Max User Counts */
        IF data_store.maxbusy[Fathom-i] LT 1 THEN 
        DO:
            data_store.maxbusy[Fathom-i] = Ar_Dev.Dev_Pct_Busy.
        END.
        ELSE IF Ar_Dev.Dev_Pct_Busy GT 0 THEN 
        DO:
            IF Ar_Dev.Dev_Pct_Busy GT data_store.maxbusy[Fathom-i] THEN 
                data_store.maxbusy[Fathom-i] = Ar_Dev.Dev_Pct_Busy.
        END.

    END. /* of REPEAT. */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

    pgm-name = "systemdisk.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}.

END.

/*
** Print Section
*/
{ include/report-name.i }.

RUN xml-systemdisk.p.

pgm-name = "systemdisk.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** systemfilesize.p
** This program will present a trend report for 
** the file size monitor.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Define temp table to store data output
*/

DEF NEW GLOBAL SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD filesize AS DECIMAL EXTENT 366 INITIAL 0
   FIELD minavail AS DECIMAL EXTENT 366 INITIAL -1
   FIELD maxavail AS DECIMAL EXTENT 366 INITIAL -1
   FIELD cnt AS INTEGER EXTENT 366
   INDEX three Name.

/*DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.*/

/* 
** Begin Main Processing
*/
/* File size report only outputs raw data. */
Fathom-i-intervaltype = "d".

/* Create directories. */
{ include/report-name.i }.

/* Set up date buckets */
{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/
{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/

pgm-name = "systemfilesize.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

/*
** Initial for each query
*/
{include/sample-query.i}

{include/setup-i.i}
      
/*      tmp1 = integer(cf_sample.sample_len / 60). */
/*      tmp2 =cf_sample.sample_trans. */
    Fathom-Rec-Count = Fathom-Rec-Count + 1.
      
    FOR EACH Sys_FileSize
        WHERE
        cf_sample.sample_id = Sys_FileSize.sample_id:
        FIND FIRST data_store
            WHERE
            data_store.NAME = Sys_FileSize.FileSize_Name NO-ERROR.
        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.NAME = Sys_FileSize.FileSize_Name.
        END.
        ASSIGN
           data_store.filesize[Fathom-i] = data_store.filesize[Fathom-i] + Sys_FileSize.FileSize_Size
           data_store.cnt[Fathom-i] = data_store.cnt[Fathom-i] + 1.

        /* Min Available */
        IF data_store.minavail[Fathom-i] LT 0 THEN
        DO:
            data_store.minavail[Fathom-i] = Sys_FileSize.FileSize_Size.
        END.
        ELSE IF Sys_FileSize.FileSize_Size GT -1 THEN
            DO:
            IF Sys_FileSize.FileSize_Size LT data_store.minavail[Fathom-i] THEN 
                data_store.minavail[Fathom-i] = Sys_FileSize.FileSize_Size.
        END.
    
        /* Max Available */
        IF data_store.maxavail[Fathom-i] LT 0 THEN
        DO:
            data_store.maxavail[Fathom-i] = Sys_FileSize.FileSize_Size.
        END.
        ELSE IF Sys_FileSize.FileSize_Size GT 0 THEN
        DO:
            IF Sys_FileSize.FileSize_Size GT data_store.maxavail[Fathom-i] THEN 
                data_store.maxavail[Fathom-i] = Sys_FileSize.FileSize_Size.
        END.

    END. /* of FOR EACH DB_ActServ */

    IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
    ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN 
        fathom-ar-date = (cf_sample.sample_date - 1).
   
END. /* of assignment of FOR EACH (in sample-query.i) */

/*
** Process archive records if we need additional data
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "systemfilesize.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "systemfilesize.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}.

    {include/archive-type.i}.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_FileSize:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_FileSize WHERE " +
                     "Ar_FileSize.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_FileSize.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_FileSize.FileSize_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_FileSize.FileSize_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_FileSize.FileSize_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_FileSize.FileSize_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_FileSize.FileSize_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.

        /*
        ** Set the fathom-store-value appropriately based on the Fathom-i-intervaltype.
        */
        /*CASE Fathom-i-intervaltype:
            WHEN "R" THEN fathom-store-value = filesize_Recordcount.
            WHEN "S" THEN fathom-store-value = filesize_length.
            WHEN "M" THEN fathom-store-value = filesize_length / 60.
            WHEN "H" THEN fathom-store-value = filesize_length / 60 / 60.
            WHEN "T" THEN fathom-store-value = filesize_transactions.
            OTHERWISE fathom-store-value = 1.
        END CASE.*/

        /* 
        ** Determine which date column the record falls into
        */
        Fathom-i = 0.
    
        REPEAT:
           Fathom-i = Fathom-i + 1.
           IF Ar_FileSize.FileSize_startdate GE Fathom-t-beg-date[Fathom-i] AND
               Ar_FileSize.FileSize_startdate LE Fathom-t-end-date[Fathom-i] THEN
           DO:
               IF Ar_FileSize.FileSize_starttime GE Fathom-t-beg-time[Fathom-i] AND
                     Ar_FileSize.FileSize_starttime LE Fathom-t-end-time[Fathom-i] THEN
                     LEAVE.
           END.
           IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.

        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        Fathom-Rec-Count = Fathom-Rec-Count + Ar_FileSize.FileSize_RecordCount.
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_FileSize.FileSize_Length.
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_FileSize.FileSize_Transactions.
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + Ar_FileSize.FileSize_RecordCount.
    
        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store
            WHERE
            data_store.NAME = Ar_FileSize.FileSize_Name NO-ERROR.
        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.NAME = Ar_FileSize.FileSize_Name.
        END.
        ASSIGN
           data_store.filesize[Fathom-i] = data_store.filesize[Fathom-i] +
                                           (Ar_FileSize.FileSize_Size *
                                            Ar_FileSize.FileSize_RecordCount)
           data_store.cnt[Fathom-i] = data_store.cnt[Fathom-i] + Ar_FileSize.FileSize_RecordCount.

        /* Min Available */
        IF data_store.minavail[Fathom-i] LT 0 THEN
        DO:
            data_store.minavail[Fathom-i] = Ar_FileSize.FileSize_Min.
        END.
        ELSE IF Ar_FileSize.FileSize_Min GT -1 THEN
            DO:
            IF Ar_FileSize.FileSize_Min LT data_store.minavail[Fathom-i] THEN 
                data_store.minavail[Fathom-i] = Ar_FileSize.FileSize_Min.
        END.
        
        /* Max Available */
        IF data_store.maxavail[Fathom-i] LT 0 THEN
            DO:
            data_store.maxavail[Fathom-i] = Ar_FileSize.FileSize_Max.
        END.
        ELSE IF Ar_FileSize.FileSize_Max GT 0 THEN
            DO:
            IF Ar_FileSize.FileSize_Max GT data_store.maxavail[Fathom-i] THEN 
                data_store.maxavail[Fathom-i] = Ar_FileSize.FileSize_Max.
        END.
             
    END. /* of REPEAT. */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

    pgm-name = "systemfilesize.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}.

END. /* of date validation */


/* 
** Validate data stores against # of samples...  
*/
FIND FIRST data_store NO-LOCK NO-ERROR.
IF NOT AVAILABLE data_store THEN Fathom-Rec-Count = 0.


/*
** Print Section
*/

RUN xml-systemfilesize.p.

sec-name = "Exiting Program".
pgm-name = "systemfilesys.p".
{include/debug.i "pgm-name" "sec-name"}.

QUIT.
/*
** systemfilesystem.p
** This program will present a trend report for Filesystems.  This is 
** based on the dates provided to the report.  
** The dates will be defined in the Trend database in the table Cf_Rep_Def.  
** The only information that needs to be provided to the report is
** the Report Definition Name, Resource ID, Site ID, and ?.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
** NOTE:The header information for the report does not use the standard include.
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

/* 
** Define temp table to store results in 
*/

DEF NEW GLOBAL SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD Mount AS character 
   FIELD capacity AS DECIMAL EXTENT 366 INITIAL 0
   FIELD UsedPct AS DECIMAL  EXTENT 366 INITIAL 0
   FIELD vavail AS DECIMAL EXTENT 366 INITIAL 0
   FIELD maxavail AS DECIMAL EXTENT 366 INITIAL 0
   FIELD minavail AS DECIMAL EXTENT 366 INITIAL 0
   FIELD cnt AS INTEGER EXTENT 366 INITIAL 0
   FIELD seconds AS DECIMAL EXTENT 366 INITIAL 0
   INDEX two Mount 
   INDEX three Name.

DEF VAR Fathom-store-value AS DECIMAL NO-UNDO.

/* 
** Begin Main Processing
*/

/* Set up date buckets */

{include/trenddates.i}.

/*
** Read the resource record for resource ID
*/

{ include/read-resrc.i }

/*
** Read samples and process them into the rpt table
*/

pgm-name = "systemfilesystem.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

/* 
** Initial For each query
*/
{include/sample-query.i}
      
{include/setup-i.i}

      FOR EACH Sys_FileSys
          WHERE
          cf_sample.sample_id = Sys_FileSys.sample_id:
          FIND FIRST data_store
              WHERE
              data_store.NAME = Sys_FileSys.FileSys_Name and
              data_store.mount = Sys_FileSys.FileSys_Mount
              NO-ERROR.
          IF NOT AVAILABLE data_store THEN 
          DO:
              CREATE data_store.
              ASSIGN 
                  data_store.NAME = Sys_FileSys.FileSys_Name
                  data_store.Mount = Sys_FileSys.FileSys_Mount.
          END.
          ASSIGN
             data_store.usedpct[Fathom-i] = data_store.usedpct[Fathom-i] +
                                            (Sys_FileSys.FileSys_UsedPct *
                                             Cf_Sample.Sample_Len)
             data_store.vAvail[Fathom-i] = data_store.vAvail[Fathom-i] + Sys_FileSys.FileSys_Avail
             data_store.cnt[Fathom-i] = data_store.cnt[Fathom-i] + 1
             data_store.seconds[Fathom-i] = data_store.seconds[Fathom-i] + Cf_Sample.Sample_Len.

          Fathom-Rec-Count = Fathom-Rec-Count + 1.
          Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + 1.

          /* Max Capacity */
          IF data_store.capacity[Fathom-i] LT 1 THEN
          DO:
              data_store.capacity[Fathom-i] = Sys_FileSys.FileSys_capacity.
          END.
          ELSE IF Sys_FileSys.FileSys_capacity GT 0 THEN
          DO:
              IF Sys_FileSys.FileSys_capacity GT data_store.capacity[Fathom-i] THEN 
                  data_store.capacity[Fathom-i] = Sys_FileSys.FileSys_capacity.
          END.

          /* Min Available */
          IF data_store.minavail[Fathom-i] LT 1 THEN
          DO:
              data_store.minavail[Fathom-i] = Sys_FileSys.FileSys_Avail.
          END.
          ELSE IF Sys_FileSys.FileSys_Avail GT 0 THEN
          DO:
              IF Sys_FileSys.FileSys_Avail LT data_store.minavail[Fathom-i] THEN 
                  data_store.minavail[Fathom-i] = Sys_FileSys.FileSys_Avail.
          END.

          /* Max Available */
          IF data_store.maxavail[Fathom-i] LT 1 THEN
          DO:
              data_store.maxavail[Fathom-i] = Sys_FileSys.FileSys_Avail.
          END.
          ELSE IF Sys_FileSys.FileSys_Avail GT 0 THEN
          DO:
              IF Sys_FileSys.FileSys_Avail GT data_store.maxavail[Fathom-i] THEN 
                  data_store.maxavail[Fathom-i] = Sys_FileSys.FileSys_Avail.
          END.

      END. /* of FOR EACH DB_ActServ */

      IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
      ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN 
          fathom-ar-date = (cf_sample.sample_date - 1).
   
   END. /* of assignment of FOR EACH */
/*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "systemfilesystem.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "systemfilesystem.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}

    IF Fathom-i-intervaltype NE "D" THEN
    DO:
        PUT SKIP.
        PUT
           (STRING (TODAY) + " " + 
            STRING (TIME, "HH:MM:SS") + 
            " This report can only be run with raw data. ") 
            format "x(255)".
        PUT SKIP.
    END.

    {include/archive-type.i}.

    DEFINE VARIABLE qh AS WIDGET-HANDLE.
    
    CREATE QUERY qh.
    qh:SET-BUFFERS(BUFFER Ar_FileSys:HANDLE).
    qh:QUERY-PREPARE("FOR EACH Ar_FileSys WHERE " +
                     "Ar_FileSys.Resrc_ID EQ " + STRING(Fathom-i-Resrc_ID) + " AND " +
                     "Ar_FileSys.Site_ID EQ ~"" + Fathom-i-site_ID + "~" AND " +
                     "Ar_FileSys.FileSys_StartDate LT " + STRING(Fathom-ar-date) + " AND " +
                     "Ar_FileSys.FileSys_Startdate GE " + STRING(Fathom-i-start_date) + " AND " +
                     "Ar_FileSys.FileSys_StartTime GE " + STRING(Fathom-i-Start_time) + " AND " +
                     "Ar_FileSys.FileSys_StartTime LE " + STRING(Fathom-i-End_time) + " AND " +
                     "Ar_FileSys.FileSys_ArchiveType EQ ~"" + archiveType + "~"").
    qh:QUERY-OPEN().
    
    REPEAT:
        qh:GET-NEXT.
        IF qh:QUERY-OFF-END THEN LEAVE.

        /* 
        ** Determine which date column the record falls into
        */
        Fathom-i = 0.
        REPEAT:
           Fathom-i = Fathom-i + 1.
           IF Ar_FileSys.FileSys_startdate GE Fathom-t-beg-date[Fathom-i] AND
               Ar_FileSys.FileSys_startdate LE Fathom-t-end-date[Fathom-i] THEN
           DO:
               IF Ar_FileSys.FileSys_starttime GE Fathom-t-beg-time[Fathom-i] AND
                     Ar_FileSys.FileSys_starttime LE Fathom-t-end-time[Fathom-i] THEN
                     LEAVE.
           END.
           IF Fathom-i EQ Fathom-i-periods THEN LEAVE.
        END.

        Fathom-ar-count[1] = Fathom-ar-count[1] + 1.
        Fathom-Rec-Count = Fathom-Rec-Count + Ar_FileSys.FileSys_RecordCount.
        Fathom-Interval-Count[Fathom-i] = Fathom-Interval-Count[Fathom-i] + Ar_FileSys.FileSys_Length.
        Fathom-Transaction-Count[Fathom-i] = Fathom-Transaction-Count[Fathom-i] + Ar_FileSys.FileSys_Transactions.
        Fathom-Interval-recs[fathom-i] = Fathom-Interval-recs[fathom-i] + Ar_FileSys.FileSys_RecordCount.

        /*
        ** Process each field that is on the report
        */
        FIND FIRST data_store WHERE
            data_store.NAME = Ar_FileSys.FileSys_Name and
            data_store.mount = Ar_FileSys.FileSys_Mount
            NO-ERROR.
          
        IF NOT AVAILABLE data_store THEN 
        DO:
            CREATE data_store.
            ASSIGN 
                data_store.NAME = Ar_FileSys.FileSys_Name
                data_store.Mount = Ar_FileSys.FileSys_Mount.
        END.
        ASSIGN
            data_store.usedpct[Fathom-i] = data_store.usedpct[Fathom-i] + 
                                           (Ar_FileSys.FileSys_UsedPct *
                                            Ar_FileSys.FileSys_Length)
            data_store.vAvail[Fathom-i] = data_store.vAvail[Fathom-i] + 
                                          (Ar_FileSys.FileSys_Avail *
                                           Ar_FileSys.FileSys_RecordCount)
            data_store.cnt[Fathom-i] = data_store.cnt[Fathom-i] + Ar_FileSys.FileSys_RecordCount
            data_store.seconds[Fathom-i] = data_store.seconds[Fathom-i] + Ar_FileSys.FileSys_Length.
    
        /* Max Capacity */
        IF data_store.capacity[Fathom-i] LT 1 THEN
        DO:
            data_store.capacity[Fathom-i] = Ar_FileSys.FileSys_capacity.
        END.
        ELSE IF Sys_FileSys.FileSys_capacity GT 0 THEN
        DO:
            IF Sys_FileSys.FileSys_capacity GT data_store.capacity[Fathom-i] THEN 
                data_store.capacity[Fathom-i] = Ar_FileSys.FileSys_capacity.
        END.

        /* NOTE: min and max not available in archived data. */
        /* Min Available */
        IF data_store.minavail[Fathom-i] LT 1 THEN
        DO:
            data_store.minavail[Fathom-i] = -1.
        END.
    
        /* Max Available */
        IF data_store.maxavail[Fathom-i] LT 1 THEN
        DO:
            data_store.maxavail[Fathom-i] = -1.
        END.

    END. /* of REPEAT. */

    qh:QUERY-CLOSE().
    DELETE OBJECT qh.

    pgm-name = "systemfilesystem.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}

END. /* FOR EACH ar_filesys */

/*
** Print Section
*/
sec-name = "Printing Output".
pgm-name = "systemfilesystem.p".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i }.

RUN xml-systemfilesystem.p.

sec-name = "Exiting Program".
pgm-name = "systemfilesystem.p".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** This program is an intermediate program for trenddbsingle.p
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
 - grouped multiple assignements to 1 ASSIGN
*/

{include/definitions.i "SHARED"}

IF Fathom-PassInput NE 1 THEN
DO:
    {include/fathom-dir.i}

    {include/passinput.i}
END.

ASSIGN
  Fathom-t-rep_type = "sysmem".
  pgm-name = "systemmemory.p".
  sec-name = "Starting".
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Report Type :" + fathom-t-rep_type.
{include/debug.i "pgm-name" "sec-name"}

DEF NEW SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name          AS CHARACTER
    FIELD Type          AS CHARACTER
    FIELD physicalavg   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicalmax   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicalused  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicaltotal AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualavg    AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualmax    AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualused   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualtotal  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD pagein        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD pageout       AS DECIMAL EXTENT 366 INITIAL 0
    FIELD cnt           AS DECIMAL EXTENT 366 INITIAL 0
    INDEX three NAME.

DEF VAR include-list AS CHAR NO-UNDO.  
DEF VAR sort-num AS INT NO-UNDO. 
DEFINE VARIABLE physicalused AS DECIMAL INITIAL 0 NO-UNDO.
DEFINE VARIABLE virtualused  AS DECIMAL INITIAL 0 NO-UNDO.
/* 
** Begin Main Processing
*/
/* Memory report only outputs raw data. */
Fathom-i-intervaltype = "d".

/*
** Get the Site ID and Resource ID and read the report definition
*/
/* pass-info = SESSION:PARAMETER. */

ASSIGN
  pgm-name = "systemmemory.p"
  sec-name = "Parse Input".
{include/debug.i "pgm-name" "sec-name"}
IF Fathom-PassInput NE 1 THEN
DO:
    {include/passinput.i}
END.

/* Set up date buckets */
pgm-name = "systemmemory.p".
sec-name = "Setup Dates".
{include/debug.i "pgm-name" "sec-name"}

{ include/trenddates.i } /* Set up Dates and times in appropriate buckets */

pgm-name = "systemmemory.p".
sec-name = "include listing".
{include/debug.i "pgm-name" "sec-name"}
/*
** Read the resource record for resource ID
*/
{ include/read-resrc.i }

/* Set up rpt table */

{include/sys/mem-list.i}

/*
** Read samples and process them into the rpt table
*/
pgm-name = "systemmemory.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}

FOR EACH tmp-resrc:

    FIND FIRST data_store WHERE data_store.name = tmp-resrc.tResrcName NO-LOCK NO-ERROR.
    
    IF NOT AVAILABLE data_store THEN
    DO:
        CREATE data_store.
        ASSIGN
            data_store.name = tResrcName.
    END.
    
    /*
    ** For each query standard to reports
    */
    {include/sample-query.i}
    
        {include/setup-i.i}.
       
        /*
        ** Increment appropriate counters
        */
        {include/fathom-counters.i}.
    
        /*
        ** Reading files and loading data into temp table 
        */
        FIND FIRST Sys_Mem WHERE cf_sample.sample_id = Sys_Mem.sample_ID NO-LOCK NO-ERROR.
    
        physicalused = Sys_Mem.Mem_SysTot - Sys_Mem.Mem_SysFree.
        virtualused  = Sys_Mem.Mem_VirtTot - Sys_Mem.Mem_VirtFree.
    
        ASSIGN
            data_store.physicalavg[Fathom-i]   = data_store.physicalavg[Fathom-i] + physicalused
            data_store.physicalused[Fathom-i]  = data_store.physicalused[Fathom-i] + physicalused
            data_store.physicaltotal[Fathom-i] = data_store.physicaltotal[Fathom-i] + Sys_Mem.Mem_SysTot
            data_store.virtualavg[Fathom-i]    = data_store.virtualavg[Fathom-i] + virtualused
            data_store.virtualused[Fathom-i]   = data_store.virtualused[Fathom-i] + virtualused
            data_store.virtualtotal[Fathom-i]  = data_store.virtualtotal[Fathom-i] + Sys_Mem.Mem_VirtTot
            data_store.pagein[Fathom-i]        = data_store.pagein[Fathom-i] + Sys_Mem.Mem_PgIn
            data_store.pageout[Fathom-i]       = data_store.pageout[Fathom-i] + Sys_Mem.Mem_PgOut
            data_store.cnt[Fathom-i]           = data_store.cnt[Fathom-i] + 1.
    
        /* Physical Maximum Used. */
        IF data_store.physicalmax[Fathom-i] LT 1 THEN
        DO:
            ASSIGN data_store.physicalmax[Fathom-i] = physicalused.
        END.
        ELSE IF physicalused GT 0 AND
            physicalused GT data_store.physicalmax[Fathom-i] THEN 
        DO:
            ASSIGN data_store.physicalmax[Fathom-i] = physicalused.
        END.
    
        /* Virtual Maximum Used. */
        IF data_store.virtualmax[Fathom-i] LT 1 THEN
        DO:
            ASSIGN data_store.virtualmax[Fathom-i] = virtualused.
        END.
        ELSE IF virtualused GT 0 AND
            virtualused GT data_store.virtualmax[Fathom-i] THEN 
        DO:
            ASSIGN data_store.virtualmax[Fathom-i] = virtualused.
        END.
    
        IF fathom-ar-date = ? THEN 
            fathom-ar-date = cf_sample.sample_date.
        ELSE 
            IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN 
                fathom-ar-date = (cf_sample.sample_date - 1).
    
    END. /* of assignment of FOR EACH  - in sample-query.i */

END. /* FOR EACH tmp-resrc */

/*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "systemmemory.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date GT fathom-i-start_date THEN
DO:
    pgm-name = "systemmemory.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}
      
    RUN archive/ar-report-sysmem.p.
    
    pgm-name = "systemmemory.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}

END.

/*
** Print Section.
*/
pgm-name = "systemmemory.p".
sec-name = "Printing Data".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i } /* Set up report directory and names */

FOR EACH data_store:
    fathom-i = fathom-i + 1.
END.

pgm-name = "systemmemory.p".
sec-name = "# of Data Records :" + STRING( Fathom-i).
{include/debug.i "pgm-name" "sec-name"}

RUN xml-systemmemory.p.

pgm-name = "systemmemory.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** trenddbsingle.p
** This program will present a trend report based on the dates provided to
** the report.  The dates will be defined in the Trend database in the table
** Cf_Rep_Def.  The only information that needs to be provided to the report is
** the Report Definition Number.
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

{include/definitions.i "SHARED"} /* Field definitions common across programs */

pgm-name = "TrendSingle.p".
sec-name = "Starting".
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Report Type :" + fathom-t-rep_type.
{include/debug.i "pgm-name" "sec-name"}

{include/trendDBsingle-temptable.i "NEW GLOBAL SHARED"}

DEF VAR include-list AS CHAR NO-UNDO.  
DEF VAR sort-num AS INT NO-UNDO. 


/* 
** Begin Main Processing
*/

/* Set up date buckets */
pgm-name = "TrendSingle.p".
sec-name = "Setup Dates".
{include/debug.i "pgm-name" "sec-name"}

{ include/trenddates.i } /* Set up Dates and times in appropriate buckets */

/*
** Here is where we add multiple resource information onto the reports.
**
*/

FOR EACH tmp-resrc:

/* Read the resource record to set resource ID */

{ include/read-resrc.i }

pgm-name = "TrendSingle.p".
sec-name = "include listing".
{include/debug.i "pgm-name" "sec-name"}

/* Set up rpt table */
CASE  Fathom-t-rep_type:
    WHEN "dbai" THEN DO: {include/db/ai-list.i}. END.
    WHEN "dbbi" THEN DO: {include/db/bi-list.i}. END.
    WHEN "dbdisk" THEN DO: {include/db/disk-list.i}. END.
    WHEN "dblocks" THEN DO: {include/db/locking-list.i}. END.
    WHEN "dbmem" THEN DO: {include/db/memory-list.i}. END.
    WHEN "dbrec" THEN DO: {include/db/record-list.i}. END.
    WHEN "dbsum" THEN DO: {include/db/summary-list.i}. END.
    WHEN "dbdet" THEN DO: {include/db/include-list.i}. END.
    OTHERWISE 
        DO:
            pgm-name = "TrendSingle.p".
            sec-name = "Report Type Not Defined :" + Fathom-t-rep_type.
            {include/debug.i "pgm-name" "sec-name"}
            QUIT.
        end.
END CASE.

/* 
** Load the temp table with the appropriate records
*/
pgm-name = "TrendSingle.p".
sec-name = "Loading Temp Table".
{include/debug.i "pgm-name" "sec-name"}

for each _file where _file._file-num gt 0 and _file._file-num lt 16384:
    for each _field of _file:
       sort-num = LOOKUP(_field-name,include-list).
       IF sort-num NE 0 THEN
       DO:
          IF SUBSTRING (_file._file-name,1,3) NE "Ar_" THEN
          DO:
              create data_store.
              assign data_store.name = _field._field-name
                    data_store.FILE = _file._file-name
                    data_store.sort-order = sort-num.
              if index(_file._file-name,"DB_") ne 0 then data_store.type = "db".
              if index(_file._file-name,"SYS_") ne 0 then data_store.type = "sys".
              if index(_file._file-name,"NET_") ne 0 then data_store.type = "net".
              data_store.lable = _field._Label.
              data_store.resrcID = tresrcID. 
              release data_store.
          END.
       END. /* of IF THEN DO */
    END. /* of _Field FOR EACH */
END. /* of _File FOR EACH */

END. /* of first For each tmp-resrc. */

FOR EACH tmp-resrc:
/*
** Read samples and process them into the rpt table
*/
pgm-name = "TrendSingle.p".
sec-name = "Processing Samples".
{include/debug.i "pgm-name" "sec-name"}
sec-name = "resrc ID: " + string(fathom-i-resrc_id).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "site ID: " + fathom-i-site_id.
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin date: " + STRING(fathom-t-beg-date[1]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end date: " + STRING(fathom-t-end-date[fathom-i-periods]).
{include/debug.i "pgm-name" "sec-name"}
sec-name = "begin time: " + STRING(fathom-t-beg-time[1], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
sec-name = "end time: " + STRING(fathom-t-end-time[fathom-i-periods], "hh:mm:ss").
{include/debug.i "pgm-name" "sec-name"}
{include/sample-query.i}

{include/setup-i.i}
   
/*       tmp1 = integer(cf_sample.sample_len / 60). */
/*       tmp2 =cf_sample.sample_trans. */

/*
** Increment appropriate counters
*/

{include/fathom-counters.i}

Fathom-numsamples[Fathom-i] = Fathom-numsamples[Fathom-i] + 1.
/*
** Reading files and loading data into temp table 
*/      
      CASE  Fathom-t-rep_type:
         WHEN "dbai" THEN DO: {include/db/ai-load.i}. END.
         WHEN "dbbi" THEN DO: {include/db/bi-load.i}. END.
         WHEN "dbdisk" THEN DO: {include/db/disk-load.i}. END.
         WHEN "dblocks" THEN DO: {include/db/locking-load.i}. END.
         WHEN "dbmem" THEN DO: {include/db/memory-load.i}. END.
         WHEN "dbrec" THEN DO: {include/db/record-load.i}. END.
         WHEN "dbsum" THEN DO: {include/db/summary-load.i}. END.
         WHEN "dbdet" THEN DO: {include/db/include-load.i}. END.
      END CASE.
      IF fathom-ar-date = ? THEN fathom-ar-date = cf_sample.sample_date.
      ELSE IF Fathom-ar-date GT (cf_sample.sample_date - 1) THEN fathom-ar-date = (cf_sample.sample_date - 1).

END. /* of assignment of FOR EACH  - in sample-query.i */

/*
** Section to do archived data (if required)
*/
IF Fathom-ar-date = ? THEN
    Fathom-ar-date = Fathom-i-End_date + 1.

pgm-name = "TrendSingle.p".
sec-name = "Testing Archive Dates - Start Date :" + STRING(Fathom-i-start_date).
{include/debug.i "pgm-name" "sec-name"}

sec-name = "Testing Archive Dates - Archive Date :" + STRING(fathom-ar-date).
{include/debug.i "pgm-name" "sec-name"}

IF fathom-ar-date EQ ? OR Fathom-ar-date GE fathom-i-start_date THEN
DO:

    pgm-name = "TrendSingle.p".
    sec-name = "Preparing to access archive information".
    {include/debug.i "pgm-name" "sec-name"}
      
    CASE  Fathom-t-rep_type:
         WHEN "dbai" THEN RUN archive/ar-report-dbai.p.
         WHEN "dbbi" THEN RUN archive/ar-report-dbbi.p.
         WHEN "dbdisk" THEN RUN archive/ar-report-dbdisk.p.
         WHEN "dblocks" THEN RUN archive/ar-report-dblocks.p.
         WHEN "dbmem" THEN RUN archive/ar-report-dbmem.p.
         WHEN "dbrec" THEN RUN archive/ar-report-dbrec.p.
         WHEN "dbsum" THEN RUN archive/ar-report-dbsum.p.
         WHEN "dbdet" THEN RUN archive/ar-report-dbdet.p.
    END CASE.
    
    pgm-name = "TrendSingle.p".
    sec-name = "Accessing Archive Information Complete".
    {include/debug.i "pgm-name" "sec-name"}

END.

END. /* End of for each for multiple resources */


/*
** Print Section.
*/
pgm-name = "TrendSingle.p".
sec-name = "Printing Data".
{include/debug.i "pgm-name" "sec-name"}

{ include/report-name.i } /* Set up report directory and names */

FOR EACH data_store:
    fathom-i = fathom-i + 1.
END.

pgm-name = "TrendSingle.p".
sec-name = "# of Data Records :" + STRING( Fathom-i).
{include/debug.i "pgm-name" "sec-name"}
          
/*
** Test output to see if it should be in Report Type or data type 
*/
If Fathom-i-OutputType = "R" THEN
DO:
    RUN xml-dbsingle.p.
END.


pgm-name = "TrendSingle.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/*
** trenddriver.p
** This program will drive running all of the other trend reports.  This will take the appropriate
** parameters and call the appropriate report driver based on the report type passed into it.
** Information passed into this report are the Report Definition Name, the Resource ID, the Site ID,
** and the report type.
**
** Possible report types are:
**    dbai
**    dbbi
**    dbdisk
**    dblocks
**    dbmem
**    dbrec
**    dbsum
**    dbdet
**    dbckpt
**    dbindexstat
**    dbtablestat
**    syscpu
**    sysmem
**    dbserver
**    sysdev
**    sysfilesys
**    alert
**    general
**    net
**    recommend
**    custom
**    FileSize
**
**
** The beginning and ending date are contained in the table.  It then takes
** those dates and breaks them up into as equal of periods as possible.
** The number of periods for the report are also defined in the table.
** The report is written out to a flat file.  The file name is defined for
** the report in the table as well.
**
** If the -param arguement is used then the parameter passed is assumed
** to be the report number.  If the -param arguement is not used then
** the report number is prompted for.
**
*/

{include/definitions.i "NEW GLOBAL SHARED"}

{include/fathom-dir.i}

pgm-name = "trenddriver.p".
sec-name = "Begin processing".
{include/debug.i "pgm-name" "sec-name"}

/* 
** Begin Main Processing
*/

Fathom-pass-info = SESSION:PARAMETER.

    Fathom-i-rep_name = TRIM(ENTRY (1, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc_name = TRIM(ENTRY (2, Fathom-pass-info)) NO-ERROR.
    Fathom-i-site_id = TRIM(ENTRY (3, Fathom-pass-info)) NO-ERROR.
    Fathom-i-rep_type = TRIM(ENTRY (4, Fathom-pass-info)) NO-ERROR.
    Fathom-i-resrc_type = TRIM(ENTRY (4, Fathom-pass-info)) NO-ERROR.
    Fathom-t-Start_date = TRIM((ENTRY (5, Fathom-pass-info))) NO-ERROR.
    Fathom-t-End_date = TRIM((ENTRY (6, Fathom-pass-info))) NO-ERROR.
    Fathom-i-start_time = INTEGER (ENTRY (7, Fathom-pass-info)) NO-ERROR.
    Fathom-i-end_time = INTEGER (ENTRY (8, Fathom-pass-info)) NO-ERROR.
    Fathom-i-periods = INTEGER (ENTRY (9, Fathom-pass-info)) NO-ERROR.
    Fathom-i-OutputType = ENTRY (10, Fathom-pass-info) NO-ERROR.
    Fathom-i-program = ENTRY (11, Fathom-pass-info) NO-ERROR.
    Fathom-i-Title = ENTRY (12, Fathom-pass-info) NO-ERROR.
    Fathom-i-IntervalType = ENTRY (13, Fathom-pass-info) NO-ERROR.
    Fathom-i-OutputDir = ENTRY (14, Fathom-pass-info) NO-ERROR.
    Fathom-i-ResrcStatus = ENTRY (15, Fathom-pass-info) NO-ERROR.

/* Set up rpt table */

pgm-name = "trenddriver.p".
sec-name = "Run Specific Program".
{include/debug.i "pgm-name" "sec-name"}

IF fathom-i-program NE "" THEN
DO:

    /* 
    ** Make sure the program exists before running it.  We check if it has a .p or .r on the end
    ** and then try and find it.  If we can't find it then we error out.
    */
    IF SUBSTRING (fathom-i-program, LENGTH(fathom-i-program) - 1,2) NE ".r" AND 
       SUBSTRING (fathom-i-program, LENGTH(fathom-i-program) - 1,2) NE ".p" AND
       SUBSTRING (fathom-i-program, LENGTH(fathom-i-program) - 1,2) NE ".w" THEN
    DO:
        fathom-t-program = fathom-i-program + ".r".
        sec-name = SEARCH (fathom-t-program).

        IF sec-name NE ? THEN
        DO:        
            pgm-name = "trenddriver.p".
            sec-name = "Program to run :" + sec-name.
            {include/debug.i "pgm-name" "sec-name"}
        END.
        ELSE
        DO:
            fathom-t-program = fathom-i-program + ".p".
            sec-name = SEARCH (fathom-t-program).
            IF sec-name NE ? THEN
            DO:
                pgm-name = "trenddriver.p".
                sec-name = "Program to run :" + sec-name.
                {include/debug.i "pgm-name" "sec-name"}
            END.
            ELSE
            DO:           
                fathom-t-program = fathom-i-program + ".w".
                sec-name = SEARCH (fathom-t-program).
                IF sec-name NE ? THEN
                DO:
                    pgm-name = "trenddriver.p".
                    sec-name = "Program to run :" + sec-name.
                    {include/debug.i "pgm-name" "sec-name"}
                END.
                ELSE
                DO:
                    PUT SKIP "ERROR - Could not find file : " fathom-i-program " in PROPATH!".
                END.
            END.
        END.
    END.
    ELSE
    DO: 
        /*
        ** The program has an appropriate suffix so we need to validate it exists before running it.
        */
        fathom-t-program = fathom-i-program.
        sec-name = SEARCH (fathom-t-program).
        
        IF sec-name = ? THEN
        DO:
            PUT SKIP "ERROR - Could not find file : " fathom-i-program " in PROPATH!".
        END.
    END.
    IF sec-name NE ? THEN RUN VALUE(Fathom-i-program).
END.
ELSE
DO:
    CASE  Fathom-i-rep_type:
        WHEN "dbai" THEN DO: run src/dbafterimage. END.
        WHEN "dbbi" THEN DO: run src/dbbeforeimage. END.
        WHEN "dbdisk" THEN DO: run src/dbdisk. END.
        WHEN "dblocks" THEN DO: run src/dblocks. END.
        WHEN "dbmem" THEN DO: run src/dbmemory. END.
        WHEN "dbrec" THEN DO: run src/dbrecord. END.
        WHEN "dbserver" THEN DO: run src/dbservers. END.
        WHEN "dbsum" THEN DO: run src/dbsummary. END.
        WHEN "dbdet" THEN DO: run src/dbdetail. END.
        WHEN "dbckpt" THEN DO: run src/dbcheckpoint. END.
        WHEN "dbindexstat" THEN DO: run src/dbindexstat. END.
        WHEN "dbtablestat" THEN DO: run src/dbtablestat. END.
        WHEN "syscpu" THEN DO: run src/systemcpu. END.
        WHEN "sysmem" THEN DO: run src/systemmemory. END.
        WHEN "sysdev" THEN DO: run src/systemdevice. END.
        WHEN "sysfilesys" THEN DO: run src/systemfilesystem. END.
        WHEN "Alert" THEN DO: run src/alertindividual. END.
        WHEN "general" THEN DO: run src/alertgeneral. END.   
        WHEN "net" THEN DO: run src/network. END.
        WHEN "filesize" THEN DO: run src/systemfilesize. END.
        WHEN "recommend" THEN DO: run src/trendrecommend. END.
        OTHERWISE 
            DO:
                PUT SKIP "Report type of " fathom-i-rep_type " unknown!".
            END.
    END CASE.
END.

pgm-name = "trenddriver.p".
sec-name = "Exiting Program".
{include/debug.i "pgm-name" "sec-name"}

QUIT.
/* 
** xml-alertgeneral.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD h-resrc-name AS CHARACTER
   FIELD h-Site_ID AS CHARACTER
   FIELD h-Resrc_ID AS INTEGER
   FIELD h-samples AS INT EXTENT 366
   FIELD h-alert1 AS INT EXTENT 366
   FIELD h-alert2 AS INT EXTENT 366
   FIELD h-alert3 AS INT EXTENT 366
   FIELD h-alert4 AS INT EXTENT 366
   INDEX three h-resrc-name.

DEFINE VARIABLE t-sample AS INT EXTENT 366 NO-UNDO.
DEFINE VARIABLE t-alert1 AS INT EXTENT 366 NO-UNDO.
DEFINE VARIABLE t-alert2 AS INT EXTENT 366 NO-UNDO.
DEFINE VARIABLE t-alert3 AS INT EXTENT 366 NO-UNDO.
DEFINE VARIABLE t-alert4 AS INT EXTENT 366 NO-UNDO.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE del-flag AS INTEGER NO-UNDO.

dataprecision = "0".

xml-numcolumns = 5.

ASSIGN
   xmlcolumnnames[1] = "Total Alerts" 
   xmlcolumnnames[2] = "Severe Alerts"
   xmlcolumnnames[3] = "Error Alerts"
   xmlcolumnnames[4] = "Warning Alerts"
   xmlcolumnnames[5] = "Information Alerts"
   .

pgm-name = "xml-alertgeneral.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-alertgeneral.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
    
Fathom-rec-count = 0.
for each data_store:
   fathom-rec-count = fathom-rec-count + 1.
END.

IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-alertgeneral.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    /*
    ** Take out resources without alerts
    */
    FOR EACH Data_Store:
       del-flag = 0.
       DO Fathom-x = 1 to Fathom-i-periods:
           IF h-alert1[fathom-x] GT 0 THEN del-flag = 1.
           IF h-alert2[fathom-x] GT 0 THEN del-flag = 1.
           IF h-alert3[fathom-x] GT 0 THEN del-flag = 1.
           IF h-alert4[fathom-x] GT 0 THEN del-flag = 1.
       END.
       IF del-flag NE 1 THEN delete Data_Store.
    END.

    /* 
    ** Come up with the summary data
    */
       
    FOR EACH Data_Store:
       DO Fathom-x = 1 to Fathom-i-periods:
           t-sample[Fathom-x] = t-sample[fathom-x] + h-samples[fathom-x].
           t-alert1[Fathom-x] = t-alert1[fathom-x] + h-alert1[fathom-x].
           t-alert2[Fathom-x] = t-alert2[fathom-x] + h-alert2[fathom-x].
           t-alert3[Fathom-x] = t-alert3[fathom-x] + h-alert3[fathom-x].
           t-alert4[Fathom-x] = t-alert4[fathom-x] + h-alert4[fathom-x].
       END.
    END.
    RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-alertgeneral.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
   
    /*
    ** Begin processing
    */
          ASSIGN
             xmlresourcename = ""
             xmlresourcetype = ""
             xmlresourcesite = "".
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */

          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-alertgeneral.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
     
          /*
          ** Print SUMMARY Information FIRST
          */

          xmldatalabel = "SUMMARY INFORMATION".

    	  /* 
	      ** Print the data label setting
	      */
      
          {include/xml-print-dataset.i}
          
	      DO fathom-j = 1 to xml-numcolumns:

              xmldataOutputlabel = xmlcolumnnames[fathom-j].
              xmltestlabel = xmlcolumnnames[fathom-j].

    	      IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
              DO:
                  RUN xml-row-header. /* Only for Graphing */
    	      END.
    
              DO fathom-x = 1 to Fathom-i-periods:

	              RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                  RUN xml-process-date.     /* subroutine to process the date */
                
		          CASE fathom-j:
		              WHEN 1 THEN xmldatavalue = STRING (t-sample[fathom-x]).
		              WHEN 2 THEN xmldatavalue = STRING (t-alert1[fathom-x]).
		              WHEN 3 THEN xmldatavalue = STRING (t-alert2[fathom-x]).
		              WHEN 4 THEN xmldatavalue = STRING (t-alert3[fathom-x]).
		              WHEN 5 THEN xmldatavalue = STRING (t-alert4[fathom-x]).
		          END CASE.
    
                  RUN xml-format-column-intervaltype.
                  RUN xml-add-data. /* subroutine to process the datum */
                    
		          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                  streamdetail = "".
    
    	          IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                  DO:
                      RUN xml-add-data-graph. /* subroutine to process the datum */
    	          END.
              END.
		      IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
              DO:
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataValues").
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataset").
              END.
	     END.

         PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
         streamdetail = "".
         PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
         graph1detail = "".

         RUN print-endtag (INPUT-OUTPUT streamdetail,
                           INPUT "dataset").
         PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
         streamdetail = "".

          /*
          ** End of Summary Information
          */

          FOR EACH data_store
	      USE-INDEX three:
   
             pgm-name = "xml-alertgeneral.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	         ** Message Received Data
	         */

             xmldatalabel = data_store.h-resrc-name.

    	     /* 
	         ** Print the data label setting
	         */
      
             {include/xml-print-dataset.i}
          
	         DO fathom-j = 1 to xml-numcolumns:

                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

                 DO fathom-x = 1 to Fathom-i-periods:
	                 RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                     RUN xml-process-date.     /* subroutine to process the date */
                
		             CASE fathom-j:
		                 WHEN 1 THEN xmldatavalue = STRING (data_store.h-samples[fathom-x]).
		                 WHEN 2 THEN xmldatavalue = STRING (data_store.h-alert1[fathom-x]).
		                 WHEN 3 THEN xmldatavalue = STRING (data_store.h-alert2[fathom-x]).
		                 WHEN 4 THEN xmldatavalue = STRING (data_store.h-alert3[fathom-x]).
		                 WHEN 5 THEN xmldatavalue = STRING (data_store.h-alert4[fathom-x]).
		             END CASE.
    
		             RUN xml-format-column-intervaltype.
                     RUN xml-add-data. /* subroutine to process the datum */
                    
		             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                     streamdetail = "".
    
                 END. /* of DO fathom-j = 1 to num-columns */
	         END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
          RUN print-endtag (INPUT-OUTPUT streamdetail,
                            INPUT "resource").
          RUN print-endtag (INPUT-OUTPUT streamdetail,
                            INPUT "report").
    
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          RUN print-endtag (INPUT-OUTPUT graph1detail,
                            INPUT "graphDataSets").
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
    
      END.
      RUN print-endtag (INPUT-OUTPUT streamdetail,
                        INPUT "reportDataSets").
      PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
      streamdetail = "".

/*
** Close up the graphing stuff
*/

{include/xml-close-graph.i}

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-alertindividual.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD h-resrc-name AS CHARACTER
   FIELD h-Site_ID AS CHARACTER
   FIELD h-Resrc_ID AS INTEGER
   FIELD h-samples AS INT EXTENT 366
   FIELD h-alert1 AS INT EXTENT 366
   FIELD h-alert2 AS INT EXTENT 366
   FIELD h-alert3 AS INT EXTENT 366
   FIELD h-alert4 AS INT EXTENT 366
   INDEX three h-resrc-name.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE temptotal as INTEGER.

dataprecision = "0".

xml-numcolumns = 5.

ASSIGN
   xmlcolumnnames[1] = "Total Alerts" 
   xmlcolumnnames[2] = "Severe Alerts"
   xmlcolumnnames[3] = "Error Alerts"
   xmlcolumnnames[4] = "Warning Alerts"
   xmlcolumnnames[5] = "Information Alerts"
   .

pgm-name = "xml-alertindividual.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-alertindividual.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").

PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
/* Fathom-rec-count = 0.
for each data_store:
   fathom-rec-count = fathom-rec-count + 1.
END. */
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-alertindividual.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.    
    streamdetail = "".
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").    
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-alertindividual.p".
    sec-name = "Completed Initialization".    
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
   
    /*
    ** Begin processing
    */
          /* Setup the root header and data information */
   
          xmlresourcename = Fathom-i-resrc_name.
          RUN xml-resource-header.
          /*
          ** DO the labels section 
          */

          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-alertindividual.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          FOR EACH data_store
	      USE-INDEX three:
   
             pgm-name = "xml-alertindividual.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	     ** Message Received Data
	     */

             xmldatalabel = data_store.h-resrc-name.

    	     /* 
	     ** Print the data label setting
	     */
      
             {include/xml-print-dataset.i}
          
             /* xmldataOutputlabel = data_store.lable. */
	     DO fathom-j = 1 to xml-numcolumns:

            /* xmldataOutputlabel = xmldatalabel + ":" + xmlcolumnnames[fathom-j]. */
            xmldataOutputlabel = xmlcolumnnames[fathom-j].
            xmltestlabel = xmlcolumnnames[fathom-j].

    	         /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    	    IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
            DO:
                    RUN xml-row-header. /* Only for Graphing */
    	    END.
    
            DO fathom-x = 1 to Fathom-i-periods:
	            RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                RUN xml-process-date.     /* subroutine to process the date */
                
		        CASE fathom-j:
		            WHEN 1 THEN 
                    DO: 
                       xmldatavalue = STRING (data_store.h-samples[fathom-x]).
                    END.
		            WHEN 2 THEN 
                    DO:
                       xmldatavalue = STRING (data_store.h-alert1[fathom-x]).
                    END.
		            WHEN 3 THEN
                    DO:
                       xmldatavalue = STRING (data_store.h-alert2[fathom-x]).
                    END.
		            WHEN 4 THEN
                    DO:
                       xmldatavalue = STRING (data_store.h-alert3[fathom-x]).
                    END.
		            WHEN 5 THEN
                    DO:
                       xmldatavalue = STRING (data_store.h-alert4[fathom-x]).
                    END.
		        END CASE.
    
		        RUN xml-format-column-intervaltype.
                    RUN xml-add-data. /* subroutine to process the datum */
                    
		        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    	        IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                DO:
                    RUN xml-add-data-graph. /* subroutine to process the datum */
    	        END.
             END.

		     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataValues").
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataset").
             END.
	     END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    /* 	     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END. */

             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.


/* 
** Output the details section of the Severe Alerts
*/
RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
RUN print-tag (INPUT-OUTPUT streamdetail,
               INPUT "reporttitle",
               INPUT "",
               INPUT "",
               INPUT "Severe Alert Details").
    
RUN print-tag (INPUT-OUTPUT streamdetail,
               INPUT "resourcename",
               INPUT "",
               INPUT "",
               INPUT xmlresourcename).

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "resource",
                    INPUT "",
                    INPUT "",
                    INPUT "").
/* 
** Start by putting in a labels section
*/

xml-numcolumns = 7.

xmlcolumnnames[1] = "Alert Value".
xmlcolumnnames[2] = "Threshold".
xmlcolumnnames[3] = "Description".
xmlcolumnnames[4] = "Date Cleared".
xmlcolumnnames[5] = "Time Cleared".
xmlcolumnnames[6] = "Cleared By".
xmlcolumnnames[7] = "Clear Note".

{include/xml-print-labels.i}

/*
** Do the date sections as headers to the lines
*/

RUN print-starttag (INPUT-OUTPUT streamdetail,
    INPUT "times",
    INPUT "",
    INPUT "",
    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

FOR EACH cf_alert_detail WHERE
    Cf_Alert_Detail.Resrc_ID = Fathom-i-Resrc_ID AND
    Cf_Alert_Detail.Site_ID = Fathom-i-site_ID AND  
    Cf_Alert_Detail.Alert_Date GE Fathom-t-beg-date[1] AND
    Cf_Alert_Detail.Alert_Date LE Fathom-t-end-date[Fathom-i-periods] AND 
    Cf_Alert_Detail.Alert_Time GE Fathom-t-beg-time[1] AND
    Cf_Alert_Detail.Alert_Time LE Fathom-t-end-time[Fathom-i-periods] AND 
    Cf_Alert_Detail.Alert_Severity = 1:

    xmlsamplebegdate = Cf_Alert_Detail.Alert_Date.
    xmlsamplebegtime = Cf_Alert_Detail.Alert_Time.
    xmlsampleenddate = Cf_Alert_Detail.Alert_Date.
    xmlsampleendtime = Cf_Alert_Detail.Alert_Time.
                    
    RUN xml-process-date.  /* subroutine to process the date */
    /*
    ** This creates the time sub-level under times
    */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "time",
			INPUT "",
			INPUT "",
			INPUT "").

    xmlen-intext = xmldayoutbeg + " " + xmldateoutbeg.
    xmlen-intext = xmlen-intext + " " + xmltimeoutbeg.
    
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "name",
		   INPUT "",
		   INPUT "",
		   INPUT xmlen-intext).

    /*
    ** This creates the begin and end sub-levels under time
    */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "begin",
			INPUT "",
			INPUT "",
			INPUT "").

    /* Add Begin Day Name */
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "dayname",
		   INPUT "",
                   INPUT "",
                   INPUT xmldayoutbeg).

    /* Add begin date */
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "date",
                   INPUT "format",
                   INPUT "yyyy.MM.dd",
                   INPUT xmldateoutbeg).
    
    /* Add begin time */

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "time",
                   INPUT "format",
                   INPUT "HH:mm",
                   INPUT xmltimeoutbeg).
    
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "begin").

    /* Add End Day Name */
    RUN print-starttag (INPUT-OUTPUT streamdetail,
                        INPUT "end",
			INPUT "",
			INPUT "",
			INPUT "").

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "dayname",
                   INPUT "",
                   INPUT "",
                   INPUT xmldayoutend).
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "end").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "time").
/* RUN xml-add-data-timetable.  subroutine to process the datum */
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
END.
RUN print-endtag (INPUT-OUTPUT streamdetail, INPUT "times").

PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** end of the labels section for second half of report
*/

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "dataset",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

FOR EACH cf_alert_detail WHERE
    Cf_Alert_Detail.Resrc_ID = Fathom-i-Resrc_ID AND
    Cf_Alert_Detail.Site_ID = Fathom-i-site_ID AND  
    Cf_Alert_Detail.Alert_Date GE Fathom-t-beg-date[1] AND
    Cf_Alert_Detail.Alert_Date LE Fathom-t-end-date[Fathom-i-periods] AND 
    Cf_Alert_Detail.Alert_Time GE Fathom-t-beg-time[1] AND
    Cf_Alert_Detail.Alert_Time LE Fathom-t-end-time[Fathom-i-periods] AND 
    Cf_Alert_Detail.Alert_Severity = 1:

	/* Alert Value */
    xmldataOutputlabel = xmlcolumnnames[1].
    xmldatavalue = STRING (Cf_Alert_Detail.Alert_Value , "->,>>>,>>9").
    RUN xml-add-data. 
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

	/* Threshold */
    xmldataOutputlabel = xmlcolumnnames[2].
    xmldatavalue = STRING (Cf_Alert_Detail.Alert_Threshold , "->,>>>,>>9").
    RUN xml-add-data. 
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
        
	/* Description */
    xmldataOutputlabel = xmlcolumnnames[3].
    xmldatavalue = Cf_Alert_Detail.Alert_Message .
    RUN xml-add-data. 
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
        
	/* Date Cleared */
    xmldataOutputlabel = xmlcolumnnames[4].
    xmldatavalue = STRING (Cf_Alert_Detail.Alert_ClearDate , "99/99/9999").
    IF xmldatavalue = "01/01/0001" THEN xmldatavalue = "".
    RUN xml-add-data. 
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

	/* Time Cleared */
    xmldataOutputlabel = xmlcolumnnames[5].
    IF xmldatavalue NE "" THEN
    DO:
        xmldatavalue = STRING (Cf_Alert_Detail.Alert_ClearTime, "HH:MM:SS").
        IF xmldatavalue = "00:00:00" THEN xmldatavalue = "".
    END.
    RUN xml-add-data. 
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

	/* Cleared by */
    xmldataOutputlabel = xmlcolumnnames[6].
    IF xmldatavalue NE "" THEN
    DO:
        IF Cf_Alert_Detail.Alert_ClearWho = ? THEN xmldatavalue = "".
        ELSE xmldatavalue = Cf_Alert_Detail.Alert_ClearWho .
    END.
    RUN xml-add-data. 
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
        
	/* Clear Note (IF any) */
    xmldataOutputlabel = xmlcolumnnames[7].
    xmldatavalue = Cf_Alert_Detail.Alert_ClearNote .
    RUN xml-add-data. 

	PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
END.

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "dataset").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "resource").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

/* 
** End of sub-section
*/

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/

{include/xml-close-graph.i}

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-systemdisk.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
    FIELD name AS character 
    FIELD areanum AS DECIMAL
    FIELD freenum AS INT64 EXTENT 366 INITIAL 0
    FIELD totblks AS DECIMAL EXTENT 366 INITIAL 0
    FIELD hiwater AS DECIMAL EXTENT 366 INITIAL 0
    FIELD rmnum AS INT64 EXTENT 366 INITIAL 0
    FIELD blksavail AS DECIMAL EXTENT 366 INITIAL 0
    FIELD max-rmnum AS INT64 INITIAL 0
    FIELD max-freenum AS INT64 INITIAL 0
    FIELD max-totblks AS DECIMAL INITIAL 0
    FIELD max-hiwater AS DECIMAL INITIAL 0
    FIELD min-rmnum AS INT64 INITIAL 0
    FIELD min-freenum AS INT64 INITIAL 0
    FIELD min-totblks AS DECIMAL INITIAL 0
    FIELD min-hiwater AS DECIMAL INITIAL 0
    FIELD cnt AS INTEGER EXTENT 366 INITIAL 0
    INDEX three name
    INDEX two areanum.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE xmlgraphlabel as CHARACTER FORMAT "x(32)".

/*
** Custom configuration stuff for indexstat
*/
xml-numcolumns = 7.

ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Total Blocks"
   xmlcolumnnames[3] = "Hi Water Mark"
   xmlcolumnnames[4] = "Free Blocks"
   xmlcolumnnames[5] = "RM Blocks"
   xmlcolumnnames[6] = "Blocks Available"
   xmlcolumnnames[7] = "Pct. Blocks Available"
   .

pgm-name = "xml-systemdisk.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-systemdisk.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-systemdisk.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-systemdisk.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
   
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-systemdisk.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-systemdisk.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-systemdisk.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	     ** Message Received Data
	     */

             xmldatalabel = data_store.name.
          
	     /* 
	     ** Print the data label setting
	     */

             {include/xml-print-dataset.i}

	     DO fathom-j = 1 to xml-numcolumns:

                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    xmldataOutputlabel = xmldatalabel + ":" + xmldataOutputlabel.
                    RUN xml-row-header. /* Only for Graphing */
                    xmldataOutputlabel = xmlcolumnnames[fathom-j].
    	         END.
    
                 DO fathom-x = 1 to Fathom-i-periods:
                 
                    RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                    RUN xml-process-date.     /* subroutine to process the date */
                
                    CASE fathom-j: 
                       WHEN 1 THEN xmldatavalue = STRING (data_store.cnt[fathom-x]).
                       WHEN 2 THEN
                       DO:
                           IF data_store.cnt[fathom-x] = 0 THEN
                               xmldatavalue = NOT_AVAILABLE.
                           ELSE
                               xmldatavalue = STRING (data_store.totblks[fathom-x]
                                                      / data_store.cnt[fathom-x]).
                       END. 
                       WHEN 3 THEN
                       DO:
                           IF data_store.cnt[fathom-x] = 0 THEN
                               xmldatavalue = NOT_AVAILABLE.
                           ELSE
                               xmldatavalue = STRING (data_store.hiwater[fathom-x]
                                                      / data_store.cnt[fathom-x]).
                       END. 
                       WHEN 4 THEN
                       DO:
                           IF data_store.cnt[fathom-x] = 0 THEN
                               xmldatavalue = NOT_AVAILABLE.
                           ELSE
                               xmldatavalue = STRING (data_store.freenum[fathom-x]
                                                      / data_store.cnt[fathom-x]).
                       END. 
                       WHEN 5 THEN
                       DO:
                           IF data_store.cnt[fathom-x] = 0 THEN
                               xmldatavalue = NOT_AVAILABLE.
                           ELSE
                               xmldatavalue = STRING (data_store.rmnum[fathom-x]
                                                      / data_store.cnt[fathom-x]).
                       END. 
                       WHEN 6 THEN
                       DO:
                           IF data_store.cnt[fathom-x] = 0 THEN
                               xmldatavalue = NOT_AVAILABLE.
                           ELSE
                               xmldatavalue = STRING (data_store.blksavail[fathom-x]
                                                      / data_store.cnt[fathom-x]). 
                       END.
                       WHEN 7 THEN
                       DO:
                           IF data_store.cnt[fathom-x] = 0 THEN
                               xmldatavalue = NOT_AVAILABLE.
                           ELSE
                               xmldatavalue = 
                                   STRING (DECIMAL (data_store.blksavail[fathom-x] / 
        			               data_store.totblks[fathom-x]) * 100).
                       END.
                    END CASE.
                    
                    IF fathom-j = 7 THEN 
                    DO:
                        dataprecision = "2".
                    END.
                    ELSE dataprecision = "0".
    
                    /* RUN xml-format-column-intervaltype. */
                    if xmldatavalue = ? THEN xmldatavalue = "0".
                    RUN xml-add-data. /* subroutine to process the datum */
                    
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                       RUN xml-add-data-graph. /* subroutine to process the datum */
    	            END.
                 END.
                 IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataValues").
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataset").
                 END.
             END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END.
             
             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

/*
** Finish up and close everything out
*/
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbcheckpoint.p
**
**
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED VAR data_len AS DECIMAL EXTENT 366.
DEF SHARED VAR data_flush AS DECIMAL EXTENT 366.
DEF SHARED VAR data_ckptq AS DECIMAL EXTENT 366.
DEF SHARED VAR data_scan AS DECIMAL EXTENT 366.
DEF SHARED VAR data_apwq AS DECIMAL EXTENT 366.
DEF SHARED VAR data_cnt AS DECIMAL EXTENT 366.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

/*
** Custom configuration stuff for indexstat
*/

xml-numcolumns = 6.

ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Avg. Checkpoint Length (sec.)"
   xmlcolumnnames[3] = "Avg. Buffers Scanned"
   xmlcolumnnames[4] = "Avg. Buffers on Ckpt Queue"
   xmlcolumnnames[5] = "Avg. Buffers on APW Queue"
   xmlcolumnnames[6] = "Avg. Buffers Flushed at Ckpt"
   .

pgm-name = "xml-dbcheckpoint.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbcheckpoint.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

Fathom-j = 0.
DO Fathom-x = 1 to Fathom-i-periods:
   IF data_cnt[fathom-x] GT 0 THEN fathom-j = fathom-j + 1.
END.

IF Fathom-Rec-Count LT 1 AND fathom-j = 0 THEN
DO:
    pgm-name = "xml-dbcheckpoint.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbcheckpoint.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
   
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbcheckpoint.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbcheckpoint.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

   
          /*
	      ** Message Received Data
	      */

          xmldatalabel = "".
          
	      /* 
	      ** Print the data label setting
	      */

          {include/xml-print-dataset.i}

	      DO fathom-j = 1 to xml-numcolumns:

              xmldataOutputlabel = xmlcolumnnames[fathom-j].
              xmltestlabel = xmlcolumnnames[fathom-j].

    	      IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
              DO:
                  RUN xml-row-header. /* Only for Graphing */
    	      END.
    
              DO fathom-x = 1 to Fathom-i-periods:
	             RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                 RUN xml-process-date.     /* subroutine to process the date */
                
		         CASE fathom-j: 
		             WHEN 1 THEN
                     DO:
                         dataprecision = "0".
                         xmldatavalue = STRING (data_cnt[fathom-x]).
                     END.
		             WHEN 2 THEN 
                     DO:
                         IF data_cnt[fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                         DO:
                             dataprecision = "2".
                             xmldatavalue = STRING (data_len[fathom-x] / data_cnt[fathom-x]). 
                         END.
                     END.
		             WHEN 3 THEN 
                     DO:
                         IF data_cnt[fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                         DO:
                             dataprecision = "2".
                             xmldatavalue = STRING (data_scan[fathom-x] / data_cnt[fathom-x]).
                         END.
                     END.
		             WHEN 4 THEN 
                     DO:
                         IF data_cnt[fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                         DO:
                             dataprecision = "2".
                             xmldatavalue = STRING (data_ckptq[fathom-x] / data_cnt[fathom-x]).
                         END.
                     END.
		             WHEN 5 THEN 
                     DO:
                         IF data_cnt[fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                         DO:
                             dataprecision = "2".
                             xmldatavalue = STRING (data_apwq[fathom-x] / data_cnt[fathom-x]).
                         END.
                     END.
		             WHEN 6 THEN 
                     DO:
                         IF data_cnt[fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                         DO:
                             dataprecision = "2".
                             xmldatavalue = STRING (data_flush[fathom-x] / data_cnt[fathom-x]).
                         END.
                     END.
		         END CASE.
    
                 IF xmldatavalue = ? then xmldatavalue = "0".

                 RUN xml-add-data. /* subroutine to process the datum */
                    
		         PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                 streamdetail = "".
    
    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN xml-add-data-graph. /* subroutine to process the datum */
    	         END.
             END.
		     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataValues").
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataset").
             END.
	      END. /*  OF DO Fathom-j = 1 to Num-columns */

          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
   
          IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
          DO:
              RUN print-endtag (INPUT-OUTPUT graph1detail,
                                INPUT "dataValues").
              RUN print-endtag (INPUT-OUTPUT graph1detail,
                                INPUT "dataset").
          END.
                
	      RUN print-endtag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".

    END. /* of IF AVAILABLE CF_Resrc */
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "resource").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
END. /* of for each tmp-resrc */
    
/*
** Close up the graphing stuff
*/
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphDataSets").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
    
END. /* OF IF records exist */

PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Start the detail section of each of the checkpoint details.
** 
*/
Fathom-x = 0.
{include/sample-query.i}

    FOR EACH db_Checkpoint WHERE
        cf_sample.sample_id = db_Checkpoint.sample_id NO-LOCK:
        Fathom-x = Fathom-x + 1.
    END.
END.

If Fathom-x LT 256 THEN
DO:

dataprecision = "0".

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
RUN print-tag (INPUT-OUTPUT streamdetail,
               INPUT "reporttitle",
               INPUT "",
               INPUT "",
               INPUT "Checkpoint Details").
    
RUN print-tag (INPUT-OUTPUT streamdetail,
               INPUT "resourcename",
               INPUT "",
               INPUT "",
               INPUT xmlresourcename).

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "resource",
                    INPUT "",
                    INPUT "",
                    INPUT "").
/* 
** Start by putting in a labels section
*/

xml-numcolumns = 6.

xmlcolumnnames[1] = "Checkpoint Length (sec.)".
xmlcolumnnames[2] = "Buffers Scanned".
xmlcolumnnames[3] = "Dirty Buffers".
xmlcolumnnames[4] = "Buffers on Ckpt Queue".
xmlcolumnnames[5] = "Buffers on APW Queue".
xmlcolumnnames[6] = "Buffers flushed at Ckpt".

{include/xml-print-labels.i}

/*
** Do the date sections as headers to the lines
*/

RUN print-starttag (INPUT-OUTPUT streamdetail,
    INPUT "times",
    INPUT "",
    INPUT "",
    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

{include/sample-query.i}

    FOR EACH db_Checkpoint WHERE
        cf_sample.sample_id = db_Checkpoint.sample_id
        BY Checkpoint_Num:

        xmlsamplebegdate = Cf_Sample.Sample_Date.
        xmlsamplebegtime = Cf_Sample.Sample_Time.
        xmlsampleenddate = Cf_Sample.Sample_Date.
        xmlsampleendtime = Cf_Sample.Sample_Time.
                    
        RUN xml-process-date.  /* subroutine to process the date */

        /*
        ** This creates the time sub-level under times
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "time",
			                INPUT "",
			                INPUT "",
			                INPUT "").

        xmlen-intext = xmldayoutbeg + " " + xmldateoutbeg.
        xmlen-intext = xmlen-intext + " " + xmltimeoutbeg.
    
        RUN print-tag (INPUT-OUTPUT streamdetail,
                       INPUT "name",
		               INPUT "",
		               INPUT "",
		               INPUT xmlen-intext).

        /*
        ** This creates the begin and end sub-levels under time
        */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "begin",
			                INPUT "",
			                INPUT "",
			                INPUT "").

        /* Add Begin Day Name */
        RUN print-tag (INPUT-OUTPUT streamdetail,
                       INPUT "dayname",
		               INPUT "",
                       INPUT "",
                       INPUT xmldayoutbeg).

        /* Add begin date */
        RUN print-tag (INPUT-OUTPUT streamdetail,
                       INPUT "date",
                       INPUT "format",
                       INPUT "yyyy.MM.dd",
                       INPUT xmldateoutbeg).
    
        /* Add begin time */
        RUN print-tag (INPUT-OUTPUT streamdetail,
                       INPUT "time",
                       INPUT "format",
                       INPUT "HH:mm",
                       INPUT xmltimeoutbeg).
    
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "begin").

        /* Add End Day Name */
        RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "end",
			                INPUT "",
			                INPUT "",
			                INPUT "").

        RUN print-tag (INPUT-OUTPUT streamdetail,
                       INPUT "dayname",
                       INPUT "",
                       INPUT "",
                       INPUT xmldayoutend).
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "end").
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "time").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
    END.
END. /* Of sample-query.i */

RUN print-endtag (INPUT-OUTPUT streamdetail, INPUT "times").

PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** end of the labels section for second half of report
*/

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "dataset",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

{include/sample-query.i}

    FOR EACH db_Checkpoint
        WHERE
        cf_sample.sample_id = db_Checkpoint.sample_id
	    BY Checkpoint_Num:
              
	    /* Checkpoint Length */
        xmldataOutputlabel = xmlcolumnnames[1].
        xmldatavalue = STRING (Db_Checkpoint.Checkpoint_Length).
        RUN xml-add-data. 
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

	    /* Buffers Scanned */
        xmldataOutputlabel = xmlcolumnnames[2].
        xmldatavalue = STRING (Db_Checkpoint.Checkpoint_Scan).
        RUN xml-add-data. 
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

	    /* Dirty Buffers */
        xmldataOutputlabel = xmlcolumnnames[3].
        xmldatavalue = STRING (Db_Checkpoint.Checkpoint_Dirty).
        RUN xml-add-data. 
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

	    /* Buffers on Ckpt Queue */
        xmldataOutputlabel = xmlcolumnnames[4].
        xmldatavalue = STRING (Db_Checkpoint.Checkpoint_CkptQ).
        RUN xml-add-data. 
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

	    /* Buffers on APW Queue */
        xmldataOutputlabel = xmlcolumnnames[5].
        xmldatavalue = STRING (Db_Checkpoint.Checkpoint_ApwQ).
        RUN xml-add-data. 
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

	    /* Buffers Flushed at Ckpt */
        xmldataOutputlabel = xmlcolumnnames[6].
        xmldatavalue = STRING (Db_Checkpoint.Checkpoint_Flush).
        RUN xml-add-data. 
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".

    END. /* of for each DB_Checkpoint */
END. /* of sample-query.i */

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "dataset").
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "resource").
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "report").

END. /* END OF TESTING IF THERE ARE TOO MANY CHECKPOINTS TO OUTPUT */

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/* 
** End of sub-section
*/

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

/*
** Finish up and close everything out
*/
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbdisk.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO 
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD reads AS DECIMAL EXTENT 366
   FIELD writes AS DECIMAL  EXTENT 366
   FIELD bufwrites AS DECIMAL EXTENT 366
   FIELD unbufwrites AS DECIMAL EXTENT 366
   FIELD bufreads AS DECIMAL EXTENT 366
   FIELD unbufreads AS DECIMAL EXTENT 366
   INDEX two TYPE 
   INDEX three NAME.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE xmlgraphlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE hold-interval-type as CHARACTER NO-UNDO.

hold-interval-type = fathom-i-intervaltype.

xml-numcolumns = 7.

ASSIGN
   xmlcolumnnames[1] = "Sample Count" 
   xmlcolumnnames[2] = "File Reads"
   xmlcolumnnames[3] = "File Writes"
   xmlcolumnnames[4] = "Buffered Writes"
   xmlcolumnnames[5] = "Unbuffered Writes"
   xmlcolumnnames[6] = "Buffered Reads"
   xmlcolumnnames[7] = "Unbuffered Reads"
   .

pgm-name = "xml-dbdisk.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbdisk.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbdisk.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    /* RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "". */

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbdisk.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */

          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbdisk.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbdisk.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-dbdisk.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	     ** Message Received Data
	     */

             xmldatalabel = data_store.name.

    	     /* 
	     ** Print the data label setting
	     */
      
             {include/xml-print-dataset.i}
          
	         DO fathom-j = 1 to 9:

                 xmlgraphlabel = xmldatalabel + ":" + xmlcolumnnames[fathom-j].
                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    xmldataOutputlabel = xmlgraphlabel.
                    RUN xml-row-header. /* Only for Graphing */
                    xmldataOutputlabel = xmltestlabel.
    	         END. */
    
                 DO fathom-x = 1 to Fathom-i-periods:
	                RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                    RUN xml-process-date.     /* subroutine to process the date */
                
		            CASE fathom-j:
		                WHEN 1 THEN xmldatavalue = STRING(fathom-interval-recs[fathom-x]).
		                WHEN 2 THEN
                        DO:
                            IF fathom-interval-recs[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                                xmldatavalue = STRING(data_store.reads[fathom-x]).
                        END.
		                WHEN 3 THEN
                        DO:
                            IF fathom-interval-recs[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                                xmldatavalue = STRING(data_store.writes[fathom-x]).
                        END.
		                WHEN 4 THEN
                        DO:
                            IF fathom-interval-recs[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                                xmldatavalue = STRING(data_store.bufwrites[fathom-x]).
                        END.
		                WHEN 5 THEN
                        DO:
                            IF fathom-interval-recs[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                                xmldatavalue = STRING(data_store.unbufwrites[fathom-x]).
                        END.
		                WHEN 6 THEN
                        DO:
                            IF fathom-interval-recs[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                                xmldatavalue = STRING(data_store.bufreads[fathom-x]).
                        END.
		                WHEN 7 THEN
                        DO:
                            IF fathom-interval-recs[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                                xmldatavalue = STRING(data_store.unbufreads[fathom-x]).
                        END.
		            END CASE.
   
                    IF Fathom-j = 9 THEN dataprecision = "2".
                    ELSE dataprecision = "0".

                    IF Fathom-j = 1 THEN Fathom-i-intervaltype = "D".
                    ELSE Fathom-i-intervaltype = hold-interval-type.

		            RUN xml-format-column-intervaltype.
                    RUN xml-add-data. /* subroutine to process the datum */
                    
		            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                       RUN xml-add-data-graph. /* subroutine to process the datum */
    	            END. */
                 END.
		  
                 /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataValues").
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataset").
                 END. */
	         END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             /* PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "". */

    	     /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END. */

             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/

RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphDataSets").

PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").

PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbidxanalysis.p
**
**
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE tt-data
    FIELD table-name as CHARACTER
    FIELD index-name as CHARACTER
    FIELD area-name as CHARACTER
    FIELD lable as CHARACTER
    FIELD Max-records as DECIMAL
	FIELD i-rec-count as DECIMAL EXTENT 366
	FIELD i-max-blocks as DECIMAL EXTENT 366
	FIELD i-min-blocks as DECIMAL EXTENT 366
	FIELD i-avg-blocks as DECIMAL EXTENT 366
	FIELD i-max-bytes as DECIMAL EXTENT 366
	FIELD i-min-bytes as DECIMAL EXTENT 366
	FIELD i-avg-bytes as DECIMAL EXTENT 366
	FIELD i-max-utilpct as DECIMAL EXTENT 366
	FIELD i-min-utilpct as DECIMAL EXTENT 366
	FIELD i-avg-utilpct as DECIMAL EXTENT 366
	FIELD i-max-levels as DECIMAL EXTENT 366
	FIELD i-min-levels as DECIMAL EXTENT 366
	FIELD i-avg-levels as DECIMAL EXTENT 366
	INDEX one table-name
	INDEX two index-name
	INDEX three area-name
	INDEX Four Max-Records DESCENDING
	.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

/*
** Custom configuration stuff for indexstat
*/

xml-numcolumns = 9.

/* ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Max Block Count"
   xmlcolumnnames[3] = "Min Block Count"
   xmlcolumnnames[4] = "Avg Block Count"
   xmlcolumnnames[5] = "Max Byte Count"
   xmlcolumnnames[6] = "Min Byte Count"
   xmlcolumnnames[7] = "Avg Byte Count"
   xmlcolumnnames[8] = "Max Util Percent"
   xmlcolumnnames[9] = "Min Util Percent"
   xmlcolumnnames[10] = "Avg Util Percent"
   xmlcolumnnames[11] = "Max Level Count"
   xmlcolumnnames[12] = "Min Level Count"
   xmlcolumnnames[13] = "Avg Level Count"
   . */

ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Max Block Count"
   xmlcolumnnames[3] = "Avg Block Count"
   xmlcolumnnames[4] = "Max Byte Count"
   xmlcolumnnames[5] = "Avg Byte Count"
   xmlcolumnnames[6] = "Max Util Percent"
   xmlcolumnnames[7] = "Avg Util Percent"
   xmlcolumnnames[8] = "Max Level Count"
   xmlcolumnnames[9] = "Avg Level Count"
   .
/*
** Setting up the record count for testing

FOR EACH tt-data:
   Fathom-rec-count = Fathom-rec-count + 1.
END.

*/
/*
** Starting the XML portion
*/

pgm-name = "xml-dbidxanalysis.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbidxanalysis.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbidxanalysis.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    /* RUN xml-graphspec. */

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbidxanalysis.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbidxanalysis.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbidxanalysis.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH tt-data
	      USE-INDEX Four :
    
             pgm-name = "xml-dbidxanalysis.p".
             sec-name = "Parsing tt-data records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
             ** Message Received Data
             */

             xmldatalabel = tt-data.table-name + "." +
                            tt-data.index-name. 
          
             /* 
             ** Print the data label setting
             */

             {include/xml-print-dataset.i}

             DO fathom-j = 1 to xml-numcolumns:

                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    RUN xml-row-header. /* Only for Graphing */
    	         END. */
    
                 DO fathom-x = 1 to Fathom-i-periods:
                    RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                    RUN xml-process-date.     /* subroutine to process the date */
	
                    CASE fathom-j:
                        WHEN 1 THEN xmldatavalue = STRING (tt-data.i-rec-count[fathom-x]).
                        WHEN 2 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-max-blocks[fathom-x]).
                            END.
                        END. 
                        WHEN 3 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-avg-blocks[fathom-x] / 
                                                       tt-data.i-rec-count[fathom-x]).
                            END.
                        END. 
                        WHEN 4 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-max-bytes[fathom-x]). 
                            END.
                        END.
                        WHEN 5 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-avg-bytes[fathom-x] / 
                                                       tt-data.i-rec-count[fathom-x]).
                            END.
                        END. 
                        WHEN 6 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-max-utilpct[fathom-x]). 
                            END.
                        END.
                        WHEN 7 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-avg-utilpct[fathom-x] /
                                                       tt-data.i-rec-count[fathom-x]). 
                            END.
                        END.
                        WHEN 8 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-max-levels[fathom-x]). 
                            END.
                        END.
                        WHEN 9 THEN
                        DO:
                            IF i-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.i-avg-levels[fathom-x] / 
                                                       tt-data.i-rec-count[fathom-x]).  
                            END.
                        END.
                    END CASE.
   
                    If fathom-j EQ 6 OR fathom-j EQ 7
                    THEN
                    DO:
                        dataprecision = "2".
                    END.
                    ELSE dataprecision = "0".

                    /* RUN xml-format-column-intervaltype. */

                   IF xmldatavalue = ? THEN xmldatavalue = "0".

                    RUN xml-add-data. /* subroutine to process the datum */
                    
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                       RUN xml-add-data-graph. /* subroutine to process the datum */
    	            END. */
                 END.
                 /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataValues").
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataset").
                 END. */
             END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END. */
             
             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each tt-data */
    
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
/* {include/xml-close-graph.i} */

RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbindexstat.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS CHARACTER
   FIELD Name2 AS CHARACTER FORMAT "X(28)"
   FIELD TableName AS CHARACTER FORMAT "x(28)"
   FIELD Type AS CHARACTER
   FIELD reads AS DECIMAL EXTENT 366
   FIELD splits AS DECIMAL  EXTENT 366
   FIELD creates AS DECIMAL  EXTENT 366
   FIELD deletes AS DECIMAL EXTENT 366
   INDEX three NAME2
   INDEX one Type Name2.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

/*
** Custom configuration stuff for indexstat
*/

xml-numcolumns = 4.

ASSIGN
   xmlcolumnnames[1] = "Index Reads"
   xmlcolumnnames[2] = "Index Splits"
   xmlcolumnnames[3] = "Index Creates"
   xmlcolumnnames[4] = "Index Deletes" .

pgm-name = "xml-dbindexstat.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbindexstat.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbindexstat.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbindexstat.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbindexstat.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbindexstat.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-dbindexstat.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	         ** Message Received Data
	         */

             xmldatalabel = data_store.TableName + ":" + data_store.name2.
          
	         /* 
	         ** Print the data label setting
	         */

             {include/xml-print-dataset.i}

	     DO fathom-j = 1 to xml-numcolumns:

                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    RUN xml-row-header. /* Only for Graphing */
    	         END.
    
                 DO fathom-x = 1 to Fathom-i-periods:
                 RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                 RUN xml-process-date.     /* subroutine to process the date */
                
                 CASE fathom-j: 
                     WHEN 1 THEN
                     DO:
                             xmldatavalue = STRING (data_store.reads[fathom-x]). 
                     END.
                     WHEN 2 THEN
                             xmldatavalue = STRING (data_store.splits[fathom-x]).
                     WHEN 3 THEN
                             xmldatavalue = STRING (data_store.creates[fathom-x]).
                     WHEN 4 THEN
                             xmldatavalue = STRING (data_store.deletes[fathom-x]).
                END CASE.
    
                RUN xml-format-column-intervaltype.
                RUN xml-add-data. /* subroutine to process the datum */
                    
                PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                streamdetail = "".
    
	            IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                DO:
                    RUN xml-add-data-graph. /* subroutine to process the datum */
	            END.
            END.
            IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
            DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
            END.
	     END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END.
             
	     RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbserver.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO 
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD msgrec AS DECIMAL EXTENT 366
   FIELD msgsent AS DECIMAL  EXTENT 366
   FIELD byterec AS DECIMAL  EXTENT 366
   FIELD bytesent AS DECIMAL EXTENT 366
   FIELD recrec AS DECIMAL EXTENT 366
   FIELD recsent AS DECIMAL EXTENT 366
   FIELD minusers AS DECIMAL EXTENT 366
   FIELD maxusers AS DECIMAL EXTENT 366
   FIELD avgusers AS DECIMAL EXTENT 366
   FIELD seconds AS DECIMAL EXTENT 366
   INDEX two TYPE 
   INDEX three NAME.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE xmlgraphlabel as CHARACTER FORMAT "x(32)".

xml-numcolumns = 9.

ASSIGN
   xmlcolumnnames[1] = "Messages Received" 
   xmlcolumnnames[2] = "Messages Sent"
   xmlcolumnnames[3] = "Bytes Received"
   xmlcolumnnames[4] = "Bytes Sent"
   xmlcolumnnames[5] = "Records Received"
   xmlcolumnnames[6] = "Records Sent"
   xmlcolumnnames[7] = "Min Users"
   xmlcolumnnames[8] = "Max Users"
   xmlcolumnnames[9] = "Avg Users".

pgm-name = "xml-dbserver.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbserver.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbserver.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbserver.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */

          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbserver.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbserver.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-dbserver.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	     ** Message Received Data
	     */

             xmldatalabel = data_store.name.

    	     /* 
	     ** Print the data label setting
	     */
      
             {include/xml-print-dataset.i}
          
	         DO fathom-j = 1 to 9:

                 xmlgraphlabel = xmldatalabel + ":" + xmlcolumnnames[fathom-j].
                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    xmldataOutputlabel = xmlgraphlabel.
                    RUN xml-row-header. /* Only for Graphing */
                    xmldataOutputlabel = xmltestlabel.
    	         END.
    
                 DO fathom-x = 1 to Fathom-i-periods:
	                RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                    RUN xml-process-date.     /* subroutine to process the date */
                
		            CASE fathom-j:
		                WHEN 1 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.msgrec[fathom-x]).
                        END.
		                WHEN 2 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.msgsent[fathom-x]).
                        END.
		                WHEN 3 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.byterec[fathom-x]).
                        END.
		                WHEN 4 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.bytesent[fathom-x]).
                        END.
		                WHEN 5 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.recrec[fathom-x]).
                        END.
		                WHEN 6 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.recsent[fathom-x]).
                        END.
		                WHEN 7 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                                xmldatavalue = STRING (data_store.minusers[fathom-x]).
                        END.
		                WHEN 8 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.maxusers[fathom-x]).
                        END.
		                WHEN 9 THEN
                        DO:
                            IF Fathom-Interval-recs[fathom-x] = 0 THEN
                                 xmldatavalue = NOT_AVAILABLE.
                             ELSE
                                 xmldatavalue = STRING (data_store.avgusers[fathom-x] /
                                                        data_store.seconds[fathom-x]).
                        END.
		            END CASE.
   
                    IF Fathom-j = 9 THEN dataprecision = "2".
                    ELSE dataprecision = "0".

		            RUN xml-format-column-intervaltype.
                    RUN xml-add-data. /* subroutine to process the datum */
                    
		            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    	            IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                       RUN xml-add-data-graph. /* subroutine to process the datum */
    	            END.
                 END.
		  
                 IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataValues").
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataset").
                 END.
	         END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    	     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END.

             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/

{include/xml-close-graph.i}

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbsingle.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}

{include/xmldefinitions.i "NEW SHARED"}

{include/fm-environment.i "NEW SHARED"}


DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD ResrcID AS INTEGER 
   FIELD data AS decimal EXTENT 366
   FIELD txn AS decimal  EXTENT 366
   FIELD Sec AS decimal  EXTENT 366
   FIELD lable AS character 
   FIELD name2 AS character 
   FIELD file AS character 
   FIELD sort-order AS integer 
   INDEX one FILE 
   INDEX two TYPE 
   INDEX three NAME
   INDEX four sort-order
   INDEX five ResrcID.

pgm-name = "xml-dbsingle.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}

{include/xmlinitialize.i}

pgm-name = "xml-dbsingle.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

/*
** Validate that there are in fact valid sample records
*/

Fathom-j = 0.

DO Fathom-x = 1 to Fathom-i-periods:
   IF Fathom-interval-recs[fathom-x] GT 0 THEN Fathom-j = Fathom-j + 1.

END.

IF Fathom-Rec-Count LT 1 AND Fathom-j LT 1 THEN
DO:
    pgm-name = "xml-dbsingle.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbsingle.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN print-starttag (INPUT-OUTPUT streamdetail,
                             INPUT "resource",
                             INPUT "",
                             INPUT "",
                             INPUT "").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
    
          RUN xml-root-header.
          RUN xml-graphDataSets-header.
    
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
    
          /*
          ** DO the labels section 
          */
    
          RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "labels",
    			INPUT "",
    			INPUT "",
    			INPUT "").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
    
          FOR EACH data_store WHERE data_store.ResrcID = tResrcID USE-INDEX three:
    
       /*       xmldatalabel = data_store.name. */
             xmldataOutputlabel = data_store.lable.
    	 RUN print-tag (INPUT-OUTPUT streamdetail,
    	                INPUT "label",
    			INPUT "",
    			INPUT "",
    			INPUT xmldataOutputlabel).
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".
    
          END.
          RUN print-endtag (INPUT-OUTPUT streamdetail,
                            INPUT "labels").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
    
          /*
          ** Dates section
          */
    
          RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "times",
    			INPUT "",
    			INPUT "",
    			INPUT "").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
          DO fathom-x = 1 to Fathom-i-periods:
                xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                xmlsampleenddate = Fathom-t-end-date[fathom-x].
                xmlsampleendtime = Fathom-t-end-time[fathom-x].
                    
                RUN xml-process-date.  /* subroutine to process the date */
                RUN xml-add-data-timetable. /* subroutine to process the datum */
                PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                streamdetail = "".
                PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                graph1detail = "".
          END.
          RUN print-endtag (INPUT-OUTPUT streamdetail,
                            INPUT "times").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbsingle.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          RUN print-starttag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset",
    			INPUT "",
    			INPUT "",
    			INPUT "").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
          
          pgm-name = "xml-dbsingle.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}
    
          FOR EACH data_store WHERE data_store.ResrcID = tResrcID USE-INDEX three:
    
             pgm-name = "xml-dbsingle.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
    
             xmldatalabel = data_store.name.
             xmldataOutputlabel = data_store.lable.
    	 IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN
             DO:
                RUN xml-row-header. /* Only for Graphing */
    	 END.
    
             pgm-name = "xml-dbsingle.p".
             sec-name = "Writing out row header - Label :" + xmldatalabel.
             {include/debug.i "pgm-name" "sec-name"}
    
             DO fathom-x = 1 to Fathom-i-periods:
                xmlsamplebegdate = Fathom-t-beg-date[fathom-x].
                xmlsamplebegtime = Fathom-t-beg-time[fathom-x].
                xmlsampleenddate = Fathom-t-end-date[fathom-x].
                xmlsampleendtime = Fathom-t-end-time[fathom-x].
                xmlsamplecount = STRING (Fathom-numsamples[fathom-x]).
                xmlsamplelength = STRING (Fathom-Interval-Count[fathom-x]).
                xmlsampletransactions = STRING (Fathom-Transaction-Count[fathom-x]).
                IF xmlsamplelength = ? then xmlsamplelength = "0".
                IF xmlsampletransactions = ? then xmlsampletransactions = "0".

    	    /*
    	    ** Prepare the output based on the Interval Type
    	    ** (Record, Second, Minute, Hour, Transaction, raw numbers)
    	    */
    	    CASE Fathom-i-IntervalType:
                   WHEN "R" THEN xmldatavalue = 
    	          /* STRING (data_store.data[fathom-x] / Fathom-Rec-Count ). */
    	          STRING (data_store.data[fathom-x] / INTEGER (xmlsamplecount) ).
                   WHEN "S" THEN xmldatavalue = 
    	          STRING (data_store.data[fathom-x] / 
    		          INTEGER (xmlsamplelength)).
                   WHEN "M" THEN xmldatavalue = 
    	          STRING (data_store.data[fathom-x] / 
    		          (INTEGER (xmlsamplelength) / 60)).
                   WHEN "H" THEN xmldatavalue = 
    	          STRING (data_store.data[fathom-x] / 
    		          ((INTEGER (xmlsamplelength) / 60) / 60)).
                   WHEN "T" THEN xmldatavalue = 
    	          STRING (data_store.data[fathom-x] / 
    		          INTEGER (xmlsampletransactions)).
                   OTHERWISE xmldatavalue = STRING (data_store.data[fathom-x]).
                END CASE.
                IF xmldatavalue = ? then xmldatavalue = "0".
                IF Fathom-numsamples[fathom-x] = 0 THEN xmldatavalue = NOT_AVAILABLE.
               
                RUN xml-process-date.  /* subroutine to process the date */
                RUN xml-add-data. /* subroutine to process the datum */
                PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                streamdetail = "".
    	    IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN
                DO:
                   RUN xml-add-data-graph. /* subroutine to process the datum */
                   PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                   graph1detail = "".
    	    END.
             END.
    	 IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END.
          END. /* of for each data_store */
    
          RUN print-endtag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
       
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".


/*
** Close up the graphing stuff
*/
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphSpec").
RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbtabanalysis.p
**
**
*/

{include/definitions.i "SHARED"} 
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE tt-data
    FIELD table-name as CHARACTER
    FIELD area-name as CHARACTER
    FIELD lable as CHARACTER
	FIELD Max-records as DECIMAL
	FIELD r-rec-count as DECIMAL EXTENT 366
	FIELD r-max-reccount as DECIMAL EXTENT 366
	FIELD r-min-reccount as DECIMAL EXTENT 366
	FIELD r-avg-reccount as DECIMAL EXTENT 366
	FIELD r-max-bytes as DECIMAL EXTENT 366
	FIELD r-min-bytes as DECIMAL EXTENT 366
	FIELD r-avg-bytes as DECIMAL EXTENT 366
	FIELD r-max-fragcount as DECIMAL EXTENT 366
	FIELD r-min-fragcount as DECIMAL EXTENT 366
	FIELD r-avg-fragcount as DECIMAL EXTENT 366
	FIELD r-max-scatter as DECIMAL EXTENT 366
	FIELD r-min-scatter as DECIMAL EXTENT 366
	FIELD r-avg-scatter as DECIMAL EXTENT 366
	INDEX one table-name
	INDEX three area-name
	INDEX two Max-records DESCENDING
	.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

/*
** Setting up the record count for testing

FOR EACH tt-data:
   Fathom-rec-count = Fathom-rec-count + 1.
END.
*/
/*
** Custom configuration stuff for Tablestat
*/

dataprecision = "0".

xml-numcolumns = 9.

/* ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Max Record Count"
   xmlcolumnnames[3] = "Min Record Count"
   xmlcolumnnames[4] = "Avg Record Count"
   xmlcolumnnames[5] = "Max # of Bytes"
   xmlcolumnnames[6] = "Min # of Bytes"
   xmlcolumnnames[7] = "Avg # of Bytes"
   xmlcolumnnames[8] = "Max # of Fragments"
   xmlcolumnnames[9] = "Min # of Fragments"
   xmlcolumnnames[10] = "Avg # of Fragments"
   xmlcolumnnames[11] = "Max Scatter Factor"
   xmlcolumnnames[12] = "Min Scatter Factor"
   xmlcolumnnames[13] = "Avg Scatter Factor"
   . */

ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Max Record Count"
   xmlcolumnnames[3] = "Avg Record Count"
   xmlcolumnnames[4] = "Max # of Bytes"
   xmlcolumnnames[5] = "Avg # of Bytes"
   xmlcolumnnames[6] = "Max # of Fragments"
   xmlcolumnnames[7] = "Avg # of Fragments"
   xmlcolumnnames[8] = "Max Scatter Factor"
   xmlcolumnnames[9] = "Avg Scatter Factor"
   .
pgm-name = "xml-dbtabanalysis.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbtabanalysis.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbtabanalysis.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
   /*  RUN xml-graphspec. */

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbtabanalysis.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbtabanalysis.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbtabanalysis.p".
          sec-name = "Temporary Data.store ResrcID: " + STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH tt-data
	      USE-INDEX three:
    
             pgm-name = "xml-dbtabanalysis.p".
             sec-name = "Parsing tt-data records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
             ** Message Received Data
             */

             xmldatalabel = tt-data.area-name + "." +
	                        tt-data.table-name.
          
             /* 
             ** Print the data label setting
             */

             {include/xml-print-dataset.i}

             DO fathom-j = 1 to xml-numcolumns:

                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    RUN xml-row-header. /* Only for Graphing */
    	         END. */
    
                 DO fathom-x = 1 to Fathom-i-periods:
                    RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                    RUN xml-process-date.     /* subroutine to process the date */
	
                    CASE fathom-j:
                        WHEN 1 THEN xmldatavalue = STRING (tt-data.r-rec-count[fathom-x]). 
                        WHEN 2 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-max-reccount[fathom-x]).
                            END.
                        END. 
                        WHEN 3 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-avg-reccount[fathom-x] / 
                                                       tt-data.r-rec-count[fathom-x]).
                            END.
                        END. 
                        WHEN 4 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-max-bytes[fathom-x]).
                            END.
                        END. 
                        WHEN 5 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-avg-bytes[fathom-x] / 
			                                           tt-data.r-rec-count[fathom-x]). 
                            END.
                        END.
                        WHEN 6 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-max-fragcount[fathom-x]).
                            END.
                        END. 
                        WHEN 7 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-avg-fragcount[fathom-x] /
			                                           tt-data.r-rec-count[fathom-x]).
                            END.
                        END. 
                        WHEN 8 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-max-scatter[fathom-x]).
                            END.
                        END. 
                        WHEN 9 THEN
                        DO:
                            IF r-rec-count[fathom-x] = 0 THEN
                                xmldatavalue = NOT_AVAILABLE.
                            ELSE
                            DO:
                                xmldatavalue = STRING (tt-data.r-avg-scatter[fathom-x] / 
			                                           tt-data.r-rec-count[fathom-x]). 
                            END.
                        END.
                    END CASE.
   
                        /* 
                        ** Removed from the case statement and report
                        **
                        WHEN 3 THEN xmldatavalue = STRING (tt-data.r-min-reccount[fathom-x]). 
                        WHEN 6 THEN xmldatavalue = STRING (tt-data.r-min-bytes[fathom-x]). 
                        WHEN 9 THEN xmldatavalue = STRING (tt-data.r-min-fragcount[fathom-x]). 
                        WHEN 12 THEN xmldatavalue = STRING (tt-data.r-min-scatter[fathom-x]). 
                        */

                    /* RUN xml-format-column-intervaltype. */

                    IF xmldatavalue = ? THEN xmldatavalue = "0".

                    RUN xml-add-data. /* subroutine to process the datum */
                    
                    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                       RUN xml-add-data-graph. /* subroutine to process the datum */
    	            END. */
                 END.
                 /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataValues").
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataset").
                 END. */
             END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END. */
             
             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each tt-data */
    
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
/*     RUN print-starttag (INPUT-OUTPUT graph1detail,
                        INPUT "graphSpec",
                        INPUT "",
                        INPUT "",
                        INPUT ""). */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
/* {include/xml-close-graph.i} */

RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}

/* 
** xml-dbtablestat.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS CHARACTER
   FIELD Name2 AS CHARACTER FORMAT "X(28)"
   FIELD Type AS CHARACTER
   FIELD reads AS DECIMAL EXTENT 366
   FIELD updates AS DECIMAL  EXTENT 366
   FIELD creates AS DECIMAL  EXTENT 366
   FIELD deletes AS DECIMAL EXTENT 366
   INDEX three NAME2
   INDEX one Type Name2.

DEF NEW SHARED TEMP-TABLE total_store 
   FIELD Name AS CHARACTER
   FIELD name2 AS CHARACTER FORMAT "X(28)"
   FIELD Type AS CHARACTER
   FIELD id AS INTEGER   
   FIELD reads AS DECIMAL EXTENT 366
   FIELD updates AS DECIMAL  EXTENT 366
   FIELD creates AS DECIMAL  EXTENT 366
   FIELD deletes AS DECIMAL EXTENT 366
   INDEX three NAME2
   INDEX one Type name2.
   
DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE xmlgraphcount AS INTEGER NO-UNDO.
DEFINE VARIABLE xmltablecount AS INTEGER NO-UNDO.

/*
** Custom configuration stuff for indexstat
*/

xml-numcolumns = 4.

ASSIGN
   xmlcolumnnames[1] = "Record Reads"
   xmlcolumnnames[2] = "Record Updates"
   xmlcolumnnames[3] = "Record Creates"
   xmlcolumnnames[4] = "Record Deletes" .

pgm-name = "xml-dbtablestat.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbtablestat.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbtablestat.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbtablestat.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
   
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
   
    xmlgraphcount = INTEGER (OS-GETENV("GRAPHCOUNT")) NO-ERROR.
    if xmlgraphcount = ? THEN
    
    DO:
       xmlgraphcount = 5.
    END.
    xmltablecount = 0.

    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbtablestat.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbtablestat.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-dbtablestat.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	         ** Message Received Data
	         */

             xmldatalabel = data_store.name2.
          
	         /* 
	         ** Print the data label setting
	         */

             {include/xml-print-dataset.i}

	         DO fathom-j = 1 to xml-numcolumns:

                 FIND FIRST total_store
                     WHERE
                     total_store.name = STRING (fathom-j)
                     NO-ERROR.
                 IF NOT AVAILABLE total_store THEN 
                 DO:
                     CREATE total_store.
                     ASSIGN 
                         total_store.name = STRING (fathom-j)
                         total_store.id = fathom-j.
                 END.
             
                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

                 DO fathom-x = 1 to Fathom-i-periods:
	                 RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                     RUN xml-process-date.     /* subroutine to process the date */
                
/* 20050621-001 */
		             CASE fathom-j: 
		                 WHEN 1 THEN
                         DO:
                                 xmldatavalue = STRING (data_store.reads[fathom-x]).
                             ASSIGN
                                 total_store.reads[fathom-x] = total_store.reads[fathom-x] + data_store.reads[fathom-x]. 
                         END. 
		                 WHEN 2 THEN
                         DO:
                                 xmldatavalue = STRING (data_store.updates[fathom-x]). 
                             ASSIGN
                                 total_store.updates[fathom-x] = total_store.updates[fathom-x] + data_store.updates[fathom-x]. 
                         END.
		                 WHEN 3 THEN
                         DO:
                                 xmldatavalue = STRING (data_store.creates[fathom-x]). 
                             ASSIGN
                                 total_store.creates[fathom-x] = total_store.creates[fathom-x] + data_store.creates[fathom-x]. 
                         END.
		                 WHEN 4 THEN
                         DO:
                                 xmldatavalue = STRING (data_store.deletes[fathom-x]).
                             ASSIGN
                                 total_store.deletes[fathom-x] = total_store.deletes[fathom-x] + data_store.deletes[fathom-x]. 
                         END.
		             END CASE.
    
		             RUN xml-format-column-intervaltype.
                     RUN xml-add-data. /* subroutine to process the datum */
                    
		             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                     streamdetail = "".
                 END.
                 END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

    	     /* IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END. */
	         RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

             xmltablecount = xmltablecount + 1.
          END. /* of for each data_store */
    
/*
** bug 20050621-001            
** Total all tables for graph
** When table numeric data was finally obtained for this report the graph was wrong.  
** The graph was not showing any useful information just several hundred horizontal lines (#tables * 4).
** There is too much data to plot meaningful individual R/U/C/D activity for each table on one graph.
   ** No legends could be displayed because there were so many. The choices seemed to be:
**   1. show the results up to a maximum of one or two tables (they might not have any activity).
**   2. locate and show the most active table.
**   3. show the total activity from all the tables.
**   4. show the average activity across all the tables.
** Chose #3.
*/             
          FOR EACH total_store
	      USE-INDEX three:

             xmldataOutputlabel = xmlcolumnnames[total_store.id].
             xmltestlabel = xmlcolumnnames[total_store.id].
    	      IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
              DO:
                  RUN xml-row-header.
    	      END.

              DO fathom-x = 1 to Fathom-i-periods:
	              RUN xml-setup-outputvars.
                  RUN xml-process-date.    

                  CASE total_store.id:
                      WHEN 1 THEN
                      DO:
                          xmldatavalue = STRING(total_store.reads[fathom-x]).
                      END. 
		              WHEN 2 THEN
                      DO:
                          xmldatavalue = STRING(total_store.updates[fathom-x]).
                      END.
                      WHEN 3 THEN
                      DO:
                          xmldatavalue = STRING(total_store.creates[fathom-x]).
                      END.
		              WHEN 4 THEN
                      DO:
                          xmldatavalue = STRING(total_store.deletes[fathom-x]).
                      END.
                  END CASE.
  
                  IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                  DO:
                      RUN xml-add-data-graph.
                  END.
              END.

              IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
              DO:
                  RUN print-endtag (INPUT-OUTPUT graph1detail,
                                    INPUT "dataValues").
                  RUN print-endtag (INPUT-OUTPUT graph1detail,
                                    INPUT "dataset").
              END.
          END. /* of for each total-store */
/* 20050621-001 */
             
          PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
          graph1detail = "".
             
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

/*
** Finish up and close everything out
*/
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-network.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}.
{include/xmldefinitions.i "NEW SHARED"}.
{include/xmlprocs.i "NEW SHARED"}.
{include/fm-environment.i "NEW SHARED"}.

DEF SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name AS CHARACTER
    FIELD passedSamples AS DECIMAL EXTENT 366 INITIAL 0
    FIELD failedSamples AS DECIMAL EXTENT 366 INITIAL 0
    FIELD h-values      AS DECIMAL EXTENT 366 INITIAL 0
    INDEX three Name.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".
DEFINE VARIABLE hold-intervaltype as CHARACTER FORMAT "x(32)".

xml-numcolumns = 3.

/* 
** Setting this so that we preserve sample counts appropriately.
*/
hold-intervaltype = Fathom-i-intervaltype.

ASSIGN
    xmlcolumnnames[1] = PASSED_SAMPLE_COUNT
    xmlcolumnnames[2] = FAILED_SAMPLE_COUNT
    xmlcolumnnames[3] = AVG_RESPONSE_TIME.

pgm-name = "xml-network.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}.

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}.
{include/xmlinitialize.i}.

pgm-name = "xml-network.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}.

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-network.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-network.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}.
    
    /*
    ** Get graph file names
    */
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    IF xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}.
    END.
    
    FOR EACH tmp-resrc:
    
        FIND FIRST Cf_Resrc WHERE
        tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
        IF AVAILABLE Cf_Resrc THEN
        DO:
            ASSIGN
                xmlresourcename = Cf_Resrc.Resrc_Name 
                xmlresourcetype = Cf_Resrc.Resrc_Type 
                xmlresourcesite = Cf_Resrc.Site_ID.
    
            /* Setup the root header and data information */
            RUN xml-resource-header.
    
            /*
            ** DO the labels section.
            */
            {include/xml-print-labels.i}
   
            /*
            ** Dates section.
            */
            RUN xml-print-dates.
    
            /* 
            ** Data Section.
            */
            pgm-name = "xml-network.p".
            sec-name = "Writing out Root header - Label :" + 
                       xmlresourcename + ":" +
                       xmlresourcetype + ":" +
                       xmlresourcesite.
            {include/debug.i "pgm-name" "sec-name"}
      
            pgm-name = "xml-network.p".
            sec-name = "Temporary Data.store ResrcID: " +
                       STRING (tResrcID).
            {include/debug.i "pgm-name" "sec-name"}.

            FOR EACH data_store USE-INDEX three:
    
                pgm-name = "xml-network.p".
                sec-name = "Parsing data_store records for XML output".
                {include/debug.i "pgm-name" "sec-name"}.
                
                /* This section is for when multiple resources are on one report.
                // /*
                // ** Message Received Data
                // */
                // xmldatalabel = data_store.name.
                //
                // /* 
                // ** Print the data label setting.
                // */
                // {include/xml-print-dataset.i}.
                */
                RUN print-starttag (INPUT-OUTPUT streamdetail,
                                    INPUT "dataset",
                                    INPUT "",
                                    INPUT "",
                                    INPUT "").
          
                /* xmldataOutputlabel = data_store.lable. */
                DO fathom-j = 1 to xml-numcolumns:

                    xmldataOutputlabel = xmlcolumnnames[fathom-j].
                    xmltestlabel = xmlcolumnnames[fathom-j].
    
        	        IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                        RUN xml-row-header. /* Only for Graphing */
        	        END.
        
                    DO fathom-x = 1 to Fathom-i-periods:
    	                RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                        RUN xml-process-date.     /* subroutine to process the date */
                    
    		            CASE fathom-j:
    		               WHEN 1 THEN 
                           DO:
                              dataprecision = "0".
                              xmldatavalue = STRING (data_store.passedSamples[fathom-x]).
                              Fathom-i-intervaltype = "D".
                           END.
                           WHEN 2 THEN 
                           DO:
                              dataprecision = "0".
                              xmldatavalue = STRING (data_store.failedSamples[fathom-x]).
                              Fathom-i-intervaltype = "D".
                           END.
    		               WHEN 3 THEN 
                           DO:
                              dataprecision = "2".
                              IF data_store.passedSamples[fathom-x] = 0 THEN
                              DO:
                                  xmldatavalue = NOT_AVAILABLE.
                              END.
                              ELSE DO:
                                  xmldatavalue = STRING (data_store.h-values[fathom-x] /
                                                         data_store.passedSamples[fathom-x]).
                              END.
                              Fathom-i-intervaltype = hold-intervaltype.
                           END.
    		            END CASE.
        
    		            RUN xml-format-column-intervaltype.
                        RUN xml-add-data. /* subroutine to process the datum */
                           
    		            PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                        streamdetail = "".
        
        	            IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                        DO:
                           RUN xml-add-data-graph. /* subroutine to process the datum */
        	            END.
                    END. /* fathom-x = 1 to Fathom-i-periods */
    		        IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                        RUN print-endtag (INPUT-OUTPUT graph1detail,
                                          INPUT "dataValues").
                        RUN print-endtag (INPUT-OUTPUT graph1detail,
                                          INPUT "dataset").
                    END.
    	        END. /* fathom-j = 1 to xml-numcolumns */

                PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                streamdetail = "".
                PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                graph1detail = "".

    	        /*  IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                DO:
                    RUN print-endtag (INPUT-OUTPUT graph1detail,
                               INPUT "dataValues").
                    RUN print-endtag (INPUT-OUTPUT graph1detail,
                               INPUT "dataset").
                END. */

                RUN print-endtag (INPUT-OUTPUT streamdetail,
                                  INPUT "dataset").
                PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                streamdetail = "".

            END. /* of for each data_store */
       
        END. /* of if available Cf_Resrc */
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "resource").
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "report").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
    END. /* for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}.
{include/xmlcleanup.i}.
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}.
/* 
** xml-dbserver.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO 
   FIELD Name AS character 
   FIELD Type AS character 
   FIELD msgrec AS DECIMAL EXTENT 366
   FIELD msgsent AS DECIMAL  EXTENT 366
   FIELD byterec AS DECIMAL  EXTENT 366
   FIELD bytesent AS DECIMAL EXTENT 366
   FIELD recrec AS DECIMAL EXTENT 366
   FIELD recsent AS DECIMAL EXTENT 366
   FIELD minusers AS DECIMAL EXTENT 366
   FIELD maxusers AS DECIMAL EXTENT 366
   FIELD avgusers AS DECIMAL EXTENT 366
   INDEX two TYPE 
   INDEX three NAME.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

xml-numcolumns = 9.

ASSIGN
   xmlcolumnnames[1] = "Messages Received" 
   xmlcolumnnames[2] = "Messages Sent"
   xmlcolumnnames[3] = "Bytes Received"
   xmlcolumnnames[4] = "Bytes Sent"
   xmlcolumnnames[5] = "Records Received"
   xmlcolumnnames[6] = "Records Sent"
   xmlcolumnnames[7] = "Min Users"
   xmlcolumnnames[8] = "Max Users"
   xmlcolumnnames[9] = "Avg Users".

pgm-name = "xml-dbserver.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbserver.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbserver.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}
    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbserver.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */

          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbserver.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbserver.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-dbserver.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	     ** Message Received Data
	     */

             xmldatalabel = data_store.name.

    	     /* 
	     ** Print the data label setting
	     */
      
             {include/xml-print-dataset.i}
          
             /* xmldataOutputlabel = data_store.lable. */
	     DO fathom-j = 1 to 9:

                 xmldataOutputlabel = xmldatalabel + ":" + xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    RUN xml-row-header. /* Only for Graphing */
    	         END.
    
                 DO fathom-x = 1 to Fathom-i-periods:
	            RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                    RUN xml-process-date.     /* subroutine to process the date */
                
		    CASE fathom-j:
		        WHEN 1 THEN xmldatavalue = STRING (data_store.msgrec[fathom-x]).
		        WHEN 2 THEN xmldatavalue = STRING (data_store.msgsent[fathom-x]).
		        WHEN 3 THEN xmldatavalue = STRING (data_store.byterec[fathom-x]).
		        WHEN 4 THEN xmldatavalue = STRING (data_store.bytesent[fathom-x]).
		        WHEN 5 THEN xmldatavalue = STRING (data_store.recrec[fathom-x]).
		        WHEN 6 THEN xmldatavalue = STRING (data_store.recsent[fathom-x]).
		        WHEN 7 THEN xmldatavalue = STRING (data_store.minusers[fathom-x]).
		        WHEN 8 THEN xmldatavalue = STRING (data_store.maxusers[fathom-x]).
		        WHEN 9 THEN xmldatavalue = STRING (data_store.avgusers[fathom-x]).
		    END CASE.
    
		    RUN xml-format-column-intervaltype.
                    RUN xml-add-data. /* subroutine to process the datum */
                    
		    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    	            IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                       RUN xml-add-data-graph. /* subroutine to process the datum */
    	            END.
                 END.
		 IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataValues").
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataset").
                 END.
	     END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     /* IF INDEX (xmlGraphColumns, xmldatalabel ) GT 0 THEN */
    	     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END.

             RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.
RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/


RUN print-endtag (INPUT-OUTPUT graph1detail,
                  INPUT "graphRequest").
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-systemdisk.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS CHARACTER
   FIELD Type AS CHARACTER
   FIELD pct_busy   AS DECIMAL EXTENT 366 INITIAL 0
   FIELD avgque     AS DECIMAL EXTENT 366 INITIAL 0
   FIELD avgwait    AS DECIMAL EXTENT 366 INITIAL 0
   FIELD avgserv    AS DECIMAL EXTENT 366 INITIAL 0
   FIELD minbusy    AS DECIMAL EXTENT 366 INITIAL 0
   FIELD maxbusy    AS DECIMAL EXTENT 366 INITIAL 0
   FIELD numseconds AS DECIMAL EXTENT 366 INITIAL 0
   FIELD numsamples AS DECIMAL EXTENT 366 INITIAL 0
   INDEX three NAME.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

/*
** Custom configuration stuff for indexstat
*/

xml-numcolumns = 7.

ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Pct. Busy"
   xmlcolumnnames[3] = "Avg. Queue Length"
   xmlcolumnnames[4] = "Avg. Wait Time (ms)"
   xmlcolumnnames[5] = "Avg. Serve Time (ms)"
   xmlcolumnnames[6] = "Minimum Busy Pct."
   xmlcolumnnames[7] = "Maximum Busy Pct."
   .

pgm-name = "xml-systemdisk.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-systemdisk.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-systemdisk.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-systemdisk.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
   
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name
             xmlresourcetype = Cf_Resrc.Resrc_Type
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-systemdisk.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-systemdisk.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-systemdisk.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	     ** Message Received Data
	     */

             xmldatalabel = data_store.name.
          
	     /* 
	     ** Print the data label setting
	     */

             {include/xml-print-dataset.i}

	     DO fathom-j = 1 to xml-numcolumns:

                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    RUN xml-row-header. /* Only for Graphing */
    	         END.
    
                 DO fathom-x = 1 to Fathom-i-periods:
	            RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                    RUN xml-process-date.     /* subroutine to process the date */
                
		    CASE fathom-j: 
		        WHEN 1 THEN
                DO:
                    dataprecision = "0".
                    xmldatavalue = STRING (data_store.numsamples[fathom-x]).
                END.
		        WHEN 2 THEN
                DO:
                    dataprecision = "2".
                    IF data_store.numsamples[Fathom-x] = 0 THEN
                        xmldatavalue = NOT_AVAILABLE.
                    ELSE
                        xmldatavalue = STRING (data_store.pct_busy[fathom-x] / data_store.numsamples[fathom-x]). 
                END.
		        WHEN 3 THEN
                DO:
                    dataprecision = "0".
                    IF data_store.numsamples[Fathom-x] = 0 THEN
                        xmldatavalue = NOT_AVAILABLE.
                    ELSE
                        xmldatavalue = STRING (data_store.avgque[fathom-x] / data_store.numsamples[fathom-x]).
                END.
		        WHEN 4 THEN
                DO:
                    dataprecision = "0".
                    IF data_store.numsamples[Fathom-x] = 0 THEN
                        xmldatavalue = NOT_AVAILABLE.
                    ELSE
                        xmldatavalue = STRING (data_store.avgwait[fathom-x] / data_store.numsamples[fathom-x]).
                END.
		        WHEN 5 THEN
                DO:
                    dataprecision = "0".
                    IF data_store.numsamples[Fathom-x] = 0 THEN
                        xmldatavalue = NOT_AVAILABLE.
                    ELSE
                        xmldatavalue = STRING (data_store.avgserv[fathom-x] / data_store.numsamples[fathom-x]).
                END.
		        WHEN 6 THEN
                DO:
                    dataprecision = "2".
                    IF data_store.numsamples[Fathom-x] = 0 THEN
                        xmldatavalue = NOT_AVAILABLE.
                    ELSE
                        xmldatavalue = STRING (data_store.minbusy[fathom-x]).
                END.
		        WHEN 7 THEN
                DO:
                    dataprecision = "2".
                    IF data_store.numsamples[Fathom-x] = 0 THEN
                        xmldatavalue = NOT_AVAILABLE.
                    ELSE
                        xmldatavalue = STRING (data_store.maxbusy[fathom-x]).
                END.
		    END CASE.
    
		    RUN xml-format-column-intervaltype.
                    RUN xml-add-data. /* subroutine to process the datum */
                    
		    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                    streamdetail = "".
    
    	            IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                       RUN xml-add-data-graph. /* subroutine to process the datum */
    	            END.
                 END.
		 IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataValues").
                     RUN print-endtag (INPUT-OUTPUT graph1detail,
                                       INPUT "dataset").
                 END.
	     END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END.
             
	     RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

/*
** Finish up and close everything out
*/
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-systemfilesize.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name AS CHARACTER
   FIELD filesize AS DECIMAL EXTENT 366 INITIAL 0
   FIELD minavail AS DECIMAL EXTENT 366 INITIAL -1
   FIELD maxavail AS DECIMAL EXTENT 366 INITIAL -1
   FIELD cnt AS INTEGER EXTENT 366
   INDEX three NAME.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

Fathom-report-title = "File Size Report ".

/*
** Custom configuration stuff for indexstat
*/

xml-numcolumns = 4.

ASSIGN
   xmlcolumnnames[2] = AVG_FILE_SIZE
   xmlcolumnnames[3] = MIN_FILE_SIZE
   xmlcolumnnames[4] = MAX_FILE_SIZE
   xmlcolumnnames[1] = SAMPLE_COUNT.

pgm-name = "xml-systemfilesize.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-systemfilesize.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".

IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-systemfilesize.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-systemfilesize.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
   
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
        {include/xml-graphcolumns.i}.
    END.
    
    FOR EACH tmp-resrc:
        
        FIND FIRST Cf_Resrc WHERE
        tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
        IF AVAILABLE Cf_Resrc THEN
        DO:
            ASSIGN
                xmlresourcename = Cf_Resrc.Resrc_Name
                xmlresourcetype = Cf_Resrc.Resrc_Type
                xmlresourcesite = Cf_Resrc.Site_ID.
            
            /* Setup the root header and data information */
            RUN xml-resource-header.
            
            /*
            ** DO the labels section
            */
            {include/xml-print-labels.i}.
            
            /*
            ** Dates section
            */
            RUN xml-print-dates.
            
            /*
            ** Actual Data Section
            */
            
            pgm-name = "xml-systemfilesize.p".
            sec-name = "Writing out Root header - Label :" +
                xmlresourcename + ":" +
                xmlresourcetype + ":" +
                xmlresourcesite.
            {include/debug.i "pgm-name" "sec-name"}.
                
            pgm-name = "xml-systemfilesize.p".
            sec-name = "Temporary Data.store ResrcID: " + STRING (tResrcID).
            {include/debug.i "pgm-name" "sec-name"}.
                
            FOR EACH data_store USE-INDEX three:
                
                pgm-name = "xml-systemfilesize.p".
                sec-name = "Parsing data_store records for XML output".
                {include/debug.i "pgm-name" "sec-name"}.
                
                /*
                ** Message Received Data
                */
                xmldatalabel = data_store.Name.
                
                /*
                ** Print the data label setting
                */
                
                RUN print-starttag (INPUT-OUTPUT streamdetail,
                                    INPUT "dataset",
                                    INPUT "",
                                    INPUT "",
                                    INPUT "").
                    
                DO fathom-j = 1 to xml-numcolumns:
                    
                    xmldataOutputlabel = xmlcolumnnames[fathom-j].
                    xmltestlabel = xmlcolumnnames[fathom-j].
                        
                    IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                        RUN xml-row-header. /* Only for Graphing */
                    END.
                        
                    DO fathom-x = 1 to Fathom-i-periods:
                        RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                        RUN xml-process-date.     /* subroutine to process the date */
                        
                        CASE fathom-j:
                            WHEN 1 THEN
                            DO:
                                xmldatavalue = STRING (data_store.cnt[fathom-x]).
                                dataprecision = "0".
                            END.
                            WHEN 2 THEN
                            DO:
                                data_store.filesize[fathom-x] = data_store.filesize[fathom-x] /
                                                                1024 /
                                                                data_store.cnt[fathom-x].
                                IF data_store.filesize[fathom-x] = ? THEN
                                DO:
                                    data_store.filesize[fathom-x] = 0.
                                    xmldatavalue = NOT_AVAILABLE.
                                END.
                                ELSE xmldatavalue = STRING (data_store.filesize[fathom-x]).
                                dataprecision = "2".
                            END.
                            WHEN 3 THEN
                            DO:
                                IF data_store.minavail[fathom-x] LT 0 THEN xmldatavalue = NOT_AVAILABLE.
                                ELSE xmldatavalue = STRING (data_store.minavail[fathom-x] / 1024).
                                dataprecision = "2".
                            END.
                            WHEN 4 THEN
                            DO:
                                IF data_store.maxavail[fathom-x] LT 0 THEN xmldatavalue = NOT_AVAILABLE.
                                ELSE xmldatavalue = STRING (data_store.maxavail[fathom-x] / 1024).
                                dataprecision = "2".
                            END.
                        END CASE.
                            
                        RUN xml-format-column-intervaltype.
                        RUN xml-add-data. /* subroutine to process the datum */
                        
                        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                        streamdetail = "".
                            
                        IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                        DO:
                            RUN xml-add-data-graph. /* subroutine to process the datum */
                        END.

                    END. /* DO fathom-x = 1 to Fathom-i-periods */
                        
                    IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                    DO:
                        RUN print-endtag (INPUT-OUTPUT graph1detail,
                                          INPUT "dataValues").
                        RUN print-endtag (INPUT-OUTPUT graph1detail,
                                          INPUT "dataset").
                    END.

                END. /* DO fathom-j = 1 to xml-numcolumns: */
                
                PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                streamdetail = "".
                PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
                graph1detail = "".
                    
                IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                DO:
                    RUN print-endtag (INPUT-OUTPUT graph1detail,
                                      INPUT "dataValues").
                    RUN print-endtag (INPUT-OUTPUT graph1detail,
                                      INPUT "dataset").
                END.
                    
                RUN print-endtag (INPUT-OUTPUT streamdetail,
                                  INPUT "dataset").
                PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                streamdetail = "".
                    
            END. /* of for each data_store */
            
        END. /* of if available Cf_Resrc */
        
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "resource").
        RUN print-endtag (INPUT-OUTPUT streamdetail,
                          INPUT "report").
        PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
        streamdetail = "".
        PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
        graph1detail = "".
            
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

/*
** Finish up and close everything out
*/
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-dbtablestat.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
   FIELD Name     AS character 
   FIELD Mount    AS character 
   FIELD capacity AS DECIMAL EXTENT 366 INITIAL 0
   FIELD UsedPct  AS DECIMAL EXTENT 366 INITIAL 0
   FIELD vavail   AS DECIMAL EXTENT 366 INITIAL 0
   FIELD maxavail AS DECIMAL EXTENT 366 INITIAL 0
   FIELD minavail AS DECIMAL EXTENT 366 INITIAL 0
   FIELD cnt      AS INTEGER EXTENT 366 INITIAL 0
   FIELD seconds  AS DECIMAL EXTENT 366 INITIAL 0
   INDEX two Mount 
   INDEX three Name.

DEFINE VARIABLE xmltestlabel as CHARACTER FORMAT "x(32)".

/*
** Custom configuration stuff for indexstat
*/

xml-numcolumns = 6.

ASSIGN
   xmlcolumnnames[1] = "Sample Count"
   xmlcolumnnames[2] = "Maximum Capacity (kb)"
   xmlcolumnnames[3] = "Pct. Used"
   xmlcolumnnames[4] = "Average Available (kb)"
   xmlcolumnnames[5] = "Maximum Available (kb)"
   xmlcolumnnames[6] = "Minimum Available (kb)" .

pgm-name = "xml-dbtablestat.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-dbtablestat.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
IF Fathom-Rec-Count LT 1 THEN
DO:
    pgm-name = "xml-dbtablestat.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-dbtablestat.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
   
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
    
    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-dbtablestat.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-dbtablestat.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          FOR EACH data_store
	      USE-INDEX three:
    
             pgm-name = "xml-dbtablestat.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}
   
             /*
	         ** Message Received Data
	         */

             xmldatalabel = data_store.Mount.
          
	         /* 
	         ** Print the data label setting
	         */

             {include/xml-print-dataset.i}

	         DO fathom-j = 1 to xml-numcolumns:

                 xmldataOutputlabel = xmlcolumnnames[fathom-j].
                 xmltestlabel = xmlcolumnnames[fathom-j].

    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                    RUN xml-row-header. /* Only for Graphing */
    	         END.
    
                 DO fathom-x = 1 to Fathom-i-periods:
	             RUN xml-setup-outputvars. /* Subroutine to setup dates and counts */
                 RUN xml-process-date.     /* subroutine to process the date */
                
		         CASE fathom-j: 
		             WHEN 1 THEN 
                     DO:
                         xmldatavalue = STRING (data_store.cnt[fathom-x]). 
                     END.
		             WHEN 2 THEN 
                     DO:
                         IF data_store.cnt[Fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                             xmldatavalue = STRING (data_store.capacity[fathom-x] / 1024).
                     END.
		             WHEN 3 THEN 
                     DO:
                         IF data_store.cnt[Fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                             xmldatavalue = STRING (data_store.usedpct[fathom-x] /
    			                                    data_store.seconds[fathom-x]).
                     END.
		             WHEN 4 THEN 
                     DO:
                         IF data_store.cnt[Fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                             xmldatavalue = STRING ((data_store.vavail[fathom-x] /
    			                                     data_store.cnt[fathom-x]) / 1024).
                     END.
		             WHEN 5 THEN 
                     DO:
                         IF data_store.cnt[fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                             xmldatavalue = STRING (data_store.maxavail[fathom-x] / 1024).
                     END.
		             WHEN 6 THEN 
                     DO:
                         IF data_store.cnt[fathom-x] = 0 THEN
                             xmldatavalue = NOT_AVAILABLE.
                         ELSE
                             xmldatavalue = STRING (data_store.minavail[fathom-x] / 1024).
                     END.
		         END CASE.
   
                 IF fathom-j = 3 THEN dataprecision = "2".
                 ELSE dataprecision = "0".

		         RUN xml-format-column-intervaltype.
                 RUN xml-add-data. /* subroutine to process the datum */
                    
		         PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
                 streamdetail = "".
    
    	         IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
                 DO:
                     RUN xml-add-data-graph. /* subroutine to process the datum */
    	         END.
             END.
		     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataValues").
                 RUN print-endtag (INPUT-OUTPUT graph1detail,
                                   INPUT "dataset").
             END.
	     END.

             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

    	     IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataValues").
                RUN print-endtag (INPUT-OUTPUT graph1detail,
                                  INPUT "dataset").
             END.
             
	     RUN print-endtag (INPUT-OUTPUT streamdetail,
                               INPUT "dataset").
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".

          END. /* of for each data_store */
    
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

/*
** Finish up and close everything out
*/
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
/* 
** xml-systemmemory.p
**
**
*/

/*
llaubach 10/2005
 - data_store temp table defined with NO-UNDO
*/

{include/definitions.i "SHARED"}
{include/xmldefinitions.i "NEW SHARED"}
{include/xmlprocs.i "NEW SHARED"}
{include/fm-environment.i "NEW SHARED"}

DEF SHARED TEMP-TABLE data_store NO-UNDO
    FIELD Name          AS CHARACTER
    FIELD Type          AS CHARACTER
    FIELD physicalavg   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicalmax   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicalused  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD physicaltotal AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualavg    AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualmax    AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualused   AS DECIMAL EXTENT 366 INITIAL 0
    FIELD virtualtotal  AS DECIMAL EXTENT 366 INITIAL 0
    FIELD pagein        AS DECIMAL EXTENT 366 INITIAL 0
    FIELD pageout       AS DECIMAL EXTENT 366 INITIAL 0
    FIELD cnt           AS DECIMAL EXTENT 366 INITIAL 0
    INDEX three NAME.

DEFINE VARIABLE xmltestlabel as CHARACTER NO-UNDO FORMAT "x(32)".
DEFINE VARIABLE display-divider as INTEGER NO-UNDO.
display-divider = 1024 * 1024.

/*
** Custom configuration stuff for indexstat
*/

dataprecision = "0".

xml-numcolumns = 9.

ASSIGN
    xmlcolumnnames[1] = SAMPLE_COUNT
    xmlcolumnnames[2] = AVG_PHYS_MEM_USED_PCT
    xmlcolumnnames[3] = AVG_PHYS_MEM_USED
    xmlcolumnnames[4] = MAX_PHYS_MEM_USED
    xmlcolumnnames[5] = AVG_VIRT_MEM_USED_PCT
    xmlcolumnnames[6] = AVG_VIRT_MEM_USED
    xmlcolumnnames[7] = MAX_VIRT_MEM_USED
    xmlcolumnnames[8] = MEM_PAGES_IN
    xmlcolumnnames[9] = MEM_PAGES_OUT.

pgm-name = "xml-systemmemory.p".
sec-name = "Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

{include/xmlhandles.i "CREATE X-NODEREF" "CREATE X-DOCUMENT"}
{include/xmlinitialize.i}

pgm-name = "xml-systemmemory.p".
sec-name = "After Initializing XML file".
{include/debug.i "pgm-name" "sec-name"}

RUN print-starttag (INPUT-OUTPUT streamdetail,
                    INPUT "report",
                    INPUT "",
                    INPUT "",
                    INPUT "").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".
PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
graph1detail = "".
fathom-j = 0.
for each data_store:
    fathom-j = fathom-j + 1.
end.

IF Fathom-Rec-Count LT 1 AND fathom-j lt 1 THEN
DO:
    pgm-name = "xml-systemmemory.p".
    sec-name = "Writing ERROR to XML file".
    {include/debug.i "pgm-name" "sec-name"}

    RUN print-tag (INPUT-OUTPUT streamdetail,
                   INPUT "error",
                   INPUT "",
                   INPUT "",
                   INPUT "There were no samples selected for this report.").
    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "report").

    RUN print-endtag (INPUT-OUTPUT streamdetail,
                      INPUT "reportDataSets").

    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphRequest").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".

    RETURN.
END.
ELSE
DO:
    RUN xml-graphspec.

    RUN xml-report-header.
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
      
    pgm-name = "xml-systemmemory.p".
    sec-name = "Completed Initialization".
    {include/debug.i "pgm-name" "sec-name"}
    
    /*
    ** Get graph file names
    */
   
    
    xmlGraphColumns = OS-GETENV("GRAPH1COLUMNS") NO-ERROR.
    
    if xmlGraphColumns = ? THEN
    DO:
       {include/xml-graphcolumns.i}
    END.
   

    FOR EACH tmp-resrc:
    
       FIND FIRST Cf_Resrc WHERE
       tResrcID = Cf_Resrc.Resrc_ID NO-LOCK NO-ERROR.
    
       IF AVAILABLE Cf_Resrc THEN
       DO:
          ASSIGN
             xmlresourcename = Cf_Resrc.Resrc_Name 
             xmlresourcetype = Cf_Resrc.Resrc_Type 
             xmlresourcesite = Cf_Resrc.Site_ID.
    
          /* Setup the root header and data information */
    
          RUN xml-resource-header.
    
          /*
          ** DO the labels section 
          */
   
          {include/xml-print-labels.i}
   
          /*
          ** Dates section
          */
   
          RUN xml-print-dates.
    
          /* 
          ** Actual Data Section
          */
    
          pgm-name = "xml-systemmemory.p".
          sec-name = "Writing out Root header - Label :" + 
                     xmlresourcename + ":" +
                     xmlresourcetype + ":" +
                     xmlresourcesite.
          {include/debug.i "pgm-name" "sec-name"}
      
          pgm-name = "xml-systemmemory.p".
          sec-name = "Temporary Data.store ResrcID: " +
                     STRING (tResrcID).
          {include/debug.i "pgm-name" "sec-name"}

          xmldatalabel = "".
          
	      /* 
	      ** Print the data label setting
	      */
          /* Used in multiple resource lists only.
          {include/xml-print-dataset.i}
          */
          RUN print-starttag (INPUT-OUTPUT streamdetail,
                              INPUT "dataset",
                              INPUT "",
                              INPUT "",
                              INPUT "").

          /*
          ** This outputs the sample counts
          */
          xmldataOutputlabel = xmlcolumnnames[1].
          xmltestlabel = xmlcolumnnames[1].

          /* 
          ** Graphing dataValue Tags
          */
    	  IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
          DO:
              RUN xml-row-header. /* Only for Graphing */
    	  END.
          DO Fathom-x = 1 to Fathom-i-periods:
		      xmldatavalue = STRING (fathom-interval-recs[Fathom-x]). 
              RUN output-data.
		  END.

          /* 
          ** Graphing dataValue END Tags
          */
    	  IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
          DO:
              RUN xml-row-end. /* Only for Graphing */
          END.

          /*
          ** This does the data in the data_store table
          */
          FOR EACH data_store USE-INDEX three:
    
             pgm-name = "xml-systemmemory.p".
             sec-name = "Parsing data_store records for XML output".
             {include/debug.i "pgm-name" "sec-name"}.

             /* Average Physical Memory Used % */
             xmldataOutputlabel = xmlcolumnnames[2].
             xmltestlabel = xmlcolumnnames[2].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING ((data_store.physicalused[Fathom-x] /
                                             data_store.physicaltotal[Fathom-x]) * 100). 
                RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.

             /* Average Physical Memory Used (mb) */
             xmldataOutputlabel = xmlcolumnnames[3].
             xmltestlabel = xmlcolumnnames[3].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING (data_store.physicalavg[Fathom-x] /
                                            data_store.cnt[Fathom-x] /
                                            display-divider). 
                 RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.

             /* Maximum Physical Memory Used (mb) */
             xmldataOutputlabel = xmlcolumnnames[4].
             xmltestlabel = xmlcolumnnames[4].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING (data_store.physicalmax[Fathom-x] /
                                            display-divider). 
                 RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.

             /* Average Virtual Memory Used % */
             xmldataOutputlabel = xmlcolumnnames[5].
             xmltestlabel = xmlcolumnnames[5].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING ((data_store.virtualused[Fathom-x] /
                                             data_store.virtualtotal[Fathom-x]) * 100).
                 RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.

             /* Average Virtual Memory Used (mb) */
             xmldataOutputlabel = xmlcolumnnames[6].
             xmltestlabel = xmlcolumnnames[6].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING (data_store.virtualavg[Fathom-x] /
                                            data_store.cnt[Fathom-x] /
                                            display-divider). 
                 RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.

             /* Maximum Virtual Memory Used (mb) */
             xmldataOutputlabel = xmlcolumnnames[7].
             xmltestlabel = xmlcolumnnames[7].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING (data_store.virtualmax[Fathom-x] /
                                            display-divider).
                 RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.

             /* Pages In */
             xmldataOutputlabel = xmlcolumnnames[8].
             xmltestlabel = xmlcolumnnames[8].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING (data_store.pagein[Fathom-x]). 
                 RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.

             /* Pages Out */
             xmldataOutputlabel = xmlcolumnnames[9].
             xmltestlabel = xmlcolumnnames[9].

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-header. /* Only for Graphing */
             END.

             DO Fathom-x = 1 to Fathom-i-periods:
                 IF data_store.cnt[Fathom-x] = 0 THEN
                     xmldatavalue = NOT_AVAILABLE.
                 ELSE
                     xmldatavalue = STRING (data_store.pageout[Fathom-x]). 
                 RUN output-data.
             END.

             IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
             DO:
                 RUN xml-row-end. /* Only for Graphing */
             END.
                     
             PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
             streamdetail = "".
             PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
             graph1detail = "".

          END. /* of for each data_store */

	      RUN print-endtag (INPUT-OUTPUT streamdetail,
                            INPUT "dataset").
          PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
          streamdetail = "".
    
       END. /* of if available Cf_Resrc */
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "resource").
       RUN print-endtag (INPUT-OUTPUT streamdetail,
                         INPUT "report").
       PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
       streamdetail = "".
       PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
       graph1detail = "".
    END. /* of for each tmp-resrc */
    
    /*
    ** Close up the graphing stuff
    */
    RUN print-endtag (INPUT-OUTPUT graph1detail,
                      INPUT "graphDataSets").
    PUT STREAM Gxmlstream UNFORMATTED SKIP graph1detail.
    graph1detail = "".
    
END.

RUN print-endtag (INPUT-OUTPUT streamdetail,
                  INPUT "reportDataSets").
PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
streamdetail = "".

/*
** Close up the graphing stuff
*/
{include/xml-close-graph.i}

/*
** Finish up and close everything out
*/
{include/xmlcleanup.i}
{include/xmlhandles.i "DELETE OBJECT" "DELETE OBJECT"}
RETURN.
PROCEDURE output-data.

    RUN xml-setup-outputvars.
    RUN xml-process-date.
    RUN xml-format-column-intervaltype.
    RUN xml-add-data. /* subroutine to process the datum */
                    
    PUT STREAM xmlstream UNFORMATTED SKIP streamdetail.
    streamdetail = "".
    
    IF INDEX (xmlGraphColumns, xmltestlabel ) GT 0 THEN
    DO:
        RUN xml-add-data-graph. /* subroutine to process the datum */
    END.

END PROCEDURE.
placeholder file for 3.1B feature freeze.

/*
** Placeholder file
*/

/* 
** Procedure to dump the table data contents of a trend database
** This procedure should be built under 3.1A
** DUMP_FILES_WRKDIR must exist and point to the directory
** being used to store the output.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".
DEF VAR dump-dir AS CHARACTER INITIAL "".
DEF VAR dump-path AS CHARACTER INITIAL "".

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Dumping table content - ERROR! DLC not set! Aborting".
    QUIT.
END.

dump-dir = OS-GETENV("DUMP_FILES_WRKDIR"). 
IF dump-dir = "" OR dump-dir = ? THEN  
DO:
   PUT SKIP "Dumping table content - ERROR! DUMP_FILES_WRKDIR not set! Aborting".
   QUIT.
END.
  
/*
 * Dump the contents
 */
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Dump table data contents".

/*
** RUN prodict/dump_d.p ("ALL", dump-dir, " ").
*/

OUTPUT TO VALUE(dump-dir + "/" + "cf_samp.d").
FOR EACH cf_sample NO-LOCK:
    EXPORT cf_sample.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_resrc.d").
FOR EACH cf_resrc NO-LOCK:
    EXPORT cf_resrc.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_cpu.d").
FOR EACH sys_cpu NO-LOCK:
    EXPORT sys_cpu.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_dev.d").
FOR EACH sys_dev NO-LOCK:
    EXPORT sys_dev.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_mem.d").
FOR EACH sys_mem NO-LOCK:
    EXPORT sys_mem.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_File.d").
FOR EACH sys_filesize NO-LOCK:
    EXPORT sys_filesize.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_fsys.d").
FOR EACH sys_filesys NO-LOCK:
    EXPORT sys_filesys.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActAP.d").
FOR EACH db_actapw NO-LOCK:
    EXPORT db_actapw.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActBu.d").
FOR EACH db_actbuf NO-LOCK:
    EXPORT db_actbuf.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActId.d").
FOR EACH db_actidx NO-LOCK:
    EXPORT db_actidx.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActIO.d").
FOR EACH db_actiofile NO-LOCK:
    EXPORT db_actiofile.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActLo.d").
FOR EACH db_actlock NO-LOCK:
    EXPORT db_actlock.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActRe.d").
FOR EACH db_actrec NO-LOCK:
    EXPORT db_actrec.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActSu.d").
FOR EACH db_actsum NO-LOCK:
    EXPORT db_actsum.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_Check.d").
FOR EACH db_checkpoint NO-LOCK:
    EXPORT db_checkpoint.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_Table.d").
FOR EACH db_tablestat NO-LOCK:
    EXPORT db_tablestat.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_Index.d").
FOR EACH db_indexstat NO-LOCK:
    EXPORT db_indexstat.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActSe.d").
FOR EACH db_actserv NO-LOCK:
    EXPORT db_actserv.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_site.d").
FOR EACH cf_site NO-LOCK:
    EXPORT cf_site.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActL1.d").
FOR EACH db_actlog NO-LOCK:
    EXPORT db_actlog.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Db_ActI1.d").
FOR EACH db_actiotype NO-LOCK:
    EXPORT db_actiotype.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "AlertDet.d").
FOR EACH cf_alert_detail NO-LOCK:
    EXPORT cf_alert_detail.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_contr.d").
FOR EACH cf_control NO-LOCK:
    EXPORT cf_control.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "net_data.d").
FOR EACH net_data NO-LOCK:
    EXPORT net_data.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_statu.d").
FOR EACH cf_status NO-LOCK:
    EXPORT cf_status.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "AreaStat.d").
FOR EACH db_areastatus NO-LOCK:
    EXPORT db_areastatus.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_taskD.d").
FOR EACH cf_task_detail NO-LOCK:
    EXPORT cf_task_detail.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActAP.d").
FOR EACH ar_actapw NO-LOCK:
    EXPORT ar_actapw.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActBu.d").
FOR EACH ar_actbuf NO-LOCK:
    EXPORT ar_actbuf.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActId.d").
FOR EACH ar_actidx NO-LOCK:
    EXPORT ar_actidx.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActIO.d").
FOR EACH ar_actiofile NO-LOCK:
    EXPORT ar_actiofile.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActI1.d").
FOR EACH ar_actiotype NO-LOCK:
    EXPORT ar_actiotype.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActLo.d").
FOR EACH ar_actlock NO-LOCK:
    EXPORT ar_actlock.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActL1.d").
FOR EACH ar_actlog NO-LOCK:
    EXPORT ar_actlog.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActRe.d").
FOR EACH ar_actrec NO-LOCK:
    EXPORT ar_actrec.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActSe.d").
FOR EACH ar_actserv NO-LOCK:
    EXPORT ar_actserv.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_ActSu.d").
FOR EACH ar_actsum NO-LOCK:
    EXPORT ar_actsum.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "AreaSta1.d").
FOR EACH ar_areastatus NO-LOCK:
    EXPORT ar_areastatus.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_Check.d").
FOR EACH ar_checkpoint NO-LOCK:
    EXPORT ar_checkpoint.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_CPU.d").
FOR EACH ar_cpu NO-LOCK:
    EXPORT ar_cpu.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_dev1.d").
FOR EACH ar_dev NO-LOCK:
    EXPORT ar_dev.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_Fil1.d").
FOR EACH ar_filesize NO-LOCK:
    EXPORT ar_filesize.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_fsy1.d").
FOR EACH ar_filesys NO-LOCK:
    EXPORT ar_filesys.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_Index.d").
FOR EACH ar_indexstat NO-LOCK:
    EXPORT ar_indexstat.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "sys_mem1.d").
FOR EACH ar_mem NO-LOCK:
    EXPORT ar_mem.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "net_dat1.d").
FOR EACH ar_net_data NO-LOCK:
    EXPORT ar_net_data.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Ar_Table.d").
FOR EACH ar_tablestat NO-LOCK:
    EXPORT ar_tablestat.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_log.d").
FOR EACH cf_log NO-LOCK:
    EXPORT cf_log.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "db_idxan.d").
FOR EACH db_idxanalysis NO-LOCK:
    EXPORT db_idxanalysis.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "db_taban.d").
FOR EACH db_tabanalysis NO-LOCK:
    EXPORT db_tabanalysis.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_task_.d").
FOR EACH cf_task_resrc NO-LOCK:
    EXPORT cf_task_resrc.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "ar_oeasp.d").
FOR EACH ar_oe_actasproc NO-LOCK:
    EXPORT ar_oe_actasproc.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "ar_oebrk.d").
FOR EACH ar_oe_actbrk NO-LOCK:
    EXPORT ar_oe_actbrk.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "ar_oesrv.d").
FOR EACH ar_oe_actserv NO-LOCK:
    EXPORT ar_oe_actserv.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "ar_oe_ac.d").
FOR EACH ar_oe_actwsproc NO-LOCK:
    EXPORT ar_oe_actwsproc.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "ar_oeSvc.d").
FOR EACH ar_oe_appservice NO-LOCK:
    EXPORT ar_oe_appservice.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "ar_proce.d").
FOR EACH ar_process NO-LOCK:
    EXPORT ar_process.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "oe_ASapr.d").
FOR EACH oe_actasproc NO-LOCK:
    EXPORT oe_actasproc.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "oe_actBr.d").
FOR EACH oe_actbrk NO-LOCK:
    EXPORT oe_actbrk.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "oe_actSv.d").
FOR EACH oe_actsrv NO-LOCK:
    EXPORT oe_actsrv.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "oe_WSapr.d").
FOR EACH oe_actwsproc NO-LOCK:
    EXPORT oe_actwsproc.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "cf_appse.d").
FOR EACH oe_appservice NO-LOCK:
    EXPORT oe_appservice.
END.
OUTPUT CLOSE.
 
OUTPUT TO VALUE(dump-dir + "/" + "Sys_Proc.d").
FOR EACH sys_process NO-LOCK:
    EXPORT sys_process.
END.
OUTPUT CLOSE.
 

QUIT.  


/* 
** Procedure to dump the sequence values of a 3.1A
** trend database. This is built against 3.1A db.
**
** DUMP_FILES_WRKDIR must exist and point to the directory
** being used to store the output.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".
DEF VAR dump-dir AS CHARACTER INITIAL "".
DEF VAR dump-path AS CHARACTER INITIAL "".

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Dumping data - ERROR! DLC not set! Aborting".
    QUIT.
END.

dump-dir = OS-GETENV("DUMP_FILES_WRKDIR"). 
IF dump-dir = "" OR dump-dir = ? THEN  
DO:
   PUT SKIP "Dumping data - ERROR! DUMP_FILES_WRKDIR not set! Aborting".
   QUIT.
END.

/*
 * Dump the sequence values
 */
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Dump sequence values: _seqvals.d".
dump-path = dump-dir + "/_seqvals.d".
OUTPUT TO VALUE(dump-path) NO-MAP NO-ECHO.
EXPORT 0 "Ar_Sample-Seq" CURRENT-VALUE(Ar_Sample-Seq,fathom31a).
EXPORT 1 "TAB_ID_Sequence" CURRENT-VALUE(TAB_ID_Sequence,fathom31a).
OUTPUT CLOSE.

QUIT.

/* 
** Procedure to:
** Erase the existing Cf_Control records.
** Prior to loading data into a 3.1B trend database
**
** DUMP_FILES_WRKDIR must exist and point to the directory
** being used to store the input files.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Loading data - ERROR! DLC not set! Aborting".
    QUIT.
END.



/*
** Delete the records
*/  
FOR EACH Cf_Control:
   DELETE Cf_Control.
END.


QUIT.
/* 
** Procedure to:
** - Load the table data contents of a 3.1A
**   trend database into a 3.1B database
**
** DUMP_FILES_WRKDIR must exist and point to the directory
** being used to store the input files.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".
DEF VAR dump-dir AS CHARACTER INITIAL "".
DEF VAR dump-path AS CHARACTER INITIAL "".

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Loading table data - ERROR! DLC not set! Aborting".
    QUIT.
END.

dump-dir = OS-GETENV("DUMP_FILES_WRKDIR"). 
IF dump-dir = "" OR dump-dir = ? THEN  
DO:
   PUT SKIP "Loading table data - ERROR! DUMP_FILES_WRKDIR not set! Aborting".
   QUIT.
END.


/*
 * Load the table data
 */
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Load table data contents: ".
/*
 * RUN prodict/load_d.p ("ALL", dump-dir).
 */

INPUT FROM VALUE(dump-dir + "/" + "cf_samp.d").
REPEAT:
    CREATE cf_sample.
    IMPORT cf_sample.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_resrc.d").
REPEAT:
    CREATE cf_resrc.
    IMPORT cf_resrc.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_cpu.d").
REPEAT:
    CREATE sys_cpu.
    IMPORT sys_cpu.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_dev.d").
REPEAT:
    CREATE sys_dev.
    IMPORT sys_dev.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_mem.d").
REPEAT:
    CREATE sys_mem.
    IMPORT sys_mem.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_File.d").
REPEAT:
    CREATE sys_filesize.
    IMPORT sys_filesize.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_fsys.d").
REPEAT:
    CREATE sys_filesys.
    IMPORT sys_filesys.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActAP.d").
REPEAT:
    CREATE db_actapw.
    IMPORT db_actapw.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActBu.d").
REPEAT:
    CREATE db_actbuf.
    IMPORT db_actbuf.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActId.d").
REPEAT:
    CREATE db_actidx.
    IMPORT db_actidx.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActIO.d").
REPEAT:
    CREATE db_actiofile.
    IMPORT db_actiofile.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActLo.d").
REPEAT:
    CREATE db_actlock.
    IMPORT db_actlock.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActRe.d").
REPEAT:
    CREATE db_actrec.
    IMPORT db_actrec.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActSu.d").
REPEAT:
    CREATE db_actsum.
    IMPORT db_actsum.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_Check.d").
REPEAT:
    CREATE db_checkpoint.
    IMPORT db_checkpoint.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_Table.d").
REPEAT:
    CREATE db_tablestat.
    IMPORT db_tablestat.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_Index.d").
REPEAT:
    CREATE db_indexstat.
    IMPORT db_indexstat.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActSe.d").
REPEAT:
    CREATE db_actserv.
    IMPORT db_actserv.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_site.d").
REPEAT:
    CREATE cf_site.
    IMPORT cf_site.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActL1.d").
REPEAT:
    CREATE db_actlog.
    IMPORT db_actlog.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Db_ActI1.d").
REPEAT:
    CREATE db_actiotype.
    IMPORT db_actiotype.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "AlertDet.d").
REPEAT:
    CREATE cf_alert_detail.
    IMPORT cf_alert_detail.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_contr.d").
REPEAT:
    CREATE cf_control.
    IMPORT cf_control.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "net_data.d").
REPEAT:
    CREATE net_data.
    IMPORT net_data.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_statu.d").
REPEAT:
    CREATE cf_status.
    IMPORT cf_status.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "AreaStat.d").
REPEAT:
    CREATE db_areastatus.
    IMPORT db_areastatus.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_taskD.d").
REPEAT:
    CREATE cf_task_detail.
    IMPORT cf_task_detail.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActAP.d").
REPEAT:
    CREATE ar_actapw.
    IMPORT ar_actapw.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActBu.d").
REPEAT:
    CREATE ar_actbuf.
    IMPORT ar_actbuf.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActId.d").
REPEAT:
    CREATE ar_actidx.
    IMPORT ar_actidx.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActIO.d").
REPEAT:
    CREATE ar_actiofile.
    IMPORT ar_actiofile.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActI1.d").
REPEAT:
    CREATE ar_actiotype.
    IMPORT ar_actiotype.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActLo.d").
REPEAT:
    CREATE ar_actlock.
    IMPORT ar_actlock.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActL1.d").
REPEAT:
    CREATE ar_actlog.
    IMPORT ar_actlog.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActRe.d").
REPEAT:
    CREATE ar_actrec.
    IMPORT ar_actrec.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActSe.d").
REPEAT:
    CREATE ar_actserv.
    IMPORT ar_actserv.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_ActSu.d").
REPEAT:
    CREATE ar_actsum.
    IMPORT ar_actsum.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "AreaSta1.d").
REPEAT:
    CREATE ar_areastatus.
    IMPORT ar_areastatus.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_Check.d").
REPEAT:
    CREATE ar_checkpoint.
    IMPORT ar_checkpoint.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_CPU.d").
REPEAT:
    CREATE ar_cpu.
    IMPORT ar_cpu.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_dev1.d").
REPEAT:
    CREATE ar_dev.
    IMPORT ar_dev.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_Fil1.d").
REPEAT:
    CREATE ar_filesize.
    IMPORT ar_filesize.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_fsy1.d").
REPEAT:
    CREATE ar_filesys.
    IMPORT ar_filesys.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_Index.d").
REPEAT:
    CREATE ar_indexstat.
    IMPORT ar_indexstat.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "sys_mem1.d").
REPEAT:
    CREATE ar_mem.
    IMPORT ar_mem.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "net_dat1.d").
REPEAT:
    CREATE ar_net_data.
    IMPORT ar_net_data.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Ar_Table.d").
REPEAT:
    CREATE ar_tablestat.
    IMPORT ar_tablestat.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_log.d").
REPEAT:
    CREATE cf_log.
    IMPORT cf_log.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "db_idxan.d").
REPEAT:
    CREATE db_idxanalysis.
    IMPORT db_idxanalysis.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "db_taban.d").
REPEAT:
    CREATE db_tabanalysis.
    IMPORT db_tabanalysis.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_task_.d").
REPEAT:
    CREATE cf_task_resrc.
    IMPORT cf_task_resrc.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "ar_oeasp.d").
REPEAT:
    CREATE ar_oe_actasproc.
    IMPORT ar_oe_actasproc.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "ar_oebrk.d").
REPEAT:
    CREATE ar_oe_actbrk.
    IMPORT ar_oe_actbrk.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "ar_oesrv.d").
REPEAT:
    CREATE ar_oe_actserv.
    IMPORT ar_oe_actserv.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "ar_oe_ac.d").
REPEAT:
    CREATE ar_oe_actwsproc.
    IMPORT ar_oe_actwsproc.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "ar_oeSvc.d").
REPEAT:
    CREATE ar_oe_appservice.
    IMPORT ar_oe_appservice.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "ar_proce.d").
REPEAT:
    CREATE ar_process.
    IMPORT ar_process.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "oe_ASapr.d").
REPEAT:
    CREATE oe_actasproc.
    IMPORT oe_actasproc.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "oe_actBr.d").
REPEAT:
    CREATE oe_actbrk.
    IMPORT oe_actbrk.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "oe_actSv.d").
REPEAT:
    CREATE oe_actsrv.
    IMPORT oe_actsrv.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "oe_WSapr.d").
REPEAT:
    CREATE oe_actwsproc.
    IMPORT oe_actwsproc.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "cf_appse.d").
REPEAT:
    CREATE oe_appservice.
    IMPORT oe_appservice.
END.
INPUT CLOSE.
 
INPUT FROM VALUE(dump-dir + "/" + "Sys_Proc.d").
REPEAT:
    CREATE sys_process.
    IMPORT sys_process.
END.
INPUT CLOSE.
 
QUIT.

/* 
** Procedure to load the sequence values and user table of a 3.1A
** trend database into a 3.1B database
**
** DUMP_FILES_WRKDIR must exist and point to the directory
** being used to store the input files.
*/
DEF VAR dlc-dir AS CHARACTER INITIAL "".
DEF VAR dump-dir AS CHARACTER INITIAL "".
DEF VAR dump-path AS CHARACTER INITIAL "".

DEF VAR seqname   AS CHARACTER NO-UNDO.
DEF VAR seqnumber AS CHARACTER NO-UNDO.
DEF VAR seqvalue  AS INTEGER   NO-UNDO.

dlc-dir = OS-GETENV("DLC").
IF dlc-dir = "" OR dlc-dir = ? THEN 
DO:      
    PUT SKIP "Loading data - ERROR! DLC not set! Aborting".
    QUIT.
END.

dump-dir = OS-GETENV("DUMP_FILES_WRKDIR"). 
IF dump-dir = "" OR dump-dir = ? THEN  
DO:
   PUT SKIP "Loading data - ERROR! DUMP_FILES_WRKDIR not set! Aborting".
   QUIT.
END.

/*
 * Load the sequence values
 */
PUT SKIP TODAY " " STRING(TIME, "HH:MM:SS") " Load sequence values: _seqvals.d".
dump-path = dump-dir + "/_seqvals.d".
INPUT FROM VALUE(dump-path).
REPEAT:
  IMPORT seqnumber seqname seqvalue.
  IF INDEX(seqname,".") = 0 THEN seqname = "fathom." + seqname.
  CASE seqname:
    WHEN "fathom.Ar_Sample-Seq" THEN CURRENT-VALUE(Ar_Sample-Seq, fathom) = seqvalue.
    WHEN "fathom.TAB_ID_Sequence" THEN CURRENT-VALUE(TAB_ID_Sequence, fathom) = seqvalue.
  END CASE.
END.
INPUT CLOSE.

QUIT.
ÿ21aalertname.p;ö*ÿf[Ÿø/I¤eÿ21acontrol.pp˜ÿU[Ÿø/I¤eÿ21afix.p¡båÿ8[Ÿø/I¤eÿ21aresourceupdate.pdÿ¤[Ÿø/I¤eÿ21asampledate.pˆ%Áÿr[Ÿø/I¤eÿ30achangefield.pî13ÿ	u[Ÿø/I¥™Vÿ
30aindex.p¼–(¨ÿÏ[Ÿø/I¥™Uÿ30anewfield.pi¥.wÿ¾[Ÿø/I¤eþÿ30aupdate.pC´75ÿø[Ÿø/I¤eÿalertgeneral.p:-ÿQ[Ÿø/I¤eÿalertindividual.p>lP~ÿ²[Ÿø/I¤eÿarchive/ar-actapw.pz¢i0ÿA[Ÿø/I¤eÿarchive/ar-actbuf.p½hqÿ„[Ÿø/I¤eÿarchive/ar-actidx.pBZ•õÿ¯[Ÿø/I¤eÿarchive/ar-actiofile.pžPª¤ÿô[Ÿø/I¤eþÿarchive/ar-actiotype.p•iÃ˜ÿô[Ÿø/I¤eÿarchive/ar-actlock.pèdÛŒÿ[Ÿø/I¤eÿarchive/ar-actlog.pé’ô¢ÿu[Ÿø/I¤eÿarchive/ar-actrec.p$IÿÁ[Ÿø/I¤e
ÿarchive/ar-actserv.p4	%Øÿæ[Ÿø/I¤e	ÿarchive/ar-actsum.pã°=¾ÿó[Ÿø/I¤e	ÿarchive/ar-areastatus.pšjW±ÿy[Ÿø/I¥™Sþÿarchive/ar-checkpoint.p:t*ÿ‡[Ÿø/I¤eÿarchive/ar-cpu.pt¨’±ÿÄ[Ÿø/KÔóÿarchive/ar-dev.pC*¨uÿo[Ÿø/I¤eÿarchive/ar-filesize.pSÚ¿äÿV[Ÿø/I¤eÿarchive/ar-filesys.pmõØ:ÿý[Ÿø/I¤eÿarchive/ar-h-actapw.pzóò7ÿ[Ÿø/I¥™Sÿarchive/ar-h-actbuf.p¼DÿÇ[Ÿø/I¥™Rþÿarchive/ar-h-actidx.pà,ÿ¾[Ÿø/I¥™Qÿarchive/ar-h-actiofile.p}-Éÿx[Ÿø/I¥™Qÿarchive/ar-h-actiotype.p‰;DAÿˆ[Ÿø/I¥™Pÿarchive/ar-h-actlock.päYÉÿç[Ÿø/I¥™Pÿarchive/ar-h-actlog.påÏq°ÿ[Ÿø/I¥™Oÿarchive/ar-h-actrec.pï‰Êÿ[Ÿø/I¥™Oÿarchive/ar-h-actserv.pqæŸåÿö[Ÿø/I¥™Nþÿarchive/ar-h-actsum.p7ÆºÛÿ[Ÿø/I¥™Mÿarchive/ar-h-areastatus.pûœÒïÿ~[Ÿø/I¥™Mÿarchive/ar-h-checkpoint.p~ëmÿ5[Ÿø/I¥™Lÿarchive/ar-h-cpu.pMQ¢ÿÊ[Ÿø/KÔíÿarchive/ar-h-dev.p·Zlÿ<[Ÿø/I¥™Kÿarchive/ar-h-filesize.p%Z3¨ÿÂ[Ÿø/I¥™Jÿarchive/ar-h-filesys.pâ±IjÿX[Ÿø/I¥™Jþÿarchive/ar-h-indexstat.p²_Âÿf[Ÿø/I¥™Iÿarchive/ar-h-mem.p!³u(ÿÀ[Ÿø/I¥™Iÿarchive/ar-h-net.pi8‰èÿw[Ÿø/I¥™Hÿarchive/ar-h-oe_actasproc.p&ž_ÿì[Ÿø/I¥™Hÿarchive/ar-h-oe_actbrk.p–¼Kÿ[Ÿø/I¥™Gÿarchive/ar-h-oe_actsrv.p¢ÉÙ^ÿ¼[Ÿø/I¥™Fÿarchive/ar-h-oe_actwsproc.pïÁöÿL[Ÿø/I¥™Fþÿarchive/ar-h-oe_appservice.p¸Àfÿw[Ÿø/I¥™Eÿarchive/ar-h-process.p³¨Ýÿ°[Ÿø/I¥™Eÿarchive/ar-h-tablestat.p+õ5ÿÙ[Ÿø/I¥™Dÿarchive/ar-indexstat.p“»KfÿÅ[Ÿø/I¤dôÿarchive/ar-lock.pèÈd+ÿo[Ÿø/I¤dôÿarchive/ar-mem.pEvfšÿH[Ÿø/I¤dóÿarchive/ar-net.pWÚ|âÿÿ[Ÿø/I¤dòþÿarchive/ar-oe_actasproc.pye‘áÿ*n[Ÿø/I¤dòÿarchive/ar-oe_actbrk.pŸ¼Oÿ!­[Ÿø/I¤dñÿarchive/ar-oe_actsrv.pÃ§Ýüÿ&Ï[Ÿø/I¤dðÿarchive/ar-oe_actwsproc.p›ðËÿ&Î[Ÿø/I¤dðÿarchive/ar-oe_appservice.p(§+™ÿ`[Ÿø/I¤dïÿarchive/ar-process.p;t-ùÿ(G[Ÿø/I¤dîþÿarchive/ar-report-add-actapw.p‘âV@ÿŽ[Ÿø/I¥™Dÿarchive/ar-report-add-actbuf.pœ2oÎÿ“[Ÿø/I¥™Cÿarchive/ar-report-add-actidx.p
‚aÿß[Ÿø/I¥™Cÿ!archive/ar-report-add-actiofile.p1•@ÿ [Ÿø/I¥™Bÿ!archive/ar-report-add-actiotype.pvq¨`ÿ‡[Ÿø/I¥™Aÿarchive/ar-report-add-actlock.pC½çÿ[Ÿø/I¥™Aþÿ!archive/ar-report-add-actlog-ai.pÀ¶Üÿ¦[Ÿø/I¥™@ÿ#archive/ar-report-add-actlog-aibi.pÝªî«ÿ[Ÿø/I¥™@ÿ!archive/ar-report-add-actlog-bi.pþ»ÿ[Ÿø/I¥™?ÿarchive/ar-report-add-actrec.pw´"Óÿ®[Ÿø/I¥™>ÿarchive/ar-report-add-actsum.pÍ>ÿ‚[Ÿø/I¥™>ÿ!archive/ar-report-add-tablestat.p%Zÿ3[Ÿø/I¥™=þÿarchive/ar-report-dbai.p½»l6ÿf[Ÿø/I¤dæÿarchive/ar-report-dbbi.p³mœÿÆ[Ÿø/I¤dåÿarchive/ar-report-dbdet.pKõobÿÇ[Ÿø/I¤dåÿarchive/ar-report-dbdisk.p™úr)ÿÃ[Ÿø/I¤däÿarchive/ar-report-dblocks.pŽCsìÿg[Ÿø/I¤däÿarchive/ar-report-dbmem.pMkuSÿ[Ÿø/I¤dãþÿarchive/ar-report-dbrec.páŠvðÿe[Ÿø/I¤dâÿarchive/ar-report-dbsum.p­sxUÿ¤[Ÿø/I¤dâÿarchive/ar-report-syscpu.pìøzùÿZ[Ÿø/I¥™=ÿarchive/ar-report-sysmem.påSÿÔ[Ÿø/I¤dàÿarchive/ar-tablestat.pD¢'ÿ[Ÿø/I¤dàÿarchive/ar-unlock.p¨º>ÿÊ[Ÿø/I¤dßÿarchive/compact_fix_30a.pë°¼ÿ$2[Ÿø/I¤dßÿarchive/purge-data.p—à:ÿ[Ÿø/I¤dÞÿarchivedetail.pþ ãEÿ-[Ÿø/I¤dÝÿarchivedriver.pNßórÿ˜[Ÿø/S"£ÿarchiverundetail.py‘
ÿ‘[Ÿø/I¤dÜÿcompactindex.pÆ=›ÿ”[Ÿø/Rýç8ÿ	compile.p^À/ÿ“[Ÿø/I¤dÛÿ	cpu_fix.p‹þ/Âÿz[Ÿø/I¤dÚÿcustomreport.pO7<ÿb[Ÿø/I¤dÚþÿ
dba-load.p¡?žÿo|[Ÿø/S¨/¾ÿdbafterimage.pŠ¯ÿ[Ÿø/I¤dØÿdbareastatus.p›°ÿ5«[Ÿø/I¥™;ÿdbbeforeimage.pÞµåÅÿ[Ÿø/I¤d×ÿdbcheckpoint.pø¥æÆÿÆ[Ÿø/I¤d×ÿ
dbdetail.pdžŒÿ[Ÿø/I¤dÖÿdbdisk.p?.Žÿ$5[Ÿø/I¤dÕÿdbidxanalysis.pvd*Ãÿ^[Ÿø/I¤dÕþÿdbindexstat.pFðH!ÿ&ä[Ÿø/I¤dÔÿ	dblocks.poÿ[Ÿø/I¤dÔÿ
dbmemory.p_ëpÿ[Ÿø/I¤dÓÿ
dbrecord.p)äq	ÿ[Ÿø/I¤dÒÿ
dbserver.pBÎr
ÿ-;[Ÿø/I¤dÒÿdbsummary.p}'ŸEÿý[Ÿø/I¤dÑÿdbtabanalysis.pP BÿÇ[Ÿø/I¤dÑÿdbtablestat.pÙ¸½	ÿ%Ó[Ÿø/I¤dÐþÿdelete-hist.pZâÜÿ•[Ÿø/I¤dÏÿdeletedata.pq¯ÿqÿ$Þ[Ÿø/I¤dÏÿfathom-compile.pr 	$Oÿ+[Ÿø/I¤dÎÿfathom30a_delete.dfÁw	*zÿ}[Ÿø/I¤dÎÿfathom30a_index.df	*÷ÿ"@[Ÿø/I¤dÍÿfathom30a_new.dfE¥	M7ÿé[Ÿø/I¤dÌÿfathom30a_rename.dfm	O ÿ1[Ÿø/I¤dÌþÿgen-alert.p‹Ú	PQÿ[Ÿø0Sëóÿinclude/alert-definitions.iî	aYÿ[Ÿø0I¤dÉÿinclude/ar-debug.i	enÿ[Ÿø0I¤dÉÿinclude/ar-definitions.iT«	fzÿO[Ÿø0N2Å£ÿinclude/ar-delete-loop.i‚	¶
ÿ?[Ÿø0I¤dÈÿinclude/ar-delete-loop2.i	·Iÿˆ[Ÿø0I¤dÇÿinclude/ar-delete-table.iG	¸ÑÿM[Ÿø0I¤dÆþÿinclude/ar-log-msgs.iB	¹ÿé[Ÿø0I¤dÆÿinclude/ar-pass-input.iä(	ºÿ‚[Ÿø0I¤dÅÿinclude/ar-reset.iä=	Í‰ÿ"[Ÿø0KÔçÿinclude/ar-select-criteria.i“3	Ñ«ÿ-[Ÿø0I¤dÄÿinclude/ar-setupdefs.i<ü	ÝØÿ[Ÿø0S–Êµÿinclude/ar-setuptimes.i­h	ðuÿŠ[Ÿø0I¤dÃÿinclude/archive-type.iª¡	òÿÿ³[Ÿø0I¤dÂþÿinclude/data-header.iª€	ó²ÿ¯[Ÿø0I¤dÂÿinclude/db/ai-list.iÛ	øaÿ£[Ÿø0I¤dÁÿinclude/db/ai-load.iô›	ùÿB[Ÿø0I¤dÀÿinclude/db/bi-list.iWg	ÿFÿý[Ÿø0I¤dÀÿinclude/db/bi-load.iI”
CÿË[Ÿø0I¤d¿ÿinclude/db/disk-list.i?8
ÿ[Ÿø0I¤d¾ÿinclude/db/disk-load.i2
,ÿÞ[Ÿø0I¤d¾þÿinclude/db/include-list.i…
;
ÿY[Ÿø0I¤d½ÿinclude/db/include-load.iWØ
@cÿlZ[Ÿø0I¤d¼ÿinclude/db/locking-list.i³=
¬½ÿ0[Ÿø0I¤d¼ÿinclude/db/locking-load.is{
­íÿg[Ÿø0I¤d»ÿinclude/db/memory-list.iE¸
ºTÿì[Ÿø0I¤d»ÿinclude/db/memory-load.iµ7
»@ÿè[Ÿø0I¤dºþÿinclude/db/record-list.i 
Ñ(ÿû[Ÿø0I¤dºÿinclude/db/record-load.iæ
Ò#ÿ
¸[Ÿø0I¤d¹ÿinclude/db/single_load.i
ÜÛÿUk[Ÿø0I¤d¸ÿinclude/db/summary-list.iO2Fÿ›[Ÿø0I¤d¸ÿinclude/db/summary-load.iá®3áÿUj[Ÿø0I¤d·ÿinclude/db-status.iU—‰Kÿ[Ÿø0I¤d·þÿinclude/dbstatus-definitions.iÌ:”Vÿ
[Ÿø0I¤d¶ÿinclude/dd-pass-input.iåžVÿˆ[Ÿø0I¤dµÿinclude/dd-setupdefs.iå"£Þÿu[Ÿø0I¤dµÿinclude/debug.iKEªSÿ5[Ÿø0I¤d´ÿinclude/definitions.iá«ˆÿ$	[Ÿø0I¤d´ÿinclude/dh-pass-input.ix
Ï‘ÿ"[Ÿø0I¤d³ÿinclude/fathom-counters.iÑ³ÿ*[Ÿø0I¤d³þÿinclude/fathom-dir.iòYÒÝÿ3[Ÿø0S8§ÿinclude/fm-environment.i"ŠÕÿ¥[Ÿø0S–Ëÿinclude/genpassinput.i.NÖµÿ)½[Ÿø0I¤d±ÿinclude/no-data.iÊrÿ	£[Ÿø0I¤d°ÿinclude/passinput.i¨¾
ÿDÕ[Ÿø0I¤d°ÿinclude/read-resrc.iTzNêÿª[Ÿø0I¤d¯ÿinclude/recommend-list.iQòP”ÿŒ[Ÿø0I¤d®þÿinclude/recommend-load.i»²R ÿ4¨[Ÿø0I¤d®ÿinclude/report-name.i<ã†Èÿ	a[Ÿø0I¤d­ÿinclude/sample-query.i~l)ÿÉ[Ÿø0I¤d­ÿinclude/setup-i.iò|‘òÿ’[Ÿø0I¤d¬ÿinclude/setup-k.i‹º“„ÿ”[Ÿø0I¤d¬ÿinclude/single-header.i)•ÿ%N[Ÿø0I¤d«ÿinclude/sys/all-load.iÐºfÿ»[Ÿø0I¤dªþÿinclude/sys/cpu-list.i0YÈ!ÿ;[Ÿø0I¤d©ÿinclude/sys/cpu-load.i÷¥È\ÿÒ[Ÿø0I¤d©ÿinclude/sys/mem-list.iÀsË.ÿ[[Ÿø0I¤d¨ÿinclude/sys/mem-load.i‚OË‰ÿ´[Ÿø0I¤d¨ÿ!include/trendDBsingle-temptable.i|ÍÐ=ÿ[Ÿø0I¤d§ÿinclude/trenddates.ikÖÒIÿ~[Ÿø0I¤d§ÿinclude/xml-close-graph.i ”ïÇÿñ[Ÿø0I¤d¦þÿinclude/xml-graphcolumns.i
€ð¸ÿ&[Ÿø0I¤d¥ÿinclude/xml-print-dataset.iˆüÞÿ[Ÿø0I¤d¥ÿinclude/xml-print-labels.iRŠþ{ÿÇ[Ÿø0I¤d¤ÿinclude/xmlcleanup.i–rBÿ²[Ÿø0I¤d¤ÿinclude/xmldefinitions.iDØôÿÊð[Ÿø0I¤d£ÿinclude/xmlhandles.i	¨Îäÿ¢[Ÿø0I¤d£ÿinclude/xmlinitialize.i+¬Ó†ÿ'[Ÿø0I¤d¢þÿinclude/xmlprocs.iƒ°×­ÿû[Ÿø0S­Ýÿmig10_20a.pìàé¨ÿg[Ÿø0I¤d¡ÿmig20a_21a.pYðÿ‘[Ÿø0I¤d ÿ	network.p¤dó ÿ[Ÿø0I¤dŸÿopenedge/asprofile.p¢j¶ÿ>D[Ÿø0I¤džÿopenedge/brokeractivity.p¾ôNúÿé[Ÿø0I¤džÿopenedge/clientactivity.pgìSãÿ«.[Ÿø0I¤dþÿopenedge/performance.pšŽÿÿÚ[Ÿø0I¤dœÿopenedge/serveractivity.pÀ2ëÿ#~[Ÿø0I¤dœÿopenedge/wsprofile.p^[Aiÿ5¾[Ÿø0I¤d›ÿopenedge/xml-asprofile.p¿5w'ÿ‘A[Ÿø0I¤d›ÿopenedge/xml-wsprofile.pR5hÿ\®[Ÿø0I¤dšÿorphan.p9¦eÿ²[Ÿø0I¤dšÿpurgedb_indexstat.pogsÈÿ[Ÿø0I¤d™þÿpurgedb_tablestat.pCžwÛÿ[Ÿø0I¤d˜ÿstatusdetail.pyë{èÿdu[Ÿø0I¤d˜ÿstatussummary.p‹èà]ÿež[Ÿø0I¤d—ÿsystemcpu.p©1EûÿÝ[Ÿø0I¤d–ÿsystemdisk.p!^Øÿ%\[Ÿø0I¤d–ÿsystemfilesize.p–c„4ÿ# [Ÿø0I¤d•ÿsystemfilesystem.p~K§Tÿ*q[Ÿø0I¤d•ÿsystemmemory.p–òÑÅÿÞ[Ÿø0I¤d”ÿtrendDBsingle.pêí£ÿC[Ÿø0I¤d“ÿtrenddriver.pl‰
æÿ½[Ÿø0I¤d“ÿxml-alertgeneral.p³°#£ÿ)Ì[Ÿø0I¥™7ÿxml-alertindividual.p}'Moÿ>Ô[Ÿø0I¤d‘ÿxml-dbareastatus.pšÏŒCÿ-D[Ÿø0I¥™7ÿxml-dbcheckpoint.p]H¹‡ÿB¨[Ÿø0I¤dÿxml-dbdisk.pºü/ÿ*¤[Ÿø0I¤dþÿxml-dbidxanalysis.p˜&Óÿ4¾[Ÿø0I¤dÿxml-dbindexstat.pB[‘ÿ ×[Ÿø0I¥™6ÿxml-dbserver.p¬ñ|hÿ.Ó[Ÿø0I¤dŽÿxml-dbsingle.p.¹«;ÿ0Å[Ÿø0I¤dÿxml-dbtabanalysis.p,çÜÿ6{[Ÿø0I¤dÿxml-dbtablestat.pÜ{ÿ/Ë[Ÿø0I¥™6ÿxml-network.pðBFÿ'‰[Ÿø0I¤d‹þÿxml-statusdetail.p‘iÏÿ$s[Ÿø0I¤d‹ÿxml-systemdisk.pk«ŽBÿ(Ï[Ÿø0I¤dŠÿxml-systemfilesize.p¯·ÿ){[Ÿø0I¤d‰ÿxml-systemfilesystem.pŠJàŒÿ'‰[Ÿø0I¤d‰ÿxml-systemmemory.p¢mÿ;L[Ÿø0I¤dˆÿ31bupdate.dfÄLCaÿ+[Ÿø0I¥™Uÿ31bupdate.p?˜CŒÿ[Ÿø0I¥™Tþÿdbdumpdata.p´C§ÿ!W[Ÿø0I¥™;ÿdbdumpseqval.pS¥dþÿô[Ÿø0I¥™:ÿdberasecf.pIhòÿõ[Ÿø0I¥™:ÿdbloaddata.p¢àjçÿ!É[Ÿø0I¥¿`ÿdbloadseqval.púŒ°ÿ[Ÿø0I¥™9ÿÈ:d'þ