// 
// smeg - A satellite modelling and prediction tool
// Copyright (C) 1999  Tom Rothamel
// 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; see the file COPYING.  If not, write to
// the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.

#include "sts2.h"

Site::Site(double la, double lo, double a) {
	alt = a;
	latr = la * DEGRAD;
	lonr = lo * DEGRAD;

	sinlat = sin(latr);
	coslat = cos(latr);
}

static const double F = (1.0/298.257222);
static const double sqomf = (1.0-F)*(1.0-F); 
static const double ffff = (F + F - F * F);

void Site::calcpos(double t) {
	double theta;
	double c;
	double s;
	
	if (ct == t) return;
	ct = t;

	theta = sgp_gmst(t) + lonr;
       
	c = 1.0/sqrt(1 - ffff * sinlat * sinlat);
	s = sqomf * c;

 	x[0] = (R*c + alt) * coslat * cos(theta);
	x[1] = (R*c + alt) * coslat * sin(theta);
	x[2] = (R*s + alt) * sinlat;

	dx[0] = -ROTRATE * x[1];
	dx[1] = ROTRATE * x[0];
	dx[2] = 0;
}

extern double lat;
extern double lon;
extern double alt;

/* This is pretty much useless now. It was once used to debug why the
 * doing calclla on a Site would return results different from the
 * Site's inputs. It's sits here with honor, and a knowledge of a job
 * well done.
 *
 * Yes, it _is_ 2:30 am. Why do you ask?
 */

void DebugLocation () {
	double now;
	Site *si;
	LLA *lla;
	
	now = sgp_now();
	
	si = new Site(lat, lon, alt);
	si->calcpos(now);
	lla = si->calclla();;

	fprintf(out, "Calculated ECI, then LLA. Results:\n"
		"Lat: %f Lon: %f Alt: %f\n", lla->lat, lla->lon, lla->alt);

	delete lla;
	delete si;
}

	
	

// RadecAzrael *CalcAngles(Locatable *l, Site *s) {
// 	RadecAzrael *ra = new RadecAzrael;
// 	double ang;
	
// 	l->stash();
// 	l->recenter(s);

// 	ra->range = sqrt(l->x[0]*l->x[0] +
// 			 l->x[1]*l->x[1] +
// 			 l->x[2]*l->x[2]);

// 	/* Could be bogus! */
// 	ra->ra = M_PI - atan2(-l->x[1], l->x[0]);
// 	ra->dec = atan2(l->x[2], hypot(l->x[0], l->x[1])); 
	
// 	ang = sgp_gmst(s->ct) + s->lonr + M_PI;

// 	l->x[0]  = -l->x[0];
// 	zrot(l->x, sin(ang), cos(ang));
// 	yrot(l->x, s->coslat, s->sinlat);
// 	/* yrot(l->x, s->sinlat, s->coslat); */ 
	
// 	ra->az = M_PI - atan2(-l->x[1], l->x[0]);
// 	ra->el = atan2(l->x[2], hypot(l->x[0], l->x[1])); 
	

// 	l->unstash();
// 	return ra;
// }
