/*//////////
//
//  alarmlib.c
//
//      AUTHOR: Russell Lowke
//   CSCIE-215: Assignment Four
//
//
// Description: timer functions for higher resolution clock
//              
//
//       Notes: adapted from Bruse's alarmlib (version 98.03.16)
*/


// include header
#include        "alarmlib.h"

extern int errno;


/*
//  set_ticker
//
//     arranges for the interval timer to issue
//     SIGALRM's at regular intervals
//
//     args:  n_msecs      --  in milliseconds, converted into micro seoncds
*/
void set_ticker( int n_msecs )
{
	struct itimerval new_timeset, old_timeset;
	long	n_sec, n_usecs;

	n_sec = n_msecs / 1000 ;
	n_usecs = ( n_msecs % 1000 ) * 1000L ;

	new_timeset.it_interval.tv_sec  = n_sec;        /* set reload */
	new_timeset.it_interval.tv_usec = n_usecs;	/* new ticker value */
	new_timeset.it_value.tv_sec     = n_sec  ;	/* store this */
	new_timeset.it_value.tv_usec    = n_usecs ;	/* and this */

	if ( setitimer( ITIMER_REAL, &new_timeset, &old_timeset ) != 0 ){
		printf("Error with timer..errno=%d\n", errno );
		exit(1);
	}

}



/*
//  millisleep
//
//     set a flag in the [*info] struct to ON or OFF
//
//     args:  n            --  period for millisleep
*/
void millisleep( int n )
{
        static void tickerOff();             /* handler for ticker off */

	signal( SIGALRM , tickerOff);	     /* set handler */
	set_ticker( n );                     /* set alarm timer */
        pause();                             /* wait for sigalrm */
}



/*
//  tickerOff
//
//     turns off ticker
*/
static void tickerOff()
{
	set_ticker( 0 );			        
}

