/*************************************************************
 timeconv.c
 UT time data structure manipulation subroutines.
 Author: K. Scholberg Feb 1998
 *************************************************************/


#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include "uttime.h"


struct UTall dt_to_UTall(int * datetime)
{
  /* Convert datetime in 3 integer format to UTall structure */

  int day,month,year;
  int hour,minute,second;
  int nanosec;
  struct UTall uttime;
  struct tm ut;

  int idmonth[12]={31,28,31,30,31,30,31,31,30,31,30,31};
  int ytest;   /* For leap year check */
  int i;

  /* Fill the time_t part of the structure */
  /* Separate year, month, day */

  ut.tm_mday = datetime[0]/10000;
  ut.tm_mon = (datetime[0]-ut.tm_mday*10000)/100 -1;
  ut.tm_year = datetime[0]%100;
  /* Only works for 1950 to 2050 ! */

  if (ut.tm_year<50) ut.tm_year+=100;

  /* Separate hour, minute, second */

  ut.tm_hour = datetime[1]/10000;
  ut.tm_min = (datetime[1] - ut.tm_hour*10000)/100;
  ut.tm_sec = datetime[1]%100;


  /* Days since beginning of year */

  /* Leap year check, valid between 1901 and 2099 */

  ytest = ut.tm_year%4;
  if (ytest == 0)
  {
    idmonth[1] = 29;
  }
  else
  {
    idmonth[1] = 28;
  }


  ut.tm_yday = 0;
  for (i=0;i<ut.tm_mon;i++)
  {
    ut.tm_yday +=idmonth[i];
  }

  ut.tm_yday += ut.tm_mday -1;

  /* Weekday-- dummy value for now, 0=Sunday -- need to fix this */
  ut.tm_wday = 0;
  ut.tm_isdst = 0;

  /* Note: nanosec variable is actually 100 ns ticks */

  uttime.basetime =  ut;
  uttime.nanosec = datetime[2];

/*  printf("asctime %s\n",asctime(&ut)); */

  return uttime;

}

/*------------------------------------------------------------*/

float rough_diff(struct UTall ut2, struct UTall ut1)
{

  /* Get time difference t2 - t1 to the nearest second */


  time_t t1,t2;

  t1 = mktime(&(ut1.basetime));
  t2 = mktime(&(ut2.basetime));

  return (float)difftime(t2,t1);

}

/*------------------------------------------------------------*/

double precise_diff(struct UTall ut2, struct UTall ut1)
{

  /* Get time difference t2 - t1 to the nearest nanosecond */


  time_t t1,t2;

  double diff;
  double nandiff;

  t1 = mktime(&(ut1.basetime));
  t2 = mktime(&(ut2.basetime));

  /* Difference in base times */
  diff = difftime(t2,t1);

  nandiff = ut2.nanosec - ut1.nanosec;
  diff += nandiff/1.e9;
  
  return diff;
}

/*------------------------------------------------------------ */

time_t get_current_time()
{

  /* Get the current time in tm structure format */

  struct tm* timenow;
  time_t calendar_time;

  calendar_time = time(NULL);

  timenow = gmtime(&calendar_time);

/*  fprintf(stdout,"Current time: %s\n",asctime(timenow)); 
  fflush(stdout); */

  return calendar_time;

}

