# Author:  James Tam
# Version: June 1, 2021
# Learning objective: reading from an arbitrary sized text file into a 2D list.

END_OF_LINE = ""
EMPTY = ""
NEWLINE = "\n"
SPACE = " "

def display(grades,numRows,numColumns):
    currentRow = 0
    currentColumn = 0
    total = 0
    average = 0
    while (currentRow < numRows):
        total = 0
        average = 0
        currentColumn = 0
        while (currentColumn < numColumns):
            print("%s" %grades[currentRow][currentColumn], end=SPACE)
            total = total + int(grades[currentRow][currentColumn])
            currentColumn = currentColumn + 1
        average = total / numColumns
        print("\tAverage=%.2f" %(average))
        currentRow = currentRow + 1

def fileRead():
    fileOK = False
    grades = []
    maxColumns = 0
    while (fileOK == False):
        try:
            filename = input("Name of input file: ")       
            inputfile = open(filename,"r") 
            fileOK = True
            aLine = inputfile.readline()
            if (aLine == EMPTY):
                print("%s is an empty file")
            else:
                aLine = inputfile.readline()
                currentRow = 0
                while (aLine != END_OF_LINE):
                    currentCharacter = 0
                    grades.append([])
                    while (aLine[currentCharacter] != NEWLINE):
                        #Only add grades not spaces to the list of grade points
                        if (aLine[currentCharacter] != SPACE):
                            grades[currentRow].append(aLine[currentCharacter])
                        currentCharacter = currentCharacter + 1
                    currentRow = currentRow + 1  
                    aLine = inputfile.readline()                                                 
                inputfile.close()
        except IOError:
            print("Problem reading from file %s" %(filename))
            fileOK = False
    numRows = currentRow
    numColumns = len(grades[0])
    return(grades,numRows,numColumns)

def start():
    grades,numRows,numColumns = fileRead()
    display(grades,numRows,numColumns)
 
start()
