/*-------------------------------------------------------------------------
   Copyright (C) 1994-1997, Massachusetts Institute of Technology.
	 Sea Grant Autonomous Underwater Vehicles Laboratory.
			 All rights reserved.
  $Id: o2_time0.c,v 1.3 1997/05/27 22:40:15 bamoran Exp $
  -----------------------------------------------------------------------*/

#include <math.h>
#include <time.h>

#include "mex.h"		/* MATLAB */

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    struct tm time_str;
    time_t time_utc;
    int error = 0;
				/* require 1 argument, either string
				   or 1x6, year is two digits only */
    if ( nrhs < 1 )
	mexErrMsgTxt( "usage: time0( [YY MM DD hh mm ss] ) or "
		      "time0 'YY/MM/DD hh:mm:ss'" );

				/* stuff the tm structure */
    if ( mxIsString(prhs[0]) )
    {
	char *p;
	int n;
	n = mxGetN(prhs[0]) + 1;
	p = mxCalloc( n, sizeof(char) );
	mxGetString( prhs[0], p, n );
	if ( sscanf( p, "%u/%u/%u %u:%u:%u", &time_str.tm_year,
		     &time_str.tm_mon, &time_str.tm_mday,
		     &time_str.tm_hour, &time_str.tm_min,
		     &time_str.tm_sec ) != 6 )
	    error = 1;
	else			/* subtract 1 to get the number of months
				   since January */
	    time_str.tm_mon--;
	mxFree( p );
    }
    else if ( mxGetM(prhs[0])*mxGetN(prhs[0]) != 6 )
	error = 1;
    else
    {
	double *pr;
	pr = mxGetPr( prhs[0] );

	time_str.tm_year = pr[0];
	time_str.tm_mon  = pr[1] - 1;
	time_str.tm_mday = pr[2];
	time_str.tm_hour = pr[3];
	time_str.tm_min  = pr[4]; 
	time_str.tm_sec  = pr[5];
    }
    if ( error )
	mexErrMsgTxt( "usage: time0( [YY MM DD hh mm ss] ) or "
		      "time0 'YY/MM/DD hh:mm:ss'" );

				/* ensure GMT */
    putenv( "TZ=GMT" );
				/* get the utc value, with error check */
    if ( (time_utc = mktime(&time_str)) == -1 )
	mexErrMsgTxt( "time out of bounds?" );

				/* stuff the output value for matlab */
    plhs[0] = mxCreateDoubleMatrix( 1, 1, mxREAL );
    *(mxGetPr(plhs[0])) = time_utc;

    return;
}
