/* ------------------------------------------------------------------
 * ------------------ Mega Stat Spot - version 1.0 ------------------
 * ------------------      By Paul Nuzzo, 1995     ------------------
 * ------------------------------------------------------------------
 * ------------------    Fidonet : 2:254/270.5     ------------------
 * ------------------------------------------------------------------
 *                  $VER: Mega Stat v1.0 (26.12.95)
 * ------------------------------------------------------------------
 */

/* YOU MAY CHANGE THESE TWO LINES, AND ONLY THESE!!*/

config          = "Mail:MegaStat.cfg"
spot_path       = "Mail:spot/spot"

/***************************************************/
/* DONT TOUCH THE REST - YOU HAVE BEEN WARNED      */
/***************************************************/

if ~show('ports','SPOT') then do
    address command 'run 'spot_path
    'WaitForPort SPOT'
    quit = 'YES' /* Marker to quit Spot afterwards */
end

Address 'SPOT'
Options Results

'lockgui'

'isiconified'
   if rc = 0 then do
      icon= 'YES'
      'uniconify'
   end

version = 'v1.0'
CR      = '0d'x
NL      = '0a'x
blank   = ''

/* File variables */

temp_file   = 't:Megastat.tmp'
output_file = 't:Megastat.txt'
log_file    = 'Megastat.log'

'getusername' ; sysname = result

parse arg commandline

if commandline = "?" then do
   say "MegaStat "version
   say "Usage: rx MegaStat.spot [SUPPRESS] [FLAGS <WRQSTNHD>] [SAVE <YES/NO>] [DATE <WEEK/FORTNIGHT/MONTH/ALL>] [TABLE <length>] [MULTIPLE] [JOINT <Area to post>] [STAT <Areatag>]"
   call cleanup()
end

'spot2front'

/* Setup all values.......... */

preftext        =                   "Welcome to Mega Stat Spot "version"!"
preftext        = preftext CR||CR   "There is no preference file available,"
preftext        = preftext CR       "so this must be your first time setting up."
preftext        = preftext CR||CR   "You will now be presented with a series of requesters."
preftext        = preftext CR       "These are NOT permenant - you have the option of changing them"
preftext        = preftext CR       "when loading Mega Stat, but it is easier for the user to store them."
preftext        = preftext CR||CR   "Please refer to the docs if you are in any doubt about this program!"
preftext        = preftext CR||CR   "Now, here come the questions...."

tbar            = "MegaStat "version"..."
creator         = "Posted by 'sysname'"
errortitle      = "An error has occured..."

/* Defaults for the script, overridden usually */

xsquote          = 55
newtopic_content = 30
tablebar         = ' +---------------------------------------------------------------------+'
tablelen_seperator = 1
jointpost          = 0

/* Initialise some variables */

date             = date(i)
time.            = 0
day.             = 0

/* ------------------------------------------------------ */
/* --------- Check for libraries MegaStat needs --------- */
/* ------------------------------------------------------ */

if ~show(l, 'rexxsupport.library') then do
  if ~addlib('rexxsupport.library', 0, -30) then
     do
        'requestnotify TITLE "'errortitle'" CENTER PROMPT "Please install the rexxsupport.library in your libs: directory'CR'and run the script again"'
        call cleanup
     end
end

if ~show(l, 'traplist.library') then do
   if ~addlib('traplist.library', 0, -30) then
      do
         'requestnotify TITLE "'errortitle'" CENTER PROMPT "Please install the traplist.library in your libs: directory'CR'and run the script again"'
         call cleanup
      end
end

if ~exists(config) then do
    'requestresponse Title "'tbar'" Center Prompt "You don`t have a prefs file.  Do you wish to create one?" Gadgets "Yes please!|_Exit"'
    if rc=0 then call cleanup

    /* Setting up prefs... */

    if ~open(cfg,config,'w') then do
        'requestnotify Title "'tbar'" Center Prompt "Sorry, I cannot open a config file."'
        call cleanup
    end

'requestnotify Title "'tbar'" Center Prompt "'preftext'"'

skip = '|_Skip'
skip2 = '_Skip|'
skipnumber = 0

'requestnumber TITLE "'tbar'" CENTER PROMPT "What value would you like to set the Excessive Quote Ratio as?" DEFAULT "55"'
xsquote = result ; if rc ~= 0 then call cleanup()

'requestnumber TITLE "'tbar'" CENTER PROMPT "What value would you like to set the New Topic Content as?" DEFAULT "30"'
newtopic_content = result ; if rc ~= 0 then call cleanup()

