# include "Ximage.h"

int InterpretPresses (Graphic *graphic, Layout *layout, XButtonEvent *event) {

  int             status, done, this_button;
  Button         *button;

  status = TRUE;
  this_button = event[0].button;
  
  if ((event[0].type == ButtonPress) && InPicture (event, &layout[0].picture)) {
    ReorientOnButton (graphic, layout, event);
  }

  if ((event[0].type == ButtonPress) && InPicture (event, &layout[0].cmapbar)) {
    DragColorbar (graphic, layout, event);
  }

  /* if on an exisiting button, Invert, wait for release, then go (or not) */
  if ((button = CheckButtons (event, layout)) != (Button *) NULL) {
    InvertButton (graphic, button); 
    done = FALSE;
    while (!done) { /* wait for release of this button */
      XNextEvent (graphic[0].display, (XEvent *) event);
      if ((event[0].type == ButtonRelease) && (event[0].button == this_button)) {
	done = TRUE;
      }
    }
    DrawButton (graphic, button);
    if (InButton (event, button)) {
      switch (event[0].button) {
      case 1:
	status = button[0].function_1(graphic, layout);
	break;
      case 2:
	status = button[0].function_2(graphic, layout);
	break;
      case 3:
	status = button[0].function_3(graphic, layout);
	break;
      }
    }
    else {
      return (status);
    }
  }

  return (status);

}

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

  double X, Y;

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

  switch (mouse_event[0].button) {
    case 1:
      Reorient (graphic, layout, X, Y, 0);
      break;
    case 2:
      Reorient (graphic, layout, X, Y, -1);
      break;
    case 3:
      Reorient (graphic, layout, X, Y, +1);
      break;
    default:
      break;
  }
}
