!------------------------------------------------------------------------------
!  Written by:   Tim Hunter in January, 2016
!                based off NbsForCGLRRM.f95
!
!  Purpose:
!     Reads the DLYTBL* files that were archived as part of an AHPS run.
!     Writes out the nbs data files required for running the Coordinated
!     Great Lakes Routing and Regulation Model (CGLRRM).
!     This is a special single-purpose version intended for use by Lauren Fry
!     at USACE-Detroit on the NYPA-OPG project.
!
!  Notes:
!     I have simplified the program from the original NbsForCGLRRM version.
!     That version was built to handle setup, historical, and forecast runs,
!     and it pulled info (dates, mode) from BSNNM and START.LEV.
!     In this version I am assuming it is for forecast data and that the 
!     DLYTBL????.xxx files are in the current folder.
!     I also assume that the DLYTBL files start on the first of the month,
!     since that was the procedure for the NYPA-OPG project. Thus, I don't
!     need to worry about backfilling to the start of the month, etc.
!     I can just use the data in DLYTBL to compute and output NBS. 
!     More than anything, this is a format conversion tool to convert the
!     binary AHPS output into text files useable by CGLRRM.
!
!  Also note the definition of a quarter-month as extracted from the CGLRRM manual:
!    In February, the four quarter months are evenly spaced (seven days each (1-7, 
!    8-14, 15-21, 22-28); fourth quarter has eight days in leap years, though (22-29)).  
!    For all other months, the first quarter is eight days (1-8), the second quarter 
!    is seven (9-15), the third quarter is eight days (16-23), and the forth quarter 
!    is seven or eight days (24-30 or 31).
!
!------------------------------------------------------------------------------


MODULE Dlytbl_CGLRRM_Subs

   USE FcstUtil

   INTEGER, PARAMETER :: DAYS     = 20000
   INTEGER, PARAMETER :: OtlkDays = 20000
   INTEGER, PARAMETER :: MaxScen  = 75
   INTEGER, PARAMETER :: MAXYRS   = 150

   LOGICAL :: TCFS, CMS

   !
   ! The DlyOtlk(:,:) array contains daily NBS values for the outlook period
   ! (i.e. from SOtlkData to EOtlkData). Units are TCFS. 
   !
   REAL, DIMENSION(OtlkDays,MaxScen) :: DlyOtlk

CONTAINS

!-----------------------------------------------------------------------
!  Read daily data from DLYTBL????.INT files and store it in DlyOtlk array
!  which has indices (Day_of_forecast, Scenario_number).  
!
!  SSeq and ESeq will be assigned with information derived from the files.
!-----------------------------------------------------------------------
      SUBROUTINE GetDailyOtlkNBS(LkNumIn, SSeq, ESeq, Scenarios)
      IMPLICIT   NONE

      INTEGER,               INTENT(IN)    :: LkNumIn
      INTEGER,               INTENT(OUT)   :: SSeq, ESeq
      INTEGER, DIMENSION(:), INTENT(INOUT) :: Scenarios

      INTEGER :: I, J, K, K2, LkNum, Lk, Lk1, Lk2, Year
      INTEGER :: ScenCount, Dy, Mn, Yr, Seq1, Seq2, U11
      INTEGER :: TScenarios(3, MaxScen), TScenCount(3), IOS

      LOGICAL :: Found, MakeMissing

      REAL :: R(DAYS,3), P(DAYS,3), E(DAYS,3), PrcArea(3)
      REAL :: LakeArea, LandArea, Land2Lake
      REAL :: PW, RW, EW, Prc, Run, Evp, NBScm

      CHARACTER (LEN=3)   :: Bsn
      CHARACTER (LEN=4)   :: YrNum
      CHARACTER (LEN=8)   :: Skip8
      CHARACTER (LEN=15)  :: FileName, S
      CHARACTER (LEN=99)  :: File11
      CHARACTER (LEN=115) :: Cmnd

      
