/*******************************************************************************
NAME                            TRANSVERSE MERCATOR

PURPOSE:	Transforms input Easting and Northing to longitude and
		latitude for the Transverse Mercator projection.  The
		Easting and Northing must be in meters.  The longitude
		and latitude values will be returned in radians.

PROGRAMMER              DATE
----------              ----
D. Steinwand, EROS      Nov, 1991
T. Mittan		Mar, 1993

ALGORITHM REFERENCES

1.  Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
    Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
    State Government Printing Office, Washington D.C., 1987.

2.  Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
    U.S. Geological Survey Professional Paper 1453 , United State Government
    Printing Office, Washington D.C., 1989.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>        /* for abs() declaration */
#include "gctpc/cproj.h"
#include "gctpc/report.h"


/* Variables common to all subroutines in this code file
  -----------------------------------------------------*/
static double r_major;          /* major axis                           */
static double r_minor;          /* minor axis                           */
static double scale_factor;     /* scale factor                         */
static double lon_center;       /* Center longitude (projection center) */
static double lat_origin;       /* center latitude                      */
static double e0,e1,e2,e3;      /* eccentricity constants               */
static double e,es,esp;         /* eccentricity constants               */
static double ml0;              /* small value m                        */
static double false_northing;   /* y offset in meters                   */
static double false_easting; 	/* x offset in meters			*/
static long ind;		/* sphere flag value			*/


/* Initialize the Universal Transverse Mercator (UTM) projection
  -------------------------------------------------------------*/
long
utminvint(double r_maj, double r_min, double scale_fact, long int zone)

             			/* major axis				*/
             			/* minor axis				*/
                  		/* scale factor				*/
          			/* zone number				*/
{
double temp;			/* temprorary variables			*/
double e0fn(double x),e1fn(double x),e2fn(double x),e3fn(double x),mlfn(double e0, double e1, double e2, double e3, double phi);	/* functions		*/

if ((abs(zone) < 1) || (abs(zone) > 60))
   {
   p_error("Illegal zone number","utm-invint");
   return(11);
   }
/*
if (zone == 0)
   zone = 1;
*/
r_major = r_maj;
r_minor = r_min;
scale_factor = scale_fact;
lat_origin = 0.0;
lon_center = ((6 * abs(zone)) - 183) * D2R;
false_easting = 500000.0;
false_northing = (zone < 0) ? 10000000.0 : 0.0;

temp = r_minor / r_major;
es = 1.0 - SQUARE(temp);
e = sqrt(es);
e0 = e0fn(es);
e1 = e1fn(es);
e2 = e2fn(es);
e3 = e3fn(es);
ml0 = r_major * mlfn(e0, e1, e2, e3, lat_origin);
esp = es / (1.0 - es);

if (es < .00001)
   ind = 1;
else 
   ind = 0;

/* Report parameters to the user
  -----------------------------*/
ptitle("UNIVERSAL TRANSVERSE MERCATOR (UTM)"); 
genrpt_long(zone,   "Zone:     ");
radius2(r_major, r_minor);
genrpt(scale_factor,"Scale Factor at C. Meridian:     ");
cenlonmer(lon_center);
return(OK);
}

/* Initialize the Transverse Mercator (TM) projection
  -------------------------------------------------------------*/
long
tminvint(double r_maj, double r_min, double scale_fact, double center_lon, double center_lat, double false_east, double false_north)

             			/* major axis			*/
             			/* minor axis			*/
                  		/* scale factor			*/
                  		/* center longitude		*/
                  		/* center latitude		*/
                  		/* x offset in meters		*/
                   		/* y offset in meters		*/
{
double temp;			/* temporary variable		*/
double e0fn(double x),e1fn(double x),e2fn(double x),e3fn(double x),mlfn(double e0, double e1, double e2, double e3, double phi);	/* functions		*/

/* Place parameters in static storage for common use
  -------------------------------------------------*/
r_major = r_maj;
r_minor = r_min;
scale_factor = scale_fact;
lon_center = center_lon;
lat_origin = center_lat;
false_northing = false_north;
false_easting = false_east;

temp = r_minor / r_major;
es   = 1.0 - SQUARE(temp);
e    = sqrt(es);
e0   = e0fn(es);
e1   = e1fn(es);
e2   = e2fn(es);
e3   = e3fn(es);
ml0  = r_major * mlfn(e0, e1, e2, e3, lat_origin);
esp  = es / (1.0 - es);

if (es < .00001)
   ind = 1;

/* Report parameters to the user
  -----------------------------*/
ptitle("TRANSVERSE MERCATOR (TM)"); 
radius2(r_major, r_minor);
genrpt(scale_factor,"Scale Factor at C. Meridian:    ");
cenlonmer(lon_center);
origin(lat_origin);
offsetp(false_easting,false_northing);
return(OK);
}


