c     pt_standardized.f
c
c     Standardized regional Pt with ERA interim's mean and
c     standard deviation
c
      use commondata, only : ensmem,mx,my,seasons,area,tmp_path,
     & pt_mean_path,pt_std_path,era_pt_mean,era_pt_std,date,time

      implicit none

      real :: values(20000),results(20000)
      real :: ave(20000),std(20000)
      integer :: valid,iyear,imonth,iday,ihour,k,i,mem,runs
      character(len=50) :: sno(3),snd(3),smem,input,model

      data snd /'_r','_SLP_','.txt'/
      data sno /'_r','_Pt_Standardized_','.txt'/

c      call idate(date)
c      call itime(time)
c      write(*,1000) date(2),date(1),date(3)+2000,time
c1000  format('pt_standardized start at: Date ', i2.2, '/', i2.2, 
c     &         '/', i4.4,'; 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

         mem=runs
         smem=ensmem(mem)

         open(7,file=trim(tmp_path)//trim(model)//trim(snd(1))//
     & trim(smem)//trim(snd(2))//trim(seasons(k))//trim(snd(3)))
         read(7,*) i
         close(7)
         open(8,file=trim(pt_std_path)//trim(era_pt_std(1))//
     & trim(seasons(k))//trim(era_pt_std(2)))
         read(8,'(10f9.3)') (std(i),i=1,valid)
         close(8)
         open(9,file=trim(pt_mean_path)//trim(era_pt_mean(1))//
     & trim(seasons(k))//trim(era_pt_mean(2)))
         read(9,'(10f9.3)') (ave(i),i=1,valid)
         close(9)
         
         do mem=runs,runs
         smem=ensmem(mem)

         open(10,file=trim(tmp_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)//trim(sno(2))//
C    & trim(seasons(k))//trim(sno(3))
         
         do
            read(2,*,end=99) iyear,imonth,iday,ihour
            read(2,'(10f9.3)') (values(i),i=1,valid)
            do i=1,valid
               if(values(i).lt.-899.99.or.ave(i).lt.-899.99.or.
     & std(i).lt.-899.99) then
                  results(i)=-900.99
               else
                  results(i)=(values(i)-ave(i))/std(i)
               endif
            enddo
            write(10,'(i6,3i3,i6)') iyear,imonth,iday,ihour,valid
            write(10,'(10f9.3)') (results(i),i=1,valid)
         enddo
99       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('pt_standardized end at: Date ', i2.2, '/', i2.2, 
c     &         '/', i4.4,'; time ',i2.2, ':', i2.2, ':', i2.2 )

      end
