/* convdate version 1.3 */

/* Usage convdate -{c,m,a} filename  -- returns the create, modified, or
 *                                      accessed time of a file in canonical
 *                                      form.
 *       convdate -d date            -- takes a date of the type returned by
 *                                      `date` and converts it to canonical
 *                                      form.
 *       convdate -y date            -- takes a date of the type returned by
 *                                      `date` and returns it in the form
 *                                      MMDDYY
 *
 * Canonical form is defined as
 * YEAR * 365 +
 * sum (i= 1..MONTH)[ days_in_month[i] ] + DAYS +
 * YEAR/4 - YEAR/100 + YEAR/400
 * This should take into account leap years and such correctly I think.
 * This canonical form should map each day to a discreet interger with 1
 * being the first of january in the year 1.
 *
 * Compile Instructions:
 *   cc -o convdate convdate.c
 *
 */
/* This program was written by Joseph Traub (jtraub@cs.cmu.edu).
 * Feel free to use it, hack it, have sex with it, or whatever.
 * The author disclaims any responsibility for above said actions with
 * this program or any derivitive thereof.
 */


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>

char *mo_name[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int d_in_m[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

void main (int argc, char **argv)
{
  int month, day, year;
  int temp, i;
  struct stat buf;
  struct tm *t;

  if(argc < 2) exit(0);

  switch(argv[1][1]) {
    case 'd':
      if((--argc) < 6) exit(0);
      for (month = 1; month < 13; month++)
         if(!strcmp(argv[3], mo_name[month-1])) break;
      day = atoi(argv[4]);
      year = atoi(argv[7]);
      break;
    case 'c':
    case 'm':
    case 'a':
      if(stat(argv[2], &buf))
        exit(0);
      if(argv[1][1] == 'c')
        t = localtime(&buf.st_ctime);
      else if(argv[1][1] == 'm')
        t = localtime(&buf.st_mtime);
      else
        t = localtime(&buf.st_atime);
      month = t->tm_mon+1;
      year = t->tm_year+1900;
      day = t->tm_mday;
      break;
    case 'y':
      if((--argc) < 6) exit(0);
      for (month = 1; month < 13; month++)
         if(!strcmp(argv[3], mo_name[month-1])) break;
      day = atoi(argv[4]);
      year = atoi(argv[7]+2);
      fprintf(stdout,"%02d%02d%02d\n",month,day,year);
      exit(0);
    default:
      exit(0);
  }
  for(i = 1, temp = 0; i < month; i++)
    temp += d_in_m[i-1];
  fprintf(stdout, "%d\n", year*365 + temp + day + year/4 - year/100 +
                          year/400);
}
