      PROGRAM OUTCOMBINE

C****************************************************************************
C Program to combine two types of post-processed CAMx output csv files
C (avrg and sa), convert the input species to those needed to calculate 
C light extinction, and write the results to a single ASCII file.
C*************************************************************************** 
      USE M3UTILIO
      IMPLICIT NONE

c17 ifort -fPIC -check -traceback -extend_source -zero -O3 -mp1 -o out_combine.exe out_combine.F -L/home/local-rhel7/apps/netcdf-4.4.1/intel-17.0/lib -lnetcdf -lnetcdff -L/home/local-rhel7/apps/ioapi-3.2/intel-17.0/lib -lioapi -module /home/local-rhel7/apps/ioapi-3.2/intel-17.0/Linux2_x86_64ifort

C...........   Parameters
      CHARACTER *16 PNAME
      PARAMETER    (PNAME='OUTCOMBINE')
      INTEGER, PARAMETER :: MXTCOL = 40  ! max columns in sitefile 
      INTEGER, PARAMETER :: NVMAX  = 15  ! max species in input files 
      CHARACTER*1, PARAMETER:: SEP = '/' ! separator for calendar date
      INTEGER, PARAMETER :: NSITES = 13  ! number of Class I areas 
      INTEGER, PARAMETER :: NFTYP  =  2  ! number of input file types 
      CHARACTER*5, PARAMETER :: SITENAME( NSITES ) = ! Class I area names
     $     ( / 'BAND1', 'BIBE1', 'BRIS1', 'CACR1', 'GRSA1', 'GUMO1',
     $         'HEGL1', 'MING1', 'SACR1', 'UPBU1', 'WHIT1', 'WHPE1',
     $         'WIMO1' / )
      INTEGER, PARAMETER :: NSTMX( 2 ) = ! Class I areas in grd01/02 files
     $     ( / 0, 13 / )
      INTEGER, PARAMETER :: NSPMX( 2 ) = ! Max # of species in sa/avrg files
     $     ( / 8, 13 / )
      INTEGER, PARAMETER :: NDAYS = 365  ! number of days of data per site
      INTEGER, PARAMETER :: NSRC  = 20   ! number of sources (untagged source 1, tagged sources 2-19 + Base 2016) 
      INTEGER, PARAMETER :: NSPC  = 8    ! number of output species
      CHARACTER*14, PARAMETER :: SPNAME( NSPC ) = ! output species names
     $     ( / '     NO2      ', '    Soil     ', '    Amm_NO3   ',
     $         '     OMC      ', '    LAC      ', '      CM      ',
     $         '   Amm_SO4    ', '   Sea_Salt  ' / )   

C...........   Local variables

      CHARACTER *16  SAFILE1           ! input sa (ascii) CAMx grd1 file
      CHARACTER *16  SAFILE2           ! input sa (ascii) CAMx grd2 file
      CHARACTER *16  AVRGFILE1         ! input avrg (ascii) CAMx grd1 file 
      CHARACTER *16  AVRGFILE2         ! input avrg (ascii) CAMx grd2 file 
      CHARACTER *16  OUTFILE           ! output combined (ascii) data file
      CHARACTER *16  DEFAULT
      CHARACTER *256 MESG
      CHARACTER *256 LINE  
      INTEGER        I, S, V, T        ! scratch variables
      INTEGER        IGRID             ! grid counter
      INTEGER        ISITE             ! monitor site counter
      INTEGER        ISRC              ! source index
      INTEGER        IFTYP             ! file type index
      INTEGER        IUNIT             ! file unit counter
      INTEGER        NMAX, SPMAX       ! loop max indices
      INTEGER        AVUNIT(2)         ! unit # for AVRGFILE (grd01, grd02)
      INTEGER        SAUNIT(2)         ! unit # for SAFILE   (  "       " )
      INTEGER        OUTUNIT           ! unit # for OUTFILE

      CHARACTER*40   FMTHDR
      CHARACTER*64   FMTDATA
      REAL           RAY  ( NSITES ), FSRH( NSITES ),
     $               FLRH ( NSITES ), 
     $               FSSRH( NSITES ),
     $               FRH  ( NSITES )
      INTEGER        YEAR                         ! input year var
      INTEGER        DAY                          ! input day var
      INTEGER        MON                          ! input month var
      CHARACTER*20   DATE                         ! input calendar date
      CHARACTER*6    SITE( NSITES )               ! input source, site vars
      REAL           SPC( NSITES, NVMAX )         ! input concs
      REAL           RAYSS( NDAYS, NSITES ), FS  ( NDAYS, NSITES ),
     $               FL   ( NDAYS, NSITES ), FSS ( NDAYS, NSITES ),
     $               F    ( NDAYS, NSITES )       ! for output
      INTEGER        IMON ( NDAYS, NSITES ), IDAY( NDAYS, NSITES ),
     $               IYEAR( NDAYS, NSITES )       ! for output
      CHARACTER*20   ODATE( NDAYS, NSITES )       ! for output
      REAL           OUT( NSRC, NDAYS, NSITES, NSPC ) ! output concs
      CHARACTER *16  SRC( NSRC )                      ! source tag array
