/*
   This is an ugly set of routines to give a simple line-and-circle
   set of routines for X. It was adapted from an example X program
   floating around on the net.

   It includes a set on interface modules for GPM modula 2, if the macro
   MODULA2 is true.

   See graph.def for the interface definitions for the modula2 functions.

   Author: Andrew Tridgell, March 1994
*/

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/xpm.h>

#include "Graph.h"

/* a few macros and types to make things easier */
#ifndef True
#define True (1==1)
#endif
#ifndef False
#define False (!True)
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif

/* a useful boolean type */
typedef int BOOL;

/* this is used for easy extraction of prototypes with grep */
#define FN
#if MODULA2
#define STATIC static
#else
#define STATIC 
#endif

/* debugfile is used for any important error messages */
#define debugfile stderr


/* prototypes for functions in the module */
STATIC BOOL xStartDisplay(int width,int height,int argc,char *argv[],int use_shadow);
STATIC void xEndDisplay(void);
STATIC void xRainbow(int start,int end);
STATIC void xSetTitle(char *title);
STATIC int xGetEvent(void);
STATIC int xWaitEvent(unsigned int eventmask);
STATIC void xProcessDisplay(void (*process_fn)());
STATIC BOOL xPutPixel(int x,int y,int color);
STATIC BOOL xSetForeground(int color);
STATIC BOOL xSetBackground(int color);
STATIC BOOL xPutPoint(int x,int y);
STATIC BOOL xClearArea(int x,int y,int width, int height);
STATIC BOOL xClearDisplay(void);
STATIC BOOL xSync(int discard);
STATIC BOOL xSetColor(int color, char *colorname);
STATIC int xGetColor(char *colorname);
STATIC int xScreenWidth(void);
STATIC int xScreenHeight(void);
STATIC int xWindowWidth(void);
STATIC int xWindowHeight(void);
STATIC BOOL xDrawString(int x,int y, char *str);
STATIC BOOL xLoadFont( char *fontname);
STATIC int xStringWidth( char *str);
STATIC int xStringHeight( char *str);
STATIC BOOL xDrawLine(int x_1,int y_1,int x_2,int y_2);
STATIC BOOL xDrawRectangle(int x,int y,int width,int height);
STATIC BOOL xFillRectangle(int x,int y,int width,int height);
STATIC BOOL xDrawArc(int x,int y,int width,int height,int angle1,int angle2);
STATIC BOOL xDrawEllipse(int x,int y,int width,int height);
STATIC BOOL xFillArc(int x,int y,int width,int height,int angle1,int angle2);
STATIC BOOL xFillEllipse(int x,int y,int width,int height);
STATIC void xGetMousePos(int *x,int *y);
STATIC void xGetLastPos(int *x,int *y);
STATIC void xSetDrawFunction(int function);
STATIC void xSetLineStyle(int style);
STATIC void xSetLineWidth(int width);
STATIC void xGetDrag(int *x_1,int *y_1,int *x_2,int *y_2);
STATIC void xSaveGC(void);
STATIC void xRestoreGC(void);
STATIC void xDisplay(void);


/* the last event to occur */
static int lastevent = 0;

/* are we using a shadow buffer? */
static int shadowed;
#define BUFFER (shadowed?xs.shadow:xs.window)

/* is the display currently open? */
static BOOL display_is_open = False;

#define NUM_FONTS 30

typedef struct {
	Font f;
	char *name;
} FontCache;

/* structure to hold all of the current X info */
typedef struct
	{
		/* declarations */
	Display         *display;
	Window          window,
			rootwindow;
	Pixmap          shadow;
	Colormap	cmap;
	GC              gc;
	XEvent          event;
	XSizeHints      hint;
	XWMHints	wmhint;
	int             screen;
	int		no_screens;
	int             current_font;
	FontCache	fonts[NUM_FONTS];
        XClassHint	classhint;	/* suggested name and window class */

	/* user settable entries */
	unsigned long   foreground,
			background;

	char fontname[100];
	char title[100];
	int draw_function;
	int line_style;
	int line_width;
	} xstuff_struct;

static xstuff_struct xs;
static xstuff_struct xs_saved;

#define MAX_IMAGES 100

static struct Image {
	int used;
	XpmAttributes attributes;
	Pixmap pixmap, clipmask, saved;
        int x,y;
} Images[MAX_IMAGES];

