! 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 4.21 Total weight and average weight of cats.
  program E21
    implicit none
    integer :: How_Many, EoF
    character (len = 1) :: Sex
    real :: Next_Weight, Total_Weight
! start program E21
    How_Many = 0
    Total_Weight = 0.0
    open (unit = 2, file = "myfile.txt", status = "old", action = "read", position = "rewind")
    do
      read (unit = 2, fmt = *, iostat = EoF) Sex, Next_Weight
      if (EoF < 0) then
        exit
      else if ((Sex /= "m") .and. (Sex /= "f") .and. (Sex /= "M") .and. (Sex /= "F")) then
        write (unit = *, fmt = *) " Sex data error. "
        stop
      end if
      How_Many = How_Many + 1
      Total_Weight = Total_Weight + Next_Weight
    end do
    write (unit = *, fmt = *) How_Many, Total_Weight
    if (How_Many > 0) then
      write (unit = *, fmt = *) " Average weight: ", Total_Weight / real( How_Many )
    else
      write (unit = *, fmt = *) " There are no cats in this sample. "
    end if
    stop
  end program E21
