#! /usr/bin/perl

use warnings;
use strict;

use lib "scripts/netcdf";
use abinit_readtype;

my $type = "";
my $cont = 0;
my $wait = 1;

my ($var,$grp,$i,@tmp1,@tmp2,%vars);

%vars = extract_variables("Src_defs/defs_datatypes.F90","dataset_type");

#print "Writing backup routine...";

open(OUT,">Src_3ionetcdf/put_dtset_ncdf.F90")
or die "Could not open Src_3ionetcdf/put_dtset_ncdf.F90 for writing";

print OUT <<EOF
!{\\src2tex{textfont=tt}}
!!****f* ABINIT/put_dtset_ncdf
!! NAME
!! put_dtset_ncdf
!!
!! FUNCTION
!!  Stores a specified dataset into a NetCDF file.
!!
!! COPYRIGHT
!!  Copyright (C) 2005 ABINIT group (YP)
!!  This file is distributed under the terms of the
!!  GNU General Public License, see ~ABINIT/Infos/copyright
!!  or http://www.gnu.org/copyleft/gpl.txt .
!!  For the initials of contributors, see ~ABINIT/Infos/contributors .
!!
!! INPUTS
!!  ncid = identifier of an open NetCDF file
!!  dtset <type(dataset_type)> = all input variables in this dataset
!!
!! OUTPUT
!!  (no direct output : data written to a NetCDF file)
!!
!! NOTES
!!  Please do not edit this file. Since it is automatically generated (see
!!  the makencdf script), your changes would be systematically overwritten.
!!  Instead you should directly modify the generating script itself
!!  (~ABINIT/scripts/netcdf/put_dtset_ncdf.pl) to suit your needs.
!!
!! PARENTS
!!
!! CHILDREN
!!
!! SOURCE

subroutine put_dtset_ncdf(ncid,dtset)

 use defs_basis
 use defs_datatypes
#if defined NETCDF
 use netcdf
#endif

 implicit none

!Arguments ------------------------------------
!scalars
 integer,intent(in) :: ncid
 type(dataset_type),intent(in) :: dtset

!Local variables-------------------------------
!scalars
 integer :: ncerr,ncvar
 character(len=500) :: message

! ***************************************************************************
#if defined NETCDF
EOF
;

foreach $var (sort keys %vars)
{
	$var =~ s/\(.*//;

	print OUT " ! Put $var\n";
	print OUT " ncerr = nf90_inq_varid(ncid,name='$var',varid=ncvar)\n";
	print OUT " call handle_ncerr_new('INQ','VAR','$var','put_dtset_ncdf',ncerr)\n";
	print OUT " ncerr = nf90_put_var(ncid,ncvar,dtset\%$var)\n";
	print OUT " call handle_ncerr_new('PUT','VAR','$var','put_dtset_ncdf',ncerr)\n";
}

print OUT <<EOF
#else
 write(message,'(4a)') ch10,' put_dtset_ncdf - ERROR',ch10,&
&  'This version has not been compiled with NetCDF support'
 call wrtout(std_out,message,'COLL')
 call leave_new('COLL')
#endif

end subroutine put_dtset_ncdf
!!***
EOF
;

close(OUT);

#print "done.\n\n";