C =======================================================================
C...... beginning of the code

C Get input file names
            
      DEFAULT = 'SAFILE1'
      CALL GETSTR('Enter name for input sa (ascii) file ',
     $            DEFAULT, SAFILE1)

      DEFAULT = 'SAFILE2'
      CALL GETSTR('Enter name for input sa (ascii) file ',
     $            DEFAULT, SAFILE2)

      DEFAULT = 'AVRGFILE1'
      CALL GETSTR('Enter name for input avrg (ascii) file ',
     $             DEFAULT, AVRGFILE1)
      
      DEFAULT = 'AVRGFILE2'
      CALL GETSTR('Enter name for input avrg (ascii) file ',
     $             DEFAULT, AVRGFILE2)


C Read input files; load output arrays including species mapping for each file 
C type (avrg, sa), and all sources and sites from each grid 

      DO IFTYP = 1, 2           ! 1 =  sa, 2 = avrg              
         DO IGRID = 2, 2        ! 1 = grd01, 2 = grd02

            IF (IFTYP .EQ. 1) THEN

               IF (IGRID .EQ. 1) THEN

                  SAUNIT(IGRID) = GETEFILE(SAFILE1, .FALSE., .TRUE.,
     $                                     PNAME)
                  IF (SAUNIT(1) .LT. 0) then
                     CALL M3EXIT (PNAME, 0, 0,
     &                    'SAFILE1 file opening error', 2 )
                  END IF        ! if site input failed
                  
               ELSE             ! IGRID = 2
                  
                  SAUNIT(IGRID) = GETEFILE(SAFILE2, .FALSE., .TRUE.,
     $                                     PNAME)
                  IF (SAUNIT(2) .LT. 0) then
                     CALL M3EXIT (PNAME, 0, 0,
     &                    'SAFILE2 file opening error', 2 )
                  END IF        ! if site input failed
                  
               ENDIF            ! if IGRID = 1 or 2

               IUNIT = SAUNIT( IGRID )
                  
            ELSE                ! IFTYP = 2

               IF (IGRID .EQ. 1) THEN 

                  AVUNIT(1) = GETEFILE(AVRGFILE1, .FALSE., .TRUE., PNAME)
                  IF (AVUNIT(1) .LT. 0) then
                     CALL M3EXIT (PNAME, 0, 0,
     &                 'AVRGFILE1 file opening error', 2 )
                  END IF        ! if site input failed

               ELSE             ! IGRID = 2
                     
                  AVUNIT(2) = GETEFILE(AVRGFILE2, .FALSE., .TRUE., PNAME)
                  IF (AVUNIT(2) .LT. 0) then
                     CALL M3EXIT (PNAME, 0, 0,
     &                    'AVRGFILE2 file opening error', 2 )
                  END IF        ! if site input failed

               ENDIF            ! if IGRID = 1 or 2
               IUNIT = AVUNIT( IGRID )
               
            ENDIF               ! if IFTYP = 1 or 2
                  
            NMAX  = NSTMX(  IGRID )
            SPMAX = NSPMX(  IFTYP )

            READ( IUNIT, 1000, END = 100 ) LINE ! read  header
            
            DO ISRC = 1, NSRC - 1 
                     
               DO ISITE = 1, NMAX
                  DO I = 1, NDAYS
                     
                     IF (IFTYP .EQ. 1) THEN

                        READ( IUNIT, 2000, END = 100 ) SRC( ISRC ), 
     $                       SITE( ISITE ), RAY( ISITE ),
     $                       MON, DAY,  YEAR,  
     $                       FSRH(  ISITE ), FLRH( ISITE ), 
     $                       FSSRH( ISITE ),  FRH( ISITE ),   
     $                       DATE,( SPC( ISITE,V ), V = 1,SPMAX )

                        S = INDEX1( SITE( ISITE ), NSITES, SITENAME )
                        
                        RAYSS( I, S )     = RAY(   ISITE )
                        FL(    I, S )     = FLRH(  ISITE )
                        FS(    I, S )     = FSRH(  ISITE )
                        FSS(   I, S )     = FSSRH( ISITE )
                        F  (   I, S )     = FRH(   ISITE )
                        IMON(  I, S )     = MON
                        IDAY(  I, S )     = DAY
                        IYEAR( I, S )     = YEAR
                        ODATE( I, S )     = DATE
