program depth
  implicit none

  integer :: ios, space_index, second_int, nforward = 0, ndepth = 0
  integer, parameter :: read_unit = 99
  character(len=30) :: line, first_part, second_part

  open(unit=read_unit, file='input', iostat=ios)
  if ( ios /= 0 ) stop "Error opening file"

  do
    read(read_unit, "(A)", iostat=ios) line 
    if (ios /= 0) exit

    space_index = scan(line, ' ')
    first_part = line(1:space_index)
    second_part = line(space_index+1:)

    read(second_part, *, iostat=ios) second_int 

    select case (first_part)
    
    case ("forward")
      nforward = nforward + second_int

    case ("up")
      ndepth = ndepth - second_int

    case ("down")
      ndepth = ndepth + second_int

    end select

  end do

  print*, "Total forward:", nforward
  print*, "Total depth:", ndepth
  print*, "Product:", nforward * ndepth
  
end program depth