#include "options.inc"


c=======================================================================
c    simple program to concatenate sbc forcing files 
c=======================================================================
c
c#define real_8
c
      module kind_mod
#ifdef real_8
      integer, parameter::  r_knd  = selected_real_kind(13)
#else
      integer, parameter::  r_knd  = selected_real_kind(6)
#endif

      end module kind_mod


      program cat_sbc
      use kind_mod
      implicit none
      real,parameter :: version = 0.1
      integer :: nr_com,nr_infiles,io
      character (len=80), allocatable :: infile(:)
      character (len=80) :: outfile
      character (len=2000) :: outstr
      character (len=32) :: stamp,stamp2
      integer :: i,itm,j,io2,imt,jmt,ierr,n
      real (kind=r_knd), allocatable :: buf(:,:),aprec(:)

      print'(" This is cat_sbc.x :: version ",f5.3)',version

c  read command line input
      call get_commandline_argnr(nr_com)
      if (nr_com<3) goto 100
      nr_infiles = nr_com-3
      allocate( infile(nr_infiles)  )
      call get_commandline_arg(nr_com-2,outfile,ierr)
      call get_commandline_arg_int(nr_com-1,imt,ierr)
      call get_commandline_arg_int(nr_com,jmt,ierr)
c    write some information to stdout
      print*,' outfile : ',outfile
      print*,' imt x jmt : ',imt,jmt
      outstr=' concatenating forcing in files :'
      do n=1,nr_infiles
       call get_commandline_arg(n,infile(n),ierr)
       outstr=outstr(1:len_trim(outstr))//
     &            infile(n)(1:len_trim(infile(n)))//','
      enddo
      outstr=outstr(1:len_trim(outstr)-1)//' and writing to file '//
     &   outfile(1:len_trim(outfile))
      print*,outstr(1:len_trim(outstr))

c   open input files 
      itm=0
      do n=1,nr_infiles
       call getunit(io,infile(n),'usr ieee')
       if (n==1) then
        read (io) i,stamp
       else
        read (io) i
       endif
       close(io)
       itm=itm+i
      enddo
      print*,' altogether ',itm,' time steps '
      allocate( aprec(itm), buf(imt,jmt) )
      j=1
      do n=1,nr_infiles
       call getunit(io,infile(n),'usr ieee')
       read (io) i
       rewind(io)
       read (io) i,stamp2,aprec(j:j+i-1)
       close(io)
       j=j+i
      enddo

      call getunit(io2,outfile,'usr ieee')
      write (io) itm,stamp,aprec
      do n=1,nr_infiles
       call getunit(io,infile(n),'usr ieee')
       read (io) i
       do j=1,i
        read (io) buf
        write (io2) buf
       enddo
       close(io)
      enddo
      close(io2)

      print*,'all done, bye'
      stop

 100  print*,' program needs command line parameter'
      print*,' input file names, output file name, imt, jmt'
      print*,' files must be sbc forcing files for SPFLAME'
      stop
      end program cat_sbc



c   dummy routines

      subroutine barrier
      end

      subroutine halt_stop(s)
      character*(*) s
      print*,s
      stop
      end




