/*
**	Functions that do misc. date and time calculations. 
**
**	This work is derived from GNU software, so you should read
**	the GNU license agreement if you are plannning to use
**	them in commercial software.
*/
#include <stdio.h>
#include <common/portability.h>

#include "timelib.h"

/*
**	Return TRUE if the given year is a Gregorian leap year.
*/
int
is_leap_year (year)
	int	year;
{
    return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
}

/*
**	Day number of the given date.  The first day of the year is day 
**	number 1 and the last day is either 365 or 366.
*/
int
day_number (day, month, year)
	int 	day, 
		month, 
		year;
{
    int result;

    result = day + 31 * (month - 1);
    if (month > 2)
    {
	result -= (23 + 4 * month) / 10;
	if (is_leap_year (year))
	    result += 1;
    }

    return result;
}

/*
**	Return the length in days of a given month.
*/
int
month_length (month, year)
	int 	month, 
		year;
{
    static int length[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    if (month == 2 && is_leap_year(year))
	return 29;
    else
	return length[month - 1];
}

/*
**	The number of seconds we are since midnight.
*/
int
seconds_since_midnight ()
{
	struct timeval t;
	struct tm *tmp;

	gettimeofday (&t, (struct timezone *) NULL);
	tmp = localtime (&(t.tv_sec));

	return ((tmp->tm_hour * 3600) + (tmp->tm_min * 60) + tmp->tm_sec);
}

/*
**	The number of seconds time is from Greenwich mean time (w/re to 
**	our current location).
*/
int
seconds_from_gmt (time)
	time_t	time;
{
        long    localTime,
                gmtTime;

        localTime = 60*60*24;   /* Epoch + 1 day */
        gmtTime = mktime(gmtime((time_t *)&localTime));
        return(localTime - gmtTime);
}
