Program cs101grades
Use cs101  ! all variables and types declared in cs101 now available
Implicit None ! no other implicit vars

!********* Comparison Functions defined later*************
LOGICAL  :: lt_roll     ! Comparison fn for rollnumbers
LOGICAL  :: lt_quizi    ! Comparison fn for ith quiz
LOGICAL  :: lt_total  ! Comparison fn for quiz average
INTEGER :: choice       ! Choice of how to sort database
!************ Local Variable Declarations ************************
Integer, Parameter :: max_students = 10;
! Declare an array of type cs101student (defined in cs101 module)
TYPE (cs101student), Dimension(max_students) :: students
CHARACTER(len=20) :: filename    ! Input data file name
Integer :: status, I

!************** Data Initialization**************************
! Get the name of the file containing the input data.
Write (*,'(A)',ADVANCE='NO') 'Enter the file name with student marks: '
READ (*,'(A20)') filename
! Open input data file.  Status is OLD because the input data must 
! already exist.
OPEN(UNIT=9, FILE=filename, STATUS='OLD', IOSTAT=status )
! Was the OPEN successful? 
IF ( status /= 0 ) THEN       
   write (*,*) 'Input file could not be opened. Try again.'
   Stop  ! program halts for now. 
End IF
! Open successful. read data for student.
DO I = 1, max_students
 READ (9, 1010, IOSTAT=status) students(i)   ! Get value
 1010 FORMAT (A9,3(9X,I2))
End Do

!************* Sorting by various criteira **********
!find out how to sort data.
Write (*,1030,Advance='no') 
1030 Format (1X,'Enter way to sort database:',/, &
                   1X,'  1 -- By Roll Num ',/, &
                   1X,'  2 -- By i-th quiz ',/, &
                   1X,'  3 -- By Quiz Total  ---> ')
Read (*,1032) choice
1032 Format (I1)
! Sort database
Select Case ( choice)
  Case (1)
    CALL sort_students(students, max_students, lt_roll, 1)
  CASE (2)
    Write(*,1031,Advance='no') 'Which quiz do you want to sort by? (1-',num_quiz,') --> '
    1031 Format(' ', A39, I3, A6)
    Read(*,1032) I
    CALL sort_students(students, max_students, lt_quizi, I)
  CASE (3)
    CALL sort_students (students, max_students, lt_total, num_quiz)
  CASE DEFAULT
    WRITE (*,*) 'Invalid choice entered!'
End SELECT

! Now write out the sorted data.
Write (*,'(A)') ' The sorted list is: '
Do i = 1, max_students
 Write (*,1040) students(i)
1040 Format(' ', A12, 3(I4))
End Do
END PROGRAM cs101grades
