c     gt_mask_SQ_2.f
c
c     Get big regional Gt from global Gt
c
      use commondata, only : ensmem,mx,my,seasons,loc_sq,area,tmp_path,
     & sur_path,date,time

      implicit none

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

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

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

         valid=0
         open(9,file=trim(sur_path)//trim(loc_sq(1))//trim(area(z))//
     & trim(loc_sq(2)))
         do
            read(9,*,end=77) a
            valid=valid+1
         enddo
77       close(9)
         open(9,file=trim(sur_path)//trim(loc_sq(1))//trim(area(z))//
     & trim(loc_sq(2)))
         read(9,*) a
         valid=valid-1
         do i=1,valid
            read(9,*) num(i)
         enddo
         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(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(seasons(k))//trim(snd(3)))
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))

         do
            read(2,*,end=99) iyear,imonth,iday,ihour
            read(2,'(10f9.3)') (values(i),i=1,mx*(my-1))
            do i=1,valid
               results(i)=values(num(i))
               if(results(i).lt.-899.99) results(i)=-900.99
            enddo
            write(10,'(i6,3i3,i6)') iyear,imonth,iday,ihour,valid
            write(10,'(10f9.3)') (results(i),i=1,valid)
         enddo
99       close(10)
         close(2)
         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_mask_SQ end at: Date ', i2.2, '/', i2.2, '/', i4.4,
c     &         '; time ',i2.2, ':', i2.2, ':', i2.2 )

      end
