/* given Julian Date and Longitude (decimal degrees West) compute and
 * display Local Sidereal Time, in decimal hours.  
 *
 * Provided courtesy of ecdowney@noao.edu (Elwood Downey)
 */


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


#include "../Include/constants.h"


#define degrad(x)       ((x)*FG_PI/180.)
#define raddeg(x)       ((x)*180./FG_PI)
#define deghr(x)        ((x)/15.)
#define radhr(x)        deghr(raddeg(x))

static void usage(void);
void utc_gst (double mjd, double *gst);


int
submain (double mjd, double lng)
{
	double gst;
	double lst;

	/* convert to float and print */
	/* mjd = atof (av[1]);
	lng = atof (av[2]); */
	printf ("Lst on JD %13.5f at %8.4f degrees West: ", mjd + MJD0, lng);

	/* convert to required internal units */
	/* mjd -= MJD0; */
	lng *= DEG_TO_RAD;

	/* compute LST and print */
	utc_gst (mjd, &gst);
	lst = gst - radhr (lng);
	lst -= 24.0*floor(lst/24.0);
	printf ("%7.4f\n", lst);

	/* that's all */
	return (0);
}


/* my main wrapper */
int main (int argc, char *argv[]) {
    struct tm *gmt;
    time_t cur_time;
    double mjd, lng;

    /* insure 1 arguments */
    if (argc != 2)
	usage();

    lng = atof (argv[1]);

    cur_time = time(NULL);
    printf("Time = %ld\n", cur_time);

    gmt = gmtime(&cur_time);
    printf("GMT = %d/%d/%2d %d:%02d:%02d\n", 
           gmt->tm_mon+1, gmt->tm_mday, gmt->tm_year,
           gmt->tm_hour, gmt->tm_min, gmt->tm_sec);

    mjd = cal_mjd ((int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
	     (int)(gmt->tm_year + 1900));

    /* add in partial day */
    mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
	   (gmt->tm_sec / (24.0 * 60.0 * 60.0));

    submain(mjd, lng);

    return(0);
}


static void
usage()
{
	fprintf (stderr, "usage: lst /*JD*/ Longitude (in decimal degrees West)\n");
	fprintf (stderr, "prints Local Sidereal Time (in decimal hours).\n");
	exit(1);
}

/* given an mjd, return greenwich mean siderial time, *gst */
void
utc_gst (mjd, gst)
double mjd;
double *gst;
{
	double day = floor(mjd-0.5)+0.5;
	double hr = (mjd-day)*24.0;
	double T, x;

	T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
	x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
	x /= 3600.0;
	*gst = (1.0/SIDRATE)*hr + x;
}
