#include <stdio.h>
#include <time.h>
#include <math.h>

/* Moonphase.c calculates moon phase info from system clock time */
/*  written by John Nordlie   July '96                           */

void main() {
	double phase, julian_day, age;
	struct tm *gm;
	time_t t;
	long year, month, day, k1, k2, k3;

/* get current time */
t = time(NULL);
gm = gmtime(&t);

/* put into variables */
year = gm->tm_year + 1900;
month = gm->tm_mon + 1;
day = gm->tm_mday;

/* output content tag for browser */
printf("Content-type: text/html %c%c", 10, 10);
printf("<PRE>%c", 10);

/* print time and date */
printf("Current year: %d  month: %d  day: %d\n", year, month, day);

/* calculate julian day */
year = year - (int)(( 12 - month ) / 10);
month = month + 9; 
if (month >= 12) {
	month = month - 12;
}

k1 = (int)(365.25 * ( year + 4712 ));
k2 = (int)(30.6 * month + 0.5 );
k3 = (int)((int)((year / 100) + 49) * 0.75) - 38;

julian_day = k1 + k2 + day + 59;

if (julian_day > 2299160) {
	julian_day = julian_day - k3;
}

/* print Julian day */
printf("Julian day is: %.0f\n", julian_day);

/* calculate moon phase */
phase = (julian_day - 2451550.1) / 29.53058868;
phase = phase - (int)(phase);
if (phase < 0) {
	phase = phase + 1;
}

/* calculate age of moon */
age = phase * 29.53;

/* convert phase to illumination percentage */
phase = phase * 2.0;

if (phase > 1.99) {
	phase = 0.0;
}

if (phase > 1.00) {
	phase = 1.00 - (phase - 1.00);
}

phase = (int)(phase * 100.0);

/* print it out here */
printf("Moon phase is %.0f percent. \n", phase);
printf("Moon age is %.2f days. \n", age);

/* close PRE tag */
printf("</PRE>%c", 10);

} /* end main */

