/**
 * Main outer class for Lists/Sublists problem.
 * @author dlevine
 *
 */

class Lists{

	public static boolean VERBOSE = false;
	
	// (this holds list being built during read/build operation)
	static IList workList;
	
	public static void main(String[] args) {
		try {
			// arrange for creating an appropriate String Tokenizer.
			// If arg is given, it's name of file to use. (or could
			// be explicit "keyboard", which is also the default)
			String file = args.length > 0? args[0] : "keyboard";
			if (VERBOSE)
				System.out.println("Starting with file " + file);
			Tokenizer tz = new Tokenizer(file);

			// read an Item (atom or list), print it, repeat.
			while (! tz.atEOF()){
				workList = null;    // remove any leftovers from last time
				tz.getNext();
				Item root = mkItem(tz);
				System.out.println();
				System.out.print("Root: ");
				root.print();
				System.out.println();
			}
		} 
		catch (Exception e) {
			System.out.println("OOPS, problem - exception ");
			e.printStackTrace();
		}
		finally {
			System.out.println("...All done");
		}
		;
	}
	
/** Top-level make an item -- atom or list
 * 
 * @param tz
 * @return
 */
	private static Item mkItem(Tokenizer tz) {
		Token t = tz.getCurrent();
		//See if it's a list or an atom
		if ("(".equals(t.getSval())) {
			// a list.  First, create structure which will hold the list,
			// and anchor it at workList.  List is empty at this point
			workList = new IList();
			// Second, process the Items, filling in the IList structure
			workList.readList(tz);
			// Having read a whole list, the terminating ')' should be current.
			assert ")".equals(tz.getCurrent().getSval());
			
			return workList;
		} else {
			Item i = new Atom(t);
			return i;
		}

	}

}