c     merge2glb.f
c
c     Merge regional Hs into global Hs
c
      use commondata, only : tmp_path,loc_path

      character ifhead*200, areas(13)*4, sea*3, ifloc*200, ifdata*200,
     &          ofhead*200
      integer yy,mm,dd,hh,nums(13),idx(13,5000),ymdh,gth,ilat,ilon,
     &        iflg(360*181),lat(360*181),lon(360*181)
      real odata(360*181),idata(5000), landmask(360*181)

      data areas/"NA","NP","SA","SP","SIO","NIO","TNA",
     &           "TSIO","TSA","WTNP","WTSP","ETNP","ETSP"/
      call get_command_argument(1,ifhead)
      call get_command_argument(2,ofhead)
      call get_command_argument(3,sea)
      iflg=0

      open (1, file='land-sea-mask.dat',form='unformatted',
     &      access='direct',recl=181*360*4)
      read(1,rec=1) landmask ! land=1, sea=0
      close(1)

      do ith=1,13
        ifloc=trim(loc_path)//'locations_Hs_'//trim(areas(ith))//
     & '_'//trim(sea)//'_1x1.txt'
        open(10,file=trim(ifloc))
        N=1
80      read(10,*,end=100) gth
        idx(ith,N)=gth
        if(iflg(gth).eq.0) then
          iflg(gth)=1
          lat(gth)=ilat
          lon(gth)=ilon
        endif
c        if(((ilat+90)*360+ilon+1).ne.gth) then
c          print*,trim(ifloc),N,gth,ilat,ilon,'error1'
c          stop
c        endif
        N=N+1
        goto 80
100     N=N-1
        nums(ith)=N
        close(10)
      enddo

      open(200,file=trim(tmp_path)//trim(ofhead)//'_'//trim(sea)//
     &     '_GLOB.dat',form='unformatted',
     &     access='direct',recl=181*360*4)
      open(201,file=trim(tmp_path)//trim(ofhead)//'_'//trim(sea)//
     & '_time.txt')
      do ith=1,13
        ifdata=trim(ifhead)//'_'//trim(areas(ith))//'_'//
     &         trim(sea)//'.txt'
        open(ith+10,file=trim(tmp_path)//trim(ifdata))
      enddo

C    1) assign the initial value 0.000; 
C    2) replace NaN in the Hs output with -99.999
C    3) assign the Hs values to the array
C    4) assign -0.099 to land areas.
C
C    step 3) done at proj_PM, here we apply step 1), 2) and 4)

      N=0
180   odata=-999.99 ! initial value is 0.
      do ith=1,13
        read(ith+10,*,end=200) yy,mm,dd,hh,idata(1:nums(ith))
        if(ith.eq.1) then
          ymdh=yy*1000000+mm*10000+dd*100+hh
        else
          if(ymdh.ne.yy*1000000+mm*10000+dd*100+hh) then
            print*,areas(ith),yy,yy1,'error2'
            stop
          endif
        endif
        do j=1,nums(ith)
          if(idata(j).gt.-99.) odata(idx(ith,j))=idata(j)
        enddo
      enddo
      do j=1,360*181
        if(abs(landmask(j)-1.).lt.1E-5) then
          odata(j)=-0.099 ! assign land area as -0.099
        endif
      enddo
      N=N+1
      write(200,rec=N) (odata(j),j=1,360*181)
      write(201,*) yy,mm,dd,hh
      goto 180
200   continue
      close(200)
      close(201)

      end
