module hes_fileio_mod
  use  base_struct_mod
  implicit none
  integer, external, private :: sreed_window, srite_window
contains

  !!------------------------------------------------------------------------------------------------------
  !!.. write or read a model 
  !!------------------------------------------------------------------------------------------------------
  subroutine hes_fileio_modl(hess, hgrid, index_x_offd, index_y_offd, index_z_offd, filetag, flag)
    real, dimension(:,:,:) :: hess
    type(hes_grid)         :: hgrid
    integer                :: index_x_offd, index_y_offd, index_z_offd
    character(len=*)       :: filetag
    character(len=4)       :: flag

    integer, dimension(6)  :: n_cube, j_wind, n_wind, f_wind
    integer                :: n_dim_cube, err

    n_dim_cube = 6
    n_cube = (/hgrid%ax_modl%n,hgrid%ay_modl%n,hgrid%az_modl%n,hgrid%ax_offd%n,hgrid%ay_offd%n,hgrid%az_offd%n/)
    j_wind = (/1,1,1,1,1,1/)
    n_wind = (/hgrid%ax_modl%n,hgrid%ay_modl%n,hgrid%az_modl%n,1,1,1/)
    f_wind = (/0,0,0,index_x_offd-1,index_y_offd-1,index_z_offd-1/)

    if (flag == "rite") then
       err = srite_window(filetag,n_dim_cube,n_cube,n_wind,f_wind,j_wind,4,hess)
    else if (flag == "reed") then
       hess = 0.
       err = sreed_window(filetag,n_dim_cube,n_cube,n_wind,f_wind,j_wind,4,hess)
    end if

    return
  end subroutine

  !!-------------------------------------------------------------------------------------------------
  !!.. write or read off-diagonals
  !!-------------------------------------------------------------------------------------------------
  subroutine hess_fileio_offd(hess, hgrid, index_x_modl, index_y_modl, index_z_modl, filetag, flag)
    real, dimension(:,:,:) :: hess
    type(hes_grid)         :: hgrid
    integer                :: index_x_modl, index_y_modl, index_z_modl
    character(len=*)       :: filetag
    character(len=4)       :: flag

    integer, dimension(6)  :: n_cube, j_wind, n_wind, f_wind
    integer                :: n_dim_cube, err

    n_dim_cube = 6
    n_cube = (/hgrid%ax_offd%n,hgrid%ay_offd%n,hgrid%az_offd%n,hgrid%ax_modl%n,hgrid%ay_modl%n,hgrid%az_modl%n/)
    j_wind = (/1,1,1,1,1,1/)
    n_wind = (/hgrid%ax_offd%n,hgrid%ay_offd%n,hgrid%az_offd%n,1,1,1/)
    f_wind = (/0,0,0,index_x_modl-1,index_y_modl-1,index_z_modl-1/)

    if (flag == "rite") then
       err = srite_window(filetag,n_dim_cube,n_cube,n_wind,f_wind,j_wind,4,hess)
    else if (flag == "reed") then
       hess = 0.
       err = sreed_window(filetag,n_dim_cube,n_cube,n_wind,f_wind,j_wind,4,hess)
    end if

    return
  end subroutine




end module
