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

#define PI              3.14159265358979326433

typedef struct
{
        double lon;
        double lat;
        double lonWidth;
        double latHeight;
} Coord;

static  double pixelsPerLonDegree[18];
static  double pixelsPerLonRadian[18];
static  double numTiles[18];
static  double bitmapOrigo[18];
static  double bc = 2 * PI;
static  double Wa = PI / 180;


void initLatLon() {
        static int c = 256;
	int d;
        for (d = 17; d >= 0; --d) {
                 pixelsPerLonDegree[d] = c / 360;
                 pixelsPerLonRadian[d] = c / bc;
                 double e = c / 2;
                 bitmapOrigo[d] = c/2;
                 numTiles[d] = c / 256;
                 c *= 2;
        }
}


Coord getXY(double lat, double lon, int zoomLevel ) {
        Coord c;
        int x,y;
         x= (int)(bitmapOrigo[zoomLevel] + lon * pixelsPerLonDegree[zoomLevel]);
         x/=256;
                double e = sin(lat * Wa);

                if (e > 0.9999) {
                        e = 0.9999;
                }

                if (e < -0.9999) {
                        e = -0.9999;
                }

                y = (int)(bitmapOrigo[zoomLevel] + 0.5
                                * log((1 + e) / (1 - e)) * -1
                                * (pixelsPerLonRadian[zoomLevel]));
                y/=256;

                c.lon=x;
                c.lat=y;
                return c;

}

int main( int argc, char *argv[] ) {
	Coord c;
	initLatLon();
	//c=getXY( 39.909736, -79.628906, 2 ); 
	c=getXY( -79.628906,39.909736, 2 ); 
	printf("x=%f y=%f\n",c.lon,c.lat);

}
