! --------------------------------------------------------
! Instituto Nacional de Pesquisas Espaciais - INPE
! Coordenacao-Geral de Ciencias da Terra - CGCT
! Divisao de Impactos, Adaptacao e Vulnerabilidade - DIIAV
!
! Projeto: SisMOM
! Sistema de Monitoramento e Modelagem Oceanica e Costeira
! --------------------------------------------------------
! Leitura das grades regulares de saida (grid_XX.txt).
! --------------------------------------------------------
module mod_grid
  use mod_kinds, only: dp
  implicit none
  private
  public :: grid_t, read_grid

  type :: grid_t
    character(len=8)      :: name
    integer               :: nx, ny, npoints
    real(dp)              :: center_lon, center_lat, dlon, dlat
    real(dp), allocatable :: lon(:), lat(:), bottom(:)
    integer,  allocatable :: landmask(:)
  end type grid_t

contains

  subroutine read_grid(path, name, g)
    character(len=*), intent(in)  :: path
    character(len=*), intent(in)  :: name
    type(grid_t),     intent(out) :: g
    integer :: u, ios, p, ii, jj

    open(newunit=u, file=path, status='old', action='read', iostat=ios)
    if (ios /= 0) then
      write(*,*) 'ERRO: nao foi possivel abrir a grade: ', trim(path)
      stop 1
    end if

    read(u, *, iostat=ios) g%nx, g%ny, g%center_lon, g%center_lat, g%dlon, g%dlat
    if (ios /= 0) stop 'ERRO: cabecalho da grade invalido'
    read(u, *)  ! linha de header das colunas

    g%name = name
    g%npoints = g%nx * g%ny
    allocate(g%lon(g%npoints), g%lat(g%npoints), g%bottom(g%npoints), &
         g%landmask(g%npoints))

    do p = 1, g%npoints
      read(u, *, iostat=ios) ii, jj, g%lon(p), g%lat(p), g%bottom(p), g%landmask(p)
      if (ios /= 0) then
        write(*,*) 'ERRO: leitura da grade falhou no ponto ', p
        stop 1
      end if
    end do
    close(u)
  end subroutine read_grid

end module mod_grid
