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

   SCHEDULER PROGRAM FOR FOOTBALL REXX SUITE
  -------------------------------------------
                   Copyright  Mark Naughton 1996


Version    Date     History
--------------------------------------------------------------------------
 1.0       090996   First release.
           180996   Changed record-count so that it is stored in element
                    zero of each array. Deleted some variable assigns
                    that weren't needed. Amended reading into arrays so
                    that the count is set correctly for one element.
                    Removed all "call "references before library routines.
           270996   Added code to sort 'Teams.df' and to recreate it.
                    Changed a few messages and tidied up.
           ******   Decided not to store goalscorers. Was not viable as
                    too much data would have to be collected.
           270996   Added code for points_per_draw and points_per_loss.
                    Now uses DOS Delete command, not the support function.
                    Amended reading in of teams - quicker, tidier. Added
                    code to display a report on the league. Updated to
                    use new filenames. Improved error messages. Added
                    error check for more than 1000 matches.
 1.1       131196   Added argument so it can become a component of
                    FOOTBALL. Removed all messages. Added checks for
                    files - if not found, exits without a message.
                    Rewrote report.
           201196   Added code to store relegation. All this will do is
                    display a line across the league table. Amended msg
                    for play_each_other. Added code to allow teams to
                    play each other more than twice.
           201196   Decided not to implement PreviousPosition as it would
                    require file changes and a reformat of the league
                    table. It may be implemented soon though.
           211196   Updated and tidied the display.
           201296   Fixed bug where if the number of times that each team
                    play each other is an even number, then its not set
                    to the correct value (only works for odd matches).
           110197   Blanks are now removed from the filename, before
                    creation.
 1.2       110497   Added code to support Points_Per_Goals.
 2.0       010997   Have been working on Scheduling for about a week. Put
                    in code and now ready to test.
           030997   Problem with format of '.sf' file - fixed. Program
                    failed due to missing 'do' - fixed. All works.
           050997   Added extra '*' at end of '.sf' file in line with
                    manual created one.
           070997   Fixed bug for AUTOSCHED - no. of matches in report was
                    wrong - needed to be reset before the loop.
           220997   Added code for promotion and divisions.
           240997   Removed all data such as teams count, points per win,
                    relegation etc, as they are already stored in '.df'.
           250997   Wasn't creating the files - traced to resetting the
                    strings that were used to pick the number of divisions
                    and the divisions themselves, to the variables that
                    are used as the assignments/counters. Made amendments
                    to display of the report.
           151297   Tidied display.
           240898   Amended code that regenerates .df file as it was
                    adding two blank lines before the teams and causing
                    it to fail.

**************************************************************************

Procedure
---------

1. Check files exist.
2. Read 'Teams.df' and write teams to output file.
3. If AutoSched is specified then store parameters.
4. Using external program, sort the teams.
5. Re-read the teams and recreate 'Teams.df'.
6. Open 'Teams.df' for reading.
7. Extract data and store.
8. If no separator in it, then take it as a
   team. Strip blanks and store.
9. Close input file.
10.IF AUTOMATIC - Read specified schedule file.
11.Read schedules and store dates/weeks.
12.Give error if the number of teams does not equal
   the number of lines in the schedule file.
13.Write the dates/weeks to a file then use an
   external program to sort them, writing back to the file.
14.Read dates into array and delete file.
15.Format dates array with season start date.
16.Format and write '.sf' files.
17.IF MANUAL - Open 'Teams.sf' file.
18.Write league name to it.
19.Loop and write all teams with a schedule of
   all other teams. Number of matches is stored.
20.Close output file.
21.Open 'Teams.stats' for writing.
22.Write all data such as PLAYED,WIN,DRAW,LOST,GOALS_FOR,GOALS_AGAINST and
   POINTS for each team.
23.Close file, create a report on the league created and then exit.

************************************************************************** */
PARSE ARG league_file