!
!  Initial values of SSeq and ESeq that are unreasonable and will
!  be overwritten.
!
      CALL DateSequence(31, 12, 2999, SSeq)
      CALL DateSequence( 1,  1,  999, ESeq)      

!
!  In the main program, there were only 5 valid lake choices:
!    SUP = 1      STC = 3      ONT = 5
!    MHU = 2      ERI = 4
!
!  Convert that numbering to the numbering used here, which includes
!  all 8 possibilities.
!    SUP = 1      STC = 5
!    MIC = 2      ERI = 6
!    HUR = 3      ONT = 7
!    GEO = 4      MHU = 8
!
      LkNum = 0
      IF (LkNumIn .EQ. 1) LkNum = 1
      IF (LkNumIn .EQ. 2) LkNum = 8
      IF (LkNumIn .EQ. 3) LkNum = 5
      IF (LkNumIn .EQ. 4) LkNum = 6
      IF (LkNumIn .EQ. 5) LkNum = 7

      IF (LkNum .EQ. 0) THEN
         ErrorMessage = 'Internal error in lake designator (GetDailyOtlkNBS)!'
         CALL PassMsg
         WRITE(ErrorMessage, 9101) 'Lake Number = ', LkNumIn
         CALL PassMsg
      ENDIF

!
!  If we're doing SUP, STC, ERI, or ONT then just do that one basin.  For
!  MHU we will have to do 3 basins and combine them.
!
      IF (LkNum .EQ. 8) THEN
         Lk1 = 2
         Lk2 = 4
      ELSE
         Lk1 = LkNum
         Lk2 = LkNum
      ENDIF

!
!     Generate list of DLYTBL????.xxx files to process.  We will only process
!     those years which are common to all lakes in the list of lakes to
!     process.  In the case of SUP, STC, ERI, ONT this is trivial.  In the case
!     of MHU, though, we have to ensure that the same year is present for all
!     3 lakes.
!
      DO Lk = Lk1, Lk2
        K = Lk-Lk1+1
        Bsn = LakeName3(Lk)
        FileName = 'DLYTBL????.'//Bsn
        Cmnd = 'DIR/b/on '//TRIM(FileName)//' > DLYLIST.TMP'
        CALL SYSTEM(Cmnd)
        
!
!       First, fill arrays TScenarios and TScenCount for each lake.
!       Also make sure we don't exceed the array limits.
!
        I = 0
        TScenCount(K) = 0
        File11 = 'DLYLIST.TMP'
        U11 = GetFreeUnitNumber(); IF (ErrorLevel .NE. 0) GOTO 899
        OPEN(UNIT=U11, FILE=TRIM(File11), STATUS='OLD', ERR=811)
        CALL FileWasOpened(U11); IF (ErrorLevel .NE. 0) GOTO 899
        READ(U11, 5500, IOSTAT=IOS) FileName
        DO WHILE (IOS .EQ. 0)
           S = TRIM(ADJUSTL(FileName))
           YrNum = S(7:10)
           READ(YrNum, '(I4)') Year
           I = I + 1
           IF (I .GT. MaxScen) THEN
              ErrorMessage = 'Too many outlook years available for Dlytbl_CGLRRM!'
              CALL PassMsg
              ErrorMessage = 'Either increase parameter "MaxScen" ..OR..'
              CALL PassMsg
              ErrorMessage = 'reduce the number of outlook years used!'
              CALL PassMsg
              WRITE(ErrorMessage, 9050) I, MaxScen
              CALL PassMsg
              GOTO 898
           ENDIF
           TScenarios(K,I) = Year
           TScenCount(K) = I
           READ(U11, 5500, IOSTAT=IOS) FileName
        ENDDO
        CLOSE(U11, STATUS='DELETE')
        CALL FileWasClosed(U11); IF (ErrorLevel .NE. 0) GOTO 899
      ENDDO

