#include	<stdio.h>
#include	<Point.h>
#include	<OverView.h>

#define		TOO_BIG		10000

extern "C" int rp_init();

int rp_init(char *init_str)
{
  return 1;
}


extern "C" int rp_to_screen();

int rp_to_screen(
  double x, double y, int *sx, int *sy,
  double min_x, double x_span, double min_y, double y_span, int ext_x, int ext_y)
{
  if (sx) {
    *sx= (int) ((x - min_x) / x_span * ext_x);
    if (*sx > TOO_BIG || *sx < -TOO_BIG)
      return 0;
  }

  if (sy) {
    *sy= (int) (ext_y - ((y - min_y) / y_span * ext_y));
    if (*sy > TOO_BIG || *sy < -TOO_BIG)
      return 0;
  }
  
  return 1;
}


extern "C" int screen_to_rp();

int screen_to_rp(
  int x, int y, double *rx, double *ry,
  double min_x, double x_span, double min_y, double y_span, int ext_x, int ext_y)
{
  if (rx) {
    *rx= double(x) / ext_x * x_span + min_x;
  }

  if (ry) {
    *ry= double(ext_y - y) / ext_y * y_span + min_y;
  }
  
  return 1;
}


extern "C" void rp_constrain();

void rp_constrain(
  MapView *mapview, MapView *targetview,
  int anchor_x, int anchor_y, int cur_x, int cur_y, int *new_x, int *new_y
)
{
#if 0 // Quick method but ignore aspect ratio

  int extent_x= cur_x-anchor_x;
  int extent_y= cur_y-anchor_y;
  int xdiff= abs(extent_x);
  int ydiff= abs(extent_y);
  int maxextent= xdiff > ydiff ? xdiff: ydiff;
  
  *new_x= anchor_x + (extent_x > 0 ? maxextent: -maxextent);
  *new_y= anchor_y + (extent_y > 0 ? maxextent: -maxextent);

#else // Take aspect ratio into account

  float	ax= mapview->XToLong(anchor_x), ay= mapview->YToLat(anchor_y);
  float lngdiff= fabs(mapview->XToLong(cur_x) - ax);
  float newlat;
  float latdiff= fabs((newlat= mapview->YToLat(cur_y)) - ay);
  float maxextent= lngdiff > latdiff ? lngdiff: latdiff;
  bool	own_aspect= targetview->IsKindOf(OverView) || mapview->ZoomingIn();
  float aspect= (own_aspect ? mapview: targetview)->AspectRatio();
  Point new_extent(cur_x - anchor_x, cur_y - anchor_y);

  Point new_p= mapview->GeoToPoint(
	ax + (new_extent.x > 0 ? maxextent: -maxextent)*aspect,
	ay + (new_extent.y > 0 ? -maxextent: maxextent));
  *new_x= new_p.x;
  *new_y= new_p.y;

#endif
}


extern "C" void rp_to_text(double x, double y, char *tx, char *ty)
{
  sprintf(tx, "X: %10.2f", x);
  sprintf(ty, "Y: %10.2f", y);
}
