      PROGRAM MERGE
************************************************************************
* Program to read two files of records containing a student number, a  *
* student name, and a cumulative GPA, where the files are sorted so    *
* that student numbers are in ascending order, and merge these two     *
* files to produce another that is also sorted.  Variables used are:   *
*     FNAME1, FNAME2  : names of files to be merged                    *
*     FNAME3          : name of file produced                          *
*     SNAME1, SNAME2  : name of student in FILE1, FILE2                *
*     SNUMB1, SNUMB2  : number of student in FILE1, FILE2              *
*     GPA1, GPA2      : cumulative GPA of student in FILE1, FILE2      *
*     EOF1, EOF2      : indicator of end of FILE1, FILE2               *
*                                                                      *
* Input (keyboard): FNAME1, FNAME2, FNAME3                             *
* Output (screen):  User prompts and message that sorting has been     *
*                   completed                                          *
************************************************************************

      CHARACTER*20, FNAME1, FNAME2, FNAME3, SNAME1, SNAME2
      INTEGER SNUMB1, SNUMB2, EOF1, EOF2
      REAL GPA1, GPA2

* Get the names of the files and open them

      PRINT *, 'ENTER THE NAMES OF THE FILES TO BE MERGED AND THE NAME'
      PRINT *, 'OF THE FILE TO BE PRODUCED ON SEPARATE LINES:'
      READ '(A)', FNAME1, FNAME2, FNAME3
      OPEN (UNIT = 10, FILE = FNAME1, STATUS = 'OLD',
     +     ACCESS = 'SEQUENTIAL')
      OPEN (UNIT = 20, FILE = FNAME2, STATUS = 'OLD',
     +     ACCESS = 'SEQUENTIAL')
      OPEN (UNIT = 30, FILE = FNAME3, STATUS = 'NEW',
     +     ACCESS = 'SEQUENTIAL')

* Read the first two records from each file

      READ (10, 100, IOSTAT = EOF1) SNUMB1, SNAME1, GPA1
      READ (20, 100, IOSTAT = EOF2) SNUMB2,SNAME2, GPA2
100   FORMAT(I5, 1X, A, F4.2)

* While neither the end of FILE1 or FILE2 has been reached,
* do the following:

10    IF (EOF1 .EQ. 0 .AND. EOF2 .EQ. 0) THEN
          IF (SNUMB1 .LE. SNUMB2) THEN
              WRITE (30, 100) SNUMB1, SNAME1, GPA1
              READ (10, 100, IOSTAT = EOF1) SNUMB1, SNAME1, GPA1
          ELSE
              WRITE (30,100) SNUMB2, SNAME2, GPA2
              READ (20, 100, IOSTAT = EOF2) SNUMB2, SNAME2, GPA2
          END IF
      GO TO 10
      END IF

* If more records remain in FILE1, copy them to FILE3

20    IF (EOF1 .EQ. 0) THEN
          WRITE (30,100) SNUMB1, SNAME1, GPA1
          READ (10, 100, IOSTAT = EOF1) SNUMB1, SNAME1, GPA1
      GO TO 20
      END IF

* If more records remain in FILE2, copy them to FILE3

30    IF (EOF2 .EQ. 0) THEN
          WRITE (30,100) SNUMB2, SNAME2, GPA2
          READ (20, 100, IOSTAT = EOF2) SNUMB2, SNAME2, GPA2
      GO TO 30
      END IF

      PRINT *
      PRINT *, 'FILE MERGING IS COMPLETE'

      END
