c     slp_mean.f
c
c     Calculate SLP mean
c
c     Please note that only the mean and standard deviation from historical
c     run 1 is needed to standardized dataset
c
      use commondata, only : ensmem,mx,my,seasons,tmp_path,mean_path,
     &          date,time

      implicit none

      real :: values(20000),results(20000)
      integer :: valid,iyear,k,i,mem,runs,counter(20000),mm,dd,hh,cc
      character(len=50) :: sno(3),snd(3),smem,model,input

      data snd /'_r','_SLP_Unadjusted_','.txt'/
      data sno /'_r','_SLP_Mean1981-2000_','.txt'/

c      call idate(date)
c      call itime(time)
c      write(*,1000) date(2),date(1),date(3)+2000,time
c1000  format('slp_mean start at: Date ', i2.2, '/', i2.2, '/', i4.4,
c     &         '; time ',i2.2, ':', i2.2, ':', i2.2 )

      call get_command_argument(1,input)
      read(input,*) model
      call get_command_argument(2,input)
      read(input,*) runs

      valid=mx*(my+1)
      do k=1,4

         do mem=runs,runs
         smem=ensmem(mem)

         open(10,file=trim(mean_path)//trim(model)//trim(sno(1))//
     & trim(smem)//trim(sno(2))//trim(seasons(k))//trim(sno(3)))
         open(2,file=trim(tmp_path)//trim(model)//trim(snd(1))//
     & trim(smem)//trim(snd(2))//trim(seasons(k))//trim(snd(3)))
C        print*,trim(model)//trim(sno(1))//trim(smem)//
C    & trim(sno(2))//trim(seasons(k))//trim(sno(3))
         results=0.
         counter=0
         cc=0
         
         do
            read(2,*,end=99) iyear,mm,dd,hh
            read(2,'(10f9.3)') (values(i),i=1,valid)
c            if(mm.eq.1.and.dd.eq.1.and.hh.eq.0) print*,iyear,values(1)
            if(iyear.ge.1981.and.iyear.le.2000) then
               do i=1,valid
                  if(values(i).gt.-899.99) then
                     results(i)=results(i)+values(i)
                     counter(i)=counter(i)+1
                  endif
               enddo
               cc=cc+1
            endif
         enddo

99       continue
         do i=1,valid
            if(counter(i).lt.cc) then
               results(i)=-900.99
               counter(i)=1
            endif
         enddo

         write(10,'(10f9.3)') (results(i)/real(counter(i)),i=1,valid)
         close(2)
         close(10)
         enddo

      enddo
c      call idate(date)
c      call itime(time)
c      write(*,2000) date(2),date(1),date(3)+2000,time
cc000  format('slp_mean end at: Date ', i2.2, '/', i2.2, '/', i4.4,
c     &         '; time ',i2.2, ':', i2.2, ':', i2.2 )

      end
