package week3exercise;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import week3exercise.NumberReadingException;

/**
 * This class reads the first 5 lines
 * of a file and print out the lines
 * in reverse order.
 */
class LineReverser{
	public static void main(String[] argv) throws IOException, NumberReadingException {
		if (argv.length != 1){
			System.out.println("Usage: FileReader <inputFile>");
			System.exit(1);
		}
		String fileName = argv[0];
		FileReader fin = new FileReader(fileName);
		BufferedReader in = new BufferedReader(fin);

		String[] lines = new String[5];

		//Read the 5 lines
		for (int i = 0; i < 5; i++) {
			try {
				lines[i] = in.readLine();
			} catch (NumberFormatException nfe) {
				throw new NumberReadingException("Bad Number Format.  Make sure it's an Integer.");
			}
				
			if (lines[i] == null) throw new NumberReadingException("Number of lines is probably less than 5.");
		}
		
		//Now Print out the lines in reverse order
		for (int i = 4; i >= 0; i--) {
			System.out.println(lines[i]);
		}

		// Parse the next 5 lines and print the sum
		LineReverser lineReverser = new LineReverser();
		System.out.println("This is the Sum: " + lineReverser.CalSum(in));
		
		// clean up
		fin.close();
		System.out.println("DONE.");
		
		
		
		
	}

	
	public int CalSum(BufferedReader in) throws IOException, NumberReadingException{
		
		String nextLines[] = new String[5];
		int total = 0;
		
		for (int i = 0; i < 5; i++) {
			nextLines[i] = in.readLine();
			try {
				total = total + Integer.parseInt(nextLines[i]);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				throw new NumberReadingException("This is probably not a number.");
			}
		}
		return total;
	}
}
