# include "Ximage.h"

void Reorient (Graphic *graphic, Layout *layout, XButtonEvent *mouse_event) {

  int x, y, dummy2;
  double X0, Y0;
  unsigned int dummy3;
  Window dummy1;

  if (layout[0].expand == 0)
    layout[0].expand = 1;

  Screen_to_Image (&X0, &Y0, (double)mouse_event[0].x, (double)mouse_event[0].y, layout);
  X0 = 0.5*layout[0].matrix.Naxis[0] - X0;
  Y0 = 0.5*layout[0].matrix.Naxis[1] - Y0;

  switch (mouse_event[0].button) {
  case 1:
    if ((layout[0].X != X0) || (layout[0].Y != Y0)) {
      layout[0].X = X0;
      layout[0].Y = Y0;
    }
    break;
  case 2: 
    layout[0].expand--;
    if ((layout[0].expand == 0) || (layout[0].expand == -1))
      layout[0].expand = -2;
    if (layout[0].expand < -30) {
      fprintf (stderr, "can't get smaller!\n");
      layout[0].expand = -30;
      return;
    }
    layout[0].X = X0;
    layout[0].Y = Y0;
    break;
  case 3:
    layout[0].expand++;
    if ((layout[0].expand == 0) || (layout[0].expand == -1))
      layout[0].expand = 1;
    if (layout[0].expand > 30) {
      fprintf (stderr, "can't get bigger!\n");
      layout[0].expand = 30;
      return;
    }
    layout[0].X = X0;
    layout[0].Y = Y0;
    break;
  }

  Remap (graphic, layout, &layout[0].matrix);
  Refresh (graphic, layout, 0);
 
# ifndef NOWARP  /* the "warp" function seems to be a problem on SUNs for some reason */
  XQueryPointer (graphic[0].display, graphic[0].window, &dummy1, &dummy1, &dummy2, &dummy2, &x, &y, &dummy3); 
  if ((x > layout[0].picture.x) && (x < layout[0].picture.x + layout[0].picture.dx) &&
      (y > layout[0].picture.y) && (y < layout[0].picture.y + layout[0].picture.dy) &&
      ((mouse_event[0].button == 2) || (mouse_event[0].button == 3))) {
    XWarpPointer (graphic[0].display, None, graphic[0].window, 0, 0, 0, 0, 
		  layout[0].picture.x + 0.5*layout[0].picture.dx,
		  layout[0].picture.y + 0.5*layout[0].picture.dy);
  }
# endif

  XFlush (graphic[0].display);
}
