/* @(#)year.c	1.2  99/10/22 */
/*
 *  include files
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 *  function prototypes
 */

long ymdmjd( );
void mjdymd( );

/*
 *  global definitions and variables
 */




int main( int argc, char **argv )
/********1*********2*********3*********4*********5*********6*********7*********
 * name:            year
 * version:         9910.22
 * written by:      M. Schenewerk
 * purpose:         Converts the year/month/day <-> year
 *
 * input parameters
 * ----------------
 *
 * output parameters
 * -----------------
 *
 *
 * local variables and constants
 * -----------------------------
 *
 * global variables and constants
 * ------------------------------
 *
 *
 * called by:       
 *
 * calls:           
 *
 * include files:   
 *
 * references:      
 *
 * comments:        
 *
 * see also:        
 *
 ********1*********2*********3*********4*********5*********6*********7*********
 *:modification history
 *:9401.03, MSS, Creation.
 *:9910.22, MSS, Make computation a little more clear and robust.
 *:              Force output to always display a four-digit year.
 ********1*********2*********3*********4*********5*********6*********7*********/

{
   char *pgm;
   char *ptr;
   float year;
   int iday;
   int imon;
   int iyr;
   long mjd;

   static int c1= 1, c12= 12, c31= 31;
   static float round=0.5/366.0;

   pgm= argv[0];
   while( (ptr= strpbrk( pgm, "/\\:" )) != NULL )
     pgm= ptr+1;

   if( argc > 4 || argc < 2 ) {
      printf("%s(1.2): Converts the year/month/day <-> year\n", pgm );
      printf("Usage: %s yy mm dd  or\n", pgm);
      printf("Usage: %s yy doy    or\n", pgm);
      printf("Usage: %s yy.yyyyy\n", pgm);
      exit(0);
   }

   if( argc == 4 ) {
      iyr= atoi( argv[1] );
      imon= atoi( argv[2] );
      iday= atoi( argv[3] );
      mjd= ymdmjd( iyr, imon, iday );
      mjdymd( mjd, &iyr, &imon, &iday );

      mjd= ymdmjd( iyr, c1, c1 );
      year= (float)iyr
         + (float)(ymdmjd( iyr, imon, iday )-mjd)
         / (float)(ymdmjd( iyr, c12, c31 )-mjd+1L);
      printf( "%f\n", year );
   } else if( argc == 3 ) {
      iyr= atoi( argv[1] );
      iday= atoi( argv[2] );
      mjd= ymdmjd( iyr, c1, c1 ) + (long)iday - 1L;
      mjdymd( mjd, &iyr, &imon, &iday );

      mjd= ymdmjd( iyr, c1, c1 );
      year= (float)iyr
         + (float)(ymdmjd( iyr, imon, iday )-mjd)
         / (float)(ymdmjd( iyr, c12, c31 )-mjd+1L);
      printf( "%f\n", year );
   } else {
      year= atof( argv[1] );
      if( year < 79.0 )
        year= year + 2000.0;
      else if( year < 100.0 )
        year= year + 1900.0;

      iyr= (int)year;
      year= year - (float)iyr;
      mjd= ymdmjd( iyr, c1, c1 );
      mjd= mjd
         + (long)((year+round)
         * (float)(ymdmjd( iyr, c12, c31 )-mjd+1L));
      mjdymd( mjd, &iyr, &imon, &iday );
      printf( "%.2d %.2d %.2d\n", iyr, imon, iday );
   }

   exit( 0 );
}
