module m_get_mod_xyz
! Gets model dimensions in file './mask.nc' 
! (unless another netcdf file is submitted) and returns them.
! Added by F. Massonnet to the NERSC-ENKF routines, May 2013.
! (Presumably) Coded by C. König Beatty, in 2009
! Goal is to quickly retrieve model dimensions without using parseblk

  use netcdf
#if defined (QMPI)
  use qmpi
#else
  use qmpi_fake
#endif

  private handle_err

contains 
  subroutine get_mod_xyz(x, y, z, moddimfilein)

  implicit none

  ! In/out
  integer,          intent(out)          :: x, y, z
  character(len=*), intent(in), optional :: moddimfilein

  ! NetCDF vars
  integer            :: ncid, dimID, error
  character(len=120) :: moddimfile

  logical ex


  if (present(moddimfilein)) then
     moddimfile=moddimfilein
  else
     moddimfile='./mask.nc'
  end if

  ! check the netCDF file exists
  inquire(file=moddimfile, exist=ex)
  if (.not.ex) then
     if (master) then
        print *, '(get_mod_xyz): file does not exist: '//trim(moddimfile)
     end if
     call stop_mpi()
  end if


  ! open the netCDF file
  error = nf90_open(trim(moddimfile),nf90_NoWrite,ncid)
  if (error.ne.nf90_noerr) call handle_err(error, "opening")


  ! Find DimID of x
  error = nf90_inq_dimid(ncid, 'x', dimID)
  if (error.ne.nf90_noerr) call handle_err(error, "inquiring dimID x")
  ! Get size of dimension
  error = nf90_inquire_dimension(ncid, dimID, len = x)
  if (error.ne.nf90_noerr) call handle_err(error, "getting dimension x")

  ! Find DimID of y
  error = nf90_inq_dimid(ncid, 'y', dimID)
  if (error.ne.nf90_noerr) call handle_err(error, "inquiring dimID y")
  ! Get size of dimension
  error = nf90_inquire_dimension(ncid, dimID, len = y)
  if (error.ne.nf90_noerr) call handle_err(error, "getting dimension y")

  ! Find DimID of z
  error = nf90_inq_dimid(ncid, 'z', dimID)
  if (error.ne.nf90_noerr) call handle_err(error, "inquiring dimID z")
  ! Get size of dimension
  error = nf90_inquire_dimension(ncid, dimID, len = z)
  if (error.ne.nf90_noerr) call handle_err(error, "getting dimension z")


  ! Close file
  error = nf90_close(ncid)              ! close netCDF dataset
  if (error.ne.nf90_noerr) call handle_err(error, "closing")


contains

  subroutine handle_err(status, infomsg) 
    integer,            intent ( in) :: status 
    character(len = *), intent ( in), optional :: infomsg
    if(status /= nf90_noerr) then
       if (present(infomsg)) then
          print *, 'Error while '//infomsg//' - '//trim(nf90_strerror(status)) 
       else
          print *, trim(nf90_strerror(status)) 
       endif
       stop " Stopped" 
    end if
  end subroutine handle_err

end subroutine get_mod_xyz

end module m_get_mod_xyz