!
!     Second, for each lake, if a year in that lake's list is not 
!     in EVERY lake's list of scenarios, replace it with a 9999 
!     value in this lake's list.
!
      DO Lk = Lk1, Lk2
         K = Lk-Lk1+1
         DO I = 1, TScenCount(K)
            Year = TScenarios(K,I)
            MakeMissing = .FALSE.
            DO J = Lk1, Lk2
               Found = .FALSE.
               DO K2 = 1, TScenCount(J-Lk1+1)
                  IF (TScenarios(J-Lk1+1,K2) .EQ. Year) Found = .TRUE.
               ENDDO
               IF (.NOT. Found) MakeMissing = .TRUE.
            ENDDO
            IF (MakeMissing) TScenarios(K,I) = 9999
         ENDDO
      ENDDO

!
!     Third, sort each lake's list in ascending order.  For simplicity
!     (and because it's such a small set of numbers) we'll use a bubble sort.
!
      DO Lk = Lk1, Lk2
         K = Lk-Lk1+1
         DO I = 1, TScenCount(K)-1
            Year = TScenarios(K,I)
            DO J = I+1, TScenCount(K)
               IF (Year .GT. TScenarios(K,J)) THEN
                  TScenarios(K,I) = TScenarios(K,J)
                  TScenarios(K,J) = Year
                  Year = TScenarios(K,I)
               ENDIF
            ENDDO
         ENDDO
      ENDDO

!
!     Fourth, compact the lists, removing the 9999 entries.  This is
!     accomplished quite easily, since they are all now at the end of
!     the array as a result of the sort we just did.  Just change the
!     TScenCount values.
!
      DO Lk = Lk1, Lk2
         K = Lk-Lk1+1
         I = 1
         DO WHILE (I .LE. TScenCount(K))
            IF (TScenarios(K,I) .GT. 9998) TScenCount(K) = I-1
            I = I + 1
         ENDDO
      ENDDO
      
!
!     As a result of the 4 steps just taken, we now have a compacted
!     list of scenarios which are common to ALL lakes we are processing
!     in this routine (1 or 3 lakes).  We can now continue processing.
!
!     Fill "Scenarios" array.
!
      ScenCount = TScenCount(1)
      DO I = 1, ScenCount
         Scenarios(I) = TScenarios(1,I)
      ENDDO
      DO I = ScenCount+1, MaxScen
         Scenarios(I) = -9999
      ENDDO

!
!     If there were ZERO common outlook years found, then return
!     to main program.  It will be the job of the main program to
!     trap this possible error.
!
      IF (ScenCount .EQ. 0) RETURN

!
!     Now do an initializing read process to determine values of SSeq and ESeq
!
      DO K2 = 1, ScenCount
         Year = Scenarios(K2)
         WRITE(YrNum, '(I4)') Year
         DO Lk = Lk1, Lk2
            K = Lk-Lk1+1
            Bsn = LakeName3(Lk)
            File11 = 'DLYTBL'// YrNum // '.' // Bsn
            U11 = GetFreeUnitNumber(); IF (ErrorLevel .NE. 0) GOTO 899
            OPEN(UNIT=U11, FILE=TRIM(File11), STATUS='OLD', RECL=24,         &
     &           ACCESS='DIRECT', FORM='UNFORMATTED', ERR=811)
            READ(U11, REC=1, ERR=812) Seq1, Seq2
            CLOSE(U11)
            IF (Seq1 .LT. SSeq) SSeq = Seq1
            IF (Seq2 .GT. ESeq) ESeq = Seq2
         END DO
      END DO

!
!     Main loop - read each DLYTBL????.xxx file.  Store data in DlyOtlk array.
!
!     As we read the NBS data, convert it from cm to TCFS to make the 
!     process of combining lake basins easier.  As usual, for 4 of the 5
!     basins (SUP,STC,ERI,ONT) the combining is trivial, but we ARE combining
!     3 basins for MHU.
!
      DO K2 = 1, ScenCount
         Year = Scenarios(K2)
         WRITE(YrNum, '(I4)') Year
         DO I = SSeq, ESeq
            J = I - SSeq + 1
            DlyOtlk(J,K2) = 0.0
         ENDDO
         DO Lk = Lk1, Lk2
            K = Lk-Lk1+1
            LandArea = DigitLandArea(Lk)
            LakeArea = DigitLakeArea(Lk)
            Land2Lake = LandArea / LakeArea   ! to convert land depth to lake depth
            PrcArea(K) = LandArea             ! assume AHPS was run using 'BASN' precip code

            Bsn = LakeName3(Lk)
            File11 = 'DLYTBL'// YrNum // '.' // Bsn
            U11 = GetFreeUnitNumber(); IF (ErrorLevel .NE. 0) GOTO 899
            OPEN(UNIT=U11, FILE=TRIM(File11), STATUS='OLD', RECL=24,    &
     &           ACCESS='DIRECT', FORM='UNFORMATTED', ERR=811)
            READ(U11, REC=1, ERR=812) Seq1, Seq2
            IF (Seq1 .NE. SSeq) THEN
               ErrorMessage = 'Error!! '//TRIM(FileName)//' inconsistent forecast start date'
               CALL PassMsg
               CALL SequenceDate(Dy, Mn, Yr, SSeq); IF (ErrorLevel .NE. 0) GOTO 899
               WRITE(ErrorMessage,2827) 'Required Start Date is (M/D/Y) = ', Mn, Dy, Yr
               CALL PassMsg
               CALL SequenceDate(Dy, Mn, Yr, Seq1); IF (ErrorLevel .NE. 0) GOTO 899
               WRITE(ErrorMessage,2827) TRIM(FileName)//' start date is (M/D/Y) = ', Mn, Dy, Yr
               CALL PassMsg
               GOTO 898
            ENDIF
            DO I = Seq1, Seq2
               J = I - SSeq + 1
               READ(U11, REC=J+1, ERR=812) Skip8, R(J,K), P(J,K), E(J,K)   ! **millimeters**
               R(J,K) = R(J,K) / 10.0                               ! mm -> cm
               P(J,K) = P(J,K) / 10.0                               ! mm -> cm
               E(J,K) = E(J,K) / 10.0                               ! mm -> cm
            ENDDO
            CLOSE(U11)
            CALL FileWasClosed(U11); IF (ErrorLevel .NE. 0) GOTO 899
         END DO

         DO I = SSeq, ESeq 
            J = I - SSeq + 1 
            !
            ! combine basins
            !
            Prc = 0.0
            Run = 0.0
            Evp = 0.0
            NBScm = 0
            DO Lk = Lk1, Lk2   ! first just test for missing data
               K = Lk - Lk1 + 1
               IF (R(J,K) .LT. 0) NBScm = -9999
               IF (P(J,K) .LT. 0) NBScm = -9999
               IF (E(J,K) .LT. -98) NBScm = -9999
            ENDDO
            IF (NBScm .GT. -9998) THEN     ! no missing values -- compute NBS
               PW = 0.0
               RW = 0.0
               EW = 0.0
               DO Lk = Lk1, Lk2
                  K = Lk - Lk1 + 1
                  Prc = Prc + P(J,K)*PrcArea(K)
                  Run = Run + R(J,K)*CoordLakeArea(Lk)
                  Evp = Evp + E(J,K)*CoordLakeArea(Lk)
                  PW = PW + PrcArea(K)
                  RW = RW + CoordLakeArea(Lk)
                  EW = EW + CoordLakeArea(Lk)
               ENDDO
               Prc = Prc / PW            ! weighted overland precip depth
               Run = Run / RW            ! weighted overlake runoff depth
               Evp = Evp / EW            ! weighted overlake evap depth
               NBScm = Run + Prc - Evp
               K = I - SSeq + 1
               DlyOtlk(K,K2) = CM2TCFS(NBScm, CoordLakeArea(LkNum), 86400)
               IF (ErrorLevel .NE. 0) GOTO 899
            ELSE
               K = I - SSeq + 1
               DlyOtlk(K,K2) = -9999.9
            ENDIF
         ENDDO
      ENDDO
      RETURN

!
!  ****** Error conditions ******
!
 811  ErrorMessage = 'Dlytbl_CGLRRM: Error opening ' // TRIM(File11)
      CALL PassMsg; GOTO 898
 812  ErrorMessage = 'Dlytbl_CGLRRM: Error reading ' // TRIM(File11)
      CALL PassMsg; GOTO 898

 898  ErrorLevel = 1
 899  ErrorMessage = '[traceback] : GetDailyOtlkNBS...'
      CALL PassMsg
      RETURN

!
! FORMATs
!
 2827 FORMAT('O:', A, I2,'/',I2,'/',I4)
 5500 FORMAT(A)

 9050 FORMAT(' There were ', I0, ' years available, but MaxScen is only ', I0) 
 9101 FORMAT(A, I0)

      END SUBROUTINE GetDailyOtlkNBS

!----------------------------------------------------------------------
      SUBROUTINE WrtCGLRRM_Otlk_Daily(LkNum, SSeq, ESeq, Scenarios)
      IMPLICIT  NONE
      INTEGER, INTENT(IN) :: LkNum, SSeq, ESeq
      INTEGER, INTENT(IN) :: Scenarios(MaxScen)
      
      INTEGER :: I, J, M1, M2, D1, D2, U11
      INTEGER :: D, M, DM, IOS
      INTEGER :: Year, Mon, Day, Qtr, SNum
      INTEGER :: SYr, EYr, SMn, EMn
      REAL    :: Tmp, TVal
      CHARACTER (LEN=3)  :: Bsn
      CHARACTER (LEN=4)  :: YNum
      CHARACTER (LEN=10) :: Lake
      CHARACTER (LEN=80) :: File11
      REAL, DIMENSION(:,:,:,:), ALLOCATABLE :: OutData          ! (Yr, Mon, Qtr, Day[1:8])

      !
      CALL SequenceDate(Day, SMn, SYr, SSeq); IF (ErrorLevel .NE. 0) GOTO 899
      CALL SequenceDate(Day, EMn, EYr, ESeq); IF (ErrorLevel .NE. 0) GOTO 899

      !
      !  Assign value to Lake variable
      !
      Bsn  = LevLkCode3(LkNum)
      Lake = LevLkName10(LkNum)

      !
      !  main loop
      !
      DO SNum = 1, MaxScen
        IF (Scenarios(SNum) .GT. 0) THEN

           !
           ! Open output file and write header lines
           !
           WRITE(YNum, '(I4)') Scenarios(SNum)
           File11 = TRIM(LevLkCode2(LkNum))//'DNBS_'//YNum//'.txt'
           U11 = GetFreeUnitNumber(); IF (ErrorLevel .NE. 0) GOTO 899
           OPEN(UNIT=U11, FILE=TRIM(File11), STATUS='REPLACE', ERR=811)
           CALL FileWasOpened(U11); IF (ErrorLevel .NE. 0) GOTO 899

           WRITE(U11, 1201, ERR=813) Lake(1:8)
           WRITE(U11, 1202, ERR=813)
           WRITE(U11, 1203, ERR=813) SYr, EYr
           WRITE(U11, 1204, ERR=813)
           WRITE(U11, 1205, ERR=813)
           WRITE(U11, 1206, ERR=813)
           WRITE(U11, 1210, ERR=813)

           !
           !  Assign daily NBS values into the output array
           !
           ALLOCATE(OutData(SYr:EYr, 12, 4, 8), STAT=IOS)
           IF (IOS .NE. 0) THEN
              ErrorMessage = 'Error Allocating RAM'; CALL PassMsg
              GOTO 899
           END IF               
           OutData(:,:,:,:) = -99999.
           
           DO I = SSeq, ESeq
              CALL SequenceDate(Day, Mon, Year, I); IF (ErrorLevel .NE. 0) GOTO 899
              DM  = DaysInMonth(Mon, Year)
              Qtr = QtrMonNumber (Day, Mon, Year)
              D   = DayOfQtrMon(Day, Mon, Year)
              J   = I - SSeq + 1
              TVal = TCFM3(DlyOtlk(J, SNum)) / 10.0        !  convert to tens of cms
              OutData(Year, Mon, Qtr, D) = TVal
           END DO
           
           !
           !  Write the data lines
           !
           DO Year = SYr, EYr
              M1 = 1
              M2 = 12
              IF (Year .EQ. SYr) M1 = SMn
              IF (Year .EQ. EYr) M2 = EMn
              DO M = M1, M2
                DM = DaysInMonth(M, Year)
                DO Qtr = 1, 4
                  D = FirstDayOfQtrMon(DM, Qtr)
                  D1 = 1
                  D2 = LastDayOfQtrMon(DM, Qtr) - D + 1
                  DO D = D1, D2
                     Tmp = OutData(Year,M,Qtr,D) 
                     IF ((Tmp .LT. -999999.) .OR. (Tmp .GT. 9999999.)) THEN
                        WRITE(ErrorMessage, 9001) Year, M, Qtr, D, Tmp
                        CALL PassMsg 
                     END IF
                  END DO
                  WRITE(U11, 1225, ERR=813) Year, M, Qtr, (OutData(Year,M,Qtr,D), D = D1,D2)
                END DO
              END DO
           END DO
           CLOSE(U11)
           CALL FileWasClosed(U11); IF (ErrorLevel .NE. 0) GOTO 899
           DEALLOCATE(OutData, STAT=IOS)
           CLOSE(U11)
           CALL FileWasClosed(U11); IF (ErrorLevel .NE. 0) GOTO 899
        END IF
      END DO

      RETURN

!
!  ****** Error conditions ******
!
 811  ErrorMessage = 'DlyTbl_CGLRRM: Error opening ' // TRIM(File11)
      CALL PassMsg; GOTO 898
 813  ErrorMessage = 'DlyTbl_CGLRRM: Error writing ' // TRIM(File11)
      CALL PassMsg; GOTO 898

 898  ErrorLevel = 1
 899  ErrorMessage = '[traceback] : WrtCGLRRM_Otlk_Daily...'
      CALL PassMsg
      RETURN

!
 1201 FORMAT('# LAKE ', A8, ' DAILY NET BASIN SUPPLIES (CMS*10)')
 1202 FORMAT('#                [e.g. 149 = 1490 cms]')
 1203 FORMAT('# ', I4, ' to ', I4)
 1204 FORMAT('# Fortran format: I5, I3, I2, 12F8.0')
 1205 FORMAT('INTERVAL: Daily')
 1206 FORMAT('UNITS: 10m3s')
 1210 FORMAT('#  YR  M Q       1       2       3       4       5       6       7       8')
 1225 FORMAT(I5, I3, I2, 12F8.0)
 9001 FORMAT(' NBS value out of range for (Y-M-Q-D) ', I4.4,'-',I2.2,'-',I1,'-',I1, ' = ', F0.1) 

      END SUBROUTINE WrtCGLRRM_Otlk_Daily

!----------------------------------------------------------------------
      REAL FUNCTION MM2TCFS(Value, Area, Seconds)
      IMPLICIT  NONE
      INTEGER   Seconds
      REAL      Value, Area, Val

      Val = Value / 1000.              ! mm -> meters
      Val = Val * Area / Seconds       ! meters -> cu meters/sec
      Val = Val * 35.31467 / 1000.     ! M3 -> TCFS
      MM2TCFS = Val

      RETURN
      END FUNCTION MM2TCFS

!----------------------------------------------------------------------
      REAL FUNCTION CM2TCFS(Value, Area, Seconds)
      IMPLICIT  NONE
      INTEGER   Seconds
      REAL      Value, Area, Val

      Val = Value / 100.               ! cm -> meters
      Val = Val * Area / Seconds       ! meters -> cu meters/sec
      Val = Val * 35.31467 / 1000.     ! M3 -> TCFS
      CM2TCFS = Val

      RETURN
      END FUNCTION CM2TCFS

!----------------------------------------------------------------------
      REAL FUNCTION CM2M3(Value, Area, Seconds)
      IMPLICIT  NONE
      INTEGER   Seconds
      REAL      Value, Area, Val

      Val = Value / 100.               ! cm -> meters
      Val = Val * Area / Seconds       ! meters -> cu meters/sec
      CM2M3 = Val

      RETURN
      END FUNCTION CM2M3

!----------------------------------------------------------------------
      REAL FUNCTION TCFM3(Value)
      IMPLICIT  NONE
      REAL      Value, Val

      Val = Value * 1000 / 35.31467     ! TCF -> cubic meters
      TCFM3 = Val

      RETURN
      END FUNCTION TCFM3


END MODULE DlyTbl_CGLRRM_Subs


!=============================================================================
!=============================================================================
!=============================================================================


      PROGRAM DlyTbl_CGLRRM

      USE  FcstUtil
      USE  DlyTbl_CGLRRM_Subs

      IMPLICIT   NONE
      INTEGER :: I, LkNum
      INTEGER :: StartSeq, EndSeq, NumArgs
      INTEGER :: Scenarios(MaxScen)

      CHARACTER (LEN=3)  :: Lake, S1, S2
      CHARACTER (LEN=10) :: L10
      CHARACTER (LEN=25) :: Args(10)
      CHARACTER (LEN=99) :: CLine

      ErrorLevel = 0
      CALL ClearFilesOpen(); IF (ErrorLevel .NE. 0) GOTO 899

!
!  Get input from user and parse into Args array.
!     Fortran 2003 style command line handling
!     It includes the program name (Lahey did not), so I need to strip
!     that off before any further processing.
!
      CALL GET_COMMAND(CLine)
      CALL ParseCmdLine(CLine, Args, NumArgs)
      IF (NumArgs .LT. 2) GOTO 800
      DO I=2, NumArgs
         Args(I-1) = Args(I)
      END DO
      NumArgs = NumArgs-1

!
!  Determine which lake to process
!
      LkNum = -1
      Lake = Args(1)(1:3)
      S1 = Lake
      CALL Caps(S1); IF (ErrorLevel .NE. 0) GOTO 899
      DO I = 1, 5
         S2 = LevLkCode3(I)
         CALL Caps(S2)
         IF (S1 .EQ. S2) LkNum = I
      ENDDO
      IF (LkNum .LT. 1) THEN
         PRINT*, 'Invalid lake code: '//TRIM(Lake)
         GOTO 800
      END IF
      L10 = LevLkName10(LkNum)
      PRINT*, 'Processing '//TRIM(L10)
      CMS  = .TRUE.
      
!
!  Process the lake specified by the user.
!  NBS values are assigned into the global array DlyOtlk(1:n,Scenario)
!  StartSeq and EndSeq will be assigned in the subroutine as a result of reading
!  the data files.
!
      CALL GetDailyOtlkNBS(LkNum, StartSeq, EndSeq, Scenarios)
      IF (ErrorLevel .NE. 0) GOTO 899

!
!  Now output the data and we're done.
!
      CALL WrtCGLRRM_Otlk_Daily(LkNum, StartSeq, EndSeq, Scenarios); IF (ErrorLevel .NE. 0) GOTO 899

      GOTO 999

!
!  ****** Error conditions ******
!
 800  PRINT*, 'USAGE: Dlytbl_CGLRRM lakename'
      PRINT*, '   lakename = SUP, MHU, STC, ERI, ONT'
      PRINT*, '   Can specify one of those.'
      GOTO 899


 899 ErrorMessage = '[traceback] : Dlytbl_CGLRRM Main...'
     CALL PassMsg
     CALL MakeErrorInt
     CALL CloseAllFiles
     CALL EXIT(1)

 999 CALL CloseAllFiles
     CALL EXIT(0)

      END PROGRAM DlyTbl_CGLRRM


