! Program Example from "Essential Fortran 90 & 95" by Loren P. Meissner
! Copyright 1996. Copying for sale requires permission from the author.
! Otherwise, distribution is permitted if these three lines are included.

! Example 5.6. (Enhanced; file input.) Rodent evaluation.
  program F06
    implicit none
    integer, parameter :: N_Rats = 10
    real :: Time
    real, dimension(N_Rats) :: Total
    integer :: Rat_ID, EoF
    integer, dimension(N_Rats) :: Runs
! start program F06
    open (unit = 1, file = "rat_data.txt", status = "old", action = "read", position = "rewind")
    Total = 0.0
    Runs = 0
    do
      read (unit = 1, fmt = *, iostat = EoF) Rat_ID, Time
      if (EoF < 0) then
        exit
      end if
      select case (Rat_ID)
      case (1: N_Rats)
        Runs(Rat_ID) = Runs(Rat_ID) + 1  ! Choose an array element.
        Total(Rat_ID) = Total(Rat_ID) + Time
      case default
        write (unit = *, fmt = *) " Rat ID number is not between 1 and ", N_Rats
      end select
    end do
    do Rat_ID = 1, N_Rats
      if (Runs(Rat_ID) > 0) then
        write (unit = *, fmt = *) Rat_ID, " Runs: ", Runs(Rat_ID), &
          " Average time: ", Total(Rat_ID) / Runs(Rat_ID)
      else
        write (unit = *, fmt = *) Rat_ID, " No runs. "
      end if
    end do
    stop
  end program F06