version      = 2
league_file  = "Data/" || strip(league_file)
input_file   = '.df'
output_file  = '.sf'
output2_file = '.stats'
output3_file = '.temp'
title        = '*LEAGUE_NAME='
points_win   = '*POINTS_PER_WIN='
points_drw   = '*POINTS_PER_DRW='
points_lse   = '*POINTS_PER_LSE='
points_gls   = '*POINTS_PER_GLS='
releg        = '*RELEGATION='
playother    = '*PLAY_OTHER='
promoted     = '*PROMOTED='
num_divs     = '*NUM_DIVISIONS='
divisions    = '*DIVISIONS='
pkauthor     = '*  Author ='
pkversion    = '*  Version='
separator    = '*'
teams.       = '???'
tcount       = 0
ttc          = 0
ptsgls       = 0
input2_file  = '.schd'
separator    = '*'
not_played   = '__   __'
dateweeks.   = '???'
tdateweeks.  = '???'
schedules.   = '???'
months       = "January February March April May June July August September October November December"
autosched    = "*AUTOSCHD="
autos        = 0
ndivs        = 0
promo        = 0
divs         = ''


if exists(league_file || input_file) = 0 then exit

tcount = 0
if open(datafile,league_file || input_file,'r') then do
   if open(datafile2,league_file || output3_file,'w') then do
      do while ~eof(datafile)
         line = readln(datafile)
         line = strip(line)
         if pos(separator,line) > 0 & line ~='' then do
            if pos(autosched,line) > 0 then do
               autofile = delstr(line,1,10)
               autos = 1
            end
            tcount = tcount + 1
            teams.tcount = line
         end
         else do
            ttc = ttc + 1
            writeln(datafile2,line)
         end
      end
      close(datafile2)
   end
   else do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Cannot write to '"league_file||output3_file"'."
      close(datafile)
      exit
   end
   close(datafile)
end
else do
   say
   say "ERROR :    (Scheduler)"
   say
   say "Cannot open '"league_file || input_file"' for reading/sorting."
   exit
end

address command 'sort 'league_file || output3_file league_file || output3_file

if open(datafile2,league_file || output3_file,'r') then do
   if open(datafile,league_file || input_file,'w') then do
      do i=1 to tcount
         if teams.i ~= '' then
            writeln(datafile,teams.i)
      end
      do j=1 to ttc                   /* while ~eof(datafile2)  */
         line = readln(datafile2)
         line = strip(line)
         if line ~= '' then do
            if j = ttc then
               writech(datafile,line)
            else
               writeln(datafile,line)
         end
      end
      close(datafile)
   end
   else do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Cannot write to '"league_file||input_file"'."
      close(datafile2)
      exit
   end
   close(datafile2)
end
else do
   say
   say "ERROR :    (Scheduler)"
   say
   say "Cannot open '"league_file || output3_file"' for reading/sorting."
   exit
end

address command 'delete >NIL: 'league_file || output3_file

tcount = 0
if open(datafile,league_file || input_file,'r') then do
   do while ~eof(datafile)
      line = readln(datafile)
      if pos(title,line) > 0 then        league_title = delstr(line,1,13)
      if pos(pkauthor,line) > 0 then     author = delstr(line,1,12)
      if pos(pkversion,line) > 0 then    fversion = delstr(line,1,12)
      if pos(points_win,line) > 0 then   ptswin=delstr(line,1,16)
      if pos(points_drw,line) > 0 then   ptsdrw=delstr(line,1,16)
      if pos(points_lse,line) > 0 then   ptslse=delstr(line,1,16)
      if pos(points_gls,line) > 0 then   ptsgls=delstr(line,1,16)
      if pos(releg,line) > 0 then        reg = delstr(line,1,12)
      if pos(playother,line) > 0 then    playo = delstr(line,1,12)
      if pos(promoted,line) > 0 then     promo = delstr(line,1,10)
      if pos(num_divs,line) > 0 then     ndivs = delstr(line,1,15)
      if pos(divisions,line) > 0 then    divs  = delstr(line,1,11)
      if pos(separator,line) = 0 then do
         line = strip(line)
         tcount       = tcount + 1
         teams.tcount = line
      end
   end
   close(datafile)