/*********************************************************************
Start the X display and set up a pixmap
The argc/argv should allow the standard X parameters (like -display) 
... maybe
*********************************************************************/
STATIC BOOL xStartDisplay(int width,int height,int argc,char *argv[],int use_shadow)
{
  if (display_is_open) xEndDisplay();
  
  xs.display = XOpenDisplay("");

  shadowed = use_shadow;
  
  if (!xs.display)
    {
      fprintf(debugfile, "Error: couldn't open display\n");
      exit(1);
    }
  
  /* find the number of screens */
  xs.no_screens = ScreenCount(xs.display);
  
  /* assume screen 0 anyway */
  xs.screen = 0;

  xs.rootwindow = RootWindow(xs.display, xs.screen);

  /* default pixel values */
  xs.background = WhitePixel(xs.display, xs.screen);
  xs.foreground = BlackPixel(xs.display, xs.screen);

  /* if width or height is 0 then return now */
  if (width == 0 || height == 0)
    return(True);
  
  /* default program-specified window position and size */
  xs.hint.x = 100;
  xs.hint.y = 100;
  xs.hint.width = width;
  xs.hint.height = height;
  xs.hint.flags = PPosition | PSize;
  
  /* window creation */
  xs.window = XCreateSimpleWindow(xs.display, xs.rootwindow,
				    xs.hint.x, xs.hint.y, xs.hint.width, 
				    xs.hint.height, 5, 
				    xs.foreground, xs.background);
  if (argv)
    XSetStandardProperties(xs.display, xs.window,
			   argv[0], argv[0], None, argv, argc, &xs.hint);
  
  /* Tell Window Manager to give us Input Focus */
  xs.wmhint.flags = 0;
  xs.wmhint.input = True;
  xs.wmhint.flags |= InputHint;
  XSetWMHints(xs.display, xs.window, &xs.wmhint);
  xs.classhint.res_name = NULL; xs.classhint.res_class = NULL;
  XSetClassHint(xs.display, xs.window, &xs.classhint);
  
  /* GC creation and intialisation */
  xs.gc = XCreateGC(xs.display, xs.window, 0, 0);
  
  XSetBackground(xs.display, xs.gc, xs.background);
  XSetForeground(xs.display, xs.gc, xs.foreground);

  /* input event selection */
  XSelectInput(xs.display, xs.window,0xFFFF);

  /* window mapping */
  XMapRaised(xs.display, xs.window);

  /* set up backing store and save-unders */
  {
    XSetWindowAttributes attributes;
    attributes.backing_store = Always;
    attributes.save_under = True;
    XChangeWindowAttributes(xs.display,
			    xs.window,
			    CWBackingStore | CWSaveUnder,
			    &attributes);
  }

  xLoadFont("fixed");  
  xWaitEvent(eExpose);
  xSetTitle("Modula-2 Graphics Display");
  xSetDrawFunction(GXcopy);
  xSetLineStyle(LineSolid);
  xSetLineWidth(1);


  xs.shadow = XCreatePixmap(xs.display, xs.window, width, height,
			    DefaultDepth(xs.display, xs.screen));


  display_is_open = True;
   
  xSaveGC();

  /* clear the display */
  xClearDisplay();

  /* make sure it is all displayed */
  xDisplay();

  return(True);
}

/*********************************************************************
end the X display
*********************************************************************/
STATIC void xEndDisplay(void)
{
  XCloseDisplay(xs.display);
  display_is_open = False;
}

/*******************************************************************
  set up a rainbow colormap
  ********************************************************************/
STATIC void xRainbow(int start,int end)
{
  int red_inc,green_inc,blue_inc;
  int red=0,green=0,blue=0;
  XColor color;
  int i;
  
  red_inc = 1;
  green_inc = red_inc*2;
  blue_inc = green_inc*2;
  
  for (i=start;i<=end;i++)
    {
      color.flags = DoRed|DoGreen|DoBlue;
      color.pixel = i;
      color.red = red%256;
      color.green = green%256;
      color.blue = blue%256;
      red += red_inc;
      green += green_inc;
      blue += blue_inc;
      XStoreColor(xs.display, xs.cmap, &color);
    } 
}

/*******************************************************************
set the window title
*********************************************************************/
STATIC void xSetTitle(char *title)
{
  strcpy(xs.title,title);
  XStoreName(xs.display,xs.window,title);
}

/*******************************************************************
get the next event
********************************************************************/
STATIC int xGetEvent(void)
{
  XNextEvent(xs.display, &xs.event);
  return(xs.event.type);
}

