/** DivisionMaker.java divides a group of students into two divisions.
 * @author Joel Adams, for Alice+Java.
 */

import java.util.*;      // ArrayList, Scanner, ...
import java.io.*;        // File, ...

public class DivisionMaker {	
	public void readStudents(String inputFile) {
		myStudents = new ArrayList<Student>();
		Scanner fin = null;
		try { 
			fin = new Scanner( new File(inputFile) ); 
			while ( fin.hasNext() ) {
				Student student = new Student();
				student.read(fin);
				myStudents.add(student);
			}
		} catch (FileNotFoundException fnfe) { 
			fnfe.printStackTrace(); 
		} finally {
			fin.close();
		}
	}
	
	public void makeDivisions() {
		double median = findMedian();
		myDivisionAA = new LinkedList<Student>();
		myDivisionA = new LinkedList<Student>();
		for (Student stu : myStudents) {
			if (stu.getScore() > median) {
				myDivisionAA.add(stu);
			} else {
				myDivisionA.add(stu);
			}
		}
	}
	
	public double findMedian() {
		Collections.sort(myStudents);
		int numStudents = myStudents.size();
		int median, midIndex1, midIndex2;
		midIndex1 = numStudents / 2;
		if ( numStudents % 2 != 0 ) { // size is odd
			median = myStudents.get(midIndex1).getScore();
		} else {                      // size is even
			midIndex2 = midIndex1 - 1;
			median = ( myStudents.get(midIndex1).getScore() +
			           myStudents.get(midIndex2).getScore() ) / 2;
		}
		return median;
	}
	
	public LinkedList<Student> getDivisionA() { return myDivisionA; }
	public LinkedList<Student> getDivisionAA() { return myDivisionAA; }
	
	private ArrayList<Student> myStudents = null;
	private LinkedList<Student> myDivisionA = null;
	private LinkedList<Student> myDivisionAA = null;
	
	public static void main(String[] args) {
		System.out.println("To make the 'A' and 'AA' divisions,");
		System.out.print(" enter the name of the input file: ");
		Scanner kbd = new Scanner(System.in);
		String inFileName = kbd.nextLine();
		DivisionMaker dm = new DivisionMaker();
		dm.readStudents(inFileName);
		dm.makeDivisions();
		System.out.println("\nDivisionA:\n" + dm.getDivisionA() );
		System.out.println("\nDivision AA:\n" + dm.getDivisionAA() );
	}
}