end
else do
   say
   say "ERROR :    (Scheduler)"
   say
   say "Unable to open '"league_file || input_file"' file."
   exit
end

if ndivs > 1 then do
   if words(divs)+1 ~= ndivs then do
      say
      say "ERROR :"
      say
      say "The number of divisions specified does not match the"
      say "number selected. The number of divisions specified"
      say "must include the ones selected BUT also, the one that"
      say "you are creating. ie, Three divisions specified, so you"
      say "change the number of divisions to FOUR."
      say
      say "In this league that you have tried to create, you have specified"
      say "words(divs)" leagues but the number was set to "ndivs"."
      say "The number should have been '"words(divs)+1"' leagues."
      say
      say "Schedule creation aborted."
      exit
   end

   fd = 0
   do i=1 to ndivs-1
      if exists("Data/"||word(divs,i)||input_file) = 0 then do
         if fd = 0 then do
            say
            say "ERROR :    (Scheduler)"
            say
         end
         say "League '"word(divs,i)"' does not exist."
         fd = fd + 1
      end
   end
   if fd > 0 then
      exit
end

                                          /* Automatic Schedule creation */
if autos = 1 then do
   if exists("Data/"autofile||input2_file) = 0 then do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Cannot find 'Data/"autofile||input2_file"'."
      exit
   end

   ct = 0
   sct= 0
   weeks = 0
   dates = 0

   if open(datafile,"Data/"autofile||input2_file,'r') then do
      do while ~eof(datafile)
         line = readln(datafile)
         if pos("*WEEKS",line) then do
            weeks=1
         end
         if pos("*DATES=",line) then do
            startdate=substr(line,8,8)
            dates = 1
         end
         if line ~= '' & pos(separator,line) = 0 then do
            sct = sct + 1
            schedules.sct = line
            counter = words(line)
            do i=1 to counter
               sdate = word(line,i)
               if sdate = 0 then
                  iterate
               if ct = 0 then do
                  ct = ct + 1
                  dateweeks.ct = sdate
               end
               else do
                  ij = 0
                  do j=1 to ct
                     if sdate = dateweeks.j then do
                        ij = 1
                        leave
                     end
                  end
                  if ij = 0 then do
                     ct = ct + 1
                     dateweeks.ct = sdate
                  end
               end
            end
         end
      end
      close(datafile)
   end
   else do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Cannot find 'Data/"autofile||input2_file"' for reading."
      exit
   end

   if tcount ~= sct then do
      say
      say "ERROR :    (Scheduler)"
      say
      say "The schedule file specified only has "sct" scheduled"
      say "teams whereas there are "counter" teams in the league."
      say
      say "Creation of files aborted. Re-specify correct schedule."
      say
      exit
   end

   if open(datafile2,"RAM:schd.temp",'w') then do
      do j=1 to ct
         writeln(datafile2,dateweeks.j)
      end
      close(datafile2)
   end
   else do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Cannot create temporary file in RAM:."
      exit
   end

   if weeks = 1 then
      address command 'sort RAM:schd.temp RAM:schd.temp'
   if dates = 1 then
      address command 'Exec/SortWkDts'

   if open(datafile2,"RAM:schd.temp",'r') then do
      do j=1 to ct
         dateweeks.j = readln(datafile2)
      end
      close(datafile2)
   end
   else do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Cannot find temporary file in RAM:."
      exit
   end

   address command 'delete >NIL: RAM:schd.temp'

   if dates = 1 then do
      do j=1 to ct
         if dateweeks.j = startdate then do
            say j-1
            do i=1 to j-1
               tdateweeks.i = dateweeks.i
            end
            k = 1
            do i=j to ct
               dateweeks.k = dateweeks.i
               k = k + 1
            end
            do i=1 to j-1
               dateweeks.k = tdateweeks.i
               k = k + 1
            end
            leave
         end
      end
   end

   if open(outfile,league_file || output_file,"w") then do
      writeln(outfile,"*")
      writeln(outfile,"**" league_title)
      writeln(outfile,"*")
      writeln(outfile,"*")

      matches = 0
      do i=1 to ct
         if weeks = 1 then
            writeln(outfile,"*Week: "dateweeks.i)
         if dates = 1 then do
            mnth = substr(dateweeks.i,3,2)
            ndate= substr(dateweeks.i,5,4)||mnth||substr(dateweeks.i,1,2)
            weekd= date('w',ndate,'s')
            writeln(outfile,"*Date: "weekd" "substr(dateweeks.i,1,2)" "word(months,mnth)" "substr(dateweeks.i,5,4))
         end
         writeln(outfile,"*")
         do k=1 to counter
            do j=1 to counter
               sdate = word(schedules.k,j)
               if dateweeks.i = sdate then do
                  writech(outfile,left(teams.k,30))
                  writeln(outfile," __   __ " teams.j)
                  matches = matches + 1
                  leave
               end
            end
         end
         writeln(outfile,"*")
      end
      writeln(outfile,"*")
      close(outfile)
   end
   else do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Unable to write to '"league_file || output_file"'."
      exit
   end