/*******************************************************************
wait for a specified event - eg. an Expose event.
********************************************************************/
STATIC int xWaitEvent(unsigned int eventmask)
{
  int ev;
#define CHECK_ONE(xx) if ((eventmask & xx) != 0) {lastevent=xx;return(xx);} break;

  while (True)
    {
      ev = xGetEvent();
      switch (ev)
	{
	case Expose: CHECK_ONE(eExpose);
	case KeyPress: CHECK_ONE(eKeyPress);
	case ButtonPress: CHECK_ONE(eButtonPress);
	case KeyRelease: CHECK_ONE(eKeyRelease);
	case ButtonRelease: CHECK_ONE(eButtonRelease);
	case MotionNotify: CHECK_ONE(eMotion);
	}
    }
#undef CHECK_ONE  
}


/*********************************************************************
update the display - wait for some events and do the work when
an event is received.
*********************************************************************/
STATIC void xProcessDisplay(void (*process_fn)())
{
  process_fn();
  xWaitEvent(eKeyPress | eButtonPress);
}

/*********************************************************************
draw a pixel
*********************************************************************/
STATIC BOOL xPutPixel(int x,int y,int color)
{
  XSetForeground(xs.display, xs.gc, color);
  XDrawPoint(xs.display,BUFFER,xs.gc, x, y);
  XSetForeground(xs.display, xs.gc, xs.foreground);
  return(True);
}

/*********************************************************************
set the foreground color
*********************************************************************/
STATIC BOOL xSetForeground(int color)
{
  xs.foreground = color;
  XSetForeground(xs.display, xs.gc, color);
  return(True);
}

/*********************************************************************
set the background color
*********************************************************************/
STATIC BOOL xSetBackground(int color)
{
  xs.background = color;
  XSetBackground(xs.display, xs.gc, color);
  return(True);
}


/*********************************************************************
draw a point in foreground color
*********************************************************************/
STATIC BOOL xPutPoint(int x,int y)
{
  XDrawPoint(xs.display,BUFFER,xs.gc, x, y);
  return(True);
}


/*********************************************************************
clear an area
*********************************************************************/
STATIC BOOL xClearArea(int x,int y,int width, int height)
{
  int saved_fg = xs.foreground;
  xSetForeground(xs.background);
  xFillRectangle(x,y,width,height);
  xSetForeground(saved_fg);
  return(True);
}

/*********************************************************************
clear the display
*********************************************************************/
STATIC BOOL xClearDisplay(void)
{
  xClearArea(0,0,xWindowWidth(),xWindowHeight());
  return(True);
}


/*********************************************************************
sync the display. Normally discard is 0 - unless you want to lose events!
*********************************************************************/
STATIC BOOL xSync(int discard)
{
  XSync(xs.display,discard);
  return(True);
}


/*********************************************************************
set a color value to a named color
*********************************************************************/
STATIC BOOL xSetColor(int color, char *colorname)
{
  XStoreNamedColor(xs.display,xs.cmap,
		   colorname,color,DoRed | DoGreen | DoBlue);
  return(True);
}

/*********************************************************************
get an integer for a named color
*********************************************************************/
STATIC int xGetColor(char *colorname)
{
  XColor color;
  XWindowAttributes attributes;

  XGetWindowAttributes(xs.display,xs.rootwindow,&attributes);
  color.pixel = xs.foreground;
   if (!XParseColor (xs.display, attributes.colormap, colorname, &color)) 
     {
       fprintf(debugfile,"Couldn't parse color %s\n",colorname);
     }
   else if(!XAllocColor (xs.display, attributes.colormap, &color)) 
     {
       fprintf(debugfile,"Couldn't alloc color %s\n",colorname);
     }
  return color.pixel;
}


/*********************************************************************
get an integer for the specifed RGB value
*********************************************************************/
STATIC int xGetColorRGB(int red,int green,int blue)
{
  char color_name[10];

  sprintf(color_name,"#%02x%02x%02x",red%256,green%256,blue%256);
  return xGetColor(color_name);;
}

/*******************************************************************
return the width of the current screen
********************************************************************/
STATIC int xScreenWidth(void)
{
  if (!display_is_open)
    {
      int res;
      xStartDisplay(0,0,0,NULL,0);
      res = WidthOfScreen(ScreenOfDisplay(xs.display,xs.screen));
      xEndDisplay();
      return(res);
    }
  
return(WidthOfScreen(ScreenOfDisplay(xs.display,xs.screen)));
}

