import java.util.*;
import java.io.*;

/**
 * This class provides a simple main for running on cat and mouse
 * data.
 */
public class CatMouse {

    /** This is a simple main.  When invoked, the first argument gives
     * the name of the file containing a description of the MDP, and
     * the second optional argument gives the desired number of steps
     * in the cat-mouse animation.  This main simply loads the MDP,
     * runs both value iteration and policy iteration on it, runs
     * policy evaluation on the returned policy, prints out the
     * optimal policies and utilities, and finally animates the cat
     * chasing the mouse.  Note that this animation will almost
     * certainly crash if run on MDP's other than those for a cat
     * chasing a mouse.  If the second argument is omitted, the
     * cat-mouse animation is skipped.
     */
    public static void main(String argv[]) throws FileNotFoundException, IOException {
	double discount = 0.95;

	// parse options
	int anim_steps = -1;
	String err_msg = "arguments: <filename> [<num.animation.steps>]";
	if (argv.length == 0) {
	    System.err.println(err_msg);
	    return;
	}	    

	if (argv.length > 1) {
	    try {
		anim_steps = Integer.parseInt(argv[1]);
	    } catch (NumberFormatException e) {
		System.err.println(err_msg);
		return;
	    }
	}		
	String filename = argv[0];

	// build MDP
	Mdp mdp = new Mdp(filename);

	// run value iteration
	ValueIter vpi = new ValueIter(mdp, discount);

	// run policy iteration
	PolicyIter ppi = new PolicyIter(mdp, discount);

	// evaluate returned policy
	double[] util = (new PolicyEval(mdp, discount, ppi.policy)).utility;

	// print results
	System.out.println("Optimal policies:");
	for(int s = 0; s < mdp.numStates; s++)
	    System.out.println(mdp.stateName[s] + "\t" +
			       mdp.actionName[vpi.policy[s]] + "\t" +
			       mdp.actionName[ppi.policy[s]] + "\t" +
			       vpi.utility[s] + "\t" + util[s]);
	System.out.println();
	System.out.println();

	// animate cat chasing mouse
	if (anim_steps > 0) {
	    CatMouseAnimator cm = new CatMouseAnimator(mdp);
	    cm.animate(ppi.policy, anim_steps);
	}
    }

}