C                       OUT( ISRC,I,S,1 ) = 1000.* SPC( ISITE,1 )           ! NO2 (ppb)  *** commented out because we do not   ***
                        OUT( ISRC,I,S,1 ) =        0.0                      ! NO2 (ppb)  *** have RGN in the current sa output ***
                        OUT( ISRC,I,S,2 ) =        SPC( ISITE,1 ) +
     $                                             SPC( ISITE,6 )           ! Soil = PFC(1) + PFN(6)      
                        OUT( ISRC,I,S,3 ) = 1.29 * SPC( ISITE,3 )           ! NH4NO3 or Amm_NO3 = 1.29 * PN3(3)
                        OUT( ISRC,I,S,4 ) =        SPC( ISITE,5 )           ! OMC = POA(5)
                        OUT( ISRC,I,S,5 ) =        SPC( ISITE,4 )           ! LAC = PEC(4)
                        OUT( ISRC,I,S,6 ) =        SPC( ISITE,7 ) +
     $                                             SPC( ISITE,8 )           ! CM = PCC(7) + PCS(8)
                        OUT( ISRC,I,S,7 ) = 1.375* SPC( ISITE,2 )           ! (NH4)2SO4 or Amm_SO4 = 1.375 * PS4(2)
                        OUT( ISRC,I,S,8 ) =        0.0                      ! no seasalt extinction for tagged sources

                     ELSE                                                   ! av file 

                        READ( IUNIT, 3000, END = 100 ) SRC( ISRC ), 
     $                       SITE( ISITE ), RAY( ISITE ),
     $                       MON, DAY, YEAR, FSRH( ISITE ), 
     $                       FLRH( ISITE ), FSSRH( ISITE ),  
     $                       FRH(  ISITE ), DATE,
     $                       ( SPC( ISITE,V ), V = 1,SPMAX )
                        
                        S = INDEX1( SITE( ISITE ), NSITES, SITENAME )
                        
                        RAYSS( I, S )       = RAY(   ISITE )
                        FL(    I, S )       = FLRH(  ISITE )
                        FS(    I, S )       = FSRH(  ISITE )
                        FSS(   I, S )       = FSSRH( ISITE )
                        F  (   I, S )       = FRH(   ISITE )
                        IMON(  I, S )       = MON
                        IDAY(  I, S )       = DAY
                        IYEAR( I, S )       = YEAR
                        ODATE( I, S )       = DATE
                                              
                        OUT( NSRC,I,S,1 ) = 1000. * (SPC( ISITE,1 ) +       ! source index = 20 -> Base 2016 output
     $                                               SPC( ISITE,2 ) +
     $                                         2. *  SPC( ISITE,3 ) )       ! NO2 (ppb) (factor of 2 per Ramboll)
                        
                        OUT( NSRC,I,S,2 ) =          SPC( ISITE,8 ) +
     $                                               SPC( ISITE,9 )         ! Soil       
                        OUT( NSRC,I,S,3 ) = 1.29  *  SPC( ISITE,5  )        ! NH4NO3
                        OUT( NSRC,I,S,4 ) =          SPC( ISITE,7  )        ! OMC
                        OUT( NSRC,I,S,5 ) =          SPC( ISITE,6  )        ! LAC
                        OUT( NSRC,I,S,6 ) =          SPC( ISITE,10 ) +
     $                                               SPC( ISITE,11 )        ! CM
                        OUT( NSRC,I,S,7 ) = 1.375 *  SPC( ISITE,4  )        ! (NH4)2SO4 
                        OUT( NSRC,I,S,8 ) =          SPC( ISITE,12 ) +
     $                                               SPC( ISITE,13 )        ! sea salt
                                                
                     ENDIF      ! if IFTYP = sa or avrg 

                     WRITE(*, *) 'DATE = ', ODATE( I, S ),
     $                           'AT SITE # ', S, 'FOR SRC ', ISRC

                  END DO        ! end read on days
               END DO           ! end read on sites
            END DO              ! end read on sources
 100        CONTINUE
         END DO                 ! end read on grids
      END DO                    ! end loop on file types

      SRC( NSRC ) = 'Base_2016'                                                
                                                                            
      DEFAULT = 'OUTFILE'
      CALL GETSTR('ENTER NAME FOR OUTPUT DATA FILE ',
     $            DEFAULT, OUTFILE)

      OUTUNIT = GETEFILE(OUTFILE, .FALSE., .TRUE., PNAME)
      IF (OUTUNIT .LT. 0) THEN
         CALL M3EXIT (PNAME, 0, 0,
     &                'OUTFILE FILE OPENING ERROR', 2 )
      END IF ! if output failed

      WRITE(FMTHDR, '(A,I2.2,A)') '(1X,A10,A5,A12,7A6,A10,',NSPC,'A14)'
      WRITE(FMTDATA,'(A,I2.2,A)')
     $     '(1X,A10,A5,F12.0,3I6,F6.2,F6.1,F6.2,F6.1,A10,',NSPC,'G14.6)'