/* Transverse Mercator inverse equations--mapping x,y to lat,long 
  --------------------------------------------------------------*/
long
tminv(double x, double y, double *lon, double *lat)
         		/* (I) X projection coordinate 			*/
         		/* (I) Y projection coordinate 			*/
            		/* (O) Longitude 				*/
            		/* (O) Latitude 				*/
{
double adjust_lon(double x);    /* Function to adjust longitude to -180 - 180 	*/
double con,phi;		/* temporary angles				*/
double delta_phi;	/* difference between longitudes		*/
long i;			/* counter variable				*/
double sin_phi, cos_phi, tan_phi;	/* sin cos and tangent values	*/
double c, cs, t, ts, n, r, d, ds;	/* temporary variables		*/
double f, h, g, temp;			/* temporary variables		*/
long max_iter = 6;			/* maximun number of iterations	*/
double asinz(double con);

/* fortran code for spherical form 
--------------------------------*/
if (ind != 0)
   {
   f = exp(x/(r_major * scale_factor));
   g = .5 * (f - 1/f);
   temp = lat_origin + y/(r_major * scale_factor);
   h = cos(temp);
   con = sqrt((1.0 - h * h)/(1.0 + g * g));
   *lat = asinz(con);
   if (temp < 0)
     *lat = -*lat;
   if ((g == 0) && (h == 0))
     {
     *lon = lon_center;
     return(OK);
     }
   else
     {
     *lon = adjust_lon(atan2(g,h) + lon_center);
     return(OK);
     }
   }

/* Inverse equations
  -----------------*/
x = x - false_easting;
y = y - false_northing;

con = (ml0 + y / scale_factor) / r_major;
phi = con;
for (i=0;;i++)
   {
   delta_phi = ((con + e1 * sin(2.0*phi) - e2 * sin(4.0*phi) + e3 * sin(6.0*phi))
               / e0) - phi;
/*
   delta_phi = ((con + e1 * sin(2.0*phi) - e2 * sin(4.0*phi)) / e0) - phi;
*/
   phi += delta_phi;
   if (fabs(delta_phi) <= EPSLN) break;
   if (i >= max_iter) 
      { 
      p_error("Latitude failed to converge","TM-INVERSE"); 
      return(95);
      }
   }
if (fabs(phi) < HALF_PI)
   {
   sincos(phi, &sin_phi, &cos_phi);
   tan_phi = tan(phi);
   c    = esp * SQUARE(cos_phi);
   cs   = SQUARE(c);
   t    = SQUARE(tan_phi);
   ts   = SQUARE(t);
   con  = 1.0 - es * SQUARE(sin_phi); 
   n    = r_major / sqrt(con);
   r    = n * (1.0 - es) / con;
   d    = x / (n * scale_factor);
   ds   = SQUARE(d);
   *lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24.0 * (5.0 + 3.0 * t + 
          10.0 * c - 4.0 * cs - 9.0 * esp - ds / 30.0 * (61.0 + 90.0 * t +
          298.0 * c + 45.0 * ts - 252.0 * esp - 3.0 * cs)));
   *lon = adjust_lon(lon_center + (d * (1.0 - ds / 6.0 * (1.0 + 2.0 * t +
          c - ds / 20.0 * (5.0 - 2.0 * c + 28.0 * t - 3.0 * cs + 8.0 * esp +
          24.0 * ts))) / cos_phi));
   }
else
   {
   *lat = HALF_PI * sign(y);
   *lon = lon_center;
   }
return(OK);
}

/* Universal Transverse Mercator inverse equations--mapping x,y to lat,long 
  -----------------------------------------------------------------------*/
long
utminv(double x, double y, double *lon, double *lat)
         		/* (I) X projection coordinate 			*/
         		/* (I) Y projection coordinate 			*/
            		/* (O) Longitude 				*/
            		/* (O) Latitude 				*/
{
return(tminv(x, y, lon, lat));
}