/*******************************************************************
return the height of the current screen
********************************************************************/
STATIC int xScreenHeight(void)
{
  if (!display_is_open)
    {
      int res;
      xStartDisplay(0,0,0,NULL,0);
      res = HeightOfScreen(ScreenOfDisplay(xs.display,xs.screen));
      xEndDisplay();
      return(res);
    }
  
return(HeightOfScreen(ScreenOfDisplay(xs.display,xs.screen)));
}

/*******************************************************************
return the width of the current screen
********************************************************************/
STATIC int xWindowWidth(void)
{
  XWindowAttributes wattr;
  XGetWindowAttributes(xs.display,xs.window,&wattr);
  return(wattr.width);
}

/*******************************************************************
return the height of the current screen
********************************************************************/
STATIC int xWindowHeight(void)
{
  XWindowAttributes wattr;
  XGetWindowAttributes(xs.display,xs.window,&wattr);
  return(wattr.height);
}


/*******************************************************************
return the depth of the current screen
********************************************************************/
STATIC int xWindowDepth(void)
{
  XWindowAttributes wattr;
  XGetWindowAttributes(xs.display,xs.window,&wattr);
  return(wattr.depth);
}

/*******************************************************************
draw a string a pos x,y
********************************************************************/
STATIC BOOL xDrawString(int x,int y, char *str)
{
  XDrawString(xs.display,BUFFER,xs.gc, x, y,str,strlen(str));
  return(True);
}

/*******************************************************************
load a font
********************************************************************/
STATIC BOOL xLoadFont(char *fontname)
{
	int i;
	static int nexti;
	for (i=0;i<NUM_FONTS;i++) {
		if (!xs.fonts[i].name || strcmp(fontname, xs.fonts[i].name) == 0) break;
	}
	if (i == NUM_FONTS) { 
		i = nexti; 
		XUnloadFont(xs.display,xs.fonts[i].f);
		free(xs.fonts[i].name);
		xs.fonts[i].name = NULL;
		nexti = (nexti+1) % NUM_FONTS;
	}
	if (!xs.fonts[i].name) {
		xs.fonts[i].f = XLoadFont(xs.display,fontname);
		xs.fonts[i].name = strdup(fontname);
	}
	XSetFont(xs.display,xs.gc,xs.fonts[i].f);
	xs.current_font = i;
	return(True);
}

/*******************************************************************
return the number of pixels that a string will take up
********************************************************************/
STATIC int xStringWidth( char *str)
{
	int len,ret;
	XFontStruct *xf;
	len = strlen(str);
	xf = XQueryFont(xs.display,xs.fonts[xs.current_font].f);
	ret = XTextWidth(xf,str,len);
	XFreeFontInfo(NULL, xf, 0);
	return(ret);
}


/*******************************************************************
return the number of pixels that a string will take up
********************************************************************/
STATIC int xStringHeight( char *str)
{
  int i,len,ret;
  XFontStruct *xf;
  xf = XQueryFont(xs.display,xs.fonts[xs.current_font].f);
  len = strlen(str);
  ret = 0;
  for (i=0;i<len;i++)
    ret = MAX(ret,xf->per_char[str[i]].ascent + 
	      xf->per_char[str[i]].descent);
  XFreeFontInfo(NULL, xf, 0);
  return(ret);
}


/*********************************************************************
draw a line
*********************************************************************/
STATIC BOOL xDrawLine(int x_1,int y_1,int x_2,int y_2)
{
  XDrawLine(xs.display,BUFFER,xs.gc, x_1, y_1,x_2,y_2);
  return(True);
}



/*********************************************************************
draw a rectangle
*********************************************************************/
STATIC BOOL xDrawRectangle(int x,int y,int width,int height)
{
  if ((width == 0) || (height == 0)) return(False);
  XDrawRectangle(xs.display,BUFFER,xs.gc,x,y,width,height);
  return(True);
}

/*********************************************************************
fill a rectangle
*********************************************************************/
STATIC BOOL xFillRectangle(int x,int y,int width,int height)
{
  XFillRectangle(xs.display,BUFFER,xs.gc,x,y,width,height);
  return(True);
}

/*********************************************************************
draw an arc
*********************************************************************/
STATIC BOOL xDrawArc(int x,int y,int width,int height,int angle1,int angle2)
{
  XDrawArc(xs.display,BUFFER,xs.gc,x,y,width,height,angle1*64,angle2*64);
  return(True);
}

