import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Collections;

/*
 * HighestScores - a class for storing the highest scores for the space
 *                 invaders game.  Note this uses an array list of 'score'
 *                 this list is maintained in sorted order as elements are
 *                 added to the arraylist.
 * Eric McCreath - 2006                
 */

public class HighestScores extends ArrayList<Score> {

	public boolean add(Score s) {
		boolean res = super.add(s);
		Collections.sort(this);	
		return res;
	}
	
	static public HighestScores load(String filename) throws IOException {
		StreamTokenizer stream = new StreamTokenizer(new FileReader(filename));
		stream.nextToken();
		return parse(stream);
	}
	
	
	static HighestScores parse(StreamTokenizer stream) throws IOException {
		HighestScores res = new HighestScores();
		
		ParseTools.parseWord(stream,"begin");
		
		while (!ParseTools.isWord(stream,"end")) {
			res.add(Score.parse(stream));
		}
		
		ParseTools.parseWord(stream,"end");
		
		return res;
	}
	
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("begin\n");
		for (Score s : this) {
			sb.append("  " + s.toString() + "\n");
		}
		sb.append("end\n");
		return sb.toString();
	}
	
	public static void main(String[] args) throws IOException {
		HighestScores scores = load("highest.txt");
		System.out.println(scores);
	}

}

