#ifndef _TIMER_H
#define _TIMER_H

#include "basic.h"

extern "C" {
#include <sys/timers.h>
int getclock(int, struct timespec *);
}

inline float diff_time (struct timespec &t0, struct timespec &t1) {
    return (t1.tv_sec-t0.tv_sec)+(t1.tv_nsec-t0.tv_nsec)/1e9;
    // preserved significant digits by subtracting separately
}

class timer {
public:

    //Abstract: A timer measures time intervals.

    timer() {reset();}
    // Creates a timer that reads 0 and is paused.

    inline void reset() {
	// Modifies "this"
	// Effects  pauses the timer and resets its value to 0.
	running = FALSE;
	accumulated = 0.0;
    }

    inline void start() {
	// Modifies "this"
	// Effects  Starts the timer (unpauses it).
	if (!running) {
	    running = TRUE;
	    getclock(TIMEOFDAY, &t0);
	}
    }

    inline void pause() {
	// Modifies "this"
	// Effects  Pauses the timer.
	if (running) {
	    running = FALSE;
	    getclock(TIMEOFDAY, &t1);
	    accumulated += diff_time(t0, t1);
	}
    }

    inline float elapsed() {
	// Effects Returns the seconds for which timer has run.
	//         i.e., the cumulative period between starts and pauses
	//         since the timer was created or last reset.
	if (running) {
	    getclock(TIMEOFDAY, &t1);
	    float runtime = diff_time(t0, t1);
	    return (accumulated+runtime);
	} else {
	    return accumulated;
	}
    }

private:
    struct timespec t0, t1;
    float accumulated;
    bool running;
};


#endif  /* _TIMER_H */