/*********************************************************************
draw an ellipse
*********************************************************************/
STATIC BOOL xDrawEllipse(int x,int y,int width,int height)
{
  xDrawArc(x,y,width,height,0,360);
  return(True);
}

/*********************************************************************
fill an arc
*********************************************************************/
STATIC BOOL xFillArc(int x,int y,int width,int height,int angle1,int angle2)
{
  XFillArc(xs.display,BUFFER,xs.gc,x,y,width,height,angle1*64,angle2*64);
  return(True);
}

/*********************************************************************
fill an ellipse
*********************************************************************/
STATIC BOOL xFillEllipse(int x,int y,int width,int height)
{
  xFillArc(x,y,width,height,0,360);
  return(True);
}


/*******************************************************************
return the x and y pos of the mouse
********************************************************************/
STATIC void xGetMousePos(int *x,int *y)
{
  Window root_return,child_return;
  int root_x_return,root_y_return;
  unsigned int mask_return;
  XQueryPointer(xs.display,xs.window,
		&root_return,&child_return,&root_x_return,&root_y_return,
		x,y,
		&mask_return);
  if (*x < 0) *x = 0;
  if (*y < 0) *y = 0;
}

/*******************************************************************
return the last x and y pos of the mouse
********************************************************************/
STATIC void xGetLastPos(int *x,int *y)
{
  *x = xs.event.xbutton.x;
  *y = xs.event.xbutton.y;
  if (*x < 0) *x = 0;
  if (*y < 0) *y = 0;
}

/*******************************************************************
return the last x and y pos of the mouse
********************************************************************/
STATIC int xGetLastKeyCode(void)
{
  return xs.event.xkey.keycode;
}


/*******************************************************************
set the drawing function, eg GCxor, GCand, GCcopy etc.
********************************************************************/
STATIC void xSetDrawFunction(int function)
{
  XGCValues vals;
  vals.function = function;
  XChangeGC(xs.display,xs.gc,GCFunction,&vals);
  xs.draw_function = function;
}

/*******************************************************************
set the line style. eg. LineSolid,LineDoubleDash,LineOnOffDash
********************************************************************/
STATIC void xSetLineStyle(int style)
{
  XGCValues vals;
  vals.line_style = style;
  XChangeGC(xs.display,xs.gc,GCLineStyle,&vals);
  xs.line_style = style;
}

/*******************************************************************
set the line width
********************************************************************/
STATIC void xSetLineWidth(int width)
{
  XGCValues vals;
  vals.line_width = width;
  XChangeGC(xs.display,xs.gc,GCLineWidth,&vals);
  xs.line_width = width;
}


/*******************************************************************
wait for a button then wait for the release
********************************************************************/
STATIC void xGetDrag(int *x_1,int *y_1,int *x_2,int *y_2)
{
  xWaitEvent(eButtonPress);
  xGetLastPos(x_1,y_1);
  xWaitEvent(eButtonRelease);
  xGetLastPos(x_2,y_2);
}

/*******************************************************************
save the GC for later restoration
********************************************************************/
STATIC void xSaveGC(void)
{
  memcpy(&xs_saved, &xs, sizeof(xs));
}

/*******************************************************************
restore the GC 
********************************************************************/
STATIC void xRestoreGC(void)
{
  xSetForeground(xs_saved.foreground);
  xSetBackground(xs_saved.background);
  xLoadFont(xs_saved.fontname);
  xSetTitle(xs_saved.title);
  xSetDrawFunction(xs_saved.draw_function);
  xSetLineStyle(xs_saved.line_style);
  xSetLineWidth(xs_saved.line_width);
}


STATIC int FindFreeImage(void)
{
	int i;
	for (i=0;i<MAX_IMAGES;i++)
		if (!Images[i].used) return i;
	return -1;
}

STATIC char *FindXPMFile(char *fname)
/* Return pointer to static name of apparently existing XPM file.
   As well as trying to append ".xpm", we try prepending the 
   value of the environment variable XPMDIR if it exists. */
{
	static char name[256];
	char *xpmdir,*getenv();
	struct stat buf;

	sprintf(name,"%s",fname);
	if (stat(name,&buf) == 0) return name;
	sprintf(name,"%s.xpm",fname);
        if (stat(name,&buf) == 0) return name;

	if (fname[0] == '/' || 
           (xpmdir = getenv("XPMDIR")) == NULL) return NULL;
 
        sprintf(name,"%s/%s",xpmdir,fname);
        if (stat(name,&buf) == 0) return name;
        sprintf(name,"%s/%s.xpm",xpmdir,fname);
        if (stat(name,&buf) == 0) return name;
	return NULL;
}