C Write OUTFILE header

      WRITE (OUTUNIT, FMTHDR) 'Tracer', ' site',
     $       ' ss_rayleigh', '  mon ', '  day ', ' year ', ' fsrh ', 
     $       ' flrh ','fssrh ', '  frh ', '    date  ' ,
     $       ( SPNAME(S),S = 1,NSPC )
        
C Output variables from grd01 and grd02 sites and all sources to OUTFILE 

      DO ISRC = 1, NSRC

         DO ISITE = 1, NSITES

             DO I = 1, NDAYS
                     
               WRITE (OUTUNIT, FMTDATA) SRC( ISRC  ), SITENAME(ISITE),  
     $              RAYSS(I, ISITE), IMON(I, ISITE),  IDAY(I, ISITE),
     $              IYEAR(I, ISITE),   FS(I, ISITE),    FL(I, ISITE), 
     $              FSS(  I, ISITE),    F(I, ISITE), ODATE(I, ISITE),
     $              (OUT( ISRC, I, ISITE, V ), V = 1, NSPC)
                  
            END DO              ! if I     > NDAYS

         END DO                 ! if ISITE > NSITES

      END DO                    ! if ISRC  > NSRC

      CLOSE (OUTUNIT)
      
      CALL M3EXIT( PNAME, 0, 0, 'Normal completion', 0 )

1000  FORMAT( 250A )
2000  FORMAT( 1X,A6,A5,F6.0,3I6,F6.2,F6.1,F6.2,F6.1,A10, 9G14.6)
3000  FORMAT( 1X,A6,A5,F6.0,3I6,F6.2,F6.1,F6.2,F6.1,A10, 13G14.6)

      END


C ==========================================================================
C ==========================================================================
C ==========================================================================
