!//////////////////////////////////////////////////////////////
!//
!// binio.f90
!//
!// Program to read an array from a binary file and
!// perform a calculation before writing the result
!// to a binary file
!//
!//////////////////////////////////////////////////////////////

PROGRAM binio
  !// Prevent implicit declarations of vatriables
  IMPLICIT NONE
  !// Variable declarations
  !// A constant value (length of array)
  INTEGER, PARAMETER                       :: N = 10
  !// The unit number for the input file
  INTEGER,PARAMETER                        :: ilun = 10
  !// The unit number for the output file
  INTEGER,PARAMETER                        :: olun = 11
  !// Character string to hold the input filename
  CHARACTER(LEN=80)                        :: infilename
  !// Character string to hold the output filename
  CHARACTER(LEN=80)                        :: outfilename
  !// An array to hole the values read in from the file
  REAL,DIMENSION(15)                       :: array
  !// A status variable
  INTEGER                                  :: res
  !// An index variable
  INTEGER                                  :: i
  
  !// Hardcode the input filename
  infilename = 'inndata.bin'
  !// Hardcode the output filename
  outfilename = 'outdata.bin'
  !// Open the file using the variable infilename
  !// and the file is ASCII (formatted). The status
  !// of the open operation is returned in the res
  !// variable
  OPEN(UNIT=ilun,FILE=infilename,FORM='UNFORMATTED',IOSTAT=res)
  !// Test if the opening was successful
  IF(res /= 0) THEN
    !// No, the status should have been a zero
    !// Print an error message and exit the program
    PRINT *, 'Error in opening file, status: ', res
    !// To exit a program in Fortran we use STOP unlike
    !// in other languages where it is exit
    STOP
  END IF
  !// The opening of the file was OK so now we proceed
  !// top read the content into the array 
  READ(UNIT=ilun,IOSTAT=res) array
  !// Test for success
  IF(res /= 0) THEN
    PRINT *, 'Error in opening file, status: ', res
    CLOSE(UNIT=ilun)
    STOP
  END IF
  !// When we are finished using the fiel we have to close
  !// it using the CLOSE function
  CLOSE(UNIT=ilun)
  !// Loop and change the value of the array
  DO i = 1, N
    !// Note the use of the FLOAT to ensure that the calculations
    !// are performed using flloating point numbers and not integer
    !// numbers
    array(i) = array(i) + FLOAT(i)/1.2
  END DO
  !// Open the output file. Note that the opening of a file is the
  !// same boh for reading and writing
  OPEN(UNIT=olun,FILE=outfilename,FORM='UNFORMATTED',IOSTAT=res)
  WRITE(UNIT=olun,IOSTAT=res) array
  !// Test for success
  IF(res /= 0) THEN
    PRINT *, 'Error in writing file, status: ', res
    CLOSE(UNIT=olun)
    STOP
  END IF
  !// Close the output file
  CLOSE(UNIT=olun)
END PROGRAM binio
