// sattool - visual satellite tracking and prediction tool.
// Copyright 2000 Tom Rothamel <tom-idbg@onegeek.org>
//
// 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; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  

#include "sattool.h"
#include <math.h>

static const double F = (1.0/298.257222);  /* Flattening of the Earth */
static double e2 = 2 * F - F * F;

// Calculates the latitude and longitude of a point in eci spacetime.
LLA::LLA(Position *p) {
	double theta, r, phi, c, s, sinphi;
	
	theta = atan2(p->x[1], p->x[0]);

        lon = fmod(theta - sgp_gmst(p->t), 2*M_PI);
        r = hypot(p->x[0], p->x[1]);
        lat = atan2(p->x[2], r);

        do {
                phi = lat;
                sinphi = sin(phi);
                c = 1.0/sqrt(1.00 - (e2*sinphi*sinphi));
                lat = atan2(p->x[2] +  c*e2*sinphi * R, r);
        } while (fabs(lat-phi) > 0.0000001);

	alt = r/cos(lat) - c * R;
	
        if (lon < -M_PI) lon += 2*M_PI;

	lon = lon * RADEG;
	lat = lat * RADEG;
}