STATIC int xLoadImage(char *fname)
{
	int i;
	int ret;
	char *error = NULL;
	char *actname;

	i = FindFreeImage();
	memset(&Images[i], 0, sizeof(Images[i]));

	Images[i].attributes.closeness = 40000;
	Images[i].attributes.valuemask |= XpmCloseness;

	actname = FindXPMFile(fname);

	if (actname == NULL)
	    error = "No such file";
	else {
	    ret = XpmReadFileToPixmap(xs.display, xs.window, actname, 
				      &Images[i].pixmap, 
				      &Images[i].clipmask, 
				      &Images[i].attributes);
	    switch (ret) {
	    case XpmColorError:
		    error = "Could not parse or alloc requested color";
		    break;
	    case XpmOpenFailed:
		    error = "Cannot open file";
		    break;
	    case XpmFileInvalid:
		    error = "Invalid XPM file";
		    break;
	    case XpmNoMemory:
		    error = "Not enough memory";
		    break;
	    case XpmColorFailed:
		    error = "Failed to parse or alloc some color";
		    break;
	    }
	}
	
	if (error) {
		fprintf(stderr,"%s: %s\n", fname, error);
		exit(1);
	}

	Images[i].saved = XCreatePixmap(xs.display, xs.window, 
					Images[i].attributes.width, 
					Images[i].attributes.height,
					DefaultDepth(xs.display, xs.screen));


	Images[i].used = 1;

	return i;
}


STATIC int xImageWidth(int i)
{
	if (!Images[i].used) {
		fprintf(stderr,"xImageWidth: invalid image handle %d\n", i);
		exit(1);
	}
	return Images[i].attributes.width;
}

STATIC int xImageHeight(int i)
{
	if (!Images[i].used) {
		fprintf(stderr,"xImageHeight: invalid image handle %d\n", i);
		exit(1);
	}
	return Images[i].attributes.height;
}

/* display the shadow buffer on the window */
STATIC void xDisplay(void)
{
  int width = xs.hint.width;
  int height = xs.hint.height;

  if (shadowed) {
#if 0
    XSetWindowBackgroundPixmap(xs.display, xs.window, xs.shadow);
#else
    XCopyArea(xs.display, xs.shadow, xs.window, xs.gc, 
	      0, 0, width, height, 0, 0);
#endif
  }

  xSync(0);
}


STATIC void xPlaceImage(int i, int x, int y, int clip)
{
	int width = MIN(Images[i].attributes.width, xs.hint.width-x);
	int height = MIN(Images[i].attributes.height, xs.hint.height-y);

	if (!Images[i].used) {
		fprintf(stderr,"xPlaceImage: invalid image handle %d\n", i);
		exit(1);
	}

	XSetClipMask(xs.display, xs.gc, None);

	XCopyArea(xs.display, BUFFER, Images[i].saved, xs.gc, 
		  x, y, width, height, 0, 0);

	XSetClipOrigin(xs.display, xs.gc, x, y);

	XSetClipMask(xs.display, xs.gc, clip?Images[i].clipmask:None);

	XCopyArea(xs.display, Images[i].pixmap, BUFFER, xs.gc, 
		  0, 0, width, height, x, y);

	XSetClipMask(xs.display, xs.gc, None);
}

STATIC void xRestoreImage(int i, int x, int y, int clip)
{
	int width = MIN(Images[i].attributes.width, xs.hint.width-x);
	int height = MIN(Images[i].attributes.height, xs.hint.height-y);

	if (!Images[i].used) {
		fprintf(stderr,"xRestoreImage: invalid image handle %d\n", i);
		exit(1);
	}

	XSetClipOrigin(xs.display, xs.gc, x, y);

	XSetClipMask(xs.display, xs.gc, clip?Images[i].clipmask:None);

	XCopyArea(xs.display, Images[i].saved, BUFFER, xs.gc, 
		  0,0, width, height, x, y);

	XSetClipMask(xs.display, xs.gc, None);
}

STATIC void xFreeImage(int i)
{
	if (!Images[i].used) return;

	if (!Images[i].used) {
		fprintf(stderr,"xFreeImage: invalid image handle %d\n", i);
		exit(1);
	}

	XFreePixmap(xs.display, Images[i].pixmap);
	XFreePixmap(xs.display, Images[i].saved);

	memset(&Images[i], 0, sizeof(Images[i]));
}