Call P_Entries
Call P_Sizequote
Call P_Logs
Call P_Dates
Call P_Receivers
Call P_Writers
Call P_Subjects
Call P_Tearlines
Call P_Orignodes
Call P_Quoters
Call P_Days
Call P_Times
areanumber = P_Areas()
multiareanumber = P_Multiareas()

    Call Writeln(cfg,"; -----------------------------------------------------------")
    Call Writeln(cfg,"; ----- MegaStat.spot config file produced by MegaStat ------")
    Call Writeln(cfg,"; ------------- MegaStat (c) 1995 By Paul Nuzzo -------------")
    Call Writeln(cfg,"; -----------------------------------------------------------")
    Call Writeln(cfg,"; Prefs file for MegaStat "'version'". Please refer to the docs")
    Call Writeln(cfg,"; if you are unsure about what you are doing in here!")
    Call Writeln(cfg,";"NL"; All lines beginning with ';' are ignored")

    Call writeln(cfg,NL||"; Your Spot username should be put here")
    Call Writeln(cfg,    "NAME """sysname"""")

    Call Writeln(cfg,NL||"; If you would like a logfile kept, put the full path here")
    Call Writeln(cfg,    "; otherwise, write NO")
    Call Writeln(cfg,    "LOGFILE "logpath)
    Call Writeln(cfg,NL||"; If you would like a log kept as a message, put the echotag you want here")
    Call Writeln(cfg,    "; This is usually a Keep area for your own use. If not required, write NO")
    Call Writeln(cfg,    "LOGECHO "logecho)

    Call Writeln(cfg,NL||"; The number of entries you wish per table. Use 0 to have unlimited table sizes")
    Call Writeln(cfg,    "; and SKIP to be asked the question everytime")
    Call Writeln(cfg,    "TABLELEN "tablelen)

    Call Writeln(cfg,NL||"; The default period for the stats. 0 = All messages, WEEK, FORTNIGHT, MONTH")
    Call Writeln(cfg,    "; Write SKIP if you wish to be asked this question everytime you run MegaStat")
    Call Writeln(cfg,    "DATE "datelen)

    Call Writeln(cfg,NL||"; Select which tables you want/don't wants. YES if you want a table,")
    Call Writeln(cfg,    ";  NO if you don't and SKIP if you want to be asked evertime by MegaStat")
    Call Writeln(cfg,"WRITERS "writers)
    Call Writeln(cfg,"RECEIVERS "receivers)
    Call Writeln(cfg,"SUBJECTS "subjects)
    Call Writeln(cfg,"TEARLINES "tearlines)
    Call Writeln(cfg,"NODES "nodes)
    Call Writeln(cfg,"QUOTERS "quoters)
    Call Writeln(cfg,"DAYSTAT "daystat)
    Call Writeln(cfg,"TIMESTAT "timestat)

    Call Writeln(cfg,NL||"; If you do not want the Quote Ratio/Average Message Size displayed in the")
    Call Writeln(cfg,    "; tables then write NO. This means that MegaStat will not have to save out")
    Call Writeln(cfg,    "; every messages in the area in order to process the messages. Please note")
    Call Writeln(cfg,    "; that you can't produce a Quoters table of a Tearline table if this is not")
    Call Writeln(cfg,    "; YES (see docs). Use Skip to be asked everytime.")
    Call Writeln(cfg,    "SIZEQUOTE "sizequote)

    Call Writeln(cfg,NL||"; Put here the Excessive quote maximum value you want")
    Call Writeln(cfg,    "XSQUOTE "xsquote)
    
    Call Writeln(cfg,NL||"; Put here the New topic content limit you want in the subjects table")
    Call Writeln(cfg,    "NEWTOPIC "newtopic_content)

if areanumber ~= 0 then 
   do
      do areacount=1 to areanumber
         Call Writeln(cfg,NL||"AREA "area.areacount)
      end 
   end
   
if multiareanumber ~= 0 then 
   do  
       do multiareacount=1 to multiareanumber
          Call Writeln(cfg,NL||"MULTIAREA "multiarea.multiareacount)
       end
   end

    Call Close Cfg

'requestnotify Title "'tbar'" Center Prompt "That`s the prefs file finished now.  I will save the file, and exit.'CR'Run Mega Stat again, and you will be able to use it!"'
call cleanup()

end

/* MAIN PROGRAM -------- */

/* Reading Prefs..... */

Call Open(cfg,config,R)

line = 0 /* Set the line counter - for display if there is an error */
         /* See the "otherwise" section of the select part below    */

A    = 0
MA   = 0

Do until eof(cfg)
    cfgline = readln(cfg)
    line=line+1
    keyword = word(cfgline,1)
    if left(keyword,1) ~= ";" & left(keyword,1) ~= "" then
       do
          select
               when keyword = 'NAME' then name = strip(delstr(cfgline,1,5),B,"""")
               when keyword = 'LOGFILE' then logpath = strip(word(cfgline,2))
               when keyword = 'LOGECHO' then logecho = strip(word(cfgline,2))
               when keyword = 'TABLELEN' then tablelen = strip(word(cfgline,2))
               when keyword = 'DATE' then datelen = strip(word(cfgline,2))
               when keyword = 'RECEIVERS' then receivers = strip(word(cfgline,2))
               when keyword = 'WRITERS' then writers = strip(word(cfgline,2))
               when keyword = 'SUBJECTS' then subjects = strip(word(cfgline,2))
               when keyword = 'NODES' then nodes = strip(word(cfgline,2))
               when keyword = 'QUOTERS' then quoters = strip(word(cfgline,2))
               when keyword = 'TEARLINES' then tearlines = strip(word(cfgline,2))
               when keyword = 'DAYSTAT' then daystat = strip(word(cfgline,2))
               when keyword = 'TIMESTAT' then timestat = strip(word(cfgline,2))
               when keyword = 'SIZEQUOTE' then sizequote = strip(word(cfgline,2))
               when keyword = 'XSQUOTE' then xsquote = strip(word(cfgline,2))
               when keyword = 'NEWTOPIC' then newtopic_content = strip(word(cfgline,2))
               when keyword = 'AREA' then
                   do
                      A=A+1
                      area.A=strip(word(cfgline,2))
                   end
               when keyword = 'MULTIAREA' then
                   do
                      MA=MA+1
                      multiarea.MA = strip(word(cfgline,2))
                   end               
               when keyword = 'AREAPATTERN' then areapattern = strip(word(cfgline,2))
               when keyword = 'MULTIAREAPATTERN' then multiareapattern = strip(word(cfgline,2))
               otherwise say 'Line no. 'line' is corrupt:'NL cfgline
          end
       end
end
call parse_CLI()

if suppress ~= 1 then do
    'requestresponse TITLE "'tbar'" CENTER PROMPT "Please select an option:'CR||CR'STAT - Produce stat for current area only'CR'MULTIPLE AREAS - Produce individual stats for areas listed in config'CR'JOINT AREAS - Produce joint stats for areas listed in config" GADGETS "_Exit|_Stat|_Multiple|_Joint"'
    main_result = rc
end

if main_result = 1 then call cleanup()
   
if main_result = 0 & suppress ~=1 then 
   do
      'requestresponse TITLE "Joint Area Stat Menu" CENTER PROMPT "Select an option" GADGETS "_Select Areas|_Pattern|_Use Defaults (Prefs)"'
      select = rc
      if select = 1 then MA=P_Multiareas()
      else if select = 2 then 
         do
              'requeststring CENTER PROMPT "Please enter a pattern to search for.'||CR||'This should be a common prefix to echos eg. LOCAL" TITLE "'tbar'"'
              if rc=5 then call cleanup()
              else multiareapattern=result
         end      
   end   

if main_result = 3 & suppress ~=1 then
   do 
      'requestresponse TITLE "Multiple Area Stat Menu" CENTER PROMPT "Select an option" GADGETS "_Select Areas|_Pattern|_Use Defaults (Prefs)"'
      select=rc
      if select = 1 then A=P_Areas()
      else if select = 2 then 
         do
              'requeststring CENTER PROMPT "Please enter a pattern to search for.'||CR||'This should be a common prefix to echos eg. LOCAL" TITLE "'tbar'"'
              if rc=5 then call cleanup()
              else areapattern=result
         end        
   end   
   
corrupt = 'requestnotify Title "'tbar'" Center Prompt "Your preferences file is corrupt.'CR'Please delete the file MAIL:MegaStat.cfg'CR'and try again."'

skip = ''
skip2 = '_Specify dates|'
skipnumber = 0

if suppress ~=1 then do

    if name     ~= sysname then corrupt
    if tablelen  = "SKIP" then call P_Entries
    if datelen   = "SKIP" then call P_Dates
    if receivers = "SKIP" then call P_Receivers
    if writers   = "SKIP" then call P_Writers
    if subjects  = "SKIP" then call P_Subjects
    if tearlines = "SKIP" then call P_Tearlines
    if nodes     = "SKIP" then call P_Orignodes
    if quoters   = "SKIP" then call P_Quoters
    if daystat   = "SKIP" then call P_Days
    if timestat  = "SKIP" then call P_Times
    if sizequote = "SKIP" then call P_Sizequote

end

if main_result = 2 then
   do
      'getnummsgs' ; nummsgs=result
      'getareaname' ; area = result
      call datesetup()
      call single_echo()
   end
   
if main_result = 3 then
   do
      'getnumareas' ; numareas = result
      if areapattern ~= "AREAPATTERN" & select ~= 1 then
         do 
            A=0
            'arealist'
            'firstarea'
            do counterthing=1 to numareas
                'getareaname'
                if left(upper(result),length(areapattern))=upper(areapattern) then 
                 do
                    A=A+1  
                    area.A=result
                 end
                'nextarea'
            end
         end
      call datesetup()
      do largerloop=1 to A
         'gotoarea' area.largerloop
         area = area.largerloop
         'getnummsgs' ; nummsgs = result
         if nummsgs=0 then ITERATE
         /* Drop all the variables we used, as we need them in unassigned format */         
         drop writer. receiver. writer_totbyte. writer_q. writer_nq. writer_qp. writer_byte. writer_tearline.
         drop userlist. nodelist. subjectlist. address. subjecttotal.
         drop subject. subject_q. subject_nq. subject_qp. subject_byte.
         time. = 0 ; day. = 0
         call single_echo()
         call close(mess)
         end   
   end
     
if main_result = 0 then 
   do
                 
      'getnumareas' ; numareas = result
      if multiareapattern ~= "MULTIAREAPATTERN" & select~=1 then
         do 
            MA=0
            'arealist'
            'firstarea'
            do counterthing=1 to numareas
                'getareaname'
                if left(upper(result),length(multiareapattern))=upper(multiareapattern) then 
                 do
                    MA=MA+1  
                    multiarea.MA=result
                 end
                'nextarea'
            end
         end

      starttime = time(r)

      userlist.0 = 0 
      subjectlist.0 = 0 
      nodelist.0 = 0
      usedmessages=0 
      unreg_soft = 0
      error_report = blank 
      call datesetup()
      
      do largerloop=1 to MA
         'gotoarea' multiarea.largerloop
         area = multiarea.largerloop
         'getnummsgs' ; nummsgs = result
         if nummsgs=0 then ITERATE
         call get_information()
      end
  
   call write_message_text()      
   Call write_message
   
   endtime=time(e)

   if logpath ~= 'NO' then call writelog()
   if logecho ~= 'NO' then call messagelog()
end   

call cleanup

/*!*/single_echo:

starttime = time(r)

userlist.0       = 0 
subjectlist.0    = 0 
nodelist.0       = 0
usedmessages     = 0 
error_report     = blank 
       
Call get_information
if userlist.0 ~= 0 then 
do
   
   Call write_message_text()  
   
   if main_result = 2 & suppress~=1 then 
   do
       'requestresponse TITLE "'tbar'" CENTER PROMPT "Please select output." GADGETS "_In Echo|In Echo & Edit Output|_File|_Cancel"'
       where=rc
       if where=0 then call cleanup()
       if where=3 then
           do
               'requestfile TITLE "'title'" PATH "ram:" FILE "'area'.stat"'
               if rc=0 then address command 'copy t:'output_file result
           end
       else call write_message()
    end           
  else Call write_message()

end   
endtime=time(e)
if logpath ~= 'NO' then call writelog()
if logecho ~= "NO" then call messagelog()
  
return
/*!!*/

/*!*/write_header:

/* Create the message header for the top of the message with general info */

message_header =                     '            +-----------------------------------------------+'

if main_result = 0 then
do
    message_header = message_header||NL||'            | Joint stats for the following areas:          |'
    do somebloodymoreloops=1 to MA
       message_header = message_header||NL||'            |                   'left(multiarea.somebloodymoreloops,27)||' |'
    end
end
else do
    message_header = message_header||NL||'            | Stats For Area  : 'left(area,27)||' |'
end
message_header = message_header||NL||'            | Date Created    : 'left(date(),27)||' |' 
if datelen ~= 0 then 
do
  message_header = message_header||NL||'            | Period Covered  : 'left((date(n,startdate,i)||" - "date(n,enddate,i)),27)||' |'
  if datelen = 'MONTH' then extra = 0 
     else extra = 1
  message_header = message_header||NL||'            | Days Covered    : 'left((enddate-startdate)+extra,27)' |'
end
message_header = message_header||NL||'            | No. Of Messages : 'left(usedmessages,27)' |'
message_header = message_header||NL||'            +-----------------------------------------------+'

return message_header

/*!*/write_message:

if main_result = 0 & jointpost = 0 then 
do 
  do until cancel=5 
    
    'requestarea TITLE "Select area for report.."'
    cancel= rc
    if cancel=5 then ITERATE
    'gotoarea 'result
   
    if datelen ~= 0 then periodcovered = date(n,startdate,i)||" - "||date(n,enddate,i)
    else periodcovered = date()
   'write TO "All" FROM "'sysname'" SUBJECT "Echo Stats : 'periodcovered'" ORIGIN "Created By MegaStat 'version' (c) Paul Nuzzo" FILE "'output_file'" NOEDIT NOSIG NOGUI'
      
'messages'

'lastmessage'
  end  
end
else 
do
    if jointpost=1 then 'gotoarea 'jointpostarea

    if datelen ~= 0 then periodcovered = date(n,startdate,i)||" - "||date(n,enddate,i)
       else periodcovered = date()
    'write TO "All" FROM "'sysname'" SUBJECT "Echo Stats : 'periodcovered'" ORIGIN "Created By MegaStat 'version' (c) Paul Nuzzo" FILE "'output_file'" NOEDIT NOSIG NOGUI'
    if where=2 then
       do
           'messages'
           'lastmessage'
           'edit'
       end

    'messages'

    'lastmessage'
end
return
/*!!*/
                  
/*!*/sort_writers: procedure expose blank tablebar tablelen xsquote sizequote usedmessages writer_qp. writer_totbyte. writer. NL address. userlist. writer_q. writer_nq. writer_byte.


total_writers=0

'progressopen TITLE "Creating Tables..." PROMPT "Creating Writer Table"'
preq = result

do user=1 to userlist.0

   username = userlist.user

   if sizequote = 'YES' then
       do

          select
             when writer_q.username = 0 then writer_qp.username = 0
             otherwise writer_qp.username = (writer_q.username/(writer_nq.username+writer_q.username))*100
          end

          select
             when writer_byte.username = 0 then writer_totbyte.username = 0
             otherwise writer_totbyte.username = trunc((writer_byte.username/writer.username),0)
          end

       end
       else
           do
              writer_qp.username = 0
              writer_totbyte.username = 0
           end
end

report = ""

if userlist.0~=0 then do

    do loop=1 to userlist.0
       writer=0; highest = 0

       'progressupdate REQ "'preq'" CURRENT "'loop'" TOTAL "'userlist.0'"'
       if rc = 5 then
          do
             'progressclose REQ "'preq'"'
             call cleanup()
          end

       do count=1 to userlist.0
          username = userlist.count
          if writer.username ~< highest & writer_used.username ~= "sausage" then
             do
                writer = username ; highest = writer.username
             end

       end

       if writer.writer ~= 0 then total_writers = total_writers+1

       select
          when address.writer = "?" then flag = ' '
          when traplist_info(node(address.writer)) = '?' then flag = '#'
          when writer_qp.writer > xsquote then flag = '!'

          otherwise flag = " "
       end

       if flag = '!' then flag_used_! = 1
       if flag = '#' then flag_used_# = 1

       if (loop > tablelen) & tablelen ~= 0 & flag = " " then
           do

           end
       else
       if (loop > tablelen) & tablelen ~= 0 then
           do

             if writer.writer ~= 0 then
                do

                 if sizequote = 'YES' then
                    do
               	       	report = report||NL||" |"||right(loop,3," ")||". "||flag||" "
                  	report = report||left(namecase(writer)||" ",22,".")
                   	report = report left(address.writer||" ",14,".")
                   	report = report||right(" "||writer_totbyte.writer,8,".")
                   	report = report right(left((" "||writer_qp.writer||".0"),((index((" "||writer_qp.writer||".0"),".",1))+1)),7,".")
                   	report = report||"%"
                   	report = report right(" "writer.writer||" ",6,".")
                   	report = report "|"
                    end
                 else
                    do
                   	report = report||NL||" |"||right(loop,3," ")||". "||flag||" "
                   	report = report||left(namecase(writer)||" ",22,".")
                   	report = report left(address.writer||" ",14,".")
                   	report = report||right(" "writer.writer||" ",12,".")
                   	report = report||right(" "||trunc((writer.writer/usedmessages)*100,0)||"%",11,".")||"  |"
                    end

                end

             extra_entries = 1
           end

           else
               do
                 if writer.writer ~= 0 then
                     do
                       if sizequote = 'YES' then
                       do
                         report = report||NL||" |"||right(loop,3," ")||". "||flag||" "                          
                         report = report||left(namecase(writer)||" ",22,".")
                         report = report left(address.writer||" ",14,".")
                         report = report||right(" "||writer_totbyte.writer,8,".")
                         report = report right(left((" "||writer_qp.writer||".0"),((index((" "||writer_qp.writer||".0"),".",1))+1)),7,".")
                         report = report||"%"
                         report = report right(" "writer.writer||" ",6,".")
                         report = report "|"
                       end
                       else
                       do
                         report = report||NL||" |"||right(loop,3," ")||". "||flag||" "
                         report = report||left(namecase(writer)||" ",22,".")
                         report = report left(address.writer||" ",14,".")
                         report = report||right(" "writer.writer||" ",12,".")
                         report = report||right(" "||trunc((writer.writer/usedmessages)*100,0)||"%",11,".")||"  |"
                       end
                     end
               end

           if (loop = tablelen) & tablelen ~= 0 then
               do
                 report = report||NL||tablebar
                 tablelen_seperator = 1
               end

           writer_used.writer = "sausage"

  end

  if tablelen_seperator ~= 1 | extra_entries = 1 then
     report =report||NL||tablebar

  if flag_used_! = 1 | flag_used_# = 1 then do
     footnote = 'NB.' 

     if flag_used_!  = 1 then
         do
            report   = report||NL||' | 'footnote' ! = Quoting level is considered excessive.                      |'
            footnote = "   "
         end
     if flag_used_#  = 1 then
         do
            report   = report||NL||' | 'footnote' # = Address is not present in the current nodelist.             |'
            footnote = "   "
         end

     report = report||NL||tablebar
  end

  header_title = '      |  Echomail Writers (T:'userlist.0', W:'total_writers')  |'

  writer_header   = NL||'      +'right(blank,(length(header_title)-8),"-")||'+'
  writer_header   = writer_header||NL||header_title
  writer_header   = writer_header||NL||' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,71-length(header_title),"-")||'+'

  if sizequote = 'YES' then
      do


         writer_header = writer_header||NL||' |                                              Average                |'
         writer_header = writer_header||NL||' | No.   Name                   Address        bytes/msg  Quoted  From |'
      end
  else
      do
         writer_header = writer_header||NL||' | No.   Name                   Address              From   Pct. Total |'
      end

  writer_header = writer_header||NL||tablebar

end

'progressclose REQ "'preq'"'

return writer_header||report
/*!!*/

/*!*/sort_receivers: procedure expose blank tablebar tablelen receiver. NL userlist. usedmessages

total_receivers = 0

report = ""

'progressopen TITLE "Creating Tables..." PROMPT "Creating Receivers Table"'
preq = result

if userlist.0 ~= 0 then
   do
     do loop = 1 to userlist.0
        receiver = 0 ; highest = 0

      'progressupdate REQ "'preq'" CURRENT "'loop'" TOTAL "'userlist.0'"'
        if rc = 5 then
           do
              'progressclose REQ "'preq'"'
              call cleanup()
           end

        do user = 1 to userlist.0
           username = userlist.user

           if receiver.username ~< highest & receiver_used.username ~= "sausage" then
              do
                 receiver = username ; highest = receiver.username
              end
        end


     if receiver.receiver ~= 0 then total_receivers=total_receivers+1
     
     if receiver.receiver ~= 0 then 
     do
        if (loop > tablelen & tablelen ~= 0) then
           do
              /* Do nothing */
           end
        
         else
            do
               report = report||NL||" |"||right(loop,3," ")||".  "
               report = report left(namecase(receiver)||" ",41,".")||right(" "||receiver.receiver,7,".")||" "||right(" "||trunc((receiver.receiver/usedmessages)*100,0)||"%",11,".")||"  |"
            end
     end
     receiver_used.receiver = "sausage"
     end

     report = report||NL||tablebar

     header_title = '      |  Echomail Receivers (T:'userlist.0', R:'total_receivers')  |'

     receiver_header   = NL||'      +'right(blank,(length(header_title)-8),"-")||'+'
     receiver_header   = receiver_header||NL||header_title
     receiver_header   = receiver_header||NL||' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,71-length(header_title),"-")||'+'
     receiver_header   = receiver_header||NL||' | No.   Name                                          To   Pct. Total |'
     receiver_header   = receiver_header||NL||tablebar
end

'progressclose REQ "'preq'"'

return receiver_header||report
/*!!*/

/*!*/sort_subjects: procedure expose usedmessages sizequote blank tablelen tablebar NL newtopic_content subjectlist. subjecttotal. subject_q. subject_nq. subject_byte. version

total_subjects = 0

'progressopen TITLE "Creating Tables..." PROMPT "Creating Subjects Table"'
preq = result

do subj=1 to subjectlist.0

   subjectname = subjectlist.subj

   if sizequote = 'YES' then
       do
          select
              when subject_q.subjectname = 0 then subject_new.subjectname = 100
              otherwise subject_new.subjectname = (subject_nq.subjectname/(subject_nq.subjectname+subject_q.subjectname))*100
           end

          select
             when subject_byte.subjectname = 0 then subject_totbyte.subjectname = 0
             otherwise subject_totbyte.subjectname = trunc((subject_byte.subjectname/subjecttotal.subjectname),0)
          end

       end
       else
           do
              subject_new.subjectname = 100
             subject_totbyte.subjectname = 0
           end
end


report = ''

if subjectlist.0~=0 then do
     /* sort according to amount of mail posted per subject*/
    do loop=1 to subjectlist.0
       subject=0; highest = 0
       
       'progressupdate REQ "'preq'" CURRENT "'loop'" TOTAL "'subjectlist.0'"'
       if rc = 5 then
          do
             'progressclose REQ "'preq'"'
             call cleanup()
          end
       
       do count=1 to subjectlist.0
          subjectname = subjectlist.count

          if subjecttotal.subjectname ~< highest & subject_used.subjectname ~= "sausage" then
             do
                subject = subjectname ; highest = subjecttotal.subjectname
             end
       end

     if sizequote = 'YES' then
        do
          select
             when subject_new.subject < newtopic_content then flag = '!'
             otherwise flag = " "
          end
        end
    else flag = " "

       if flag = '!' then flag_used_! = 1

       if (loop > tablelen) & tablelen ~= 0 & flag = " " then
           do
              /* Absolutely nothing. Sod all. Nowt. Not much really */
           end
       else
      if (loop > tablelen) & tablelen ~= 0 then
          do
              if sizequote = 'YES' then
                 do
                   report = report||NL||" |"||right(loop,3," ")||". "||flag||" "
                   report = report||left(subject||" ",39,".")
                   report = report||right(" "||subject_totbyte.subject,6,".")
                   report = report right(left((" "||subject_new.subject||".0"),((index((" "||subject_new.subject||".0"),".",1))+1)),7,".")
                   report = report||"%"
                   report = report right(" "subjecttotal.subject||" ",6,".")
                   report = report "|"
                 end
                 else
                 do
                   report = report||NL||" |"||right(loop,3," ")||". "||flag||" "
                   report = report||left(subject||" ",43,".")
                   report = report||right(" "subjecttotal.subject||" ",6,".")
                   report = report||right(" "||trunc((subjecttotal.subject/usedmessages)*100,0)||"%",11,".")||"  |"
                 end
            
             extra_entries = 1
           end

           else
               do
                 if sizequote = 'YES' then
                     do
                        report = report||NL||" |"||right(loop,3," ")||". "||flag||" "
                        report = report||left(subject||" ",39,".")
                        report = report||right(" "||subject_totbyte.subject,6,".")
                        report = report right(left((" "||subject_new.subject||".0"),((index((" "||subject_new.subject||".0"),".",1))+1)),7,".")
                        report = report||"%"
                        report = report right(" "subjecttotal.subject||" ",6,".")
                        report = report "|"
                     end
                  else
                     do
                        report = report||NL||" |"||right(loop,3," ")||". "||flag||" "
                        report = report||left(subject||" ",43,".")
                        report = report||right(" "subjecttotal.subject||" ",6,".")
                        report = report||right(" "||trunc((subjecttotal.subject/usedmessages)*100,0)||"%",11,".")||"  |"
                     end
              end

       if (loop = tablelen) & tablelen ~= 0 then
           do
              report = report||NL||tablebar
             tablelen_seperator = 1
          end

           subject_used.subject = "sausage"

    end
  if tablelen_seperator ~= 1 | extra_entries = 1 then
        report = report||NL||tablebar

  if flag_used_!  = 1 then
     do
        report    = report||NL||' | NB. ! = Thread is currently wasting bandwidth.                      |'
        report    = report||NL||tablebar
     end

  header_title = '      |  Echomail Subjects (T:'subjectlist.0')  |'

  subject_header   = NL||'      +'right(blank,(length(header_title)-8),"-")||'+'
  subject_header   = subject_header||NL||header_title
  subject_header   = subject_header||NL||' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,71-length(header_title),"-")||'+'

  if sizequote = 'YES' then
     do

         subject_header = subject_header||NL||' |                                              Average                |'
         subject_header = subject_header||NL||' | No.   Subject                              bytes/subj.  New   Total |'
      end
  else
      do
         subject_header = subject_header||NL||' | No.   Subject                                    Total   Pct. Total |'
      end

  subject_header = subject_header||NL||tablebar
end

'progressclose REQ "'preq'"'

return subject_header||report
/*!!*/

/*!*/sort_quoters_blacklist: procedure expose writers address. blank usedmessages writer_totbyte. tablelen tablebar NL writer. writer_qp. xsquote userlist. sizequote writer_q. writer_nq. writer_byte. 

quoters_header = blank

if sizequote ~= 'YES' then report='error'

    else do
       
       'progressopen TITLE "Creating Tables..." PROMPT "Creating Quote Blacklist Table"'
       preq = result
       
       xsquoters = 0
       report = blank   
    
if writers ~= "YES" then
do       
       do user=1 to userlist.0

       username = userlist.user
 
          select
             when writer_q.username = 0 then writer_qp.username = 0
             otherwise writer_qp.username = (writer_q.username/(writer_nq.username+writer_q.username))*100
          end

          select
             when writer_byte.username = 0 then writer_totbyte.username = 0
             otherwise writer_totbyte.username = trunc((writer_byte.username/writer.username),0)
          end

       end
       
end
       
       if userlist ~= 0 then
          do
             do loop = 1 to userlist.0
                writer = 0 ; highest = 0
                 
                'progressupdate REQ "'preq'" CURRENT "'loop'" TOTAL "'userlist.0'"'
                if rc = 5 then
                   do
                      'progressclose REQ "'preq'"'
                      call cleanup()
                   end 
                 
                do user = 1 to userlist.0
                   username = userlist.user
                    if writer_qp.username ~< highest & xsquoter_used.username ~= "sausage" then
                      do
                        writer = username ; highest = writer_qp.username
                      end
                end

                if writer_qp.writer ~= 0 then xsquoters = xsquoters+1
                
                if writer_qp.writer ~= 0 then
                do
                
                if (loop > tablelen & tablelen ~= 0) then
                   do
                     /* Nothing */
                   end
                else 
                   do
             		quote_table_used=1
             		report = report||NL||" |"||right(loop,3," ")||".  "
             		report = report left(namecase(writer)||" ",22,".")||left(" "||address.writer||" ",15,".")
 		        report = report||right(" "||writer_totbyte.writer,8,".")
             		report = report right(" "writer.writer||" ",6,".")
            		report = report||right(" "||trunc(writer_qp.writer,1),7,".")
             		report = report||"%  |"
                   end
                end
                xsquoter_used.writer = "sausage"
             end

if quote_table_used=1 then
do
     report = report||NL||tablebar


     header_title = '      |  Echomail Blacklist of Quoters (T:'xsquoters')  |'

     quoters_header   = NL||'      +'right(blank,(length(header_title)-8),"-")||'+'
     quoters_header   = quoters_header||NL||header_title
     quoters_header   = quoters_header||NL||' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,71-length(header_title),"-")||'+'
     quoters_header   = quoters_header||NL||' |                                              Average                |'
     quoters_header   = quoters_header||NL||' | No.   Name                   Address        bytes/msg  From  Quoted |'

     quoters_header   = quoters_header||NL||tablebar
  end
end

'progressclose REQ "'preq'"'

end


Return quoters_header||report

/*!!*/

/*!*/sort_node_traffic: procedure expose blank NL sizequote writer_byte. tablebar tablelen userlist. nodelist. address. writer.

total_nodes = 0
nodelist.0 = 0
report = blank

'progressopen TITLE "Creating Tables..." PROMPT "Creating Node Traffic Table"'
preq = result

if userlist.0 ~= 0 then 
   do
       do user=1 to userlist.0
          username = userlist.user
          
          if address.username ~= "?" then 
             do
                nodeaddress = node(address.username)
                
                if nodetotal.nodeaddress = 'NODETOTAL.'nodeaddress then

                   do
                      nodelist.0 = nodelist.0 + 1
                      nodetotal = nodelist.0
                      nodelist.nodetotal = nodeaddress
                      nodetotal.nodeaddress = writer.username
                      node_byte.nodeaddress = writer_byte.username
                   end
                else 
                    do

                       nodetotal.nodeaddress = nodetotal.nodeaddress + writer.username
                       node_byte.nodeaddress = node_byte.nodeaddress + writer_byte.username
                    end   
             end

        end
      
        do loop = 1 to nodelist.0
           node = 0 ; highest = 0
           
           'progressupdate REQ "'preq'" CURRENT "'loop'" TOTAL "'nodelist.0'"'
           if rc = 5 then
              do
                 'progressclose REQ "'preq'"'
                 call cleanup()
              end
           
           do n = 1 to nodelist.0
              nodeaddress = nodelist.n
              
              if nodetotal.nodeaddress ~< highest & node_used.nodeaddress ~= "sausage" then
                 do
                    node = nodeaddress
                    highest = nodetotal.nodeaddress
                 end
           end
        
           system_name = traplist_info(node)

           if system_name = "?" then flag = "#"
           else flag = " "

         
           if flag = "#" then flag_used_# = 1
           
           if (loop > tablelen) & tablelen ~= 0 & flag = " " then
             do

             end

           else
             if (loop > tablelen) & tablelen ~= 0 then
                do
                   if sizequote = 'YES' then
                      do
                         report = report||NL||" | "||right(loop,3," ")||". "||flag
                         report = report||" "||left(system_name||" ",31,".")
                         report = report||left(" "||node||" ",14,".")
                         report = report||right(" "||node_byte.node||" ",8,".")
                         report = report||right(" "||nodetotal.node,6,".")||"  |" 
                      end
                    else
                      do   
                         report = report||NL||" | "||right(loop,3," ")||". "||flag
                         report = report||" "||left(system_name||" ",32,".")
                         report = report||left(" "||node||" ",18,".")
                         report = report||right(" "||nodetotal.node,9,".")||"  |" 
                      end 
                   
                      extra_entries = 1
                end
            
             else
                do
                 if sizequote = 'YES' then
                    do
                       report = report||NL||" | "||right(loop,3," ")||". "||flag
                       report = report||" "||left(system_name||" ",31,".")
                       report = report||left(" "||node||" ",14,".")
                       report = report||right(" "||node_byte.node||" ",8,".")
                       report = report||right(" "||nodetotal.node,6,".")||"  |" 
                    end       
                 else
                    do
                       report = report||NL||" | "||right(loop,3," ")||". "||flag
                       report = report||" "||left(system_name||" ",32,".")
                       report = report||left(" "||node||" ",18,".")
                       report = report||right(" "||nodetotal.node,9,".")||"  |"
                    end
                end      
           node_used.node = "sausage"

           
           if (loop = tablelen) & tablelen ~= 0 then 
              do
                 report = report||NL||tablebar
                 tablelen_seperator = 1
              end
           
       end
      
       if tablelen_seperator ~= 1 | extra_entries = 1 then 
             report = report||NL||tablebar
                         
       if flag_used_# = 1 then 
          do
             report = report||NL||' |  NB. # = Address is not present in the current nodelist.            |'
             report = report||NL||tablebar
          end
      
        header_title = '      |  Echomail Origins (T:'nodelist.0')  |'

        node_header = NL||'      +'||right(blank,(length(header_title)-8),"-")||'+'
        node_header = node_header||NL||header_title
        node_header = node_header||NL||' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,71-length(header_title),"-")||'+'

         if sizequote = 'YES' then 
            do
               node_header = node_header||NL||' |                                                       Total         |'   
               node_header = node_header||NL||' |  No.   System Name                     Address        Bytes   Total |'
            end       
         else
            node_header = node_header||NL||' |  No.   System Name                      Address               Total |'
     
        node_header = node_header||NL||tablebar

end

'progressclose REQ "'preq'"'

return node_header||report       

/*!!*/

/*!*/sort_tearlines: procedure expose blank NL sizequote writer_tearline. tablelen tablebar userlist. writer. unreg_soft

tearline_header = blank

if sizequote ~= 'YES' then report = 'error'
  
else if tearlines=1 then 
    do

       tearlines.0 = 0
       report = blank
       
       'progressopen TITLE "Creating Tables..." PROMPT "Creating Tearline Table"'
       preq = result
       
       if userlist.0 ~= 0 then
         do
            do user = 1 to userlist.0
               username = userlist.user
                
               if (writer_tearline.username ~= "WRITER_TEARLINE."username) & (left(writer_tearline.username,5) ~= '---  ') then
                  do  

                   tearline = writer_tearline.username
                                          
                   if tearlinetotal.tearline = 'TEARLINETOTAL.'tearline then

                       do
                          tearlines.0 = tearlines.0 + 1 /* Keep a check on all tearlines held */
                          tearlinetotal = tearlines.0
                          tearlines.tearlinetotal = tearline
                          tearlinetotal.tearline = writer.username
                       end
                   
                    else 
                     
                         tearlinetotal.tearline = tearlinetotal.tearline + writer.username
                
                  end
             end        
               
              do loop = 1 to tearlines.0
                 tearline = 0 ; highest = 0
                 
                 'progressupdate REQ "'preq'" CURRENT "'loop'" TOTAL "'tearlines.0'"'
                 if rc = 5 then
                    do
                       'progressclose REQ "'preq'"'
                       call cleanup()
                    end
                 
                 do t=1 to tearlines.0
                    tear = tearlines.t
                                                 
                    if tearlinetotal.tear ~< highest & tearline_used.tear ~= "sausage" then
                       do 
                          tearline = tear
                          highest = tearlinetotal.tear
                       end

                 end
                                                   
                if (loop > tablelen) & tablelen ~= 0 then
                   do

                   end
               
                else 
                   do
                      report = report||NL||" | "||right(loop,3," ")||".  "
                      report = report||" "left(tearline||" ",50,".")
                      report = report||right(" "||tearlinetotal.tearline,9,".")||"  |"
                   end
               
                tearline_used.tearline = "sausage"
            
           
             end
         
           report = report||NL||tablebar
           
       
           header_title = '      |  Echomail Tearlines (T:'tearlines.0')  |'
        
           tearline_header = NL||'      +'||right(blank,(length(header_title)-8),"-")||'+'
           tearline_header = tearline_header||NL||header_title
           tearline_header = tearline_header||NL||' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,71-length(header_title),"-")||'+'
        
           tearline_header = tearline_header||NL||' |  No.   Tearline                                               Total |'
        
           tearline_header = tearline_header||NL||tablebar
                         
    end
'progressclose REQ "'preq'"'

end
else report = ''
return tearline_header||report
/*!!*/

/*!*/datesetup: procedure expose startdate enddate datelen date

if datelen = 'WEEK' then 
    do
       startdate = date-6
       enddate   = date
    end

if datelen = 'FORTNIGHT' then
    do
       startdate = date-13
       enddate   = date
    end

if datelen = 'MONTH' then 
    do

        lastmonth     = substr(date(s,date,i),5,2)-1
        lastmonthdate = overlay(lastmonth,date(s,date,i),5)

        if lastmonth<10 then
            do
               lastmonthdate = delstr(lastmonthdate,6,1)
               lastmonthdate = insert('0',lastmonthdate,4)
            end

        startdate    = date(i,lastmonthdate,s)
        enddate      = date
    end
return
/*!!*/


/*!*/get_information: procedure expose datelen startdate enddate date usedmessages nummsgs time. day. blank NL temp_file sizequote subjecttotal. address. subjectlist. userlist. receiver. writer. writer_q. writer_nq. writer_byte. subject_q. subject_nq. subject_byte. writer_tearline.

'messagelist'
'excludeflag ALL'

'progressopen TITLE "Assessing Echomail Information...." PROMPT "Assessing Echomail Information"'
preq = result

do loop=1 to nummsgs


'progressupdate REQ "'preq'" CURRENT "'loop'" TOTAL "'nummsgs'" PROMPT "Message: 'loop'/'nummsgs'"'
     if rc  = 5 then
       do
          'progressclose REQ "'preq'"'
          call cleanup()
       end

'gotomessage' loop

if datelen ~= 0 then
   do
      'getdatewritten' ; date=result
      if left(date, 2)<10 then date = insert('0',date)
      if substr(date,4,2)<10 then date = insert('0', date, 3)

      date=compress(right(date,4) substr(date,4,2) left(date,2))

      if left(date,4)<1978 then date = overlay("1978",date,1)

      date=date(i,date,s)

      if date<startdate | date written > enddate then ITERATE
   end
 
   if sizequote='YES' then 'markmessage'


   'getfrom'        ; from_name = upper(result)
   'getfromaddress' ; from_add  = result
   'getto'          ; to_name   = upper(result)
   'getsubject'     ; subject   = result

   usedmessages = usedmessages+1


   if writer.from_name = 'WRITER.'from_name & receiver.from_name = 'RECEIVER.'from_name then

   do
       userlist.0=userlist.0+1        /* Found a new user, so add one */
       usertotal=userlist.0           /* Add them to the total number */
       userlist.usertotal = from_name /* Add their name to the list   */

       writer.from_name      = 1
       writer_q.from_name    = 0
       writer_nq.from_name   = 0
       writer_byte.from_name = 0
       receiver.from_name    = 0
       address.from_name     = from_add
   end

   else
     do

       writer.from_name  = writer.from_name + 1
       address.from_name = from_add
     end


   if writer.to_name = 'WRITER.'to_name & receiver.to_name = 'RECEIVER.'to_name then
   do
       userlist.0 = userlist.0 + 1
       usertotal=userlist.0
       userlist.usertotal = to_name

       writer.to_name        = 0
       writer_q.to_name      = 0
       writer_nq.to_name     = 0
       writer_byte.to_name   = 0
       receiver.to_name      = 1
       address.to_name       = "?"
   end

   else

       receiver.to_name = receiver.to_name + 1


   if left(upper(subject),3) = 'RE:' then
      do
          subject = delstr(subject,1,3)
          subject = strip(subject,'L')
      end

   if subjecttotal.subject = 'SUBJECTTOTAL.'subject then

       do
          subjectlist.0 = subjectlist.0 + 1
          subjecttotal = subjectlist.0
          subjectlist.subjecttotal = subject

          subjecttotal.subject = 1
          subject_q.subject    = 0
          subject_nq.subject   = 0
          subject_byte.subject = 0
       end

   else

       subjecttotal.subject = subjecttotal.subject + 1

   if sizequote = 'YES' then
      do
         'saveascii 'temp_file' overwrite noheader nokludges noorigin'

         call open(mess,temp_file,"r")

         do until eof(mess)=1 
             currentline = readln(mess)
             if (index(currentline,">")> 1 & index(currentline,">")<6) | (index(currentline,":")>1 & index(currentline,":")<6) then /* a quoted line, add it on */
                do
                   writer_q.from_name = writer_q.from_name + length(currentline)
                   subject_q.subject = subject_q.subject +length(currentline)
                end

             else
                if line ~= "" then
                   do

                       writer_nq.from_name = writer_nq.from_name + length(currentline)
                       subject_nq.subject = subject_nq.subject + length(currentline)
                   end

             writer_byte.from_name = writer_byte.from_name + length(currentline)
             subject_byte.subject  = subject_byte.subject + length(currentline)
             if left(currentline,4)='--- ' then 
             do   
                writer_tearline.from_name = currentline      
                tearlinesused=1
             end
          end
        

writer_byte.from_name = writer_byte.from_name - length(writer_tearline.from_name)
subject_byte.subject = subject_byte.subject - length(writer_tearline.from_name)
writer_nq.from_name = writer_nq.from_name - length(writer_tearline.from_name)
subject_nq.subject = subject_nq.subject - length(writer_tearline.from_name)
  
        call close(mess)

      end

      'getdatewritten'
        date = result
      'gettimewritten'
        time=result

      if left(date,2)<10 then
         do
            date=insert('0', date)
         end

      if substr(date, 4,2)<10 then
         do
            date=insert('0', date, 3)
         end

       
      date = compress(right(date,4) substr(date,4,2) left(date,2))
     
      if left(date,4)<=1978 then date=overlay("1978",date,1)
     
      day=date(w,date,s)


      select
           when day='Monday'    then day.1=day.1+1
           when day='Tuesday'   then day.2=day.2+1
           when day='Wednesday' then day.3=day.3+1
           when day='Thursday'  then day.4=day.4+1
           when day='Friday'    then day.5=day.5+1
           when day='Saturday'  then day.6=day.6+1

      otherwise day.7=day.7+1
      end

     do armadillo=0 to 22 by 2
        if left(time,1)=0 then
            do
               time=delstr(time,1,1)
               time=overlay('.',time,2,1)
            end
       if left(time,2)>=armadillo & left(time,2)<armadillo+2 then time.armadillo=time.armadillo+1
     end
     if sizequote = 'YES' then 'markmessage CLEAR'

end

'progressclose REQ "'preq'"'

Return  /* Procedure to grab statistics from message base */
/*!!*/

/*!*/sort_daystat:

if userlist.0 ~= 0 then 
do

/* Find the highest variable for day's */

largest = 0
do sort=1 to 7
  if day.sort>=largest then largest=day.sort

end

block=largest/40

do sort=1 to 7
   block.sort=day.sort/block
end

do idx=1 to 7
   if index(block.idx,'.')~=0 then do
      if substr(block.idx,(index(block.idx,'.'))+1,1)>=5 then do
         block.idx=block.idx+1
         block.idx=delstr(block.idx, index(block.idx, '.'))
      end
     else do
         block.idx=delstr(block.idx, index(block.idx,'.'))
     end
   end
end

report =        NL||' |  Monday         |  'left((copies('*',block.1)' ('day.1')'),47," ")||"  |"
report = report NL||' |  Tuesday        |  'left((copies('*',block.2)' ('day.2')'),47," ")||"  |"
report = report NL||' |  Wednesday      |  'left((copies('*',block.3)' ('day.3')'),47," ")||"  |"
report = report NL||' |  Thursday       |  'left((copies('*',block.4)' ('day.4')'),47," ")||"  |"
report = report NL||' |  Friday         |  'left((copies('*',block.5)' ('day.5')'),47," ")||"  |"
report = report NL||' |  Saturday       |  'left((copies('*',block.6)' ('day.6')'),47," ")||"  |"
report = report NL||' |  Sunday         |  'left((copies('*',block.7)' ('day.7')'),47," ")||"  |"
report = report NL||tablebar

header_title = '      | Echomail Daily Usage Graph (T:'usedmessages') |'

header =        NL||'      +'||right(blank,(length(header_title)-8),"-")||'+'
header = header||NL||header_title
header = header||NL' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,(71-length(header_title)),"-")||'+'

end

return header||report
/*!!*/

/*!*/sort_timestat: 

if userlist.0 ~= 0 then 
do

largest_time=0

do idx=0 to 22 by 2
   if time.idx>=largest_time then largest_time=time.idx
end

block=largest_time/40

do idx=0 to 22 by 2
   time.idx.idx=time.idx/block
end

do idx=0 to 22 by 2
   if index(time.idx.idx,'.')~=0 then do
      if substr(time.idx.idx,(index(time.idx.idx,'.'))+1,1)>=5 then do
         time.idx.idx=time.idx.idx+1
         time.idx.idx=delstr(time.idx.idx, index(time.idx.idx, '.'))
      end
     else do
         time.idx.idx=delstr(time.idx.idx, index(time.idx.idx,'.'))
     end
   end
end

report =        NL||' |   0:00 -  1:59  |  'left((copies('*',time.0.0)' ('time.0')'),47," ")'  |'
report = report NL||' |   2:00 -  3:59  |  'left((copies('*',time.2.2)' ('time.2')'),47," ")'  |'
report = report NL||' |   4:00 -  5:59  |  'left((copies('*',time.4.4)' ('time.4')'),47," ")'  |'
report = report NL||' |   6:00 -  7:59  |  'left((copies('*',time.6.6)' ('time.6')'),47," ")'  |'
report = report NL||' |   8:00 -  9:59  |  'left((copies('*',time.8.8)' ('time.8')'),47," ")'  |'
report = report NL||' |  10:00 - 11:59  |  'left((copies('*',time.10.10)' ('time.10')'),47," ")'  |'
report = report NL||' |  12:00 - 13:59  |  'left((copies('*',time.12.12)' ('time.12')'),47," ")'  |'
report = report NL||' |  14:00 - 15:59  |  'left((copies('*',time.14.14)' ('time.14')'),47," ")'  |'
report = report NL||' |  16:00 - 17:59  |  'left((copies('*',time.16.16)' ('time.16')'),47," ")'  |'
report = report NL||' |  18:00 - 19:59  |  'left((copies('*',time.18.18)' ('time.18')'),47," ")'  |'
report = report NL||' |  20:00 - 21:59  |  'left((copies('*',time.20.20)' ('time.20')'),47," ")'  |'
report = report NL||' |  22:00 - 23:59  |  'left((copies('*',time.22.22)' ('time.22')'),47," ")'  |'
report = report NL||tablebar

header_title = '      | Echomail Time Usage Graph (T:'usedmessages') |'

header =        NL||'      +'||right(blank,(length(header_title)-8),"-")||'+'
header = header||NL||header_title
header = header||NL' +----+'||right(blank,(length(header_title)-8),"-")||'+'||right(blank,(71-length(header_title)),"-")||'+'

end

return header||report
/*!!*/

/*!*/parse_CLI:

do option=1 to words(commandline)

    if upper(word(commandline,option)) = "SUPPRESS" then suppress=1
    if upper(word(commandline,option)) = "SAVE" then 
      do
         sizequote=upper(word(commandline,(option+1)))
         option=option+1
      end
    if upper(word(commandline,option)) = "DATE" then
      do
         datelen = upper(word(commandline,(option+1)))
         if datelen = "ALL" then datelen = 0
         option=option+1
      end
    if upper(word(commandline,option)) = "FLAGS" then
      do
         stuff=upper(word(commandline,(option+1)))
         option=option+1
         
         if pos("W",stuff)~=0 then writers="YES"
         if pos("R",stuff)~=0 then receivers="YES"
         if pos("Q",stuff)~=0 then quoters="YES"
         if pos("S",stuff)~=0 then subjects="YES"
         if pos("T",stuff)~=0 then tearlines="YES"
         if pos("N",stuff)~=0 then nodes="YES"
         if pos("H",stuff)~=0 then timestat="YES"
         if pos("D",stuff)~=0 then daystat="YES"
      end
    if upper(word(commandline,option)) = "JOINT" then 
        do
            parameter = upper(word(commandline,(option+1)))
            option=option+1
            
            main_result=0
            jointpost=1
            jointpostarea=parameter
        end
            
    if upper(word(commandline,option)) = "MULTIPLE" then main_result=3
    if upper(word(commandline,option)) = "STAT" then 
       do 
          parameter=upper(word(commandline,(option+1)))
          option=option+1
         
          main_result=2
          'gotoarea 'parameter
      end
    if upper(word(commandline,option)) = "TABLE" then
      do
         tablelen=upper(word(commandline,(option+1)))
         option=option+1
      end       
end

return

/*!*/traplist_info:

parse arg nodenumber

system = findnode(nodenumber,'System')
parse var system success" " systemname

if success ~= 1 then systemname = '?'

return systemname
/*!!*/

/*!*/ node:

parse arg pointnumber

parse var pointnumber zone":"net"/"boss"."point

nodenumber = zone":"net"/"boss".0"

return nodenumber

/*!!*/

/*!*/writelog: 

if ~exists(logpath||log_file) then call open(log,logpath||log_file,"w")

    else call open(log,logpath||log_file,"a")

    
if datelen ~= 0 then period = "Period : "date(n,startdate,i)||" - "||date(n, enddate,i)
 else period = "All Messages"

call writeln(log,date(w)||" "||date()":")

arealist=''
if MA ~= 0 & main_result = 0 then
   do
      do loopytypething=1 to MA
        call writeln(log,time()||" Produced stats for "multiarea.loopytypething)                   
      end
   end   
else call writeln(log,time()||" Produced stats for "area)
call writeln(log,time()||" "||period ": "usedmessages" messages processed in total.")
call writeln(log,time()||" Flags: "log_flags)
call writeln(log,time()||" Time Taken : "endtime)

if error_report1 ~= 'ERROR_REPORT1' then
     call writeln(log,time()||" Error: "error_report1)
if error_report2 ~= 'ERROR_REPORT2' then
     call writeln(log,time()||" Error: "error_report2)   
call writeln(log,"")
call close(log)

return
/*!!*/

/*!*/messagelog:

call delete(temp_file)
call open(mlog,temp_file,W)

Call Writeln(mlog,"Log for MegaStat output..."NL)
call writeln(mlog,"*Produced* : "date()||" "time())

call writeln(mlog,"")

if main_result = 0 then
do
   call writeln(mlog,"*Joint* *Area* *stat* *produced* *for* :")
   do jointareas=1 to MA
      call writeln(mlog,"                    "||multiarea.jointareas)
   end
end

else call writeln(mlog,"*Stats* *produced* *for* : "area)
    
call writeln(mlog,"")
if datelen ~= 0 then periodcovered = date(n,startdate,i)||" - "||date(n,enddate,i)
else periodcovered = "All Messages"

call writeln(mlog,"*Period* : "periodcovered" - /"usedmessages"/ processed in total")

call Writeln(mlog,NL||"*_Tables_* *_Used_* :")

if pos("W",log_flags)~=0 then call writeln(mlog,"             /Writers/")
if pos("R",log_flags)~=0 then call writeln(mlog,"             /Receivers/")
if pos("Q",log_flags)~=0 then call writeln(mlog,"             /Quote/ /Blacklist/")
if pos("S",log_flags)~=0 then call writeln(mlog,"             /Subjects/")
if pos("N",log_flags)~=0 then call writeln(mlog,"             /Node/ /Traffic/")
if pos("T",log_flags)~=0 then call writeln(mlog,"             /Tearlines/")
if pos("H",log_flags)~=0 then call writeln(mlog,"             /Time/ /Usage/ /Graph/")
if pos("D",log_flags)~=0 then call writeln(mlog,"             /Daily/ /Usage/ /Graph/")
   
call writeln(mlog,"")  
   
if error_report1 ~= 'ERROR_REPORT1' then
     call writeln(mlog," /*Error*/ /*accounted*/ : "error_report1)
if error_report2 ~= 'ERROR_REPORT2' then
     call writeln(mlog," /*Error*/ /*accounted*/ : "error_report2)   

call writeln(mlog,NL||"*Time* *Taken* : "endtime" seconds")

call writeln(mlog,NL||" <---------- *END* *OF* *REPORT* ---------->")

call close(mlog)

/* Write the file into the message area selected */

'gotoarea 'logecho
if rc=2 then 
do 
   'requestnotify TITLE "'error'" CENTER PROMPT "This echo for your log message cannot be found"'
end
else
   do
      'write TO "'sysname'" FROM "MegaStat" SUBJECT "MegaStat Log" ORIGIN "Log produced by MegaStat 'version' (c) Paul Nuzzo" FILE "'temp_file'" NOSIG NOEDIT NOGUI'
      'lastmessage'
      'markmessage CLEAR'
      'markmessage TOGGLE'
      'clearflags EXPORT'
      'excludeflag ALL'
      'arealist'
   end

return
/*!!*/

/*!*/P_Entries:
'requeststring Title "'tbar'" Center Prompt "When compiling the tables, please tell me how many entries you'||CR||'would like to use.'||CR||'i.e. Top 10, Top 20, Top 100!'||CR||'Type 0 to have unlimited table sizes'||CR||'Type SKIP to be asked this question each  time you run MegaStat."'
    if rc ~= 0 then
       do
          call close(cfg)
          call delete(config)
          call cleanup
       end
    tablelen  = result
/*!!*/Return
/*!*/P_Sizequote:
'requestresponse Title "'tbar'" Center Prompt "Please select whether you want the Quote Ratio'CR'and Average Message Size displayed in the tables.'CR||CR||'Selecting NO produces much quicker results as MegaStat will not'||CR||'have to save out every message in the area.'CR'(Please see the docs for more info on this.)'CR'As usual, selecting SKIP will make this question be asked every time." GADGETS "_Yes|_No'skip'"'
   select
        when rc = 0 then sizequote = "SKIP"
        when rc = (1 - skipnumber) then sizequote = "YES"
        when rc = (2 - skipnumber) then sizequote = "NO"
   end
return
/*!!*/
/*!*/P_Logs:
'requestresponse TITLE "'tbar'" CENTER PROMPT "Would you like a log kept as a file or as a message (in a keep area)" GADGETS "Log _File|Log _Message|_Both|_Neither"'
    select
         when rc = 0 then
            do
               logpath = "NO"
               logecho = "NO"
            end
         when rc = 1 then
            do
                'requestpath TITLE "Log file path..."' PATH "mail:"
                if rc ~= 0 then
                   do
                      call close(cfg)
                      call delete(config)
                      call cleanup
                   end
                logpath = result
                logecho = "NO"
            end
         when rc = 2 then
            do
                'requestarea TITLE "Area for log message.."'
                if rc ~= 0 then
                   do
                      call close(cfg)
                      call delete(config)
                      call cleanup
                   end
                logecho = result
                logpath = "NO"
            end
         when rc = 3 then
            do
                'requestpath TITLE "Log file path..."' PATH "mail:"
                if rc ~= 0 then
                   do
                      call close(cfg)
                      call delete(config)
                      call cleanup
                   end
                logpath = result
                'requestarea TITLE "Area for log message"'
                if rc ~= 0 then
                   do
                      call close(cfg)
                      call delete(config)
                      call cleanup
                   end
                logecho = result
            end
    end
return
/*!!*/
/*!*/P_Dates:
'requestresponse Title "'tbar'" Center Prompt "How far back would you like the script to scan messages?'||CR||'Press SKIP to be asked each time." GADGETS "'skip2'_One Week|_Fortnight|_Month|_All Messages"'
    if skip ~= '' then
       do
          select 
              when rc = 2 then datelen = 'WEEK'
              when rc = 3 then datelen = 'FORTNIGHT'
              when rc = 4 then datelen = 'MONTH'
              when rc = 1 then datelen = 'SKIP'
              otherwise datelen = rc     
          end
       end   
       
    else select 
             when rc = 2 then datelen = 'WEEK'
             when rc = 3 then datelen = 'FORTNIGHT'
             when rc = 4 then datelen = 'MONTH'
             when rc = 1 then 
                 do
                    datelen = 'DATES'
      
                    'requeststring TITLE "'tbar'" CENTER PROMPT "Please enter the start date from which you wish to scan.'CR'(In the format DD.MM.YYYY, e.g. 12.09.1995)"'
                     startdate = result
        
                     parse var startdate startday"."startmonth"."startyear
                     if startyear<1978 then startyear = 1978
                     startdate=startyear||startmonth||startday
                     startdate=date(i,startdate,s) /* In internal arexx date format */
          
                     'requeststring TITLE "'tbar'" CENTER PROMPT "Please enter the end date from which you wish to scan.'CR'(In the format DD.MM.YYYY, e.g. 12.09.1995)"'
                     enddate = result
      
                      parse var enddate endday"."endmonth"."endyear
                     if endyear<1978 then endyear = 1978
                     enddate=endyear||endmonth||endday
                     enddate=date(i,enddate,s) /* In internal arexx date format */

                 end 
             
             
             otherwise datelen = rc
          end 
     
Return
/*!!*/
/*!*/P_Receivers:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a table of Receivers?" Gadgets "_Yes|_No'skip'"'
   select
        when rc = 0 then receivers = "SKIP"
        when rc = (1 - skipnumber) then receivers = "YES"
        when rc = (2 - skipnumber) then receivers = "NO"
   end
Return
/*!!*/
/*!*/P_Writers:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a table of Writers?" Gadgets "_Yes|_No'skip'"'
   select
        when rc = 0 then writers = "SKIP"
        when rc = (1 - skipnumber) then writers = "YES"
        when rc = (2 - skipnumber) then writers = "NO"
   end
Return
/*!!*/
/*!*/P_Subjects:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a table of Subjects?" Gadgets "_Yes|_No'skip'"'
    select
        when rc = 0 then subjects = "SKIP"
        when rc = (1 - skipnumber) then subjects = "YES"
        when rc = (2 - skipnumber) then subjects = "NO"
    end
Return
/*!!*/
/*!*/P_Tearlines:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a table of Tearlines?" Gadgets "_Yes|_No'skip'"'
    select
        when rc = 0 then tearlines = "SKIP"
        when rc = (1 - skipnumber) then tearlines = "YES"
        when rc = (2 - skipnumber) then tearlines = "NO"
   end
Return
/*!!*/
/*!*/P_OrigNodes:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a table of Originating Nodes?" Gadgets "_Yes|_No'skip'"'
    select
        when rc = 0 then nodes = "SKIP"
        when rc = (1 - skipnumber) then nodes = "YES"
        when rc = (2 - skipnumber) then nodes = "NO"
   end
Return
/*!!*/
/*!*/P_Quoters:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a table of Worst Quoters?" Gadgets "_Yes|_No'skip'"'
    select
        when rc = 0 then quoters = "SKIP"
        when rc = (1 - skipnumber) then quoters = "YES"
        when rc = (2 - skipnumber) then quoters = "NO"
   end
Return
/*!!*/
/*!*/P_Days:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a graph of daily usage statistics?" Gadgets "_Yes|_No'skip'"'
    select
        when rc = 0 then daystat = "SKIP"
        when rc = (1 - skipnumber) then daystat = "YES"
        when rc = (2 - skipnumber)  then daystat = "NO"
   end
Return
/*!!*/
/*!*/P_Times:
'requestresponse Title "'tbar'" Center Prompt "Would you like to create a graph of time usage statistics?" Gadgets "_Yes|_No'skip'"'
    select
        when rc = 0 then timestat = "SKIP"
        when rc = (1 - skipnumber) then timestat = "YES"
        when rc = (2 - skipnumber) then timestat = "NO"
   end
Return
/*!!*/
/*!*/P_Areas:
'Requestnotify TITLE "'tbar'" CENTER PROMPT "If you create stats for specific echos, that you would'CR'like to create when you run this script you can select them here.'CR'It is possible to select more than one echo to create stats for'CR'- press cancel if you don''t need this feature or have'||CR||'finished selecting echos"'

counter = 0

do until rc ~= 0
   'Requestarea TITLE "Multiple area no. 'counter+1'"'
    counter = counter + 1
    area.counter = result
end 

counter = counter - 1

Return counter
/*!!*/
/*!*/P_Multiareas:
'Requestnotify TITLE "'tbar'" CENTER PROMPT "MegaStat will allow you to make a joint stat of multiple echos,'CR'treating each echo as a whole. (See docs for more detail).'CR||CR'Select the echos you would like to treat as one echo,'CR'pressing cancel if you don''t need this feature or have'||CR||'finished selecting echos"'

counter = 0

do until rc ~= 0
   'Requestarea TITLE "Joint area no. 'counter+1'"'
    counter = counter + 1
    multiarea.counter = result
end 

counter = counter - 1

return counter
/*!!*/
/*!*/write_message_text:

call open(mess,output_file,"w")
          
call writeln(mess,write_header())          
          
if writers   = "YES" then 
   do
      call writeln(mess, sort_writers())         
      log_flags = "W"
   end
   else log_flags = "-"      
   if receivers = "YES" then 
      do
         call writeln(mess, sort_receivers())
         log_flags = log_flags||"R"
      end
   else log_flags = log_flags||"-"        
   if quoters   = "YES" then 
      do
         report = sort_quoters_blacklist()
         if report = "error" then error_report1 = "Quote Blacklist Table - Quote Ratios and Msg Size wasn't selected"
         else call writeln(mess, report)
         log_flags = log_flags||"Q"
      end
   else log_flags = log_flags||"-"        
   if subjects  = "YES" then 
      do
         call writeln(mess,sort_subjects())        
         log_flags = log_flags||"S"
      end
   else log_flags = log_flags||"-"       
   if nodes     = "YES" then 
      do
         call writeln(mess, sort_node_traffic())      
         log_flags = log_flags||"N"
      end
   else log_flags = log_flags||"-"    
   if tearlines = "YES" then 
      do
         report = sort_tearlines()
         if report = "error" then error_report2 = "Tearline Table - Quote Ratios and Msg Size wasn't selected"
         else call writeln(mess, report)
         log_flags = log_flags||"T" 
      end
   else log_flags = log_flags||"-"         
   if timestat  = "YES" then 
      do
         call writeln(mess,sort_timestat())        
         log_flags = log_flags||"H"
      end
   else log_flags = log_flags||"-"        
   if daystat   = "YES" then 
      do
         call writeln(mess,sort_daystat())           
         log_flags = log_flags||"D"
      end
   else log_flags = log_flags||"-"   

call close(mess)

return
/*!!*/
/*!*/namecase:

parse arg name

/* Section of code to put in lower case, and then capitalise each name */
num_words = words(name)
drop name.
namecased = ''
do numberwords=1 to num_words
   name.numberwords = left(word(name,numberwords),1)||translate(delstr(word(name,numberwords),1,1), xrange('a','z'), xrange('A', 'Z'))
   namecased = namecased||name.numberwords||" "                  	
end

return namecased
/*!!*/
/*!*/cleanup:

call delete(output_file)
call delete(temp_file)
'unlockgui'

if quit = 'YES' then 'quitspot NOREQ'
if icon = 'YES' then 'iconify NOREQ'

exit

return
/*!!*/