! string_fun  -  A simple program to test some of the limits of
!               string manipulation in Fortran.
!  by Jim Crumley 2/21/2006

PROGRAM string_fun
  IMPLICIT NONE
  
  CHARACTER (*):: filename="string_fun_data.text"
  CHARACTER(len=80) :: command
  INTEGER :: status, unit_n =2
 
  ! this command will print the entire file to the screen.
  command= 'cat ' // filename

  ! Non-standard Fortran subroutine that executes the first parameter
  ! as a Unix command and returns the status of the command as the second
  ! parameter.
  PRINT *,command
  CALL SYSTEM(command, status)
  PRINT *, 'System call status=', status 
  
  OPEN (UNIT=unit_n, FILE=filename, IOSTAT=status) 
 
  PRINT '(/,a,/)',  &
     "Above is the file that is being analyzed, below is the output"
 
  ! read in data in different formats. and print it out
  CALL read_and_print(unit_n, '*')
  CALL read_and_print(unit_n, '(3(a10))')
  CALL read_and_print(unit_n, '(3(a5))')
  CLOSE(UNIT=unit_n)
END PROGRAM

! read strings from file and prints them out with requested format
SUBROUTINE read_and_print(unit_num, format_code)
  IMPLICIT NONE
  INTEGER, INTENT(IN) :: unit_num
  CHARACTER(*), INTENT(IN) :: format_code
  CHARACTER(len=10) :: a, b, c
  INTEGER :: i, i_stat
 
  i_stat=0
  i=0

  PRINT '(/,a,a)', 'With format code ', format_code
  PRINT*, 'i (Read)        a         b         c'
  
  !loops through reading a line (or so) and print out the data
  Do WHILE (i_stat == 0)
    i=i+1
    IF (format_code == '*') THEN
      READ (unit_num,*, IOSTAT=i_stat) a,b,c
    ELSE 
      READ (unit_num,format_code, IOSTAT=i_stat) a,b,c
    ENDIF
    !Leaves loop when it hits the end of the file
    IF (i_stat /= 0) then
      PRINT *, 'IOSTAT is ', i_stat
      EXIT
    ENDIF
    PRINT '(i5,"      ",3("|",A),"|")', i, a, b, c
  END DO
  REWIND(UNIT=unit_num)

END SUBROUTINE