#if MAIN
/* a simple main program to test the above code */
int main(int argc,char *argv[])
{
  int width = 300;
  int height = 300;
  int i1, i2, x, y, n;

  /* open the display */
  xStartDisplay(width,height,0,NULL,0);

  i1 = xLoadImage("bg.xpm");
  i2 = xLoadImage("bdm.xpm");

  xPlaceImage(i1, 0, 0, 0);

  for (n=0;n<200;n++) {
	  xPlaceImage(i2, n%width, n%height, 1);

	  usleep(1000);

	  xRestoreImage(i2, n%width, n%height, 1);
  }

  xFreeImage(i1);
  xFreeImage(i2);

  /* draw a line */
  xDrawLine(10,10,100,100);

  /* wait for a mouse click */
  xWaitEvent(eButtonPress);

  /* close and exit */
  xEndDisplay();

  return(0);
}
    
#endif



/* now a section for modula-2 using the gpm C interface */
/* see the file graph.def for comments and the gpm interface */
static BOOL always_sync = True;
static BOOL graphics_initialised = False;

/* called at the start of each modula routine in case it's needed */
static void Graph1(void)
{
  if (!graphics_initialised)
    {
      fprintf(debugfile,"You must call StartGraphics() first!\n");
      exit(1);
    }
}

/* called at the end of each modula routine in case it's needed */
static void Graph2(void)
{
if (always_sync && graphics_initialised && !shadowed)
  xSync(0);
}


/*
   A routine to open the display 
*/
void StartGraphics(int Width, int Height, int use_shadow)
{
  graphics_initialised = True;
  Graph1();
  xStartDisplay(Width,Height,0,NULL, use_shadow);
  Graph2();
}

/*
   A routine to end the display 
*/
void EndGraphics(void)
{
  Graph1();
  xEndDisplay();
  graphics_initialised = False;
  Graph2();
}

/*
   draw a line
*/
void DrawLine(int x1,int y1,int x2,int y2)
{
  Graph1();
  xDrawLine(x1,y1,x2,y2);
  Graph2();
}

/*
   draw a rectangle
*/
void DrawRectangle(int x,int y,int width,int height)
{
  Graph1();
  xDrawRectangle(x,y,width,height);
  Graph2();
}

/*
   draw an ellipse
*/
void DrawEllipse(int x,int y,int width,int height)
{
  Graph1();
  xDrawEllipse(x,y,width,height);
  Graph2();
}

/*
   fill an ellipse
*/
void FillEllipse(int x,int y,int width,int height)
{
  Graph1();
  xFillEllipse(x,y,width,height);
  Graph2();
}

/*
   fill a rectangle
*/
void FillRectangle(int x,int y,int width,int height)
{
  Graph1();
  xFillRectangle(x,y,width,height);
  Graph2();
}

/* wait for a button press */
void WaitForButtonPress()
{
  Graph1();
  xWaitEvent(eButtonPress);
  Graph2();
}  

/* put a single point on the display */
void DrawPoint(int x,int y)
{
  Graph1();
  xPutPoint(x,y);
  Graph2();
}

void ClearWindow(void)
{
  Graph1();
  xClearDisplay();
  Graph2();
}

void FlushGraphics(void)
{
  Graph1();
  xSync(0);
  Graph2();
}

void DrawArc(int x,int y,int width,int height,int angle1,int angle2)
{
  Graph1();
  xDrawArc(x,y,width,height,angle1,angle2);
  Graph2();
}

void FillArc(int x,int y,int width,int height,int angle1,int angle2)
{
  Graph1();
  xFillArc(x,y,width,height,angle1,angle2);
  Graph2();
}

void MousePosition(int *x,int *y)
{
  Graph1();
  xGetMousePos(x,y);
  Graph2();
}

void EventPosition(int *x,int *y)
{
  Graph1();
  xGetLastPos(x,y);
  Graph2();
}

int EventKeyCode(void)
{
	int ret;
	Graph1();
	ret = xGetLastKeyCode();
	Graph2();
	return ret;
}

void DrawString(int x,int y,char *str)
{
  Graph1();
  xDrawString(x,y,str);
  Graph2();
}

void WaitForEvent(int event_mask)
{
  Graph1();
  xWaitEvent(event_mask);
  Graph2();
}

