/***********************************************************

  Function : Calculate the decimal week in a year and the
             seconds in the week.
  USAGE    : to_week <year_base> <decimal_day>
  INPUT    : year_base : 91 92 ...
           decimal_day : 0, 1, ... 356 (366)
  OUTPUT   : week in a year and seconds in the week.

                     (07/21/92 Mei)
*************************************************************/
#include "common.h"
#include "use_db.h"
#include "ioserv.h" /* yr4digit */

#if PROTOTYPE_ALLOWED
int main(int argc, char *argv[])
#else
int main(argc, argv)
int  argc;
char *argv[];
#endif
{
   double day, secondth;
   int    year, weekth, numl_year, s_day;

   if (argc != 3)
   {
      printf("\nUsage: to_week year_base decimal_day");
      printf("\nFor example : to_week 1992 123.452\n\n");
   }
   else
   {
      if ( (sscanf(argv[1], " %d", &year) != 1)  )
      {
         printf("\n error reading year_base\n");
         printf("\n year_base should be an integer, 2 or 4 digits\n");
         return(-1);
      }
      year = yr4digit( year );

      if ((sscanf(argv[2], " %lf", &day) != 1) ||
          (day < 0.0 || day > 366.0))
      {
         printf("\n error reading day\n");
         printf("\n decimal_day should between 0 and 366\n");
         return(-1);
      }
      numl_year = (int)(year - 1976 - 1) / 4 + 1;

      /* s_day is the start dayth information. if starts from Sunday
         s_day = 0, starts from Saturday s_day = 6, 1978 s_day = 0 */

      s_day = ( (year - 1978) + numl_year - 1 ) % 7 ;

      if ( day <= (6 - s_day))
      {
         weekth = 0;
         secondth = (day+s_day-1) * 86400L;
      }
      else
      {
         weekth = (int)(( day - 7 + s_day) / 7 ) + 1 ;
         secondth = day*86400L - (7-s_day)*86400L - (weekth-1)*7*86400L;
      }
      /*printf("\n The s_day is : %d", s_day); */
      printf("\n The decimal week is : %d", weekth);
      printf("\n The second in week is : %f \n", secondth);
   }
   return(0);
}
