/**********************************************************************
 * ti library's routine to check validity of a date string
 *
 * $Author: brlewis $
 * $Source: /afs/net.mit.edu/dev/project/techinfodev/src/libti/RCS/gooddate.c,v $
 * $Header: /afs/net.mit.edu/dev/project/techinfodev/src/libti/RCS/gooddate.c,v 3.0 93/03/03 16:29:07 brlewis Exp $
 *
 * Copyright 1993 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/

#include <mit-copyright.h>

#ifndef lint
static char rcsid_ti_gooddate_c[] = "$Header: /afs/net.mit.edu/dev/project/techinfodev/src/libti/RCS/gooddate.c,v 3.0 93/03/03 16:29:07 brlewis Exp $";
#endif /* lint */

#include <string.h>
#include <ctype.h>
#include <ti/ti.h>
#include <time.h>

/**********************************************************************
 * ti_gooddate(TI *tp, char *date_string, int n_months)
 *	caller should have opened tp
 *	date string should be of form "McDcY" or "McD"
 *	where M is month, D day, Y year (variable length)
 *	c is any non-digit character
 *
 * - changes c to :
 * - makes sure at least M and D are there
 * - makes sure date is at least n_months recent
 **********************************************************************/

#define ABORT(code) { strcpy(ti_context, date_string); return(code); }

long
ti_gooddate(tp, date_string, n_months)
     TI *tp;
     char *date_string;
     int n_months;
{
  register char *tmp1;
  int month, day, year, age_months;
  struct tm *now;
  long t_now;

  /* get current time */
  t_now = time(0);
  now = (struct tm *)localtime(&t_now);
  /* tm->tm_mon+1, tm->tm_mday, tm->tm_year */

  /* get month */
  if (!isdigit(date_string[0])) ABORT(TI_ERR_DATEFMT);
  month = atoi(date_string);

  /* skip ahead to day */
  tmp1 = date_string;
  while (isdigit(*tmp1)) tmp1++;
  tmp1++;
  if (!isdigit(*tmp1)) ABORT(TI_ERR_DATEFMT);
  day = atoi(tmp1);

  /* skip ahead to year */
  while (isdigit(*tmp1)) tmp1++;
  if (!(*tmp1)) ABORT(TI_ERR_DATEFMT);
  tmp1++;
  if (!isdigit(*tmp1)) ABORT(TI_ERR_DATEFMT);
  year = atoi(tmp1);

  age_months = 12 * (now->tm_year - year) + (now->tm_mon+1 - month);
  if (age_months < 0) ABORT(TI_ERR_DATEFUTURE);
  if (age_months > n_months) ABORT(TI_ERR_DATEOLD);
  return(0L);
}