int LastEvent(void)
{
  int res;
  Graph1();
  res = lastevent;
  Graph2();
  return(res);
}

int ScreenWidth(void)
{
  int res;
  if (graphics_initialised) Graph1();
  res = xScreenWidth();
  Graph2();
  return(res);
}

int ScreenHeight(void)
{
  int res;
  if (graphics_initialised) Graph1();
  res = xScreenHeight();
  Graph2();
  return(res);
}

int WindowWidth(void)
{
  int res;
  Graph1();
  res = xWindowWidth();
  Graph2();
  return(res);
}

int WindowHeight(void)
{
  int res;
  Graph1();
  res = xWindowHeight();
  Graph2();
  return(res);
}

int AvailableColors(void)
{
  int res;
  Graph1();
  res = xWindowDepth();
  Graph2();
  return(1 << res);
}

int StringHeight(char *s)
{
  int res;
  Graph1();
  res = xStringHeight(s);
  Graph2();
  return(res);
}

int StringWidth(char *s)
{
  int res;
  Graph1();
  res = xStringWidth(s);
  Graph2();
  return(res);
}

void LoadFont(char *font_name)
{
  Graph1();
 if (!xLoadFont(font_name))
   fprintf(debugfile,"Couldn't find the font %s\n",font_name);
  Graph2();
}

void SetLineStyle(int style)
{
  Graph1();
  xSetLineStyle(style);
  Graph2();
}

void SetLineWidth(int width)
{
  Graph1();
  xSetLineWidth(width);
  Graph2();
}

void AlwaysFlush(int setting)
{
  Graph1();
  always_sync = setting;
  Graph2();
}

void SetDrawingFunction(int fn)
{
  Graph1();
  xSetDrawFunction(fn);
  Graph2();
}

void SaveSettings(void)
{
  Graph1();
  xSaveGC();
  Graph2();
}


void RestoreSettings(void)
{
  Graph1();
  xRestoreGC();
  Graph2();
}

static BOOL random_initialised = False;

unsigned int RandomCard(void)
{
  unsigned int res;
  Graph1();
  if (!random_initialised)
    {
      srandom(getpid());
      random_initialised = True;
    }
  res = (unsigned int)(random());
  Graph2();
  return(res);
}

void SetTitle(char *title)
{
  Graph1();
  xSetTitle(title);
  Graph2();
}

int GetColor(char *name)
{
  int res;
  Graph1();
  res = xGetColor(name);
  Graph2();
  return(res);
}

int GetColorRGB(int red,int green,int blue)
{
  int res;
  Graph1();
  res = xGetColorRGB(red,green,blue);
  Graph2();
  return(res);
}

void SetForeground(int color)
{
  Graph1();
  xSetForeground(color);
  Graph2();
}

void SetBackground(int color)
{
  Graph1();
  xSetBackground(color);
  Graph2();
}

void DrawCircle(int x,int y,int radius)
{
  Graph1();
  xDrawEllipse(x-radius,y-radius,2*radius,2*radius);
  Graph2();
}

void FillCircle(int x,int y,int radius)
{
  Graph1();
  xFillEllipse(x-radius,y-radius,2*radius,2*radius);
  Graph2();
}

void ClearArea(int x,int y,int width,int height)
{
  Graph1();
  xClearArea(x,y,width,height);
  Graph2();
}

int LoadImage(char *fname)
{
	int ret;
	Graph1();
	ret = xLoadImage(fname);
	Graph2();
	return ret;
}

int ImageWidth(int i)
{
	int ret;
	Graph1();
	ret = xImageWidth(i);
	Graph2();
	return ret;
}

int ImageHeight(int i)
{
	int ret;
	Graph1();
	ret = xImageHeight(i);
	Graph2();
	return ret;
}

void PlaceImage(int i, int x, int y)
{
	Graph1();
	xPlaceImage(i, x, y, 1);
        Images[i].x = x;
        Images[i].y = y;
	Graph2();
}

void Flush(void)
{
	Graph1();
	xDisplay();
	Graph2();
}

void RestoreImage(int i)
{
	Graph1();
	xRestoreImage(i, Images[i].x, Images[i].y, 1);
	Graph2();
}

void FreeImage(int i)
{
	Graph1();
	xFreeImage(i);
	Graph2();
}

void Sleep(double sec)
{
	usleep((unsigned)(1000000.0*sec));
}

void Wait(double sec)
{
        Sleep(sec);
}
