// Timer class for COMP2100
// Richard Walker, 2005
// $Revision: 1.2 $
// $Date: 2005/05/22 06:29:50 $

public class Timer {

    private native int ticks();
    private native int ticksPerSecond();

    static {
        System.loadLibrary("timer");
    }

    private int startTicks;
    private int stopTicks;
    private boolean running;

    //@ ensures !running();
    public Timer() {
        running = false;
    }

    public boolean running() {
        return running;
    }

    //@ requires !running();
    //@ ensures running();
    public void start() {
        if (running)
            throw new IllegalStateException("Timer already running");
        startTicks = ticks();
        running = true;
    }

    //@ requires running();
    //@ ensures !running();
    public void stop() {
        if (!running)
            throw new IllegalStateException("Timer not running");
        stopTicks = ticks();
        running = false;
    }

    //@ requires !running();
    public int elapsedTicks() {
        if (running)
            throw new IllegalStateException("Timer running");
        return stopTicks - startTicks;
    }

    //@ requires !running();
    public double elapsedCPUSeconds() {
        if (running)
            throw new IllegalStateException("Timer running");
        // Must cast the numerator to double to avoid an integer
        // division!
        return ((double)elapsedTicks())/ticksPerSecond();
    }

}

