#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>

#define BILLION 1000000000L

int printCurrentTime()
{
    double accum;
    struct timespec t;
    if(clock_gettime(CLOCK_MONOTONIC, &t) == -1)
    {
        perror("printCurrentTime: clock gettime");
        return EXIT_FAILURE;
    }
    accum = t.tv_sec + ((double)(t.tv_nsec)/(double)BILLION);
    printf("Current Time: %lf\n", accum);
    return EXIT_SUCCESS;

}
int main(int argc, char *argv[])
{
    int retVal = EXIT_SUCCESS;
    int delay;
    struct timespec t;
    pthread_mutex_t dummyMutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t  dummyCond;
    pthread_condattr_t dummyAttr;

    if(argc != 2)
    {
        perror("Usage: cond_test <delay-in-secs>");
        return EXIT_FAILURE;
    }
    delay = atoi(argv[1]);

    printf("Testing pthread_cond_timedwait with delay of %d\n", delay);

    
    pthread_condattr_init(&dummyAttr);
    pthread_condattr_setclock(&dummyAttr, CLOCK_MONOTONIC);
    pthread_cond_init(&dummyCond, &dummyAttr);
//    pthread_cond_init(&dummyCond, NULL);

    clock_gettime(CLOCK_MONOTONIC, &t);
    t.tv_sec += delay;

    // Lock the mutex
    pthread_mutex_lock(&dummyMutex);

    // Print the current time
    retVal = printCurrentTime();
    if(retVal != EXIT_SUCCESS)
    {
        return retVal;
    }
    
    // Wait on cond var
    retVal = pthread_cond_timedwait(&dummyCond, &dummyMutex, &t);
    printf("retVal = %d:%s\n", retVal, strerror(retVal));
    
    // Print the current time
    retVal = printCurrentTime();
    if(retVal != EXIT_SUCCESS)
    {
        return retVal;
    }

    // Unlock the mutex
    pthread_mutex_unlock(&dummyMutex);


    printf("Hello, World.  This is cond_test!\r\n");
    return EXIT_SUCCESS;
}

