/*************************************************************
 * WebMailFolder                                             *
 * COPYRIGHT 1998 by Norbert Kuemin <norbert.kuemin@gmx.net> *
 *************************************************************/

#define DATE_FILE
#include "wmf.h"

static char *monthname[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
	"Sep","Oct","Nov","Dec"};

time_t getutc(char *atime) {
    /* converting datestring to time_t */
    time_t iserialtime;
    int ioffset;
    char smonth[4], *tmpstr;
    struct tm timeval;
    
    if (config.DebugLevel & 1) printf(".getutc(%s)\n",atime);
    if (atime == NULL) return 0;
    tmpstr = atime;
    if (atime[3] == ',') tmpstr = tmpstr + 4; /* remove day of week */

    /* remove all spaces */
    while ((tmpstr[0] == ' ') && (tmpstr[0] != '\0'))
	tmpstr++;

    timeval.tm_mday = 0;
    while ((tmpstr[0] != ' ') && (tmpstr[0] != '\0')) {
	timeval.tm_mday = timeval.tm_mday * 10 + (tmpstr[0] - 48);
	tmpstr++;
    }
    if ((timeval.tm_mday < 1) || (timeval.tm_mday > 31)) return 0;

    /* remove all spaces */
    while ((tmpstr[0] == ' ') && (tmpstr[0] != '\0'))
	tmpstr++;

    strncpy(smonth,tmpstr,4);
    smonth[3] = '\0';
    timeval.tm_mon = 0;
    while (timeval.tm_mon < 11) {
        if(strcmp(smonth,monthname[timeval.tm_mon]) == 0) break;
        timeval.tm_mon++;
    }

    if (strlen(tmpstr)>3) tmpstr = tmpstr + 4; /* remove month */

    timeval.tm_year = 0;
    while ((tmpstr[0] != ' ') && (tmpstr[0] != '\0')) {
	timeval.tm_year = timeval.tm_year * 10 + (tmpstr[0] - 48);
	tmpstr++;
    }

    /* remove all spaces */
    while ((tmpstr[0] == ' ') && (tmpstr[0] != '\0'))
	tmpstr++;

    if (timeval.tm_year > 1900)
	timeval.tm_year = timeval.tm_year - 1900;

    if (strlen(tmpstr)>2) {
	timeval.tm_hour = (tmpstr[0] - 48) * 10 + (tmpstr[1] - 48);
	tmpstr = tmpstr + 3; /* remove hour */
    }

    if (strlen(tmpstr)>1) {
	timeval.tm_min = (tmpstr[0] - 48) * 10 + (tmpstr[1] - 48);
	tmpstr = tmpstr + 2; /* remove minutes */
    }

    if (tmpstr[0] == ':') {
        tmpstr++;
	if (strlen(tmpstr)>1) {
            timeval.tm_sec = (tmpstr[0] - 48) * 10 + (tmpstr[1] - 48);
            tmpstr = tmpstr + 2; /* remove seconds */
        }
    } else {
        timeval.tm_sec = 0;
    }

    ioffset = 0;

    /* remove all spaces */
    while ((tmpstr[0] == ' ') && (tmpstr[0] != '\0'))
	tmpstr++;

    if (strlen(tmpstr) > 4) {
        if((tmpstr[0] == '+') || (tmpstr[0] == '-')) {
            ioffset = ((tmpstr[1] - 48) * 10 + (tmpstr[2] - 48)) * 60;
            ioffset = ioffset + ((tmpstr[3] - 48) * 10 + (tmpstr[4] - 48));
	    ioffset = ioffset * 60;
	}
    }
    if (tmpstr[0] == '+') {
        iserialtime = mktime(&timeval) - ioffset;
    } else {
        iserialtime = mktime(&timeval) + ioffset;
    }
    if (config.DebugLevel & 2) printf("..getutc_Return(%d)\n",iserialtime);
    return iserialtime;
}
