/* timers
 *
 * Shorthand routines for setting timers and reading out an elapsed time
 *
 * Based on code created by Henry Walker
 * Revised:
 *  Jerod Weinman,  24 June 2008
 */
#include "timers.h"
#include <stdio.h>
/* Set interval timer with specified second and microsecond value
 *
 * Parameters:
 *  which : specifies timer (ITIMER_REAL, ITIMER_VIRTUAL, ITIMER_PROF)
 *  sec   : initial value of seconds
 *  usec  : initial value of microseconds
 *
 * Preconditions:
 *  sec and usec are non-negative
 *
 * Postconditions: 
 *  Appropriate timer is set and any previous timer settings are overriden
	* 
	* Produces: 
	*  On success, zero is returned. On error, -1 is returned
	*  and errno is set appropriately.
 */
int setTimer(int which, long sec, long usec)
{
     struct itimerval ival;

     /* Interval */
     ival.it_interval.tv_sec  = sec;  /* initialize second field */
     ival.it_interval.tv_usec = usec; /* initialize microsecond field */
     
     /* Current value */
     ival.it_value.tv_sec     = sec;  /* reset second field */
     ival.it_value.tv_usec    = usec; /* reset microsecond field */

     return setitimer(which, &ival, NULL);
}

/* Get elapsed time in (fractional) seconds
 *
 * Parameters:
 *  which : specifies timer (ITIMER_REAL, ITIMER_VIRTUAL, ITIMER_PROF)
 *  sec   : initial value of seconds for timer being queried
 *
	* Produces: 
	*  On success, time is returned. On error, -1 is returned
	*  and errno is set appropriately.
 */
float getTime(int which, long sec)
{
     struct itimerval ival;

     /* Fetch the value of appropriate timer. */
     if (-1 == getitimer(which, &ival))
										return -1;

    /* We need to subtract 1 when computing the elapsed number of seconds 
     * because timers count down.  e.g., if we inititally set the timer to 
     * 9 s 0 microsec, then after 5000 microsec have elapsed the current
     * timer value will read 8 sec 994999 microsec.  To correctly recover
     * the elapsed time, one must compute 9 - 8 - 1 = 0 seconds 
     * and 999999 - 5000 = 994999 microsec.
     * 
     * Note that this will sometimes give times that are slightly less
     * than 0.  We think this occurs when the elapsed time is less than 
     * the OS timer resolution, so that the timer interrupt has not yet
     * fired and the value of seconds has not yet been decremented.
     */

					printf("sec=%d\ttv_sec=%d\n",sec,ival.it_value.tv_sec);
					printf("tv_usec=%d\n",ival.it_value.tv_usec);

     return
          (float)(sec  - ival.it_value.tv_sec - 1) +
          (float)(MAX_USEC - ival.it_value.tv_usec) / (float)MAX_USEC;


}
