! --------------------------------------------------------
! 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
! --------------------------------------------------------
! Calculo da data/hora do nome do arquivo de saida (start_date + horas).
! --------------------------------------------------------
module mod_datetime
  implicit none
  private
  public :: add_hours

contains

  pure function is_leap(y) result(leap)
    integer, intent(in) :: y
    logical :: leap
    leap = (mod(y,4) == 0 .and. mod(y,100) /= 0) .or. (mod(y,400) == 0)
  end function is_leap

  pure function days_in_month(y, m) result(d)
    integer, intent(in) :: y, m
    integer :: d
    integer, parameter :: dm(12) = [31,28,31,30,31,30,31,31,30,31,30,31]
    d = dm(m)
    if (m == 2 .and. is_leap(y)) d = 29
  end function days_in_month

  !> start_date no formato aaaammddhh + hours -> date_str (aaaammdd), hh_str (hh).
  subroutine add_hours(start_date, hours, date_str, hh_str)
    character(len=*), intent(in)  :: start_date
    integer,          intent(in)  :: hours
    character(len=8), intent(out) :: date_str
    character(len=2), intent(out) :: hh_str
    integer :: y, m, d, h, add

    read(start_date(1:4), '(i4)') y
    read(start_date(5:6), '(i2)') m
    read(start_date(7:8), '(i2)') d
    read(start_date(9:10),'(i2)') h

    h = h + hours
    do while (h >= 24)
      h = h - 24
      d = d + 1
      if (d > days_in_month(y, m)) then
        d = 1; m = m + 1
        if (m > 12) then; m = 1; y = y + 1; end if
      end if
    end do

    write(date_str, '(i4.4,i2.2,i2.2)') y, m, d
    write(hh_str,   '(i2.2)') h
  end subroutine add_hours

end module mod_datetime
