#include "options.inc"


      program nc_merge
c=======================================================================
c   merge netcdf variables distributed over several files
c   into s single file
c=======================================================================
      implicit none
      real,parameter :: version = 0.1
      integer :: ncin,varin,id
      integer :: ncout,varout,nr_infiles
      integer :: nr_com,n,ierr,m,nr
      character (len=80) :: fname,outstr
      character (len=80),allocatable :: varnames(:)
#include "netcdf.inc"
      integer :: iret

      print'(" This is nc_merge.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-1

c   create output file
      call get_commandline_arg(nr_com,fname,ierr)
      print*,' creating file ',fname(1:len_trim(fname))
      ncout = nccre (fname, NCNOCLOB, iret)
      if (iret /=0 ) goto 110
      iret=nf_set_fill(ncout, NF_NOFILL, iret)

c   open input files and search for variables
      do n=1,nr_infiles
       call get_commandline_arg(n,fname,ierr)
       print*,' reading file ',fname(1:len_trim(fname))
       iret=nf_open(fname,NF_NOWRITE,ncin)
       if (iret /=0 ) goto 110
       call copy_file_attributes(ncin,ncout)
       call search_nr_variables(ncin,nr)
       allocate(varnames(nr))
       call search_variables(ncin,nr,varnames)
       do m=1,nr
        print*,' copying variable ',varnames(m)(1:len_trim(varnames(m)))
        iret=nf_inq_varid(ncin,varnames(m),id)
        if (iret /=0 ) goto 120
        call copy_variable(ncin,ncout,varnames(m),.false.,0)
       enddo
       deallocate(varnames)
       call ncclos (ncin, iret)
       if (iret /=0 ) goto 130
      enddo

      outstr='\n merged by nc_merge.x : '
      iret = NF_PUT_ATT_TEXT (NCout, nf_global, 
     &       'history',len_trim(outstr) , outstr)
      iret = nf_enddef(ncout)

c   close all files
      call ncclos (ncout, iret); if (iret /=0 ) goto 130
      print*,'all done, bye'
      stop

 100  print*,' program needs command line parameter'
      print*,' input netcdf file names, output netcdf file name'
      stop
 110  print*,' problem opening NetCDF file ',fname(1:len_trim(fname))
      print*,' netcdf lib says: ',nf_strerror(iret)
      stop
 120  print*,' problem finding variable '
      print*,' netcdf lib says: ',nf_strerror(iret)
      stop
 130  print*,' problem closing NetCDF file '
      print*,' netcdf lib says: ',nf_strerror(iret)
      stop
      end program nc_merge





c   dummy routines

      subroutine barrier
      end

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



