#! /usr/bin/perl

use warnings;
use strict;

use lib "scripts/netcdf";
use abinit_readtype;

my ($var,%vars);

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

#print "Writing restore routine...";

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

print OUT <<EOF
!{\\src2tex{textfont=tt}}
!!****f* ABINIT/get_dtset_ncdf
!! NAME
!! get_dtset_ncdf
!!
!! FUNCTION
!!  Reads a dataset from a specified 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
!!
!! OUTPUT
!!  dtset <type(dataset_type)> = the dataset where the data will be stored
!!
!! NOTES
!!  This routines assumes that all arrays within the dataset have already
!!  been allocated (array sizes are obtained through get_dims_dtset_ncdf).
!!
!!  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/get_dtset_ncdf.pl) to suit your needs.
!!
!! PARENTS
!!
!! CHILDREN
!!
!! SOURCE

subroutine get_dtset_ncdf(ncid,dtset)

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

 implicit none

!Arguments ------------------------------------
#if defined NETCDF
 type(dataset_type),intent(out) :: dtset
#else
 integer           ,intent(in)  :: dtset
#endif
!scalars
 integer,intent(in) :: ncid

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

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

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

	print OUT " ! Get $var\n";
	print OUT " ncerr = nf90_inq_varid(ncid,name='$var',varid=ncvar)\n";
	print OUT " call handle_ncerr_new('INQ','VAR','$var','get_dtset_ncdf',ncerr)\n";
	print OUT " ncerr = nf90_get_var(ncid,ncvar,dtset\%$var)\n";
	print OUT " call handle_ncerr_new('GET','VAR','$var','get_dtset_ncdf',ncerr)\n";
}

print OUT <<EOF
#else
 write(message,'(4a)') ch10,' get_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 get_dtset_ncdf
!!***
EOF
;

close(OUT);

#print "done.\n\n";

