c     gt_mean_SQ.f
c
c     Calculate transformed Gt mean
c
c     Please note that only the mean and standard deviation from historical
c     run 1 is needed
c
      use commondata, only : ensmem,mx,my,seasons,area,tmp_path,
     & mean_path,date,time

      implicit none

      real :: values(20000),results(20000)
      integer :: iyear,imonth,k,i,z,valid,counter(20000),mem,runs,cc
      character(len=50) :: sno(4),snd(4),smem,input,model

      data snd /'_r','_trGt_','_','_SQ.txt'/
      data sno /'_r','_trGt_Mean1981-2000_','_','_SQ.txt'/

c      call idate(date)
c      call itime(time)
c      write(*,1000) date(2),date(1),date(3)+2000,time
c1000  format('gt_mean_SQ 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

      do z=1,13
      do k=1,4

         do mem=runs,runs
         smem=ensmem(mem)
        
         open(10,file=trim(tmp_path)//trim(model)//trim(sno(1))//
     & trim(smem)//trim(sno(2))//trim(area(z))//trim(sno(3))//
     & trim(seasons(k))//trim(sno(4)))
         open(2,file=trim(tmp_path)//trim(model)//trim(snd(1))//
     & trim(smem)//trim(snd(2))//trim(area(z))//trim(snd(3))//
     & trim(seasons(k))//trim(snd(4)))
C        print*,trim(model)//trim(sno(1))//trim(smem)//trim(sno(2))//
C    & trim(area(z))//trim(sno(3))//trim(seasons(k))//trim(sno(4))
         results=0.
         counter=0
         cc=0
         
         do
            read(2,*,end=99) iyear,imonth,i,i,valid
            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)
                     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
      enddo

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

      end
