/* ======================================================================
**
** GeoMag Time functions
**
** History:
**       Date       Who      Description
**      ------      ---      --------------------------------------------
**    07/22/2003    SL      Create from seabed time_utils
** ======================================================================
*/

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <math.h>


double get_utime(void)
{ struct timeval  tv;
  struct timezone tz;
  double t;

  time_t  current_time;
  struct tm  *tm;

  current_time = time(NULL);
  tm = gmtime(&current_time);

  gettimeofday(&tv, &tz);
  t = (((double)tv.tv_sec) + (((double)tv.tv_usec) *0.000001));

  return t;
}


int utime2dsltime_str(double time, char *str)
{ struct tm  *tm;
  time_t      current_time;
  double      total_secs;
  double      subsec;

  // Use time if specified (ie; time >= 0),
  // otherwise use current time
  if (time >= 0)  {total_secs = time;}
             else {total_secs = get_utime();}
  
  current_time = (time_t)total_secs;
  tm = gmtime(&current_time);

  subsec = total_secs - (int)total_secs;  // keep float-pt resolution
  
  sprintf(str,"%04d/%02d/%02d %02d:%02d:%05.2f",
		      (int) tm->tm_year+1900,
		      (int) tm->tm_mon+1,
		      (int) tm->tm_mday,
		      (int) tm->tm_hour,
		      (int) tm->tm_min,
		      (int) tm->tm_sec + subsec);
  return 1;
}



/* ----------------------------------------------------------------------
** sec2hhmmss - takes total seconds and returns d hh:mm:ss
** ---------------------------------------------------------------------- 
*/
int sec2hhmmss(int sec, char *str)
{ int dy, hr, mn, sc;

  dy = (int)(sec/86400.0);
  hr = (int)((sec - (dy*86400.0))/3600.0);
  mn = (int)((sec - (dy*86400.0) - (hr*3600.0))/60.0);
  sc = sec - (dy*86400.0) - (hr*3600.0) - (mn*60.0);
  if (dy == 0) 
    {return(sprintf(str,"%02d:%02d:%02d",hr,mn,sc));
     }
  else
    {return(sprintf(str,"%d %02d:%02d:%02d",dy,hr,mn,sc));
     }

  return 0; // shouldn't get here
}





