c     slp_std.f
c
c     Calculate SLP standard deviation
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),ave(20000),counter(20000)
      integer :: valid,iyear,k,i,mem,runs,cc
      character(len=50) :: sne(3),sno(3),snd(3),smem,input,model

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

c      call idate(date)
c      call itime(time)
c      write(*,1000) date(2),date(1),date(3)+2000,time
c1000  format('slp_std 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(9,file=trim(mean_path)//trim(model)//trim(sne(1))//
     & trim(smem)//trim(sne(2))//trim(seasons(k))//trim(sne(3)))
         read(9,'(10f9.3)') (ave(i),i=1,valid)
         close(9)

         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
            read(2,'(10f9.3)') (values(i),i=1,valid)
            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)-ave(i))**2
                     counter(i)=counter(i)+1
                  endif
               enddo
            endif
         enddo

99      continue
        do i=1,valid
            if(counter(i).lt.cc.or.ave(i).lt.-899.99) then
               results(i)=-900.99
               counter(i)=1
            else
               results(i)=(results(i)/real(counter(i)))**.5
            endif
         enddo

        write(10,'(10f9.3)') (results(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
c2000  format('slp_std end at: Date ', i2.2, '/', i2.2, '/', i4.4,
c     &         '; time ',i2.2, ':', i2.2, ':', i2.2 )

      end
