/*
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * Author:
 *         Johannes Franz
 *
 * $Id: utils.c,v 1.2 2005/11/21 09:39:01 kutzner Exp $
 *
 */

#include <iostream>
#include "utils.h"
#include <unistd.h>
#include <signal.h>
#include <assert.h>


using namespace std;


cRaiseTimer::cRaiseTimer(void (*handler)(int)) 
{
    
    Action = handler;
    sa_new.sa_handler = Action;
    sigemptyset(&sa_new.sa_mask);
//    sigaddset(&sa_new.sa_mask, SIGALRM);
    sa_new.flags = 0;

    sigaction(SIGALRM, &sa_new, &sa_old);
    alarm(0);
}

cRaisTimer::~cRaiseTimer()
{
    sigaction(SIGALRM, &sa_old, 0);
}

void cRaiseTimer::setTimer(int sec, job_t job)
{
    unsigned int remaining_sec = alarm(0);
    int diff = next_timer - remaining_sec;
    next_timer = remaining_sec;
    subList(diff);
    
    Timerjob tj = { sec, job };

    if (sec < next_timer) {
	next_timer = sec;
	curjobs.clear();
	curjobs.push_back(job);
	int rem = alarm(sec);
	assert(rem = remaining_sec);
	
    } else if (sec = next_timer) {
	curjobs.push_back(job);
    } else {
	
    }
	
	
    timerlist.push_back(tj);
}

void cRaiseTimer::subList(int diff)
{
    while (timerlist != Null) {
	timerlist.sec = timerlist.sec - diff;
	timerlist = timerlist.Next();
    }
}

void cRaiseTimer::setTimerInt(int begin, int end)
{
    srand(time(NULL));
    int timer;
    timer = rand() % (begin - end + 1);
    timer += begin;

    setTimer(timer);
}


void cRaiseTimer::clearTimer() 
{
    alarm(0);
}

time_t getRemainingSec()
{
    time_t rem = alarm(0);
    alarm(rem);
    return rem;
}

