c     merge4seas.f
c
c     Merge globel seasonal Hs into global Hs
c
      use commondata, only : out_path,tmp_path

      parameter(maxyr=150)
      character ifhead*200, seas(4)*3, ifloc*200, ifdata*200,
     &          ofhead*200
      integer yy,mm,dd,hh,ymdh(maxyr*366*4,4),nums(4),ids(4),
     &        tcnt,tar,ymdh_wk,ocnt
      real idata(360*181)
      logical tflg

      data seas/"jfm","amj","jas","ond"/
      call get_command_argument(1,ifhead)
      call get_command_argument(2,ofhead)
      iflg=0

      do ith=1,4
        ifloc=trim(tmp_path)//trim(ifhead)//'_'//trim(seas(ith))//
     & '_time.txt'
        open(10,file=trim(ifloc))
        N=1
80      read(10,*,end=100) yy,mm,dd,hh
        ymdh(N,ith)=yy*1000000+mm*10000+dd*100+hh
        N=N+1
        goto 80
100     N=N-1
        nums(ith)=N
        close(10)
c        print*,ith,nums(ith)
      enddo

      cymdh=0
      ocnt=0
      do ith=1,4
        ids(ith)=1
      enddo
      tflg=.TRUE.
      do ith=1,4
        ifdata=trim(ifhead)//'_'//trim(seas(ith))//'_GLOB.dat'
        open(10+ith,file=trim(tmp_path)//trim(ifhead)//'_'//
     &       trim(seas(ith))//
     &       '_GLOB.dat',form='unformatted',access='direct',
     &       recl=360*181*4)
      enddo
      open(20,file=trim(out_path)//trim(ofhead)//'_GLOB.dat',
     &     form='unformatted',access='direct',recl=360*181*4)
      open(21,file=trim(out_path)//trim(ofhead)//'_time.txt')

      do while (tflg)
        ymdh_wk=cymdh
        tcnt=0
        tar=0
        do ith = 1,4
          if(ids(ith).le.nums(ith)) then
            tcnt=tcnt+1
            if(ymdh_wk.eq.cymdh) then
              ymdh_wk=ymdh(ids(ith),ith)
              tar=ith
            else
              if(ymdh(ids(ith),ith).lt.ymdh_wk) then
                ymdh_wk=ymdh(ids(ith),ith)
                tar=ith
              endif
            endif
          endif
        enddo
        if(tcnt.eq.0) then
          tflg=.FALSE.
        else
C         print*,ymdh_wk,tar,ids(tar)
          ids(tar)=ids(tar)+1
        endif
        if(tflg) then
          read(10+tar,rec=ids(tar)-1) idata
          ocnt=ocnt+1
          write(20,rec=ocnt) idata
          write(21,*) ymdh_wk
        endif
      enddo

      close(21)
      close(20)
      end