end
                                          /* Manual Schedule creation */
if autos = 0 then do
   if open(outfile,league_file || output_file,"w") then do
      writeln(outfile,"*")
      writeln(outfile,"**" league_title)
      writeln(outfile,"*")
      writeln(outfile,"*")

      increm = playo / 2
      matches = 0
      do k=1 to increm
         do i=1 to tcount
            do j=1 to tcount
               if j~=i then do
                   writech(outfile,left(teams.i,30))
                   writeln(outfile," __   __ " teams.j)
                   matches = matches + 1
               end
            end
            writeln(outfile,"*")
            if i ~= tcount then
               writeln(outfile,"*")
         end
      end
      writech(outfile,"*")
      close(outfile)
   end
   else do
      say
      say "ERROR :    (Scheduler)"
      say
      say "Unable to write to '"league_file || output_file"'."
      exit
   end
end

if open(outfile,league_file || output2_file,"w") then do
   writeln(outfile,title""league_title)
   do i=1 to tcount
      writeln(outfile,"*TEAM="teams.i)
      writeln(outfile,"*PLY=0")
      writeln(outfile,"*WIN=0")
      writeln(outfile,"*DRW=0")
      writeln(outfile,"*LST=0")
      writeln(outfile,"*GOF=0")
      writeln(outfile,"*GOA=0")
      if i = tcount then
         writech(outfile,"*PTS=0")
      else
         writeln(outfile,"*PTS=0")
   end
   close(outfile)
end
else do
   say
   say "ERROR :    (Scheduler)"
   say
   say "Cannot create '"league_file || output2_file"'."
   exit
end
                                         /* create report */
select
   when playo = 2 then playo = 'Twice'
   otherwise
      playo = playo || ' times.'
end

say
say center("Report for '"league_title"'",78)
say "-------------------------------------------------------------------------------"
say "                                               Created "date('e')" at "time()
say
say "Author : "author
say "Version: "fversion
say "_______________________________________________________________________________"
say
say "Number of teams   : "tcount"                  Number of matches : "matches
say
say "Win   : "ptswin" pts.            Teams Relegated : "reg
say "Draw  : "ptsdrw" pts.            Play Each Team  : "playo
say "Lose  : "ptslse" pts.            Points Per Goals: "ptsgls
say "                          Teams Promoted  : "promo
say
say "Number of Divisions : "ndivs"   (including this league)"
say "Other Divisions     : "divs
say
if autos = 1 then do
   say "Automatic Schedule created from '"autofile||input2_file"'."
   say
end
/*
if matches > 999 then
   say "*   The number of matches exceeds 1000. 'Sortsched' can't handle it!!    *"
*/
say "_______________________________________________________________________________"
say
say "Team Listing: "
say "-------------"
say
do i=1 to tcount
   say teams.i
end
say
say "-------------------------------------------------------------------------------"
say

exit