/*
     extract - A network log processor
     Copyright (C) 1993 Douglas Lee Schales, David K. Hess, David R. Safford

     Please see the file `COPYING' for the complete copyright notice.

timesub.c - 03/20/93

*/
#include <sys/types.h>
#include <sys/time.h>
#include "timesub.h"

extern time_t time(time_t *);

int
getyear(void)
{
     time_t t;
     struct tm *tmb;

     t = time(0);

     tmb = localtime(&t);

     return tmb->tm_year;
}

unsigned long
makedate(int month, int mday, int year)
{
     time_t t;
     struct tm *tmb;
     struct tm tmbuf;

     t = time(0);

     tmb = localtime(&t);
     
     tmbuf.tm_isdst = -1;
     tmbuf.tm_sec = 0;
     tmbuf.tm_min = 0;
     tmbuf.tm_hour = 0;
     tmbuf.tm_mday = mday;
     tmbuf.tm_mon = month - 1;
     tmbuf.tm_year = year-1900;
     tmbuf.tm_wday = 0;
     tmbuf.tm_yday = 0;
     return mktime(&tmbuf);
}

unsigned long
timeofday(unsigned long sofday, int hour, int min, int sec)
{
     struct tm *tmb;
     struct tm tmbuf;
     time_t tsday = sofday;
     tmb = localtime(&tsday);
     (void)memcpy((void *)&tmbuf, (void *)tmb, sizeof(struct tm));

     tmbuf.tm_isdst = -1;
     tmbuf.tm_hour = hour;
     tmbuf.tm_min = min;
     tmbuf.tm_sec = sec;
     return mktime(&tmbuf);
}

unsigned long
today(void)
{
     time_t t;
     struct tm *tmb;
     struct tm tmbuf;

     t = time(0);

     tmb = localtime(&t);
     memcpy(&tmbuf, tmb, sizeof(struct tm));

     tmbuf.tm_isdst = -1;
     tmbuf.tm_sec = 0;
     tmbuf.tm_min = 0;
     tmbuf.tm_hour = 0;
     return mktime(&tmbuf);
}


unsigned long
yesterday(void)
{
     time_t t;
     struct tm *tmb;
     struct tm tmbuf;

     t = time(0);

     tmb = localtime(&t);
     (void)memcpy((void *)&tmbuf, (void *)tmb, sizeof(struct tm));

     tmbuf.tm_isdst = -1;
     tmbuf.tm_sec = 0;
     tmbuf.tm_min = 0;
     tmbuf.tm_hour = 0;
     tmbuf.tm_mday--;
     tmbuf.tm_yday--;
     tmbuf.tm_wday=0;
     return mktime(&tmbuf);
}

static
int daycnts[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
     
int
validmday(int month, int mday, int year)
{
     int febdays = 28;

     if(month != 2)
	  return mday > 0 && mday <= daycnts[month-1];
     if(!(year % 4) && (!(year % 100) || year % 400))
	  febdays = 29;

     return mday > 0 && mday <= febdays;
}
