
# This is a shell archive.  Remove anything before this line,
# then unpack it by saving it in a file and typing "sh file".
#
# Wrapped by yoyodyne!davet on Thu Nov 30 18:58:58 CST 1989
# Contents:  README VERSIONLOG a.c animate.c control.c contour.c ctlcontour.c
#	data.c getfile.c glob.c gr_xwi.c gr_xwi1.c graph.c i.c image.c
#	intensity.c main.c mem.c notebook.c palentry.c palette.c polar.c read.c
#	shade.c sliceSDS.c write.c xstuff.c xstuff2.c xinit.c date.c animate.h
#	buttons.h getfile.h gr_com.h gr_def.h gr_ext.h gr_inc.h gr_var.h
#	gr_xwi.h i.h list.h notebook.h palentry.h paletteP.h patterns.h
#	xstuff.h xstuff2.h ximage.icon ximage.1 Make.noImake Imakefile
 
echo x - README
sed 's/^@//' > "README" <<'@//E*O*F README//'
This directory contains source code for NCSA X Image Version 1.0.3.
At the time of this writing (11/29/89), this source code has been 
successfully compiled on the following platforms.

	Sun 3 (SunOS 3.x, 4.0)
	Sun 4 (SunOS 4.0)
	Cray 2 (UNICOS 5.0)
	Silicon Graphics Eclipse (OS 3.2A)

In each case, the MIT X.V11R3 libraries were used to compile X Image
along with the HP 2D widget set with R3 patches.

Should you decide to compile X Image, you will also need HDF 
(Hierarchical Data Format) version 2.8 or later.  Source code is 
available from anonymous ftp server (128.174.20.50).   

If you successfully port NCSA X Image to a machine not currently supported,
we would be interested in getting a copy of your patches and binaries.

This NCSA software product is public domain software.  Permission
is granted to do whatever you like with it. Should you feel compelled 
to make a contribution for the use of this software, please send 
it in the form of comments as to what you like or don't like about 
the software, how you use it, how it helps your work, etc. to 
softdev@ncsa.uiuc.edu.

Please send bug reports/fixes to:
Dave Thompson
davet@ncsa.uiuc.edu
or bugs@ncsa.uiuc.edu

--------
The latest version of all NCSA software is kept on the anonymous ftp 
server ftp.ncsa.uiuc.edu (128.174.20.50).  If you don't have access to
the anonymous ftp server, you can obtain a copies through the 
NCSA Technical Resources Catalog.  NCSA software and manuals 
are available for purchase.  To obtain a copy of the catalog, contact:

NCSA Documentation Orders
152 Computing Applications Building
605 East Springfield Avenue
Champaign, IL 61820
(217) 244-0072

--------

Sample data files may be picked up from ftp.ncsa.uiuc.edu (128.174.20.50)

--------
Compile instructions:

	Edit the Makefile to fit your system.  Type 'make'.  

@//E*O*F README//
chmod u=rw,g=r,o=r README
 
echo x - VERSIONLOG
sed 's/^@//' > "VERSIONLOG" <<'@//E*O*F VERSIONLOG//'
Please send bug reports and fixes to davet@ncsa.uiuc.edu.


Version 1.0.0	(9/17/89)
		First Release

Version 1.0.1	(9/24/89)
		Fixed XtTextReplace() call in PrintMesg() in module control.c

		Fixed IsItHDF() in read.c.  DFR8GetDims() dumped core b/c 
			hasPal was char instead of int.

		palette.c: no longer assumes 8 planes means 256 colors.
			It does a XDisplayCells() lookup now.

		Changed (void *) to (char *) for portability.

Version 1.0.2	(10/19/89)
		xstuff.c: 
			Added Callback for EnterWindow event to all 
			dialog widgets.  Callback sets input focus to the 
			window when cursor enters.  
			Makes text input compatible with OpenLook 
			and Motif wm.  

			MakeRasterImage(): image param not defined.
			fixed.

		animate.c: Prevent user from hitting 'Done' button
			while animation is still running.

			Put in XSync after XClearArea to get events
			from server dispatched while animation going on.

			Added support for machines with > 8 bit planes.

			Defined a usleep macro for SYSV machines.

		palette.c:
			Added support for machines with > 8 bit planes.

			didn't uninstall palette before XtDestroy.
			with some wm, palette was screwed up.

		xinit.c:
			(Added) Print out Display information upon startup.

		image.c:
			Added support for machines with > 8 bit planes.

		getfile.c:
			Clear current filename when opening getfile.

			Allocate space to hold filenames instead hoping
			that the values returned from readdir() would
			stick around long enough.

		i.c:
			NewIMAGE() didn't set i->prev to previous IMAGE.

Version 1.0.3 (11/29/89)
		Several changes made to source to make it comply with
		X11R4 contrib tape guidelines.

		getfile.c:
			Change directory when user presses return.
			Change directory when user selects on directory.
@//E*O*F VERSIONLOG//
chmod u=rw,g=r,o=r VERSIONLOG
 
echo x - a.c
sed 's/^@//' > "a.c" <<'@//E*O*F a.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include "animate.h"

#define NIL     (struct ANIMATION *) 0

struct ANIMATION *headANIMATION = NIL;
struct ANIMATION *tailANIMATION = NIL;


struct ANIMATION *NewAnimation()
{
struct ANIMATION *a;
	

	if (!(a = (struct ANIMATION *) XIMalloc(sizeof(struct ANIMATION)))) 
		return(NULL);

	a->name = (char *) 0;
	a->xdim = 0;
	a->ydim = 0;
	a->files = (char **) NULL;
	a->numFrames = 0;
	a->frameNum = 0;
	a->skip = 0;
	a->status = A_STOP;
	a->inMemory = FALSE;
	a->ctrl_showing = FALSE;
	a->pixmaps = (Pixmap *) NULL;
	a->raster = (unsigned char *) NULL;
	a->expRaster = (unsigned char *) NULL;
	a->isExpanded = FALSE;

	a->next = NIL;
	a->prev = NIL;

	if (headANIMATION == NIL)
	        tailANIMATION = headANIMATION = a;
	else {
	        tailANIMATION->next = a;
	        tailANIMATION = a;
	        }

	return(a);
}

void DestroyAnimation(a)
struct ANIMATION *a;
{
        if (a->prev)
                a->prev->next = a->next;
        else
                headANIMATION = a->next;
        if(a->next)
                a->next->prev = a->prev;
        else
                tailANIMATION = a->prev;

	if (a->isExpanded)
		XIFree(a->expRaster);

	XIFree(a->files);
	XIFree(a->name);
	return;
}

ReleaseAllAnimations()
{
struct ANIMATION *a;
	while (headANIMATION)
		CBDoneAnimateCtrlBox(0,headANIMATION,0);
}
@//E*O*F a.c//
chmod u=rw,g=r,o=r a.c
 
echo x - animate.c
sed 's/^@//' > "animate.c" <<'@//E*O*F animate.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>

#include <Xw/Xw.h>
#include <Xw/Valuator.h>
#include "animate.h"
#include "xstuff.h"
#include "getfile.h"

#define	PAL_WIDTH	30
#define PBOXHEIGHT	40
#define PBOXWIDTH	360
#define	ACBOXWIDTH	360
#define ACBOXHEIGHT	100

#define	ROUND(f)	((int)(f + 0.5))

#ifdef SYSV
/*#include <sys/time.h>*/
struct timeval   st_delay;
#define usleep(x)   { \
        st_delay.tv_usec = (x % 1000000); \
        st_delay.tv_sec = (x / 1000000); \
        select(32, NULL, NULL, NULL, &st_delay); }
#endif

extern	Widget	toplevelform;		/* the top composite widget */
extern  XColor  origccells[];		/* currently defined in palette.c*/
extern  XColor  rccells[];		/* currently defined in palette.c*/
extern	void	SetColormap();	
extern	struct	ANIMATION *NewAnimation();
extern	void	DestroyAnimation();

static	char	frame[80];
static	char	skip[80];
static	XImage	*palXImage;	/* display palette with this */
static	char	*palImage;
static	struct	GetFile	animateFile;
static	Widget	toggled,togglem;
static	Visual	*myVis;
static	Display *myDpy;

void	AnimateCtrlBox();




int InitAnimation(dpy)
Display *dpy;
{
register int x;
register int y;

	myDpy = dpy;
	myVis = GetVisual(myDpy);

	if (!(palXImage = MakePalette(myDpy,PAL_WIDTH,TRUE))) {
		return(0); /* malloc probably failed */
		}

	return(1);
} /* InitAnimation() */



char *ComboFile(directory,file)    /*what?*/
char *directory;
char *file;
{
static char combo[512];

	sprintf(combo,"%s/%s",directory,file);
	return(combo); /* good till called again */
}


static void DidntGetANewAnimation(a)
struct ANIMATION *a;
{
	PrintMesg("Get new animation sequence cancelled\n");
}

CBinMemory(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
static  Arg setFalse[]={{XtNset,False}};
struct	ANIMATION *a;

	a = (struct ANIMATION *) client_data;
	a->inMemory = ! a->inMemory;
	if (a->inMemory) {
		PrintMesg("Animate from server memory\n");
                XtSetValues(toggled,setFalse,1);
		}
	else {
		PrintMesg("Animate from disk\n");
                XtSetValues(togglem,setFalse,1);
		}
	
}

CBinMemoryDone(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct	ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	XtDestroyWidget(a->topQbox);
	AnimateCtrlBox(a);
}

static void GotANewAnimation(a)
struct ANIMATION *a;
{ /* initialize animation record */
char buff[256];

	a->name = animateFile.base;

	a->directory = animateFile.directory;
	a->files= animateFile.file;
	a->numFiles = animateFile.numFiles;

	a->xdim = animateFile.xdim;
	a->ydim = animateFile.ydim;

	a->isHDF = animateFile.isHDF;
	a->isFloat = animateFile.isFloat;
	a->frameNum = 1;
	a->skip = 0;
	a->status = A_STOP;

/**/	a->numFrames = a->numFiles;
	if (a->numFiles == 1)  {
		if (a->isHDF) {
			if (a->isFloat) 
			    a->numFrames = HowManySDSInHDF(
					ComboFile(a->directory,a->files[0]));
			else {
			    a->numFrames = HowManyImagesInHDF(
					ComboFile(a->directory,a->files[0]));
/*			    if(!(a->frameIndex = (int *) XICalloc(a->numFrames,
						sizeof(int)))) {
					PrintMesg("out of memory\n");
					return;
					}
			    if (!MakeHDFImageIndex(ComboFile(a->directory,
							a->files[0]),
						a->frameIndex,
						a->numFrames)) {
					PrintMesg("Can't read HDF file\n");
					return;
					}
*/
			    }
			}
		}
	
	if (a->numFrames < 2) {
		PrintMesg("Animation requires more than one frame\n");
		PrintMesg("Cancelling Animation\n");
		return;
		}
		
	sprintf(buff,"Animation sequence has %d images\n",a->numFrames);
	PrintMesg(buff);

	/* read in Palette */
/*	a->hasPalette = FALSE;*/

	a->hasPalette = TRUE;
/**/	a->palette = origccells;
	if (a->isHDF) {
	    if (ReadHDFHasPalette(ComboFile(a->directory,a->files[0])) > 0){
		    if (!(a->palette=(XColor *)XICalloc(256,sizeof(XColor)))){
			PrintMesg("Not enough memory for palette\n");
			return;
			}
		    ReadHDFPalette(ComboFile(a->directory,a->files[0]),
				a->palette);
		    a->hasPalette = TRUE;
		    }
		}
	a->inMemory = False;
	{
	Widget comp;
	int screen;

        screen = XDefaultScreen(myDpy);
	a->topQbox = MakeATopLevelOverride("X Image [Animation].inMemory?",
				toplevelform,
				(DisplayWidth(myDpy,screen)-200)/2,
				(DisplayHeight(myDpy,screen)-100)/2,
				200,100);
	comp = Make_Board("inMemory?",a->topQbox,0,0,200,200);
	togglem =  Make_Toggle("animate from X server memory",comp,5,20,
			CBinMemory,a,CBinMemory,a,False,a->inMemory);
	toggled =  Make_Toggle("animate from disk",comp,5,50,
			CBinMemory,a,CBinMemory,a,False,!a->inMemory);
	(void) MakeButton("     Ok     ",comp,5,70,CBinMemoryDone,a,0,0);
	}
	
} /* GotANewAnimation() */


CBNewAnimate(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct	ANIMATION *a;

	if (!(a = NewAnimation())){
		PrintMesg("Out of memory\n");
		return;
		}
	animateFile.yesfile = GotANewAnimation;
	animateFile.nofile = DidntGetANewAnimation;
	animateFile.type = FTYPE_IMAGE;
	animateFile.param = (char *) a;
	PrintMesg("Please select animation file(s)\n");
	GetAFile(&animateFile);
} /* CBNewAnimate() */

void CBDoneAnimateCtrlBox(w,client_data,call_data)
Widget	w;
caddr_t	client_data;
caddr_t call_data;
{
int x;
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	if (a->status != A_STOP)
		return;	/* animation running, can't quit now */

	if (a->inMemory) {
		PrintMesg("Freeing server memory\n");
		for (x = 0; x < a->numFrames; x++)
			XFreePixmap(myDpy,a->pixmaps[x]);
		}
	XIFree(a->pixmaps);
	XIFree(a->raster);

	if (a->ctrl_showing) {
/*#ifdef  NON_ICCCM_WINDOW_MANAGER*/
	        CBUnInstallImageCMap(a->topLevel,a->cmap,call_data);
/*#endif*/
		XtDestroyWidget(a->topLevel);
		}

	DestroyAnimation(a);

	return;
} /*CBDoneAnimateCtrlBox() */


static void CBUpdateCMap(w,client_data,call_data)
/* Update colormap in client_data to be same as palette module's rccells */
/* ....Sync image palette with palette windows palette */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Colormap cmap;
        cmap = (Colormap) client_data;
        StoreColors(rccells,FALSE,cmap);
}


static void CBLockPalette(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

        a->lockcmap = ! a->lockcmap;
        if (a->lockcmap) {
                StoreColors(rccells,FALSE,a->cmap);
                XtAddEventHandler(a->topLevel,EnterWindowMask,0,
                        CBUpdateCMap,a->cmap);
		}
        else {
                if (a->hasPalette) 
                        StoreColors(a->palette,FALSE,a->cmap);
                else
                        StoreColors(origccells,FALSE,a->cmap);

                XtRemoveEventHandler(a->topLevel,EnterWindowMask,
			0,CBUpdateCMap,a->cmap);
		}
} /* CBLockPalette() */


static int GetNextImage(a,frameNum)
/* prepare and put next image into a->raster or a->expRaster*/
/* takes care of source: HDF or SEQ, multiple or single file */
/* return 0 on error */

struct ANIMATION *a;
int frameNum; /* start at 1 (1..infinity) */
{
register int x;
register int y;
register int z;
int     planes;
int     nbp;    /* number of bytes per pixel */
unsigned char *p;

	if (! a->isHDF) {
		/* multiple SEQ files */

		if (! ReadSEQAnimation(ComboFile(a->directory,
				a->files[frameNum-1]),
			a->raster,a->xdim,a->ydim))
			return(0);
		}
	else {
		/* it's an HDF file */

		if (a->numFiles == 1) {
			/* animate from one HDF file */

			if (a->isFloat) {
				/*read in float
				convert it
				*/
				return(0); /*for now */
				}
			else { 
				if (!ReadHDFAnimationImage(ComboFile(
						a->directory,a->files[0]),
/*				   a->raster,a->frameIndex[frameNum-1]))*/
				   a->raster,frameNum))
					return(0);
				}
			}
		else { /* animate from multiple HDF files */
			if (a->isFloat) {
				/*
				read in float
				convert it
				*/
				return(0); /*for now */
				}
			else {
				if (!ReadHDFAnimationImage(
				    ComboFile(a->directory,
					a->files[frameNum-1]),a->raster,
				    /*a->frameIndex[0]))*/
				    1))
					return(0);
				}
			}
		} /* else: it's an HDF */


	if (a->expRaster) {
	        planes = DisplayPlanes(myDpy,DefaultScreen(myDpy));
	
		nbp = (planes > 7) ? (planes / 8 + ((planes%8)?1:0)) :1;

	        if (nbp >= 3)
			nbp = 4;

		p = a->expRaster;
		for(y = 0; y < a->ydim; y++)
			for(x = 0; x < a->xdim; x++) {
				for (z = 1; z < nbp; z++){
					(*p) = (unsigned char) 0;
					p++;
					}
				(*p) = a->raster[y*a->xdim+x];
				p++;
				}
		}


	return(1);/* ok */

} /* GetNextImage() */


static int DisplayImage(a,frameNum)
struct ANIMATION *a;
int frameNum;
{
Arg	arglist[1];
char	buff[256];

	if (! a->inMemory) {
		if (!GetNextImage(a,frameNum)) {
			if (a->numFiles == 1) 
			    sprintf(buff,"Couldn't get %dth image out of %s\n",
				frameNum,ComboFile(a->directory,a->files[0]));
			else 
			    sprintf(buff,"Couldn't get image from file %s\n",
				ComboFile(a->directory,a->files[frameNum-1]));
			PrintMesg(buff);
			return(0);
			}

		XPutImage(myDpy,XtWindow(a->awin),
				a->awinGC,a->image,
				0,0,0,0,a->xdim,a->ydim);
		}
	else {

		XSetWindowBackgroundPixmap(myDpy,
					XtWindow(a->awin),
					a->pixmaps[frameNum-1]);
		XClearArea(myDpy,XtWindow(a->awin),
				0,0,a->xdim,a->ydim,False);
		XSync(myDpy,False);
		}
	
	/* Set dialog */
	sprintf(a->dFrameString,"%d",a->frameNum);
	gr_DialogSetValue(a->dFrame,a->dFrameString);

	/* Set valuator */
	XtSetArg(arglist[0],XtNsliderOrigin,frameNum);
	XtSetValues(a->slidebar,arglist,1);

	return(TRUE);
}

static int ReadThemAll(a)
/* return 1 on success, 0 on failure */
struct ANIMATION *a;
{
register int x,j;
char buff[80];
Arg	arglist[1];
float	fourth;
int	screen;

	screen = XDefaultScreen(myDpy);

	sprintf(buff,"Reading in %d frames into server memory\n",a->numFrames);
	PrintMesg(buff);

	fourth = ((float) a->numFrames) / 4.0;
	for (j = 0; j < 4; j++) {
	    for (x = ROUND(((float)j)*fourth) 
		     ;x < ROUND((((float)j)+1.0)*fourth); x++ ) {

		if (! GetNextImage(a,x+1))
			return(0);

		a->pixmaps[x] = XCreatePixmap(myDpy,
					XtWindow(a->awin),
					a->xdim,a->ydim,
					DisplayPlanes(myDpy,screen));

/*		if (XCreatePixmap failed, BadAlloc) {
			int y;
			PrintMesg("Server out of memory \n");
			for (y = 0; y < x; y++) 
				XFreePixmap(XtDisplay->topLevel,a->pixmaps[y]);
			return(0);
			}
*/
				

		XPutImage(myDpy,a->pixmaps[x],a->awinGC,a->image,
					0,0,0,0,a->xdim,a->ydim);

/*		XPutImage(myDpy,XtWindow(a->awin),
				a->awinGC,a->image,
				0,0,0,0,a->xdim,a->ydim);
*/
		XSetWindowBackgroundPixmap(myDpy,
					XtWindow(a->awin),
					a->pixmaps[x]);
		XClearArea(myDpy,XtWindow(a->awin),
				0,0,a->xdim,a->ydim,False);
		XSync(myDpy,False);

/* doesn't work 
		XtSetArg(arglist[0],XtNsliderOrigin,x);
		XtSetValues(a->slidebar,arglist,1);
*/

		}
	    switch (j) {
		case 0: PrintMesg("Done loading 25% of animation images\n");
			break;
		case 1: PrintMesg("Done loading 50% of animation images\n");
			break;
		case 2: PrintMesg("Done loading 75% of animation images\n");
			break;
		case 3: PrintMesg("Done loading animation images\n");
			break;
		};
	}
	return(1);
} /* CBReadThemAll() */


static void CBSingleForward(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	a->frameNum = a->frameNum + 1 + a->skip;

	if ((a->frameNum > a->numFrames) || (a->frameNum < 1)) {
		if (a->repeat || (a->status == A_STOP))
			a->frameNum = 1;
		else {
			a->frameNum = a->frameNum - 1 - a->skip;
			a->status = A_STOP;
			return;
			}
		}

	DisplayImage(a,a->frameNum);

	return;

} /* CBSingleForward */



static void CBSingleReverse(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	a->frameNum = a->frameNum - 1 - a->skip;

	if ((a->frameNum > a->numFrames) || (a->frameNum < 1))
		if (a->repeat || (a->status == A_STOP))
			a->frameNum = a->numFrames;
		else {
			a->frameNum = a->frameNum + 1 + a->skip;
			a->status = A_STOP;
			return;
			}

	DisplayImage(a,a->frameNum);


	return;
} /* CBSingleReverse() */



static void CBStop(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
	((struct ANIMATION *)client_data)->status = A_STOP;
}

static void CBContinuousForward(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
XEvent event_return;
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	a->status = A_CFOR;
	while(a->status == A_CFOR) {

		CBSingleForward(w,client_data,call_data);

		while(XtPending()) {
			XtNextEvent(&event_return);
			XtDispatchEvent(&event_return);
			}
		if (a->delay)
			usleep((a->delay)*100000); /* a->delay in 1/10 sec*/
		}
} /* CBContinuousForward() */


static void CBContinuousReverse(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
XEvent event_return;
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	a->status = A_CREV;
	while(a->status == A_CREV) {

		CBSingleReverse(w,client_data,call_data);

		while(XtPending()) {
			XtNextEvent(&event_return);
			XtDispatchEvent(&event_return);
			}
		if (a->delay)
			usleep((a->delay)*100000); /* a->delay in 1/10 sec*/
		}
} /* CBContinuousReverse() */


static void CBSetFrame(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct ANIMATION *a;
int	newFrame;
char	buff[80];

	a = (struct ANIMATION *) client_data;

	newFrame = atoi(XtDialogGetValueString(a->dFrame));
	if ((newFrame > a->numFrames) || ( newFrame < 1)) {
		sprintf(buff,"Frame number out of Range (1 - %d)\n",
					a->numFrames);
		PrintMesg(buff);
		}
	else {
		a->frameNum = newFrame;
		DisplayImage(a,a->frameNum);
		}

	sprintf(a->dFrameString,"%d",a->frameNum);
	gr_DialogSetValue(a->dFrame,a->dFrameString);


} /* CBSetFrame */

static void CBValuatorRelease(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
int	newFrame;
char	buff[80];
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;
	newFrame = (int) call_data;

	if ((newFrame > a->numFrames) || ( newFrame < 1)) {
		/* this should never happen */
		sprintf(buff,"Frame number out of Range (1 - %d)\n",
					a->numFrames);
		PrintMesg(buff);
		}
	else {
		a->frameNum = newFrame;
		DisplayImage(a,a->frameNum);
		}

	sprintf(a->dFrameString,"%d",a->frameNum);
	gr_DialogSetValue(a->dFrame,a->dFrameString);

}

static void CBSetSkip(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct ANIMATION *a;
int	newSkip;
char	buff[80];

	a = (struct ANIMATION *) client_data;

	newSkip = atoi(XtDialogGetValueString(a->dSkip));
	if ((newSkip > a->numFrames) || ( newSkip < 0)) {
		sprintf(buff,"Number out of Range (0 - %d)\n",a->numFrames);
		PrintMesg(buff);
		}
	else {
		a->skip = newSkip;
		}
	sprintf(a->dSkipString,"%d",a->skip);
	gr_DialogSetValue(a->dSkip,a->dSkipString);
} /* CBSetSkip */

static void CBSetDelay(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
char	buff[80];
struct ANIMATION *a;
int	newDelay;

	a = (struct ANIMATION *) client_data;

	newDelay= atoi(XtDialogGetValueString(a->dDelay));
	if ((newDelay > 1000) || ( newDelay < 0)) 
		PrintMesg("Delay: That number just won't do...\n"); 
	else 

		a->delay = newDelay;

	sprintf(a->dDelayString,"%d",a->delay);
	gr_DialogSetValue(a->dDelay,a->dDelayString);

	if (a->delay == 10)/* I know this is silly.....adds to the esthetics */
		PrintMesg("Setting delay to 1 second\n");
	else {
		sprintf(buff,"Setting delay to %.1f seconds\n",
			((float)a->delay)/10.0);
		PrintMesg(buff);
		}
}

static void CBExpose(w,client_data,call_data)
/* Animation window exposed, redraw image */
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	if (a->frameNum == 0){
		DisplayImage(a,1);
		a->frameNum = 1;
		}
	else
		DisplayImage(a,a->frameNum);

} /* CBExpose() */

static void CBRepeat(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct ANIMATION *a;
	a = (struct ANIMATION *) client_data;

	a->repeat = ! a->repeat;
}


void AnimateCtrlBox(a)
struct ANIMATION	*a;
{
int	xpos,ypos;
int	width,height;
Widget	box1,box3,box4;
Widget	acbox;	/*animation control box */
Widget	pbox;	/*palette box */
Widget	box5,box6,box7;
XGCValues       gcvalues;
char	buff[256];


	PlaceWindow(&xpos,&ypos);
	width = a->xdim + 10;
	width = (width < ACBOXWIDTH+10)? ACBOXWIDTH +10 : width;
	width = (width < PBOXWIDTH+10)? PBOXWIDTH+10: width;
	height = a->ydim + 40 + ACBOXHEIGHT+ PBOXHEIGHT;

	if (!(a->pixmaps = (Pixmap *) 
			XICalloc(a->numFrames,sizeof(Pixmap)))) {
		PrintMesg("Can't Allocate any memory\n");
		return;
		}

	if(!(a->raster = (unsigned char *)
			XIMalloc( sizeof(char) * a->xdim * a->ydim ))){
		PrintMesg("Can't allocate memory for animation\n");
		/**** should clean up stuff here (like trash a)*/
		return;	
		}

	{
	int planes;
	int	nbp; /* number of bits per pixel */


        planes = DisplayPlanes(myDpy,DefaultScreen(myDpy));
	
	if (planes > 8){
       	    nbp = (planes > 7) ? (planes / 8 + ((planes%8)?1:0)) :1;

	   if(!(a->expRaster=(unsigned char *) XIMalloc(a->xdim*a->ydim*nbp))){
		PrintMesg("Couldn't allocate enough memory\n");
		return;
		}
	    a->image = XCreateImage(myDpy,myVis,planes,ZPixmap,0,
					a->expRaster,a->xdim,a->ydim,
					8*nbp,a->xdim*nbp);
	    a->isExpanded = TRUE;
	    }
	else {
	    a->image = XCreateImage(myDpy, myVis, 8, ZPixmap, 0, 
				a->raster, a->xdim, a->ydim, 8, a->xdim);
	    a->isExpanded = FALSE;
	    }
	}

	a->topLevel = MakeATopLevel("X Image [Animate]",toplevelform,
				xpos,ypos,width,height);
	a->lockcmap = FALSE;
	if (myVis->class == PseudoColor) {
		a->cmap = XCreateColormap(myDpy,XtWindow(a->topLevel),
			myVis,AllocAll);
			}
	else {
		a->cmap = XCreateColormap(myDpy,XtWindow(a->topLevel),
			myVis,AllocNone);
			}
        SetColormap(a->topLevel,a->cmap);

	Set_Pointer(a->topLevel,XC_gumby);

	a->composite = Make_Board(a->name,a->topLevel,0,0,
				width,height);
	
	box1 = Make_ButtonBox(a->composite,5,5,width-50,25);
        (void) Make_Label(a->name,box1,2,2,width-55);

	(void) MakeButton("Done",a->composite,width-40,5,
				CBDoneAnimateCtrlBox,a,0,0);

	a->awin = Make_Board("Animate widget",a->composite,
				(width - a->xdim)/2,35,
				a->xdim,a->ydim);

		
				
		

	a->awinGC = XtGetGC(a->awin,NULL,&gcvalues);

	pbox = Make_ButtonBox(a->composite,(width-PBOXWIDTH)/2,
				height - ACBOXHEIGHT- PBOXHEIGHT,
                                PBOXWIDTH,PAL_WIDTH +5);


        a->pal_win = MakeRasterImage("palette",pbox,
                                2,2,
                                palXImage,NULL,NULL);

	(void) Make_Toggle("Lock Palette",pbox,265,10,
			CBLockPalette,a,CBLockPalette,a,True,False);


	a->frameNum = 1;

	acbox = Make_ButtonBox(a->composite,
				(width-ACBOXWIDTH)/2,
				height-ACBOXHEIGHT,
                                ACBOXWIDTH,ACBOXHEIGHT-10);

	a->repeat = FALSE;
	Make_Toggle("Repeat",acbox,5,70,CBRepeat,a,CBRepeat,a,False,False);
#ifdef UNDER_DEVELOPMENT
	Make_Toggle("Reverse",acbox,70,70,NULL,NULL,NULL,NULL,False,False);
#endif

	box4 = Make_ButtonBox(acbox,2,2,155,60);

	a->bcrev = MakeButton("<<",box4,5,5,CBContinuousReverse,a,0,0);
	a->bsrev = MakeButton("< ",box4,30,5,CBSingleReverse,a,0,0);
	a->bstop = MakeButton("<STOP>",box4,55,5,CBStop,a,0,0);
	a->bsfor = MakeButton(" >",box4,105,5,CBSingleForward,a,0,0);
	a->bcfor = MakeButton(">>",box4,130,5,CBContinuousForward,a,0,0);

	if (a->inMemory)
		a->slidebar =MakeValuator("valuator",box4,5,30,145,25,FALSE,1,
				a->numFrames+1,a->frameNum,1,
				CBValuatorRelease,a,
				CBValuatorRelease,a,
				CBValuatorRelease,a);
	else
		a->slidebar =MakeValuator("valuator",box4,5,30,145,25,FALSE,1,
				a->numFrames+1,a->frameNum,1,
				NULL,NULL,
				CBValuatorRelease,a,
				CBValuatorRelease,a);

        Set_Pointer(a->slidebar,XC_sb_h_double_arrow);

	sprintf(a->dFrameString,"1");
	box5 = Make_ButtonBox(acbox,160,2,62,ACBOXHEIGHT-15);
	a->dFrame = Make_Dialog("name",box5,"Frame:",
			a->dFrameString,DSTRINGSIZE,2,2,56,56);
	MakeButton("  Set   ",box5,2,65,CBSetFrame,a,0,0);
	a->frameNum = 1;
	a->delay = 0;

	sprintf(a->dSkipString,"%d",a->skip);
	box6 = Make_ButtonBox(acbox,227,2,62,ACBOXHEIGHT-15);
	a->dSkip = Make_Dialog("name",box6,"Skip:",a->dSkipString,
				DSTRINGSIZE,2,2,56,56);
	MakeButton("  Set   ",box6,2,65,CBSetSkip,a,0,0);

	sprintf(a->dDelayString,"%d",a->delay);
	box6 = Make_ButtonBox(acbox,293,2,62,ACBOXHEIGHT-15);
	a->dDelay= Make_Dialog("name",box6,"Delay:",a->dDelayString,
				DSTRINGSIZE,2,2,56,56);
	MakeButton("  Set   ",box6,2,65,CBSetDelay,a,0,0);


        XtAddEventHandler(a->awin,ExposureMask,0,CBExpose,a);

	XSync(myDpy,False);	 /* a->awin must be created before cont. */


        Set_Pointer(a->awin,XC_left_ptr);

	if (a->hasPalette) {
		StoreColors(a->palette,FALSE,a->cmap);
                }
        else
                StoreColors(origccells,FALSE,a->cmap);


	if(!(a->frameIndex = (int *) XICalloc(a->numFrames,sizeof(int)))) {
		PrintMesg("out of memory\n");
		return;
		}
/*	if (!MakeHDFImageIndex(ComboFile(a->directory,a->files[0]),
			a->frameIndex,a->numFrames)) {
		PrintMesg("Can't read HDF file\n");
		return;
		}
*/

    sprintf(buff,"Dimensions of animation sequence: %dx%d\n",a->xdim,a->ydim);
	PrintMesg(buff);

	if (a->inMemory) {
		if (! ReadThemAll(a)) {
			CBDoneAnimateCtrlBox(a->awin,a,NULL);
			return;
			}
		}
	a->ctrl_showing = TRUE;

} /* AnimateCtrlBox() */

@//E*O*F animate.c//
chmod u=rw,g=r,o=r animate.c
 
echo x - control.c
sed 's/^@//' > "control.c" <<'@//E*O*F control.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xatom.h>
#include <X11/AsciiText.h>
#include <X11/cursorfont.h>

#include "xstuff.h"
#include "buttons.h"
#include "gr_def.h"
#include "gr_var.h"

#define MAIN_CTRL_DIM_X
#define MAIN_CTRL_DIM_Y
#define MSGBUFFSIZE	4096

extern void Quit();
extern void ImageBox();
extern void CBNewImage();
extern void PaletteBox();
extern void GetAFile();
extern void CBDrawSDSBox();
extern void CBNewAnimate();
extern void CBTestNotebook();


static	Widget	msg_window;
static	char msgbuff[MSGBUFFSIZE];
static	msgWinCreated = FALSE;

Init_Ctrl_Window(parent)
Widget parent;
{
Widget  ctrl_window;
Widget	buttonbox;
int	x;


	ctrl_window = Make_Window(GetVersion(),
				parent,0,0,402,200); 
	
	for(x=0; x< MSGBUFFSIZE; x++)
		msgbuff[x]=' ';
	for(x=0; x < MSGBUFFSIZE; x+=10)
		msgbuff[x]='\n';

	msgbuff[MSGBUFFSIZE-1]='\0';

/*	msg_window = Make_Text(ctrl_window,1,22,400,80,
				msgbuff);
*/

	msg_window = (Widget) gr_MakeText("LogWindow",ctrl_window,VERTONLY,
                                        SELECTABLE,STRINGSOURCE,
                                        msgbuff,
                                        1, 22, 400, 80);
	msgWinCreated = TRUE;
PrintMesg("This software is a product of the National Center for \n");
PrintMesg("Supercomputing Applications at the University of Illinois\n");
	PrintMesg("Please send bug reports to davet@ncsa.uiuc.edu\n");
	PrintMesg(GetVersionDate());

        Set_Pointer(msg_window,XC_gumby);
	buttonbox = Make_ButtonBox(ctrl_window,1,105,400,40);
	b[CTRL_IMAGE]	= MakeButton("Image",buttonbox,1,1,
				CBNewImage,NULL,0,0);
	b[CTRL_PALETTE]	= MakeButton("Palette",buttonbox,45,1,
				PaletteBox,NULL,0,0);
	b[CTRL_ANIMATE] = MakeButton("Animate",buttonbox,101,1,
				CBNewAnimate,NULL,0,0);
#ifdef UNDER_DEVELOPMENT
	b[CTRL_NOTEBOOK]= MakeButton("Notebook",buttonbox,157,1,
				CBTestNotebook,NULL,0,0);
/*	(void) MakeButton("Test",buttonbox,250,1,CBDrawSDSBox,NULL,0,0);*/
#endif
	b[CTRL_QUIT]	= MakeButton("Quit",buttonbox,365,1,Quit,NULL,0,0);
}

PrintMesg(s)
char *s;
{
static int ptr = 0;
int i;
XtTextBlock text;

int slength = strlen(s);

	if (!msgWinCreated){
		printf("%s",s);
		return;
		}
	if((strlen(s) + ptr) > MSGBUFFSIZE) {
		/* reset message buffer */
		int x;
		ptr = 0;
		for(x=0; x< MSGBUFFSIZE; x++)
			msgbuff[x]=' ';
		for(x=0; x < MSGBUFFSIZE; x+=10)
			msgbuff[x]='\n';
		msgbuff[MSGBUFFSIZE-1]='\0';
		}
	strncpy((msgbuff+ptr),s,slength); /* copy mesg except for null */

	text.ptr = s;
	text.firstPos = 0;
	text.length = slength;
	text.format = FMT8BIT;
	i = XtTextReplace(msg_window,ptr,ptr+slength,&text);
	XtTextDisplay(msg_window);
	XtTextSetInsertionPoint(msg_window,ptr);
/*XtTextSetInsertionPoint(msg_window,XtTextGetInsertionPoint(msg_window));*/
	ptr = ptr + slength;
}
@//E*O*F control.c//
chmod u=rw,g=r,o=r control.c
 
echo x - contour.c
sed 's/^@//' > "contour.c" <<'@//E*O*F contour.c//'

/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Dave Thompson, National Center for Supercomputing Applications
 * davet@ncsa.uiuc.edu
 */

/* Author: Dave Whittington */
/*  All new contour plot -- for faster execution speeds and extra  */
/*  compactness.  Now available in convenient "FamileePaks".	   */

#include	<X11/Xlib.h>
#include	<X11/Intrinsic.h>

#define	data(x,y)	(unsigned char) ri[y*xmax + x]

void Updt_Contour(w,ri,cl,xmax,ymax,px,py,xdim,ydim,fore,back)
Widget	w;
char	*ri;
unsigned char	cl[];
int	xmax,ymax,px,py,xdim,ydim;
unsigned long	fore,back;
{
int	x,y,count;
unsigned char	d0,d1,d2;
Display	*disp;
Drawable d;
GC	the_gc;
XGCValues values;
Boolean	plotMe;

/*	set up XWindows specific stuff...	*/

	disp = XtDisplay(w);
	d = XtWindow(w);
	values.foreground = fore;
	values.background = back;
	the_gc = XtGetGC(w,(GCForeground | GCBackground),&values);

	XSetForeground(disp,the_gc,fore);
	XSetBackground(disp,the_gc,back);
/*	Now, check the bounds and start plotting	*/

	if (xdim > xmax) xdim = xmax;
	if (ydim > ymax) ydim = ymax;
	for (y = py; y < ydim; y++)
	{
		x = px;
		d1 = data(x,y);
		d2 = data(x,(y+1));
		while (x < xdim)
		{
			d0 = d1;
			d1 = data(x+1,y);
			d2 = data(x,(y+1));
			plotMe = (d0 >= cl[1]) && (d0 <= cl[cl[0]]);
			plotMe = plotMe || (d1 >= cl[1]) && (d1 <= cl[cl[0]]);
			plotMe = plotMe || (d2 >= cl[1]) && (d2 >= cl[cl[0]]);
			count = 1;
			while ((count <= cl[0]) && plotMe)
			{
				if (((d0 >= cl[count]) && (d1 < cl[count])) ||
				   ((d0 < cl[count]) && (d1 >= cl[count])) ||
				   ((d0 >= cl[count]) && (d2 < cl[count])) ||
				   ((d1 < cl[count]) && (d2 >= cl[count])))
				{
					XDrawPoint(disp,d,the_gc,x,y);
					count = cl[0];
				}
				count++;
				plotMe = (d0 <= cl[cl[0]]);
				plotMe = (d1 <= cl[cl[0]]) || plotMe;
				plotMe = (d2 <= cl[cl[0]]) || plotMe;
			}
			x++;
		}
	}
}
@//E*O*F contour.c//
chmod u=rw,g=r,o=r contour.c
 
echo x - ctlcontour.c
sed 's/^@//' > "ctlcontour.c" <<'@//E*O*F ctlcontour.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <Xw/Xw.h>
#include <Xw/Toggle.h>
#include <X11/Dialog.h>

#include "i.h"
#include "xstuff.h"

#define	CTRLBOX_XDIM	350		/* dimensions of contour input box*/
#define	CTRLBOX_YDIM	110

#define EVENLY_SPACED	0
#define	USER_DEF	1

#define MAX_CONTOUR_LEVELS	256	/* maximum number of contour levels */
#define	DEFAULT_NUM_LEVELS	5	/* Default number of contour levels*/

extern  Widget  toplevelform;
extern	void	CBContour();	/* <----should be moved into this module*/

static	char	AmIOpen = FALSE;	/* is the ctrlContourBox created?*/
static	Widget	ctrlContourBox;
static	Widget	ctrlCBboard;
static	Widget	InputBox;
static	char	contourMode = EVENLY_SPACED;
static	float	contourMin,contourMax,contourIsFloat;
static	unsigned char	*contourLevels;
static	struct	IMAGE	*imageToContour;		/* Image working on */

static  Widget  mes_Dialog_NL;
static	char	mes_numLevels[10];
static	Widget	mes_Dialog_Min;
static	char	mes_minLevel[10];
static	Widget	mes_Dialog_Max;
static	char	mes_maxLevel[10];

static	Widget	mud_Dialog_L;
static	char	mud_Levels[1024];
static	Widget	esToggle;
static	Widget	udToggle;
       

static void MakeEvenlySpaced(w)
Widget w;
{
char	buff[80];


	mes_Dialog_NL = Make_Dialog("NumLevels",w,"Number of Levels",
			mes_numLevels,sizeof(mes_numLevels)-1,
			2,2, CTRLBOX_XDIM/3,CTRLBOX_YDIM/2-5);

	if (contourIsFloat)
		sprintf(buff,"Min Value (%6.3f)",contourMin);
	else
		sprintf(buff,"Min Value (%d)",(int) contourMin);
		
	mes_Dialog_Min = Make_Dialog("Min",w,buff, 
			mes_minLevel,sizeof(mes_minLevel)-1,
			CTRLBOX_XDIM/3+2,2, CTRLBOX_XDIM/3-2,CTRLBOX_YDIM/2-5);

	if (contourIsFloat)
		sprintf(buff,"Max Value (%6.3f)",contourMax);
	else
		sprintf(buff,"Max Value (%d)",(int) contourMax);
	mes_Dialog_Max = Make_Dialog("Max",w,buff, 
			mes_maxLevel,sizeof(mes_maxLevel)-1,
			CTRLBOX_XDIM*2/3+2,2, CTRLBOX_XDIM/3-5,CTRLBOX_YDIM/2-5);
} /* MakeEvenlySpaced() */

static void RemoveEvenlySpaced()
{
	XtDestroyWidget(mes_Dialog_NL);
	XtDestroyWidget(mes_Dialog_Min);
	XtDestroyWidget(mes_Dialog_Max);
}


static void MakeUserDef(w)
Widget w;
{

	mud_Dialog_L = Make_Dialog("NumLevels",w,
			"Please specify levels (separate with space)",
		mud_Levels,sizeof(mud_Levels),
		2,2, CTRLBOX_XDIM-7,CTRLBOX_YDIM/2-5);
}

static void RemoveUserDef()
{
	XtDestroyWidget(mud_Dialog_L);
}

static void CBCancel(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	PrintMesg("Cancelled Contour\n");
	XtDestroyWidget((Widget) client_data);
	AmIOpen = FALSE;

	return;

} /* CBCancel */



int TranslateFtoRI(f,min,max)
float	f;
float	min,max;
/* Translate from floating point scale to int 0-255 scale */
{
	return((int)(((f - min)/(max - min)) * 255.0));
}

static void AdvanceToBlank(s)
char **s;
{
	/* skip over any white space (if any) */
	while( (**s) && ( (**s == ' ') || (**s == '\n')))
		(*s)++;
	/* skip over test till next white space */
	while( (**s) && ( (**s != ' ') && (**s != '\n')))
		(*s)++;
	
}

static void CBOk(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
char	buff[80];
	/* check everything*/

	if (contourMode == EVENLY_SPACED) {
		float max,min;
		int num,x;
		int start,end,inc,count;

		/*** This should be atof instead of atoi ***/
		/**** but atof doesn't seem to be working */
		max = (float)atoi(XtDialogGetValueString(mes_Dialog_Max));
/*		printf("Dialog max says %s\n",
			XtDialogGetValueString(mes_Dialog_Max));
		printf("max is %f\n",max);
*/
		min = (float)atoi(XtDialogGetValueString(mes_Dialog_Min));
		num = atoi(XtDialogGetValueString(mes_Dialog_NL));
		max = (max > contourMax)? contourMax: 
				(max < contourMin)? contourMax: max;
		min = (min < contourMin)? contourMin:
				(min > contourMax)? contourMin: min;

		/* check bounds */ 
		if ((max == 0.0) && (min == 0.0)) { 
			max = contourMax; 
			min = contourMin;
			}
		num = ((num <= 0) || (num >MAX_CONTOUR_LEVELS))?
				DEFAULT_NUM_LEVELS:num;

		if (contourIsFloat) {
			start = TranslateFtoRI(min,contourMin,contourMax);
			end = TranslateFtoRI(max,contourMin,contourMax);
			sprintf(buff,
			  "Plotting %d contours levels from %6.3f to %6.3f\n",
			   num,min,max);
			PrintMesg(buff);
			}
		else {
			start = (int) min;
			end = (int) max;
			sprintf(buff,
				"Plotting %d contours levels from %d to %d\n",
				num,start,end);
			PrintMesg(buff);
			}
		inc = (end-start) / num;
		for(x=start, count=1; x < end ; x+=inc, count++)
			contourLevels[count] = x;
		contourLevels[0] = --count;
		}
	else { /* User Defined */
		char	*contourString;
		float	floatLevel;
		int	intLevel;
		int	count;

		contourString = XtDialogGetValueString(mud_Dialog_L);

		if (contourIsFloat) {
			count = 1;
			while(sscanf(contourString,"%f",&floatLevel) == 1) {
				contourLevels[count++] = (unsigned char) 
						TranslateFtoRI(floatLevel,
						contourMin,contourMax);
				AdvanceToBlank(&contourString);
				}
			contourLevels[0] = --count;
			}
		else {
			count = 1;
			while(sscanf(contourString,"%d",&intLevel) == 1) {
				contourLevels[count++] = (unsigned char)
						intLevel;
				AdvanceToBlank(&contourString);
				}
			contourLevels[0] = --count;
			}/*else*/
		}/*else*/

	XtDestroyWidget((Widget) client_data);
	AmIOpen = FALSE;
	PrintMesg("Plotting Contour\n");

/*	{ int x;
	for (x=1; x <= contourLevels[0]; x++ )
		printf("doing level %d \n",(int) contourLevels[x]);
	}
*/
	CBContour(w,imageToContour,NULL);

	return;
} /* CBOk */

static void CBEvenlySpaced(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
static	Arg setTrue[]={{XtNset,True}};
static	Arg setFalse[]={{XtNset,False}};

	if (contourMode == EVENLY_SPACED) { /* if already set */
		XtSetValues(w,setTrue,1);
		return;
		}
	else {
		XtSetValues(udToggle,setFalse,1);
		RemoveUserDef();
		MakeEvenlySpaced(InputBox);
		contourMode = EVENLY_SPACED;
		}
	return;
	
}
static void CBUserDefined(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
static	Arg setTrue[]={{XtNset,True}};
static	Arg setFalse[]={{XtNset,False}};

	if (contourMode == USER_DEF) { /* if already set */
		XtSetValues(w,setTrue,1);
		return;
		}
	else {
		XtSetValues(esToggle,setFalse,1);
		RemoveEvenlySpaced();
		MakeUserDef(InputBox);
		contourMode = USER_DEF;
		}
	return;
	
}

void CBCtrlContourBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct  IMAGE *i;		/* data set info stored here */
int	xpos,ypos;		/* where to put the box */
Widget	b1,b2,b3;
static	Arg setTrue[]={{XtNset,True}};

	if (AmIOpen) {
		PrintMesg("Contour Control Box already open\n");
		return;
		}


        i = (struct IMAGE *) client_data;

	contourMin = i->minvalue;
	contourMax = i->maxvalue;
	contourIsFloat = i->isFloat;
	imageToContour = i;
	if(!(i->contourLevels = contourLevels = (unsigned char *) 
		XICalloc(MAX_CONTOUR_LEVELS,sizeof(unsigned char)))){
		PrintMesg("Can't allocate memory for contour levels\n");
		return;
		}

	PrintMesg("Please specify contour levels to plot\n");

	PlaceWindow(&xpos,&ypos);
	ctrlContourBox = MakeATopLevel("X Image [Image.Graph.Contour]",
                                toplevelform,xpos,ypos,CTRLBOX_XDIM,
				CTRLBOX_YDIM);

	ctrlCBboard = Make_Board(i->name,ctrlContourBox,0,0,
                                CTRLBOX_XDIM,CTRLBOX_YDIM);

	InputBox = Make_Board(i->name,ctrlCBboard,0,0,
				CTRLBOX_XDIM,CTRLBOX_YDIM/2);


	b2 = Make_Board(i->name,ctrlCBboard,3,CTRLBOX_YDIM/2+2,CTRLBOX_XDIM/2-3,CTRLBOX_YDIM/2-5);
	esToggle = Make_Toggle("Evenly spaced",b2,5,5,CBEvenlySpaced,NULL,
				CBEvenlySpaced,NULL,False,False);
	udToggle = Make_Toggle("User defined levels",b2,5,30,CBUserDefined,NULL,
				CBUserDefined,NULL,False,False);

	b3 = Make_Board(i->name,ctrlCBboard,CTRLBOX_XDIM/2,CTRLBOX_YDIM/2+2,
				CTRLBOX_XDIM/2-2,CTRLBOX_YDIM/2-5);
	(void) MakeButton("    Ok    ",b3,10,(CTRLBOX_YDIM/4)-12,
				CBOk,ctrlContourBox,0,0);
	(void) MakeButton("  Cancel  ",b3,(CTRLBOX_XDIM/2)-85,
				(CTRLBOX_YDIM/4)-12,CBCancel,
				ctrlContourBox,0,0);

	if (contourMode == EVENLY_SPACED) {
		MakeEvenlySpaced(InputBox);
		XtSetValues(esToggle,setTrue,1);
		}
	if (contourMode == USER_DEF) {
		MakeUserDef(InputBox);
		XtSetValues(udToggle,setTrue,1);
		}

	AmIOpen = TRUE;
	return;
} /* CBCtrlContourBox */


/*
void CBMakeEvenlySpaced(ew,client_data,call_data)
Widget ew;
caddr_t client_data;
caddr_t call_data;
{
GC	gc;
XGCValues	gcval;
char	buff[80];
Widget	w;

	w = (Widget) client_data;
	gcval.foreground = black;
	gcval.background = white;
	gc = XtGetGC(i->ghws.box3,GCForeground | GCBackground, &gcval);

	XDrawString(XtDisplay(w),XtWindow(w),gc,5,(CTRLBOX_YDIM/4)-5,
			"Number of Levels",16);
	sprintf(buff,"Min Value (%f)",contourMin);
	XDrawString(XtDisplay(w),XtWindow(w),gc,CTRLBOX_XDIM/2,5,
			buff,strlen(buff));
	sprintf(buff,"Max Value (%f)",contourMax);
	XDrawString(XtDisplay(w),XtWindow(w),gc,CTRLBOX_XDIM/2,40,
			buff,strlen(buff));
}
*/
/****	XtAddEventHandler(ctrlContourBox,Exposure,0,
		CBMakeEvenlySpaced,w); *****/
	
@//E*O*F ctlcontour.c//
chmod u=rw,g=r,o=r ctlcontour.c
 
echo x - data.c
sed 's/^@//' > "data.c" <<'@//E*O*F data.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include <X11/List.h>

#include <math.h>

#include "xstuff.h"
/*#include "list.h"*/
#include "xstuff2.h"
#include "i.h"

#define ROUND(x)        ((int) (x + 0.5))
#define	PI	3.1415927

#define	FRACTSIZE	3
#define	WIDTH		5


#define	XLOC		300
#define	YLOC		300
#define	XDIM		350
#define	YDIM		350

extern  Widget  toplevelform;

static	Widget	topDataWidget;
static	Widget	dataBaseWidget;
static	Widget	dataListWidget;

static void MakeDataString();
void CBDoneData();
void CBSelectData();


int InitData(dpy)
Display *dpy;
{

	return(1);	/* return NULL if fatal */
}


static int MakeScalarString(datastring,length,width,ptr)
char	*datastring[];
int	length;
char	**ptr;	/* return value: storage area for strings */
{
int	x,y,z;
char	format[20];

	if(!(*ptr = (char *) XIMalloc(length*(width+1)))) { 
		printf("Can't allocate enough memory for data display\n");
		return(0);
		}
	if (width > 6)
		sprintf(format,"%%%dd   ",width-3);
	else
		sprintf(format,"%%%dd",width);
	for (z = 0 ; z < length; z++) {
		sprintf(*ptr,format,z);
		datastring[z] = *ptr;
		(*ptr) += (strlen(*ptr)+1);
		}

	datastring[length] = NULL;
	return(1);

} /* MakeScalarString() */


static void CBDataVScroll(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i = (struct IMAGE *) client_data;

	gr_VPortVertMove(i->dws.box4,(int) call_data);
}


static void CBDataHScroll(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i = (struct IMAGE *) client_data;

	gr_VPortHoriMove(i->dws.box3,(int) call_data);
}




static void DisplayData(i)
struct IMAGE *i;
{
int	x,y;
Widget	theVPort;
	if (i->data_showing)
		return;

	/* allocate space for data display strings */
	if (i->isFloat)
	    i->dws.pdata = (char *)XICalloc(i->xdim*i->ydim+1,
				i->fwidth+3);/*3=[+-].\0 */
	else
	    i->dws.pdata = (char *)XICalloc(i->xdim*i->ydim+1,i->fwidth+2);

	if (!i->dws.pdata) {
		PrintMesg("Can't allocate enough memory to display data\n");
		return;
		}
		

	/* allocate space for index of strings (for list widget) */
	i->dws.pdata2 = (char *) XICalloc(i->xdim*i->ydim + 1,sizeof(char *));
	if (!i->dws.pdata2) {
		PrintMesg("Can't allocate enough memory to display data\n");
		XIFree(i->dws.pdata);
		return;
		}

	if (i->isFloat)
		MakeDataString(i->dws.pdata2,i->dws.pdata,i->xdim,
				i->ydim,i->fdataset, TRUE,i->format);
	else
		MakeDataString(i->dws.pdata2,i->dws.pdata,i->xdim,
				i->ydim,i->ri,FALSE,i->format);
	/* Done creating string list of data for data window */

	/* Make Widgets */
	i->dws.toplevel = MakeATopLevel("X Image [Image.DataSet]",toplevelform,
				XLOC,YLOC,XDIM,YDIM);

	i->dws.composite = Make_Board(i->name,i->dws.toplevel,
				5,5,XDIM,YDIM);

	i->dws.box5 = NewMakeList("DataSet",i->dws.composite,&(i->dws.box2),
				VERTHORIZ,i->xdim,5,
				CBDataVScroll,CBDataHScroll,CBSelectData,i,
				i->dws.pdata2,40,60,XDIM-50,YDIM-65);


	/* Create X and Y string lists for data window ticks */
	i->dws.pdata3 = (char *) XICalloc(i->xdim + 2,sizeof(char *));
	if (!i->dws.pdata3) {
		PrintMesg("Can't allocate enough memory to display data\n");
		XIFree(i->dws.pdata);
		XIFree(i->dws.pdata2);
		return;
		}

	i->dws.pdata4 = (char *) XICalloc(i->ydim + 2,sizeof(char *));
	if (!i->dws.pdata4) {
		PrintMesg("Can't allocate enough memory to display data\n");
		XIFree(i->dws.pdata);
		XIFree(i->dws.pdata2);
		XIFree(i->dws.pdata3);
		return;
		}
	if(! MakeScalarString((char *) i->dws.pdata3,i->xdim+1,i->fwidth,
				&(i->dws.pdata5)))
		return;
	if(! MakeScalarString((char *) i->dws.pdata4,i->ydim+1,
				(int)log10((double)i->ydim)+1,
				&(i->dws.pdata6)))
		return;	
	i->dws.box6 = NewMakeListStatic("staticList",i->dws.composite,
			&(i->dws.box3), i->xdim,NULL,NULL,
			(char *) i->dws.pdata3,40,35,XDIM-75,20);
	i->dws.box7 = NewMakeListStatic("OogaBooga",i->dws.composite,
			&(i->dws.box4), 1,NULL,NULL,
			(char *) i->dws.pdata4,5,60,30,YDIM-90);


	i->dws.box1 = Make_ButtonBox(i->dws.composite,5,5,XDIM-60,25);
	(void) Make_Label(i->label,i->dws.box1,2,2,30);
	(void) Make_Label(i->name,i->dws.box1,33,2,XDIM-100);
	(void) MakeButton("Done",i->dws.composite,XDIM-50,6,CBDoneData,i,0,0);


	i->data_showing = TRUE;
	
	return;
} /* DisplayData() */


static void MakeDataString(datastring,mbuff,xdim,ydim,dataset,isFloat,format)
char	*datastring[];	
char	*mbuff;	
int	xdim,ydim;
float	*dataset;
char	*format;
char	isFloat;
{
int	x,y;
char	*ptr;
float	*fdataset;	/* float data set */
unsigned char	*cdataset;	/* raster image data set */


	if (isFloat) {
		fdataset = (float *) dataset;
		ptr = mbuff;
		for(y = 0 ; y < ydim ; y++) {
			for(x = 0 ; x < xdim; x++ ) {
				sprintf(ptr,format,fdataset[y*xdim+x]);
				datastring[y*xdim+x] = ptr;
				ptr += (strlen(ptr)+1);
				}
			}
		}
	else {
		cdataset = (unsigned char *) dataset;
		ptr = mbuff;
		for(y = 0 ; y < ydim ; y++) {
			for(x = 0 ; x < xdim; x++ ) {
				sprintf(ptr,format,cdataset[y*xdim+x]);
				datastring[y*xdim+x] = ptr;
				ptr += (strlen(ptr)+1);
				}
			}
		}


	datastring[xdim*ydim]=NULL;

	return;

} /* MakeDataString() */


void CBDisplayData(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{

	DisplayData((struct IMAGE *) client_data);
}



void CBDoneData(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;
	i = (struct IMAGE *) client_data;

	XIFree(i->dws.pdata);
	XIFree(i->dws.pdata2);
	XIFree(i->dws.pdata3);
	XIFree(i->dws.pdata4);
	XIFree(i->dws.pdata5);
	XIFree(i->dws.pdata6);
	XtDestroyWidget(i->dws.toplevel);
	i->data_showing = FALSE;
}


void SelectPointFromImage(i,x,y)
/* A point has been selected image, this proc highlights point in data */
struct IMAGE *i;
int x,y;	/* with respect to data set */
{
	if (! i->data_showing)
		return;
	if ((x < 0) || (x > i->xdim) || (y < 0) || (y > i->ydim))
		return;

	gr_ListHighlight(i->dws.box5,y*i->xdim+x);
	gr_ListHighlight(i->dws.box6,x);
	gr_ListHighlight(i->dws.box7,y);

	/* turn off old pixel highlight box */

	/* scroll the data window and update scales */
	gr_VPortMoveChild(i->dws.box2,&x,&y,i->xdim,i->ydim);
	gr_VPortVertMove(i->dws.box4,y);
	gr_VPortHoriMove(i->dws.box3,x);

} /* SelectPointFromImage() */

static void CBSelectData(w,client_data,call_data)
/* A point has been selected in Data window */
/* set X&Y ticks, and image */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;
XtListReturnStruct *lr;
int x,y;

	i = (struct IMAGE *) client_data;
	lr = (XtListReturnStruct *) call_data;

	y = lr->index / i->xdim;
	x = lr->index % i->xdim;
	gr_ListHighlight(i->dws.box6,x);
	gr_ListHighlight(i->dws.box7,y);
	if (i->iws.amIShowing)
		CartHighlightSelectedImage(i,x,y);
	if (i->pws.amIShowing) {
		double theta;

		theta=(((double)x)/((double)i->xdim))
			*((double)(2.0*PI)) + PI/2.0;

		PolarHighlightSelectedImage(i,
			ROUND(((double)y)*sin(theta)) + i->ydim,
			ROUND(((double)y)*cos(theta)) + i->ydim);
		}
} /* CBSelectData() */

@//E*O*F data.c//
chmod u=rw,g=r,o=r data.c
 
echo x - getfile.c
sed 's/^@//' > "getfile.c" <<'@//E*O*F getfile.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xos.h>
/*#include <sys/types.h>*/
#include <sys/stat.h>

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include <X11/List.h>
#include <X11/Dialog.h>
#include <X11/IntrinsicP.h>
#include <X11/ViewportP.h>

#ifdef SYSV
#include <dirent.h>
#define MAXPATHLEN	255
#else
#include <sys/dir.h>
#include <sys/param.h>
#endif

#include "list.h"
#include "xstuff.h"
#include "getfile.h"


#define	XDIM	300
#define YDIM	308
#define	MAXFILES	512			/* Max number of files/dir */

extern	char	*getenv();
extern	Widget	toplevelform;

static	char	usecwd = TRUE;			/* Use current working dir*/
static	char	*defdir;
static	char	*cfilename = "";
/*static	char	*defdir = ".";*/
static	char	directory[MAXPATHLEN];
static	DIR	*dirFD;
static	char	dirFDopen = FALSE;
static	Widget	topFileWidget;
static	Widget	dir_dialog_widget;
static	Widget	cfile_dialog;
static	Widget	file_list_widget;
static	Widget	file_list_vport_widget;
static	char	*listOfFiles[MAXFILES];
static	int	numFiles = 0;		/* number of files in listOfFiles */
static	Widget	inputBox;
static	char	aFileHasBeenChosen = FALSE;
static	char	fileChosen[80];
static	struct	GetFile	*thisFile;
static	Widget	xDimDialog;
static	Widget	yDimDialog;
static	char	amIAlreadyOpen = FALSE;

static  char ChangeDirTrans[] = "<Key>Return:    ETDirReturn()";

void CBChoseFile();
void CBOpen();
void CBChangeDirectory();
void CBCancel();

int InitGetAFile(dpy)
Display *dpy;
{
int x;

	if (!(defdir = (char *) XIMalloc(MAXPATHLEN))) {
		printf("Can't XIMalloc any memory\n");
		return(NULL);
		}

	for(x = 0; x < MAXPATHLEN; x++)
		directory[x]=' ';

#ifdef SYSV
	if (!getcwd(defdir,MAXPATHLEN)){
#else
	if (!getwd(defdir)) {
#endif
		printf("Can't get working directory\n");
		return(NULL);
		}

	dirFDopen = FALSE;

	return(1);
}



char DoesFileExist(f)
char *f;
{
FILE *fp;
	if (fp = fopen(f,"r")) {
		fclose(fp);
		return(TRUE);
		}
	else
		return(FALSE);
}


void GetAFile(fileinfo)
struct	GetFile	*fileinfo;
{
Widget	board;
Widget	fileCtrlWidget;
Widget	bbox;
Widget	bbox2;
Widget	box3;
int	x;
/*int	numFiles;*/
Display	*dpy;
int	screen;

	if (amIAlreadyOpen)
		return;

	thisFile = fileinfo;

	dpy = XtDisplay(toplevelform);
	screen = XDefaultScreen(dpy);
	topFileWidget = MakeATopLevelOverride("GetAFile",
				toplevelform, 
				(DisplayWidth(dpy,screen)-XDIM)/2,
				(DisplayHeight(dpy,screen)-YDIM)/2,
				XDIM,YDIM);

	fileCtrlWidget = Make_Window("NCSA X Image",topFileWidget,
				5,5,XDIM,YDIM);

	if (usecwd) {
		/* should be a getenv*/
/*		if (! (theDir = getenv("CWD")))
			PrintMesg("Can't get PWD environment variable\n");
			return(NULL);
*/

/**/		strcpy(directory,defdir);
		}

	
	if (!(CreateListofFiles(directory,listOfFiles,&numFiles)))
		return;


	board= Make_Board("blabla",fileCtrlWidget,2,22,XDIM-7,55);
	
	dir_dialog_widget = Make_Dialog("DirOfFiles",board,
			"Directory:                    ",
				directory,80,2,2,XDIM-60,50);

	DialogAddTrans(dir_dialog_widget,ChangeDirTrans);
	
	(void) MakeButton("Change", board,XDIM-54,2,CBChangeDirectory,NULL,
				0,50);

	box3 = Make_Board("blabla",fileCtrlWidget,2,80,XDIM-7,55);
	cfile_dialog = Make_Dialog("DirOfFiles",box3,
			"Current Filename:                    ",
				cfilename,80,2,2,XDIM-60,50);

	gr_DialogSetValue(cfile_dialog,"");

	aFileHasBeenChosen = FALSE;

	file_list_widget = MakeList("ListOfFiles",fileCtrlWidget,
			VERTONLY,&file_list_vport_widget,1,CBChoseFile,
			listOfFiles,2,138,150,YDIM-142,NULL,NULL);

	bbox = Make_ButtonBox(fileCtrlWidget,155,138,XDIM-160,YDIM-142);
	bbox2 = Make_ButtonBox(bbox,2,2,XDIM-165,30);
	(void) MakeButton(" Open ",bbox2,10,5,CBOpen,NULL,0,0);
	(void) MakeButton(" Cancel ",bbox2,70,5,CBCancel,NULL,0,0);
	inputBox = Make_ButtonBox(bbox,2,35,XDIM-165,YDIM-181);

	fileChosen[0]='\0';
	amIAlreadyOpen = TRUE;
	
	return;

} /* GetAFile() */


static void CloseFileWidget()
{
char **p;

	p = listOfFiles;
	while (*p) {
		XIFree(*p);
		p++;
		}

	if(dirFDopen) {
		closedir(dirFD);
		dirFDopen = FALSE;
		}
	XtDestroyWidget(topFileWidget);

/*	XFlush(XtDisplay(topFileWidget));*/
	XSync(XtDisplay(topFileWidget),False);

	amIAlreadyOpen = FALSE;
	return;
}


void CBCancel(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{

	CloseFileWidget();
	thisFile->nofile(thisFile->param);

} /*CBCancel() */


BubbleSort(list,num)
char *list[];
{
char *tmp;
int x,y;
	for(x=0; x< num; x++)
		for(y=0; y < num-x-1; y++)
			if (strcmp(list[y],list[y+1]) > 0) {
				tmp = list[y+1];
				list[y+1] = list[y];
				list[y] = tmp;
				}

}


int CreateListofFiles(theDir,listOfFiles,nf)
char	*theDir;
char	*listOfFiles[];
int	*nf; /* initially contains num files in listOfFiles,  */
	     /* and returns new value */
{
char errmesg[100];
int	count;
DIR	*newdirFD;
char **p;

#ifdef SYSV
struct dirent *dirInfo;
#else
struct	direct	*dirInfo;
#endif

	if (!(newdirFD = opendir(theDir))) {
		sprintf(errmesg,"Can't open directory %s\n",theDir);
		PrintMesg(errmesg);
		return(NULL);
		}

	if (dirFDopen) {
		closedir(dirFD);

		/* free old Malloc list */
/*{ int c; c=0;
		p = listOfFiles;
		while (*(p+1)) {
fprintf(stderr,"****** Freeing %d: %s\n",c++,*p);
			XIFree(*p);
			p++;
			}
}
*/
{ int x;
	for (x=0,p=listOfFiles; x < *nf; x++,p++) {
/* fprintf(stderr,"****** Freeing %d: %s\n",x,*p);*/
		XIFree(p);
		}
	
}
		}
	dirFD= newdirFD;
	dirFDopen = TRUE;

	count = 0;
	while((dirInfo = readdir(dirFD))  && (count < (MAXFILES-2))) {
		if (strcmp(dirInfo->d_name,".")&
			(strcmp(dirInfo->d_name,".."))) {
			listOfFiles[count] = (char *) XIMalloc(strlen(
							dirInfo->d_name));
			strcpy(listOfFiles[count], dirInfo->d_name);
			count++;
			}
		}
	*nf = count;

	BubbleSort(listOfFiles,count);

/**/	listOfFiles[count] = NULL;

	while(count < MAXFILES-2) {
		listOfFiles[count] = " ";
		count++;
		}

	listOfFiles[count] = NULL;

	return(1);
}


void CBChangeDirectory(w,client_data,call_data)
Widget w;
caddr_t client_data; /* if TRUE, directory already contains new dir */
caddr_t call_data;
{
static  Arg arglist[]={{XtNlist,(XtArgVal) listOfFiles}};
/*int	numFiles;*/

	if (!client_data) {
		strcpy(directory,XtDialogGetValueString(dir_dialog_widget));
		Terminate(directory);
		}

	usecwd = FALSE;
	if (!CreateListofFiles(directory,listOfFiles,&numFiles))
		return;

	gr_DialogSetValue(cfile_dialog,"");
	
	XtListChange(file_list_widget,listOfFiles,numFiles,0,False);

	XtMoveWidget(file_list_widget,0,0);
	XtScrollBarSetThumb(
		((ViewportWidget) file_list_vport_widget)->viewport.vert_bar,
		0,0);
	
} /* CBChangeDirectory() */


void ETDirReturn(w, event, params, num_params)
Widget w;
XEvent *event;
String *params;
int num_params;
{
	CBChangeDirectory(w,NULL,NULL);
	
}


	

void CBChoseFile(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
char path[MAXPATHLEN];
struct stat fileStat;

	strcpy (fileChosen,((XtListReturnStruct *)call_data)->string);

	sprintf(path,"%s/%s",directory,fileChosen);
	stat(path,&fileStat);
	if (fileStat.st_mode & S_IFDIR) {
		strcpy(directory,path);
		gr_DialogSetValue(dir_dialog_widget,directory);
		CBChangeDirectory(w,TRUE,NULL);
		return;
		}
		
	
	aFileHasBeenChosen = TRUE;
	gr_DialogSetValue(cfile_dialog,fileChosen);

/*	sprintf(buff,"Just chose file %s/%s\n",directory,fileChosen);
	PrintMesg(buff);
*/
}

static void CBOk(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	/* return values */
	thisFile->xdim = atoi(XtDialogGetValueString(xDimDialog));
	thisFile->ydim = atoi(XtDialogGetValueString(yDimDialog));

	CloseFileWidget();


	thisFile->yesfile(thisFile->param);
}


void CBOpen(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
char	xstring[80];
char buff[256];
char firstFile[512];

	cfilename = XtDialogGetValueString(cfile_dialog);
	if (!cfilename[0]) {
		PrintMesg("Please select a file\n");
		return;
		}

	thisFile->base = (char *) XIMalloc(strlen(cfilename)+1);
	sprintf(thisFile->base,cfilename);

	thisFile->directory = (char *) XIMalloc(strlen(directory)+1);
	sprintf(thisFile->directory,directory);

	if (!Glob(directory,cfilename,&(thisFile->numFiles),
				&(thisFile->file))){
		sprintf(buff,"Can't open directory %s\n",directory);
		PrintMesg(buff);
		return;
		}
	
	sprintf(firstFile,"%s/%s",thisFile->directory,*(thisFile->file));

	if (! DoesFileExist(firstFile)){
		sprintf(buff,"Can't open file %s\n",firstFile);
		PrintMesg(buff);
		return;
		}

	if (thisFile->numFiles > 1)
		sprintf(buff,"Selected files %s/%s\n",thisFile->directory,
						thisFile->base);
	else
		sprintf(buff,"Selected file %s\n",firstFile);
	PrintMesg(buff);

	if (thisFile->type == FTYPE_IMAGE) {
	    /* if fileChosen is HDF */
	    if (IsItHDF(firstFile,&(thisFile->xdim),&(thisFile->ydim),
			&(thisFile->isFloat))){
		thisFile->isHDF = TRUE;
		CloseFileWidget();
		thisFile->yesfile(thisFile->param);

		}
	    else {
		thisFile->isHDF = FALSE;
		PrintMesg("Please Type in the dimensions of the image\n");
		xDimDialog = Make_Dialog("GetXDimension",inputBox,
					"Width of Image:","",4,
					2,2,XDIM-170,50);
		yDimDialog = Make_Dialog("GetYDimension",inputBox,
					"Height of Image:","",4,
					2,55,XDIM-170,50);
		MakeButton("         OK         ",inputBox,2,108,CBOk,
				NULL,0,0);
		}
	    }
	else { /*Else it's a FTYPE_PAL */
		CloseFileWidget();
		thisFile->isHDF = FALSE;
		if (DFishdf(firstFile) == 0)
			thisFile->isHDF = TRUE;
		thisFile->yesfile(thisFile->param);
		}
}
@//E*O*F getfile.c//
chmod u=rw,g=r,o=r getfile.c
 
echo x - glob.c
sed 's/^@//' > "glob.c" <<'@//E*O*F glob.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xos.h>
/*#include <sys/types.h>*/

#ifdef SYSV
#include <dirent.h>
#else
#include <sys/dir.h>
#endif

#define MAXENTRY	1000
#define	MALLOC		(char *) malloc


static void BubbleSort(list,num)
char *list[];
int num;
{
char *tmp;
int x,y;
	for(x=0; x< num; x++)
		for(y=0; y < num-x-1; y++)
			if (strcmp(list[y],list[y+1]) > 0) {
				tmp = list[y+1];
				list[y+1] = list[y];
				list[y] = tmp;
				}
	return;
} /* BubbleSort() */



int Glob(dir,key,nargc,rargv)
/* expand a wild card.  Can only handle an '*' at the end of filename*/
/* didn't have time to write a decent globbing routine  :-) */
/* RETURNS 0 if can't open directory */

char	*dir;	  /*string containing directory name */
char	*key;	/*search key('*' at end of filename is only wildcard excepted*/
int	*nargc;   /* RETURNED: number of matches found */
char	***rargv; /* RETURNED: expanded file name strings */
{
char	**tmpargv;
char	**nargv;
int	numFiles=0;
int	astPos;
int	space = 0;
int	x;
char	*buff;
#ifdef SYSV
struct dirent *files[MAXENTRY];
struct dirent **tfiles;
#else
struct direct *files[MAXENTRY];
struct direct **tfiles;
#endif

	if (!(numFiles = GetDir(dir,files)))
		return(0); /* couldn't open directory */

	if (!(astPos=FindGlobChar(key))) {
		/* no wild cards, so return key */
		*nargc=1;
		*rargv = (char **) MALLOC( sizeof(char *) );
		**rargv = key;
		return(1);
		}

	tfiles = files;
	*nargc = 0;
	for (x=0 ;x < numFiles; x++) {
		if (!strncmp(files[x]->d_name,key,astPos)) {
			(*nargc)++;
			space = space + strlen(files[x]->d_name) + 1;
			}
		else {
			tfiles++;
			}
		}

	tmpargv = nargv = (char **) MALLOC(*nargc * sizeof(char *));
	buff = MALLOC(space);
	for (x=0 ;x < numFiles; x++) {
		if (!strncmp(files[x]->d_name,key,astPos)) {
			strcpy(buff,files[x]->d_name);
			*tmpargv = buff;
			tmpargv++;
			buff = buff + strlen(buff) + 1;
			}
		}
	BubbleSort(nargv,*nargc);

	*rargv = nargv;
	return(1);

} /* Glob() */


static int FindGlobChar(key)
/* What character position is the '*' in the string? */
/* return 0 if no '*' */
char *key;
{
register int	count = 0;

/*	while(*key) {
		if (*key == '*')
			return(count);
		key++;
		count++;
		}
*/
	for (count = 0;(*key)&&(*key != '*');key++,count++);

	if (! *key)
		return(0); /* no '*' found */

	return(count);

} /* FindGlobChar() */


static int GetDir(theDir,files)
/* do an `ls` */
char *theDir; 			/* a string containing the directory name */
#ifdef SYSV
struct dirent *files[];		/* RETURNED: list of files in directory */
#else
struct direct *files[];
#endif
{
int count;
DIR *newdirFD;
#ifdef SYSV
struct dirent *dirInfo;
#else
struct direct *dirInfo;
#endif

        if (!(newdirFD = opendir(theDir))) {
                printf("Can't open directory %s\n",theDir);
                return(NULL);
                }
        count = 0;
        while ((files[count] = readdir(newdirFD))&& (count < MAXENTRY)) {
			/* no files that start with a '.' */
			if (files[count]->d_name[0] != '.')
                        	count++;
                        }
        closedir(newdirFD);
        return(count);
} /* GetDir() */
@//E*O*F glob.c//
chmod u=rw,g=r,o=r glob.c
 
echo x - gr_xwi.c
sed 's/^@//' > "gr_xwi.c" <<'@//E*O*F gr_xwi.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Dave Thompson, National Center for Supercomputing Applications
 * davet@ncsa.uiuc.edu
 */

/*
 *	File:		gr_xwi.c
 *	Contents:	Manipulation functions for X widgets
 * Author: Eng-Whatt Toh
 */

/*#include "gr_com.h"*/
#include <stdio.h>
#include <X11/cursorfont.h>
#include <X11/Xatom.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Cardinals.h>

#include <Xw/Xw.h>
#include "gr_xwi.h"
#include <X11/IntrinsicP.h>
#include <X11/BoxP.h>
#include <X11/DialogP.h>
#include <X11/ViewportP.h>
#include <Xw/XwP.h>
#include <Xw/ArrowP.h>
#include <Xw/ScrollBarP.h>
#include <Xw/BBoardP.h>
#include <Xw/SWindowP.h>
#include <Xw/ValuatorP.h>

void
gr_WidgetSensitive(wid,sen)
Widget wid;
Boolean sen;
{
	Arg		argList[3];
	int		i=0;

	XtSetArg(argList[i],XtNsensitive,sen); i++;
	XtSetValues(wid,argList,i);
}

void
gr_WidgetCursor(wid,cursorfont)
Widget wid;
int cursorfont;
{
	Cursor cursor;
	Window win = XtWindow(wid);
	Display *dpy = XtDisplay(wid);

	if (win)
	{
		cursor = XCreateFontCursor(dpy,cursorfont);
		XDefineCursor(dpy,win,cursor);
	}

	return;
}

void
gr_ListChange(wid,list,nitems,longest,resize)
Widget wid;
String *list;
int nitems,longest;
Boolean resize;
{
	XtListChange(wid,list,nitems,longest,resize);
}

void
gr_ListHighlight(wid,item)
Widget wid;
int item;
{
	XtListHighlight(wid,item);
}

char
*gr_ListgetStruct(wid,ind)
Widget wid;
int	   *ind;
{
	XtListReturnStruct	*strngStruct;

	strngStruct = XtListShowCurrent(wid);
	*ind = strngStruct->index;

	return(strngStruct->string);
}

void
gr_TextReplace(wid,startPos,endPos,strng)
Widget wid;
char *strng;
long startPos,endPos;
{
	XtTextBlock	text;

	text.firstPos = 0;
	text.length = strlen(strng);
	text.ptr = strng;
	text.format = FMT8BIT;

	XtTextReplace(wid,startPos,endPos,&text);
}

void
gr_TextSetInsertionPoint(wid,atPos)
Widget wid;
long   atPos;
{
	XtTextSetInsertionPoint(wid,atPos);
}

Widget
gr_DialogGetTextWind(w)
Widget w;
{
	return (((DialogWidget)w)->dialog.valueW);
}

char
*gr_DialogGetValue(wid)
Widget wid;
{
	return(XtDialogGetValueString(wid));
}

void
gr_DialogSetValue(wid,strng)
Widget wid;
char *strng;
{
	Widget textWid;
	String oldStrng;

	textWid = ((DialogWidget)wid)->dialog.valueW;
	oldStrng = ((DialogWidget)wid)->dialog.value;
	gr_TextReplace(textWid,0,strlen(oldStrng),strng);
}

void
gr_LabelSetValue(wid,strng)
Widget wid;
char *strng;
{
	Arg		argList[2];

	XtSetArg(argList[0],XtNlabel,strng);
	XtSetValues(wid,argList,1);
}

void
gr_StaticRasterSetImage(wid,image)
Widget wid;
XImage *image;
{
	Arg		argList[3];
	int		i=0;

	XtSetArg(argList[i],XtNsRimage,image); i++;
	XtSetValues(wid,argList,i);
}

void
gr_SliderSetValue(wid,pos)
Widget wid;
int	   pos;
{
	Arg		argList[3];
	Cardinal i=0;

	XtSetArg(argList[i],XtNsliderOrigin,pos); i++;
	XtSetValues(wid,argList,i);
}

/*
	This function is called to translate the position of the child in
	a scrolledWindowWidget so that the point (xpos,ypos) of the child
	is centered in the scrolled window of size: xsize by ysize.
	The actual resulting coordinates of the translation is returned in
	(xpos,ypos).  They may then be used to update other children based 
	on the same horizontal and vertical slider values as needed.
*/
void
gr_VPortMoveChild(w,xpos,ypos,xsize,ysize)
Widget w;
int	   *xpos,*ypos,xsize,ysize;
{
	XwSWindowWidget		 sw = (XwSWindowWidget)w;
	XwScrollBarWidget	 vscroll,hscroll;
	Widget	 child;
	int		 vnewPos,hnewPos,vorg,horg;
	int		 vmin,vmax,vext,vsize;
	int		 hmin,hmax,hext,hsize;

	vscroll = sw->swindow.vScrollBar;
	hscroll = sw->swindow.hScrollBar;
	child  = sw->swindow.bbChild;

	/* Calculate the new vertical (y) position of the child */
	if (vscroll != NULL)
	{
		vmin = sw->swindow.vmin;
		vmax = sw->swindow.vmax;
		vext = sw->swindow.vExtent;
		vorg = sw->swindow.vOrigin;
		vsize = vmax - vmin;
		vnewPos = ((float)*ypos/(float)ysize)*(float)vsize;
		if ((vnewPos < vorg+20) ||
			(vnewPos > (vorg+vext-20)))
		{
			vnewPos = vnewPos - (float)((float)vext/(float)2.0);
			if (vnewPos < vmin)
				vnewPos = vmin;
			else
			if (vnewPos > (vmax-vext-1))
				vnewPos = vmax-vext-1;
			sw->swindow.vOrigin = vnewPos;
			gr_SliderSetValue((Widget)vscroll,vnewPos);
		}
		else
			vnewPos = vorg;
	}

	/* Calculate the new horizontal (x) position of the child */
	if (hscroll != NULL)
	{
		hmin = sw->swindow.hmin;
		hmax = sw->swindow.hmax;
		hext = sw->swindow.hExtent;
		horg = sw->swindow.hOrigin;
		hsize = hmax - hmin;
		hnewPos = ((float)*xpos/(float)xsize)*(float)hsize;
		if ((hnewPos < horg+20) ||
			(hnewPos > (horg+hext-20)))
		{
			hnewPos = hnewPos - (float)((float)hext/(float)2.0);
			if (hnewPos<hmin)
				hnewPos = hmin;
			else
			if (hnewPos>(hmax-hext-1))
				hnewPos = hmax-hext-1;
			sw->swindow.hOrigin = hnewPos;
			gr_SliderSetValue((Widget)hscroll,hnewPos);
		}
		else
			hnewPos = horg;
	}

	/* Translate child in the scrolledWindow viewport */
	if ((vscroll != NULL) && (hscroll != NULL) && (child != NULL))
	{
		*xpos = hnewPos;
		*ypos = vnewPos;
		XtMoveWidget(child,(Position)-hnewPos,(Position)-vnewPos);
	}
}

/*
	This function moves the first child of a box widget horizontally
	in the box to effect a horizontal scroll on the contents of the
	box.
*/
void
gr_VPortHoriMove(w,newpos)
Widget w;
int	   newpos;
{
	BoxWidget	bbw = (BoxWidget)w;
	register Widget	child = bbw->composite.children[0];
	int		 pos;

	pos = newpos + 1;
	if (pos < 1)
		pos = 1;
	else
	if (pos > child->core.width)
		pos = child->core.width;
	child->core.x = pos;

	XtMoveWidget(child, (Position)-pos, (Position)child->core.y);
}

/*
	This function moves the first child of a box widget vertically
	in the box to effect a vertical scroll on the contents of the
	box.
*/
void
gr_VPortVertMove(w,newpos)
Widget w;
int	   newpos;
{
	BoxWidget	bbw = (BoxWidget)w;
	register Widget	child = bbw->composite.children[0];
	int		 pos;

	pos	= newpos + 1;
	if (pos < 1)
		pos = 1;
	else
	if (pos > child->core.height)
		pos = child->core.height;
	child->core.y = pos;

	XtMoveWidget(child, (Position)child->core.x, (Position)-pos);
}
@//E*O*F gr_xwi.c//
chmod u=rw,g=r,o=r gr_xwi.c
 
echo x - gr_xwi1.c
sed 's/^@//' > "gr_xwi1.c" <<'@//E*O*F gr_xwi1.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Dave Thompson, National Center for Supercomputing Applications
 * davet@ncsa.uiuc.edu
 */

/*
 *	File:		gr_xwi1.c
 *	Contents:	Creation functions for X widgets
 *	Author:		Eng-Whatt Toh
 */

#include "gr_com.h"

extern unsigned long black,white;
Widget
gr_MakeBox(shellName,parent,x,y,width,height)
char		*shellName;
Widget		parent;
int			x,y;
int			width,height;
{
	Widget		shellWind;
	Arg			argList[10];
	Cardinal	i=0;

	XtSetArg(argList[i],XtNx,x); i++;
	XtSetArg(argList[i],XtNy,y); i++;
	XtSetArg(argList[i],XtNwidth,width); i++;
	XtSetArg(argList[i],XtNheight,height); i++;
	XtSetArg(argList[i],XtNborderWidth,DEF_BORDER_WIDTH); i++;
	XtSetArg(argList[i],XtNborder,
				BlackPixel(XtDisplay(parent),
						   DefaultScreen(XtDisplay(parent)))); i++;
	shellWind = XtCreateManagedWidget(shellName,boxWidgetClass,parent,
									  argList,i);

	return(shellWind);
}

Widget
gr_MakeVPort(shellName,parent,scrollType,x,y,width,height)
char		*shellName;
Widget		parent;
A_Scroll_t	scrollType;
int			x,y;
int			width,height;
{
	Widget		shellWind;
	Arg			argList[10];
	Cardinal	i=0;

	XtSetArg(argList[i],XtNx,x); i++;
	XtSetArg(argList[i],XtNy,y); i++;
	XtSetArg(argList[i],XtNwidth,width); i++;
	XtSetArg(argList[i],XtNheight,height); i++;
	switch (scrollType)
	{
		case NOSCROLL:
			break;
		case VERTONLY:
			XtSetArg(argList[i],XtNallowVert,TRUE); i++;
			XtSetArg(argList[i],XtNforceBars,TRUE); i++;
			break;
		case HORIZONLY:
			XtSetArg(argList[i],XtNallowHoriz,TRUE); i++;
			XtSetArg(argList[i],XtNforceBars,TRUE); i++;
			break;
		case VERTHORIZ:
			XtSetArg(argList[i],XtNallowVert,TRUE); i++;
			XtSetArg(argList[i],XtNallowHoriz,TRUE); i++;
			XtSetArg(argList[i],XtNforceBars,TRUE); i++;
			break;
	}

	shellWind = XtCreateManagedWidget(shellName,viewportWidgetClass,parent,
									  argList,i);

	return(shellWind);
}

Widget
gr_MakeWindow(shellName,parent,windType,label,x,y,width,height)
char		*shellName;
Widget		parent;
A_Wind_t 	windType;
char		*label;
int			x,y;
int			width,height;
{
	XFontStruct	*labelFont;
	Widget		shellWind,boxWind;
	Arg			argList[10];
	Cardinal	i=0;

	XtSetArg(argList[i],XtNx,x); i++;
	XtSetArg(argList[i],XtNy,y); i++;
	XtSetArg(argList[i],XtNwidth,width); i++;
	XtSetArg(argList[i],XtNheight,height); i++;
	XtSetArg(argList[i],XtNborderWidth,DEF_BORDER_WIDTH); i++;
	XtSetArg(argList[i],XtNborder,
				BlackPixel(XtDisplay(parent),
						   DefaultScreen(XtDisplay(parent)))); i++;
	XtSetArg(argList[i],XtNallowShellResize,FALSE); i++;
	if (windType == CNTRLWIND)
	shellWind = XtCreateManagedWidget(shellName,boxWidgetClass,parent,
									  argList,i);
	else
	shellWind = XtCreateManagedWidget(shellName,transientShellWidgetClass,
									  parent, argList,i);

	boxWind = gr_MakeBox(shellName,shellWind,2,2,width-2,height-2);
	labelFont = XLoadQueryFont(XtDisplay(boxWind),DEF_LABEL_FONT);
	i=0;
	XtSetArg(argList[i],XtNx,1);	i++;
	XtSetArg(argList[i],XtNy,1);	i++;
	XtSetArg(argList[i],XtNwidth,width-2);	i++;
	XtSetArg(argList[i],XtNlabel,label);	i++;
	XtSetArg(argList[i],XtNfont,labelFont);	i++;

	(void) XtCreateManagedWidget("XTDLabel",labelWidgetClass,boxWind,
								argList, i);

	return(shellWind);
}

Widget
gr_MakeList(shellName,parent,scrollType,ncols,callBackProc,
			strings,x,y,width,height)
char		*shellName;
Widget		parent;
A_Scroll_t	scrollType;
char		*strings[];
int			ncols;
XtCallbackProc	callBackProc;
int			x,y;
int			width,height;
{
	Widget		listWind,vportWind;
	Arg			argList[10];
	Cardinal	i=0;

	vportWind = gr_MakeVPort("XTDvport",parent,scrollType,
							 x,y,width,height);
	XtSetArg(argList[i],XtNx,x);	i++;
	XtSetArg(argList[i],XtNy,y);	i++;
/*	XtSetArg(argList[i],XtNwidth,width);	i++; */
/*	XtSetArg(argList[i],XtNheight,height);	i++; */
	XtSetArg(argList[i],XtNdefaultColumns,ncols);	i++;
	XtSetArg(argList[i],XtNforceColumns,TRUE);	i++;
/*	XtSetArg(argList[i],XtNverticalList,TRUE);	i++; */
	XtSetArg(argList[i],XtNpasteBuffer,TRUE);	i++;
	XtSetArg(argList[i],XtNlist,strings);	i++;
	listWind = XtCreateManagedWidget(shellName,
					listWidgetClass, vportWind, argList, i);
						
	if (callBackProc)
		XtAddCallback(listWind,"callback",callBackProc,NULL);

	return(listWind);
}

Widget
gr_MakeText(shellName,parent,scrollType,textSelect,textSource,
			string,x,y,width,height)
char		*shellName;
Widget		parent;
A_Scroll_t		scrollType;
A_TextSelect_t	textSelect;
A_TextSource_t	textSource;
char		*string;
int			x,y;
int			width,height;
{
	Widget		textWind;
	Arg			argList[15];
	Cardinal	i=0;

	XtSetArg(argList[i],XtNx,x);	i++;
	XtSetArg(argList[i],XtNy,y);	i++;
	XtSetArg(argList[i],XtNwidth,width);	i++;
	XtSetArg(argList[i],XtNheight,height);	i++;
	XtSetArg(argList[i],XtNforeground,black);	i++;
	XtSetArg(argList[i],XtNbackground,white);	i++;

	switch (scrollType)
	{
		case NOSCROLL:
			break;
		case VERTONLY:
			XtSetArg(argList[i],XtNtextOptions,
					scrollVertical); i++;
			break;
		case HORIZONLY:
			XtSetArg(argList[i],XtNtextOptions,
					scrollHorizontal); i++;
			break;
		case VERTHORIZ:
			XtSetArg(argList[i],XtNtextOptions,
				scrollHorizontal|scrollVertical); i++;
			break;
	}
	if (textSelect == SELECTABLE)
		XtSetArg(argList[i],XtNsensitive,TRUE);
	else
		XtSetArg(argList[i],XtNsensitive,FALSE);
	i++;
	if (textSource == STRINGSOURCE)
	{
		XtSetArg(argList[i],XtNlength,1000);	i++;
		XtSetArg(argList[i],XtNstring,string);	i++;
                XtSetArg(argList[i],XtNeditType,XttextEdit);  i++;
		textWind = XtCreateManagedWidget(shellName,
				asciiStringWidgetClass, parent, argList, i);
	}
	else
	{
                XtSetArg(argList[i],XtNeditType,XttextAppend);  i++;
		if (string)
			XtSetArg(argList[i],XtNfile,string);	i++;
		textWind = XtCreateManagedWidget(shellName,
					asciiDiskWidgetClass, parent, argList, i);
	}

	XtTextEnableRedisplay(textWind);

	return(textWind);
}
@//E*O*F gr_xwi1.c//
chmod u=rw,g=r,o=r gr_xwi1.c
 
echo x - graph.c
sed 's/^@//' > "graph.c" <<'@//E*O*F graph.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h> 
#include <X11/Intrinsic.h> 
#include <X11/StringDefs.h>
#include <X11/Xatom.h>
#include <X11/Label.h>
#include <X11/cursorfont.h>
#include <Xw/Xw.h>
#include <Xw/Toggle.h>

#include "i.h"
#include "xstuff.h"

#define	HISTO_HEIGHT	200
#define	HISTO_WIDTH	256
#define MAXNUMCONTLEVELS 50
#define	NUM_REDRAW_REGIONS	4		/* sqrt(# redraw regions) */

/*extern	void Contour_Init();*/
extern	Widget	toplevelform;
extern  unsigned long   black,white;
extern	void	CBCtrlContourBox();

static	unsigned char   contourLevels[MAXNUMCONTLEVELS] 
				= {5,64,128,192,224,255,0}; 

/*static	unsigned char   contourLevels[MAXNUMCONTLEVELS] 
				= {33,0,4,8,12,16,20,24,28,32,36,40,44,48,
				52,56,60,64,68,72,76,80,
				84,88,92,96,100,104,108,112,116,120,124,128,0};
*/
void CBDoneHistogram();
void CBHistogram();

CBDoneGraphBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	XtDestroyWidget((Widget) client_data);
}


CBDoneContourBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE *i;

	i = (struct IMAGE *) client_data;
	i->gcws.amIShowing = FALSE;
	XtDestroyWidget(i->gcws.toplevel);
} 


void CBContourExpose(w,client_data,call_data)
/* Draw the contour in parts of the window that is exposed */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE *i;
Region	region;
int	x,y;
int	xrdim,yrdim;	/* dimension of those rectanagles */
int	overlap;
int 	pdim,prdim;

	i = (struct IMAGE *) client_data;
	region  = (Region) call_data;
	
	if (i->gcws.data1) { /* plot contour */
	    xrdim=i->xdim/NUM_REDRAW_REGIONS;
	    yrdim=i->ydim/NUM_REDRAW_REGIONS;

	    for (y=0; y < i->ydim ; y+=yrdim) 
		for (x=0; x < i->xdim; x+=xrdim) {
			overlap = XRectInRegion(region,x,y,xrdim,yrdim);
			if ((overlap==RectangleIn)||(overlap==RectanglePart)){
				Updt_Contour(i->gcws.box3,i->ri,
					i->contourLevels,i->xdim,i->ydim,
					x,y,x+xrdim,y+yrdim,
					black,white);
				}
			}
		}
	else { /* plot polar */
	    pdim = i->ydim << 1;
	    prdim = pdim / NUM_REDRAW_REGIONS;
	    for (y=0; y < pdim ; y+=prdim) 
		for (x=0; x < pdim; x+=prdim) {
			overlap = XRectInRegion(region,x,y,prdim,prdim);
			if ((overlap==RectangleIn)||(overlap==RectanglePart))
				Updt_Contour(i->gcws.box3,i->polarimage,
					i->contourLevels,pdim,pdim,
					x,y,x+prdim,y+prdim,
					black,white);
			} /*for x*/
	    } /*else*/

} /* CBContourExpose() */

void CBContour(w,client_data,call_data)
/* Make Box for contour to be drawn in */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int xpos,ypos;
struct IMAGE *i;
int xdim,ydim;

	i = (struct IMAGE *) client_data;

	if (i->gcws.amIShowing) {
		PrintMesg("Contour graph already displayed.\n");
		return;
		}

	if (i->plotSepWindow) {

		if (!(i->plotCartesian)) {
			if (!i->polarimage) {
				PrintMesg("Please calculate polar first\n");
				return;
				}
			xdim = ydim = i->ydim * 2;
			}
		else {
			xdim = i->xdim;
			ydim = i->ydim;
			}
		PlaceWindow(&xpos,&ypos);
		i = (struct IMAGE *) client_data;
		i->gcws.toplevel = MakeATopLevel(
				"X Image [Image.Graph.Contour]",
				toplevelform,xpos,ypos,xdim+10,ydim+45);
		i->gcws.composite = Make_Board(i->name,i->gcws.toplevel,0,0,
				xdim+50,ydim+50);
		i->gcws.box1 =Make_ButtonBox(i->gcws.composite,5,5,xdim-50,25);
		(void) Make_Label(i->label,i->gcws.box1,2,2,30);
		(void) Make_Label(i->name,i->gcws.box1,33,2,xdim-85);

		i->gcws.box3 = MakeWorkSpace("contour",i->gcws.composite,5,35,
				xdim,ydim,
				CBContourExpose,i,
				NULL,NULL);

		(void) MakeButton("Done",i->gcws.composite,xdim-40,6,
				CBDoneContourBox,i,0,0);

		i->gcws.data1 = i->plotCartesian;  

		}
	i->gcws.amIShowing = TRUE;

} /* CBContour() */

void CBShadeExpose(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE *i;
Region	region;
int	x,y;
int	xrdim,yrdim;	/* dimension of those rectanagles */
int	overlap;
int 	pdim,prdim;

	i = (struct IMAGE *) client_data;
	region  = (Region) call_data;
	
	if (i->gsws.data1) { /* plot shade */
	    xrdim=i->xdim/NUM_REDRAW_REGIONS;
	    yrdim=i->ydim/NUM_REDRAW_REGIONS;

	    for (y=0; y < i->ydim ; y+=yrdim) 
		for (x=0; x < i->xdim; x+=xrdim) {
			overlap = XRectInRegion(region,x,y,xrdim,yrdim);
			if ((overlap==RectangleIn)||(overlap==RectanglePart)){
				Updt_Shaded(i->gsws.box3,i->ri,
					i->xdim,i->ydim,
					x,y,x+xrdim,y+yrdim);
				}
			}
		}
	else { /* plot polar */
	    pdim = i->ydim << 1;
	    prdim = pdim / NUM_REDRAW_REGIONS;
	    for (y=0; y < pdim ; y+=prdim) 
		for (x=0; x < pdim; x+=prdim) {
			overlap = XRectInRegion(region,x,y,prdim,prdim);
			if ((overlap==RectangleIn)||(overlap==RectanglePart))
				Updt_Shaded(i->gsws.box3,i->polarimage,
					pdim,pdim,
					x,y,x+prdim,y+prdim);
			} /*for x*/
	    } /*else*/

} /* CBShadeExpose() */


CBDoneShadeBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE *i;

	i = (struct IMAGE *) client_data;
	i->gsws.amIShowing = FALSE;
	XtDestroyWidget(i->gsws.toplevel);
} 

void CBShade(w,client_data,call_data)
/* Make Box for contour to be drawn in */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int xpos,ypos;
struct IMAGE *i;
int xdim,ydim;

	i = (struct IMAGE *) client_data;

	if (i->gsws.amIShowing) {
		PrintMesg("Shade graph already displayed.\n");
		return;
		}

	if (i->plotSepWindow) {

		if (!(i->plotCartesian)) {
			if (!i->polarimage) {
				PrintMesg("Please calculate polar first\n");
				return;
				}
			xdim = ydim = i->ydim * 2;
			}
		else {
			xdim = i->xdim;
			ydim = i->ydim;
			}
		PlaceWindow(&xpos,&ypos);
		i = (struct IMAGE *) client_data;
		i->gsws.toplevel = MakeATopLevel(
				"X Image [Image.Graph.Shade]",
				toplevelform,xpos,ypos,xdim+10,ydim+45);
		i->gsws.composite = Make_Board(i->name,i->gsws.toplevel,0,0,
				xdim+50,ydim+50);
		i->gsws.box1 =Make_ButtonBox(i->gsws.composite,5,5,xdim-50,25);
		(void) Make_Label(i->label,i->gsws.box1,2,2,30);
		(void) Make_Label(i->name,i->gsws.box1,33,2,xdim-85);

		i->gsws.box3 = MakeWorkSpace("shade",i->gsws.composite,5,35,
				xdim,ydim,
				CBShadeExpose,i,
				NULL,NULL);

		(void) MakeButton("Done",i->gsws.composite,xdim-40,6,
				CBDoneShadeBox,i,0,0);

		i->gsws.data1 = i->plotCartesian;  

		i->gsws.amIShowing = TRUE;
		}

	 /* plot shade in same window */
/*
	else {
		if (i->plotCartestian) {
			Updt_Shaded(i->iws.box3,i->ri,
				i->xdim,i->ydim,
				0,0,i->xdim,i->ydim);
		else
			Updt_Shaded(i->pws.box3,i->polarimage,
				i->ydim*2,i->ydim*2,
				0,0,i->ydim*2,i->ydim*2);
		}
*/
} /* CBShade */




/**** get rid of me */
void OLDCBShade(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int xpos,ypos;
struct IMAGE *i;
int xdim,ydim;

	i = (struct IMAGE *) client_data;


	if (i->plotSepWindow) {

		if (!(i->plotCartesian))
			xdim = ydim = i->ydim * 2;
		else {
			xdim = i->xdim;
			ydim = i->ydim;
			}
		PlaceWindow(&xpos,&ypos);
		i = (struct IMAGE *) client_data;
		i->gsws.toplevel = MakeATopLevel(
				"X Image [Image.Graph.Shade]"
				,toplevelform,xpos,ypos,xdim+50,ydim+50);
		i->gsws.composite = Make_Board(i->name,i->gsws.toplevel,0,0,
				xdim+50,ydim+50);
		i->gsws.box1 = Make_ButtonBox(i->gsws.composite,5,5,250,25);
		(void) Make_Label(i->label,i->gsws.box1,2,2,30);
		(void) Make_Label(i->name,i->gsws.box1,33,2,215);

		i->gsws.box3 = Make_ButtonBox(i->gsws.composite,5,35,
				xdim,ydim);

		(void) MakeButton("Done",
				i->gsws.composite,260,6,CBDoneGraphBox,
				i->gsws.toplevel,0,0);

		/* Should Actually wait for window to appear */
		XSync(XtDisplay(i->gsws.box3),False);

		if (i->plotCartesian)
			Updt_Shaded(i->gsws.box3,i->ri,i->xdim,i->ydim);
		else {
			if (i->polarimage)
				Updt_Shaded(i->gsws.box3,i->polarimage,
						i->ydim*2,i->ydim*2);
			else {
				PrintMesg("Please calculate polar first\n");
				return;
				}
			}
		}
	else {
		if (i->plotCartesian) {
			if (i->cart_showing)
			 	Updt_Shaded(i->iws.box3,i->ri,i->xdim,i->ydim);
			else {
				PrintMesg("Cartesian image not showing\n");
				return;
				}
			}
		else {
			if (i->polar_showing) {
				Updt_Shaded(i->pws.box3,i->polarimage,
						i->ydim*2,i->ydim*2);
				}
			else {
				PrintMesg("Polar image not showing\n");
				return;
				}
			} /*else*/
		} /*else*/
} /* CBShade() */

void CBIntensity(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int xpos,ypos;
struct IMAGE *i;
int xdim,ydim;

	i = (struct IMAGE *) client_data;


	if (i->plotSepWindow) {

		if (!(i->plotCartesian))
			xdim = ydim = i->ydim * 2;
		else {
			xdim = i->xdim;
			ydim = i->ydim;
			}
		PlaceWindow(&xpos,&ypos);
		i = (struct IMAGE *) client_data;
		i->gsws.toplevel = MakeATopLevel(
				"X Image [Image.Graph.Intensity]",
				toplevelform,xpos,ypos,xdim+50,ydim+50);
		i->gsws.composite = Make_Board(i->name,i->gsws.toplevel,0,0,
				xdim+50,ydim+50);
		i->gsws.box1 = Make_ButtonBox(i->gsws.composite,5,5,250,25);
		(void) Make_Label(i->label,i->gsws.box1,2,2,30);
		(void) Make_Label(i->name,i->gsws.box1,33,2,215);

		i->gsws.box3 = Make_ButtonBox(i->gsws.composite,5,35,
				xdim,ydim);

		(void) MakeButton("Done",i->gsws.composite,260,6,CBDoneGraphBox,
				i->gsws.toplevel,0,0);

		/* Should Actually wait for window to appear */
		XSync(XtDisplay(i->gsws.box3),False);

		if (i->plotCartesian)
			Updt_Intensity(i->gsws.box3,i->ri,i->xdim,i->ydim,
						black,FALSE);
		else {
			if (i->polarimage)
				Updt_Intensity(i->gsws.box3,i->polarimage,
						i->ydim*2,i->ydim*2,
						black,FALSE);
			else {
				PrintMesg("Please calculate polar first\n");
				return;
				}
			}
		}
	else {
		if (i->plotCartesian) {
			if (i->cart_showing)
			 	Updt_Intensity(i->iws.box3,i->ri,i->xdim,
						i->ydim,0,TRUE);
			else {
				PrintMesg("Cartesian Image not Showing\n");
				return;
				}
			}
		else {
			if (i->polar_showing) {
				Updt_Intensity(i->pws.box3,i->polarimage,
						i->ydim*2,i->ydim*2,
						0,TRUE);
				}
			else {
				PrintMesg("Polar Image not Showing\n");
				return;
				}
			} /*else*/
		} /*else*/
}



CBPlotWhichDataSet(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE *i;
static Arg cart[]={{XtNlabel,(int)"Plot Cartesian"},{XtNset,True}};
static Arg polar[]={{XtNlabel,(int)"Plot Polar"},{XtNset,True}};

	i = (struct IMAGE *)client_data;

	i->plotCartesian = ! i->plotCartesian;

	if (i->plotCartesian)
		XtSetValues(w,cart,2);
	else
		XtSetValues(w,polar,2);
		
}

void CBPlotInWhichWindow(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE *i;
static Arg sep[]={{XtNlabel,(int)"Plot in Separate Window"},{XtNset,True}};
static Arg overlay[]={{XtNlabel,(int)"Overlay Graph in Image Window"},
			{XtNset,True}};

	i = (struct IMAGE *)client_data;
	i->plotSepWindow = ! i->plotSepWindow;
	if (i->plotSepWindow)
		XtSetValues(w,sep,2);
	else
		XtSetValues(w,overlay,2);
}


void CBDoneGraphControlBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;
	i = (struct IMAGE *) client_data;

	if (i->gcws.amIShowing)
		CBDoneContourBox(w,i,0);
	if (i->gsws.amIShowing)
		CBDoneShadeBox(w,i,0);
	if (i->ghws.amIShowing)
		CBDoneHistogram(w,i,0);


	XtDestroyWidget(i->gws.toplevel);
	i->graph_showing = FALSE;
}


void CBGraphControlBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE *i;
int	xpos,ypos;

	i = (struct IMAGE *) client_data;
	
	if (i->graph_showing){
		PrintMesg("Graph control window already showing\n");
		/* should bring graph control window to front */
		return;
		}

	PlaceWindow(&xpos,&ypos);
	i->gws.toplevel = MakeATopLevel("X Image [Image.Graph]",
				toplevelform,xpos,ypos,300,125);
	Set_Pointer(i->gws.toplevel,XC_gumby);
	i->gws.composite= Make_Board("Graph",i->gws.toplevel,0,0,300,125);

	i->gws.box1 = Make_ButtonBox(i->gws.composite,5,5,250,25);
	(void) Make_Label(i->label,i->gws.box1,2,2,30);
	(void) Make_Label(i->name,i->gws.box1,33,2,215);

	i->gws.box2 = Make_ButtonBox(i->gws.composite,5,35,290,50);
	(void) MakeAltToggle("Plot Cartesian",i->gws.box2,5,5,
			CBPlotWhichDataSet,i,CBPlotWhichDataSet,i,
			False,False);
/*	(void) MakeAltToggle("Plot in Separate Window",i->gws.box2,5,30,
			CBPlotInWhichWindow,i,CBPlotInWhichWindow,i,
			False,False);
*/
	
	i->gws.box3 = Make_ButtonBox(i->gws.composite,5,90,290,25);
/*	(void) MakeButton("Contour",i->gws.box3,5,2,CBContour,i,0,0);*/
	(void) MakeButton("Contour",i->gws.box3,5,2,CBCtrlContourBox,i,0,0);
/*	(void) MakeButton("Intensity",i->gws.box3,000,2,CBIntensity,i,0,0);*/
	(void) MakeButton("Shade",i->gws.box3,62,2,CBShade,i,0,0);
/*	(void) MakeButton("3D",i->gws.box3,195,2,NULL,NULL,0,0);*/
/*	(void) MakeButton("XY",i->gws.box3,220,2,NULL,NULL,0,0);*/
	(void) MakeButton("Histogram",i->gws.box3,107,2,CBHistogram,i,0,0);

	(void) MakeButton("Done",i->gws.composite,260,6,
				CBDoneGraphControlBox,i,0,0);

	i->graph_showing = TRUE;
	return;
}

void CBDoneHistogram(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;
	i = (struct IMAGE *) client_data;

	XtDestroyWidget(i->ghws.toplevel);
	i->ghws.amIShowing = FALSE;
}

void CBHistoRedraw(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display	*dpy;
Window	win;
GC	gc;
static	XGCValues	gcval;
int	height;
struct IMAGE *i;
int	x;
int	*h;

	i = (struct IMAGE *) client_data;
	h = (int *)i->ghws.pdata;
	dpy = XtDisplay(i->ghws.box3);
        XSync(dpy,False);
        win = XtWindow(i->ghws.box3);
        gcval.foreground = black;
        gcval.background = white;
        gc = XtGetGC(i->ghws.box3,GCForeground | GCBackground, &gcval);
        for(x=0; x < 256; x++) {
                XSetForeground(dpy,gc,x);
                if (h[x] != i->ghws.data1) {
                        height = (int)((((float) h[x])
					/((float)i->ghws.data2))
                                        *((float) HISTO_HEIGHT));
/*	printf("data1=%d,data2=%d,h[x]=%d,height = %d\n",i->ghws.data1,
			i->ghws.data2,h[x],height);
*/

                        XDrawLine(dpy,win,gc,x+5,HISTO_HEIGHT,x+5,
                                        HISTO_HEIGHT-height);
                        }
		else 
			XDrawLine(dpy,win,gc,x+5,HISTO_HEIGHT,x+5,0);
                }
}


void CBHistoUpdate(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Window root, child;
int     root_x,root_y;
int     win_x,win_y;
unsigned int    keys_buttons;
struct IMAGE *i;
Arg	arglist[1];
char	buff[80];
float	fnum;
int 	*h;

	i = (struct IMAGE *) client_data;
        if (XQueryPointer(XtDisplay(w),XtWindow(w),&root,&child,
                &root_x,&root_y,&win_x,&win_y,&keys_buttons)) {
                }

	win_x = win_x - 5;
	if ((win_x > 255) || ( win_x < 0))
		return;
	
	if (i->isFloat) {
		fnum = ((((float)win_x)/255.0)* (i->maxvalue - i->minvalue))
			+ i->minvalue;
		sprintf(buff,"%8.3f",fnum);
		}
	else
		 sprintf(buff,"%d",win_x);


	XtSetArg(arglist[0],XtNlabel,buff);
	XtSetValues(i->ghws.box2,arglist,1);

	h = (int *)i->ghws.pdata;
	sprintf(buff,"%8.5f",
		((float)h[win_x])/((float)(i->xdim*i->ydim))*100.0);
	XtSetArg(arglist[0],XtNlabel,buff);
	XtSetValues(i->ghws.box4,arglist,1);
}



void CBHistogram(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int	*h;	/* an array containing frequency */
int 	x;
int	xpos,ypos;
int	theend;
int	highest;
int	highest2;
struct IMAGE *i;
Widget	box;

	i = (struct IMAGE *) client_data;

	PlaceWindow(&xpos,&ypos);

	i->ghws.toplevel = MakeATopLevel("X Image [Image.Graph.Histogram]",
			toplevelform,xpos,ypos,
			HISTO_WIDTH+42,HISTO_HEIGHT+120);
	SetColormap(i->ghws.toplevel,i->iws.cmap);
	Set_Pointer(i->ghws.toplevel,XC_gumby);
	i->ghws.composite = Make_Board(i->name,i->ghws.toplevel,0,0,
			HISTO_WIDTH+42,HISTO_HEIGHT+120);
	i->ghws.box1 = Make_ButtonBox(i->ghws.composite,5,5,250,25);
	(void) Make_Label(i->label,i->ghws.box1,2,2,30);
	(void) Make_Label(i->name,i->ghws.box1,33,2,215);

/*	i->ghws.box3 = Make_ButtonBox(i->ghws.composite,5,35,
			HISTO_WIDTH+10,HISTO_HEIGHT+10);
*/
	i->ghws.box3 = MakeWorkSpace("histo",i->ghws.composite,5,35,
			HISTO_WIDTH+10,HISTO_HEIGHT+10,
			CBHistoRedraw,i,NULL,NULL);
	Set_Pointer(i->ghws.box3,XC_left_ptr);
	box = Make_ButtonBox(i->ghws.composite,5,HISTO_HEIGHT+50,
			HISTO_WIDTH+10,60);
	(void) Make_Label("             Data Value:",box,5,5,HISTO_WIDTH/3*2);
	(void) Make_Label("   Frequency Percentage:",box,5,30,HISTO_WIDTH/3*2);
	i->ghws.box2=Make_Label("0",box,HISTO_WIDTH/3*2+10,5,HISTO_WIDTH/3-15);
	i->ghws.box4=Make_Label("0",box,HISTO_WIDTH/3*2+10,30,HISTO_WIDTH/3-15);
	
	XtAddEventHandler(i->ghws.box3,PointerMotionMask,0,
				CBHistoUpdate,i);

	(void) MakeButton("Done",i->ghws.composite,
			260,6,CBDoneHistogram,i,0,0);

	if (!(h = (int *) XICalloc(256,sizeof(int)))){
		PrintMesg("Can't allocate memory for Histogram\n");
		return;
		}
	i->ghws.pdata = (char *) h;


	/* MakeHistogram */
	/*if (! i->isFloat)*/
		if (i->plotCartesian) {
			theend = i->xdim * i->ydim;
			for(x=0; x < theend; x++)
				/*(h[i->ri[x]])++;*/
				h[i->ri[x]] = h[i->ri[x]]+1;
			}
		else {
			theend = (i->ydim << 1) * (i->ydim << 1);
			for(x=0; x < theend; x++)
				h[i->polarimage[x]] = h[i->polarimage[x]]+1;
				/*(h[i->polarimage[x]])++;*/
			}

	highest = h[0];
	for (x=0; x < 256; x++)
		if (h[x] > highest)
			highest = h[x];

	if  (highest == h[0])
		highest2 = h[1];
	else
		highest2 = h[0];
	for (x=1; x < 256; x++) {
		if (h[x] > highest2)
			if (highest != h[x])
				highest2 = h[x];
		}
		
		
	i->ghws.data1 =highest;
	i->ghws.data2 =highest2;
/*	printf("***** i->ghws.data2 = %d\n",i->ghws.data2);*/
	i->ghws.amIShowing = TRUE;
} /* CBHistogram() */

@//E*O*F graph.c//
chmod u=rw,g=r,o=r graph.c
 
echo x - i.c
sed 's/^@//' > "i.c" <<'@//E*O*F i.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include "i.h"
#define	NIL	(struct IMAGE *) 0
#define	NULL	0
#define FALSE	0

static struct IMAGE *headIMAGE = NIL;
static struct IMAGE *tailIMAGE = NIL;

static char	deflabel = 'a';

struct IMAGE *NewIMAGE()
/****** this routine doesn't handle XIMalloc fail yet */
{
struct	IMAGE *i;
	if (i = (struct IMAGE *) XIMalloc(sizeof(struct IMAGE))) {

#ifdef DEBUG
/**/	printf("PrintStatus: before NewIMAGE()\n");
	fflush(stdout);
/**/	PrintStatus();
#endif

		i->name = (char *) NULL;
		i->isHDF = FALSE;
		i->xdim = 0;
		i->ydim = 0;
		i->label[0] = deflabel;
		i->label[1] = '\0';
		if ((++deflabel) > 'z') 
			deflabel = 'a';

		i->isFloat = FALSE;
		i->fdataset = (float *) NULL;
		i->maxvalue = 0;
		i->minvalue = 0;
		i->format = (char *) NULL;
		i->fwidth = 0;

		i->ri = NULL;
		i->dExpRI= NULL;
		i->isDExpRI = FALSE;
		i->polarimage = NULL;
		i->dExpPI= NULL;
		i->isDExpPI = FALSE;

		i->cimage = i->pimage = (XImage *) NULL;

		i->plotCartesian = TRUE;
		i->plotSepWindow = TRUE;
		i->ctrl_showing = FALSE;
		i->data_showing = FALSE;
		i->cart_showing = FALSE;
		i->polar_showing = FALSE;
		i->graph_showing = FALSE;

		i->cws.amIShowing = FALSE;
		i->iws.amIShowing = FALSE;
		i->pws.amIShowing = FALSE;
		i->dws.amIShowing = FALSE;
		i->gws.amIShowing = FALSE;
		i->gcws.amIShowing = FALSE;
		i->giws.amIShowing = FALSE;
		i->gsws.amIShowing = FALSE;
		i->ghws.amIShowing = FALSE;
		i->hasPalette = FALSE;
		i->palette = (XColor *) NULL;

		i->image_loaded = FALSE;
		i->image_showing = FALSE;
		i->next = NIL;
		i->prev = NIL;

		if (headIMAGE == NIL) 
			tailIMAGE = headIMAGE = i;
		else {
			tailIMAGE->next = i;
			i->prev = tailIMAGE;
			tailIMAGE = i;
			}
		}
	else { /* XIMalloc failed */
		return(NULL);
		}
#ifdef DEBUG
/**/	printf("PrintStatus: after NewIMAGE()\n");
	fflush(stdout);
/**/	PrintStatus();
#endif

	return(i);

} /* NewIMAGE() */

DestroyIMAGE(im)
struct IMAGE *im;
{
#ifdef DEBUG
/**/	printf("PrintStatus: before DestroyIMAGE()\n");
	fflush(stdout);
/**/	PrintStatus();
#endif 
	
	if (im->prev) 
		im->prev->next = im->next;
	else 
		headIMAGE = im->next;
	if(im->next)
		im->next->prev = im->prev;
	else
		tailIMAGE = im->prev;


	if (im->cimage)
		XDestroyImage(im->cimage);
	if (im->pimage)
		XDestroyImage(im->pimage);
	if (im->ri)
		XIFree(im->ri);
	if (im->polarimage)
		XIFree(im->polarimage);
	if (im->name)
		XIFree(im->name);

	if (im->isDExpRI)
		XIFree(im->dExpRI);
	if (im->isDExpPI)
		XIFree(im->dExpPI);

	XIFree(im);

#ifdef DEBUG
/**/	printf("PrintStatus: after DestroyIMAGE()\n");
	fflush(stdout);
/**/	PrintStatus();
#endif

} /* DestroyIMAGE() */


ReleaseAllImages()
{
struct IMAGE  *i;

	while(headIMAGE)
		CBCloseImageCtrlBox(0,headIMAGE,0);
}

#ifdef DEBUG
PrintStatus()
/* Print IMAGE list for debugging */
{
struct IMAGE *i;

	printf("Printing image link\n");
	fflush(stdout);

	if (headIMAGE)
		printf("headIMAGE = %s\n",headIMAGE->name);
	else
		printf("headIMAGE = NIL\n");
	fflush(stdout);

	if (tailIMAGE)
		printf("tailIMAGE = %s\n",tailIMAGE->name);
	else
		printf("tailIMAGE = NIL\n");
	fflush(stdout);

	i = headIMAGE;
	while(i != NIL){
		if (i->prev) 
			printf("%s<-",i->prev->name);
		else
			printf("NIL<- ");

		printf("%s",i->name);

		if (i->next)
			printf("-> %s \n",i->next->name);
		else
			printf("-> NIL\n");

		fflush(stdout);
		i = i->next;
		}

	printf("*****done\n");
}
#endif
@//E*O*F i.c//
chmod u=rw,g=r,o=r i.c
 
echo x - image.c
sed 's/^@//' > "image.c" <<'@//E*O*F image.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <math.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>

#include "buttons.h"
#include "xstuff.h"
#include "i.h"
#include "getfile.h"

#define PAL_WIDTH	50
#define	SQUARE(x)	(x*x)
#define	ROUND(x)	((int) (x + 0.5))
#define	PI		3.1415927   /* <- defined here for convenience, should
					  the value of PI ever change :-) */


extern	Widget	toplevelform;
extern	unsigned long	black,white;
extern	struct	IMAGE *NewIMAGE();
extern 	void	CBDisplayData();
extern	void	CBGraphControlBox();
extern	XColor	rccells[];
extern	XColor	origccells[];

static	Display	*myDpy;	
static	Visual	*myVis;		
static	unsigned char	*palImage;
XImage	*palXImage;
static  struct  GetFile imageFile;
/**/	struct IMAGE *ci;	/* left in for debugging (current image)*/


void DisplayImage();
void CBDoCart();
void CBDoPolar();
int  ReadInImage();
void CreateImageCtrlBox();
void CBUnInstallImageCMap();
void CBCloseCartImageBox();
void CBClosePolarImageBox();


/**/ void CBTestShaded();

int InitImage(dpy)
Display	*dpy;
{
register int x;
register int y;
register int z;
int planes;	/* number of planes the default screen has */
int screen;
register int dooda;	 /*number of bytes needed per pixel */
register unsigned char *p;

	myDpy  = dpy;
	myVis  = GetVisual(myDpy);
/*
	screen = XDefaultScreen(myDpy);
	planes = DisplayPlanes(myDpy,screen);

	dooda = (planes > 7) ? (planes / 8 + ((planes%8)?1:0)) :1;
	if (dooda >= 3)
		dooda = 4;

	if ( ! (palImage = (unsigned char *) XIMalloc(PAL_WIDTH*256*dooda))) {
		printf("Couldn't allocate enough memory\n");
		return(0);
		}

	p = palImage;
	for(y = 0; y < 256; y++) 
		for(x = 0; x < PAL_WIDTH; x++){
			for (z = 1; z < dooda; z++) {
				*p = 0;
				p++;
				}
			*p = 255-y;
			p++;
			}

	palXImage = XCreateImage(myDpy,myVis,planes,ZPixmap,0,palImage,
				PAL_WIDTH,256,8*dooda,PAL_WIDTH*dooda);

*/
	if (!(palXImage = MakePalette(myDpy,PAL_WIDTH,FALSE)))
		return(0);

	return(1); 

} /* InitImage() */



XImage *ConformImageToNPlanes(raster,xdim,ydim,newRaster)
/* return 0 on memory failure */
/* newRaster is set to NULL if no expansion was necessary */
unsigned char *raster;	/* 8 bit raster image */
int xdim,ydim;		/* dimensions of raster */
unsigned char **newRaster; /* RETURNED: expanded raster image */
{
register int x;
register int y;
register int z;
int	planes;
int	nbp;	/* number of bytes per pixel */
XImage	*returnMe;
unsigned char *p;

	planes = DisplayPlanes(myDpy,DefaultScreen(myDpy));
	
	nbp = (planes > 7) ? (planes / 8 + ((planes%8)?1:0)) :1;

	if (nbp >= 3)
		nbp = 4;

	if (nbp > 1) {

		if ( ! (*newRaster=(unsigned char *)XIMalloc(xdim*ydim*nbp))){
			printf("Couldn't allocate enough memory\n");
			return(0);
			}
		p = *newRaster;
	    	for(y = 0; y < ydim; y++) 
		    for(x = 0; x < xdim; x++) {
			for (z = 1; z < nbp; z++){
				(*p) = 0;
				p++;
				}
			(*p) = raster[y*xdim+x];
			p++;
			}

        	returnMe = XCreateImage(myDpy,myVis,planes,ZPixmap,0,*newRaster,
                                xdim,ydim,8*nbp,xdim*nbp);
		}
	else {
        	returnMe = XCreateImage(myDpy,myVis,8,ZPixmap,0,raster,
                                xdim,ydim,8,xdim);

		*newRaster = (unsigned char *) NULL;
		}


	return(returnMe);

} /* ConformImageToNPlanes() */

static void DidntGetAFile(i)
struct IMAGE *i;
{
	PrintMesg("Get new image cancelled\n");
}

static void GotANewFile(i)
struct IMAGE *i;
{
	i->name = (char *) XIMalloc(strlen(imageFile.directory) + 
				strlen(*(imageFile.file)) + 2);
	sprintf(i->name,"%s/%s",imageFile.directory,*(imageFile.file));
	i->xdim = imageFile.xdim;
	i->ydim = imageFile.ydim;
	i->isHDF = imageFile.isHDF;
	i->isFloat = imageFile.isFloat;

	if ((i->xdim == 0 ) || (i->ydim == 0)) {
		char  errbuff[80];
		sprintf(errbuff,"Error: xdim=%d, ydim=%d\n",i->xdim,i->ydim);
		PrintMesg(errbuff);
		DestroyIMAGE(i);
		return;
		}

	if (! ReadInImage(i)){ 
		/* error reading in image */
		DestroyIMAGE(i);	
		return;
		}

	CreateImageCtrlBox(i);

	return;

} /* GotANewFile() */


CBNewImage(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct	IMAGE	*i;

	i = NewIMAGE();
/**/	ci = i;	/* left in for debugging */
	imageFile.yesfile = GotANewFile;
	imageFile.nofile = DidntGetAFile;
	imageFile.type = FTYPE_IMAGE;
	imageFile.param = (char *) i;
	PrintMesg("Please select a file\n");
	GetAFile(&imageFile);

} /* CBNewImage */


static int ReadInImage(i)
struct IMAGE *i;
/* Read in an image either seq or HDF */
/* i->name,i->isHDF,i->xdim,i->ydim must be defined */
/* if HDF, xdim & ydim don't have to be defined */
/* return NULL if error, length of image if ok */
{
int	stat;	/* return stat from reading image */

	if (i->isHDF) {
		if (i->isFloat) 
			stat = ReadHDFSDS(i,i->xdim,i->ydim,1);
		else
			stat = ReadHDFImage(i);
		}
	else
		stat = ReadSEQImage(i);


	return(stat);

} /* ReadInImage() */


void CBCloseImageCtrlBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;

	i = (struct IMAGE *) client_data;

	if (i->polar_showing)
		CBClosePolarImageBox(w,i,0);
	if (i->cart_showing)
		CBCloseCartImageBox(w,i,0);
	if (i->data_showing)
		CBDoneData(w,i,0);
	if (i->graph_showing)
		CBDoneGraphControlBox(w,i,0);
	if (i->cws.amIShowing || i->ctrl_showing)  /*<-- fix this ambiguity */
		XtDestroyWidget(i->cws.toplevel);

	/* held on for image and histogram */
	XFreeColormap(myDpy,i->iws.cmap);

	DestroyIMAGE(i);

	return;

} /* CBCloseImageCtrlBox() */


static void CreateImageCtrlBox(i)
struct	IMAGE *i;
{
int	xpos,ypos;

	PlaceWindow(&xpos,&ypos);

	i->cws.toplevel = MakeATopLevel("X Image [Image]",
				toplevelform,xpos,ypos,300,100);
	Set_Pointer(i->cws.toplevel,XC_gumby);

	i->cws.composite = Make_Board(i->name,i->cws.toplevel,0,0,300,100);

	i->cws.box1 = Make_ButtonBox(i->cws.composite,5,5,250,25);
	i->cws.label = Make_Label(i->label,i->cws.box1,2,2,30);
	i->cws.title = Make_Label(i->name,i->cws.box1,33,2,215);

	i->cws.box2 = Make_ButtonBox(i->cws.composite,5,35,140,60);
        b[IMAGE_CART] = MakeButton("Display Cartesian",i->cws.box2,
                                5,6,CBDoCart,i,0,0);
        b[IMAGE_POLAR] = MakeButton("Display Polar",i->cws.box2,
				5,30,CBDoPolar,i,0,0);

	i->cws.box3 = Make_ButtonBox(i->cws.composite,155,35,140,60);
	b[IMAGE_DATA] = MakeButton("Display Data Set",i->cws.box3,5,6,
				CBDisplayData,i,0,0);

	b[IMAGE_GRAPH] = MakeButton("Graph",i->cws.box3,5,30,
				CBGraphControlBox,i,0,0);

        b[IMAGE_DONE] = MakeButton("Done",i->cws.composite,
                                260,5,CBCloseImageCtrlBox,i,0,0);

	/* Create colormap used by Cartesian and Histogram */
	
        if (myVis->class== PseudoColor) {
                i->iws.cmap = XCreateColormap(myDpy,
                        XtWindow(i->cws.toplevel),
                        myVis,AllocAll);
                }
        else {
                if (myVis->class == StaticColor) {
                        i->iws.cmap = XCreateColormap(myDpy,
                                XtWindow(i->cws.toplevel),
                                myVis,AllocNone);
                        }
		else {
/**/	printf("\nNot sure how to create a colormap for this display\n");
/**/		printf("I think I'll die ungracefully\n");
/**/		fflush(stdout);
		}
	}
	if (i->hasPalette) {
		StoreColors(i->palette,FALSE,i->iws.cmap);
		}
	else
		StoreColors(origccells,FALSE,i->iws.cmap);

	i->ctrl_showing = TRUE;

} /* CreateImageCtrlBox() */

static void CBTestShaded(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data; 		/* should contain the IMAGE */
{
struct	IMAGE	*i;
int     xpos,ypos;

        PlaceWindow(&xpos,&ypos);

	i = (struct IMAGE *) client_data;

	i->gsws.toplevel = MakeATopLevel(i->name,toplevelform,xpos,ypos,
                                        i->xdim+50,i->ydim+50);
        i->gsws.composite = Make_Board(i->name,i->gsws.toplevel,0,0,
                                        i->xdim+50,i->ydim+50);

        i->gsws.box3 = Make_ButtonBox(i->gsws.composite,5,35,
                                i->xdim,i->ydim);

	InitShade(i);
	Updt_Shaded(i,DISPLAY_CART);
}

static void CBDoCart(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data; 		/* should contain the IMAGE */
{
struct	IMAGE	*i;

	i = (struct IMAGE *)client_data;

	
	if (i->cart_showing) {
		PrintMesg("Cartesian image already showing\n");
/****/		return;		/* <---- actually should bring to front */
		}

	if (DisplayPlanes(myDpy,XDefaultScreen(myDpy)) < 8 ) {
	  PrintMesg("Display must have more than 8 planes to display image\n");
	  return;
	  }

	i->cimage = ConformImageToNPlanes(i->ri,i->xdim,i->ydim,&(i->dExpRI));
	if (!i->cimage)
		return; /* malloc problems */
	if (i->dExpRI)
		i->isDExpRI = TRUE; /* image was depth expanded */


	DisplayImage(i,&(i->iws),DISPLAY_CART);

	i->iws.data1 = FALSE; /* point not selected (hilighted) */

	i->cart_showing = TRUE;		/* <-- this is the same(fix me)*/
	i->iws.amIShowing = TRUE;

	return;

}/* CBDoCart() */



static void CBDoPolar(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data; 		/* should contain the IMAGE */
{
struct	IMAGE	*i;
int	ydim_x_2;

	i = (struct IMAGE *)client_data;

	if (i->polar_showing) {
		PrintMesg("Polar image already showing\n");
		return;		/* <--- actually should bring to front */
		}

	if (DisplayPlanes(myDpy,XDefaultScreen(myDpy)) < 8 ) {
	  PrintMesg("Display must have more than 8 planes to display image\n");
	  return;
	  }

	ydim_x_2 = i->ydim << 1;
	if (!i->pimage) {
		if(! DrawPolar2(i))
			return; /* error creating polar (probably XIMalloc) */
	
/*		i->pimage = XCreateImage(myDpy,myVis,8,ZPixmap,0,i->polarimage,
					ydim_x_2,ydim_x_2,8,ydim_x_2);
*/
		i->pimage = ConformImageToNPlanes(i->polarimage,
					ydim_x_2,ydim_x_2,&(i->dExpPI));
		if (!i->pimage)
			return; /* malloc problems */
		if (i->dExpPI)
			i->isDExpPI = TRUE; /* image was depth expanded */
		}


	DisplayImage(i,&(i->pws),DISPLAY_POLAR); 

	i->pws.data1 = FALSE; /* point not selected (hilighted) */

	i->polar_showing = TRUE;
	i->pws.amIShowing = TRUE;
	return;

}/* CBDoPolar() */



static void CBCloseCartImageBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data; 		/* should contain the IMAGE */
{
struct IMAGE *i;

	i = (struct IMAGE *) client_data;

/*#ifdef  NON_ICCCM_WINDOW_MANAGER*/
	CBUnInstallImageCMap(i->iws.toplevel,i->iws.cmap,call_data);
/*#endif*/

/*	XFreeColormap(myDpy,i->iws.cmap);*/
	XtDestroyWidget(i->iws.toplevel);

	i->cart_showing = FALSE;
	i->iws.amIShowing = FALSE;

} /* CBCloseCartImageBox() */



static void CBClosePolarImageBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data; 		/* should contain the IMAGE */
{
struct IMAGE *i;

	i = (struct IMAGE *) client_data;

/*#ifdef  NON_ICCCM_WINDOW_MANAGER*/
	CBUnInstallImageCMap(i->pws.toplevel,i->pws.cmap,call_data);
/*#endif*/

	XFreeColormap(myDpy,i->pws.cmap);
	XtDestroyWidget(i->pws.toplevel);

	i->polar_showing = FALSE;
	i->pws.amIShowing = FALSE;

} /* CBClosePolarImageBox() */



/* these three palette setting routines should be in their own module */
void CBInstallImageCMap(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
        XInstallColormap(myDpy,(Colormap) client_data);
}

void CBUnInstallImageCMap(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{        
	XUninstallColormap(myDpy,(Colormap) client_data);
}

void SetColormap(w,cmap)
Widget w;
Colormap cmap;
{

/*#ifdef  NON_ICCCM_WINDOW_MANAGER*/
        XtAddEventHandler(w,EnterWindowMask,FALSE,
                        CBInstallImageCMap,cmap);
        XtAddEventHandler(w,LeaveWindowMask,FALSE,
                        CBUnInstallImageCMap,cmap);
/*#else*/
#ifndef DEF_STAT_VISUAL
        {/* Make compatible with Release 3 window managers */
                /* most anoying */
/*                XSetWindowAttributes attrib;
                attrib.colormap = cmap;
                XChangeWindowAttributes(myDpy,XtWindow(w),
                                        CWColormap,&attrib);
*/
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
                XSetWindowColormap(myDpy,XtWindow(w),cmap);
                XSync(myDpy,False);
        }
#endif
/*#endif*/
}


static void CBUpdateCMap(w,client_data,call_data)
/* Update colormap in client_data to be same as palette module's rccells */
/* ....Sync image palette with palette windows palette */
Widget w;
caddr_t client_data;
caddr_t call_data; 
{
Colormap cmap;
	cmap = (Colormap) client_data;
	StoreColors(rccells,FALSE,cmap);
}

static void CBLockPaletteCart(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data; 		/* should contain the IMAGE */
{
struct	IMAGE *i;
	i = (struct IMAGE *) client_data;

	i->iws.lockcmap = ! i->iws.lockcmap;

	if (i->iws.lockcmap) {
		StoreColors(rccells,FALSE,i->iws.cmap);
		XtAddEventHandler(i->iws.toplevel,EnterWindowMask,0,
			CBUpdateCMap,i->iws.cmap);
		}
	else {
		if (i->hasPalette) 
			StoreColors(i->palette,FALSE,i->iws.cmap);
		else
			StoreColors(origccells,FALSE,i->iws.cmap);

		XtRemoveEventHandler(i->iws.toplevel,
			EnterWindowMask,0,CBUpdateCMap,i->iws.cmap);
		}
			
} /* CBLockPaletteCart() */

static void CBLockPalettePolar(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data; 		/* should contain the IMAGE */
{
struct	IMAGE *i;
	i = (struct IMAGE *) client_data;

	i->pws.lockcmap = ! i->pws.lockcmap;

	if (i->pws.lockcmap) {
		StoreColors(rccells,FALSE,i->pws.cmap);
		XtAddEventHandler(i->pws.toplevel,EnterWindowMask,0,
			CBUpdateCMap,i->pws.cmap);
		}
	else {
		if (i->hasPalette) 
			StoreColors(i->palette,FALSE,i->pws.cmap);
		else
			StoreColors(origccells,FALSE,i->pws.cmap);

		XtRemoveEventHandler(i->pws.toplevel,
			EnterWindowMask,0,CBUpdateCMap,i->pws.cmap);
		}

} /* CBLockPalettePolar() */


MakeInc(w,maxvalue,minvalue,isFloat,yOffset)
Widget	w;
float   maxvalue,minvalue;
char isFloat;
int	yOffset;
{
static	char	buff[10];
static	GC	gc;
static	XGCValues	gcval;
float	d,dinc;	/* real data scale, data scale increment */
int	y,yinc;
char	*format;

/*?*/	XSync(myDpy,False);

	yinc = 25;

	dinc = (isFloat) ? ((maxvalue - minvalue) / 10.0): 25.0 ;
	
/*	gcval.font =    GCFont*/
	gcval.foreground = black;
	gcval.background = white;
	gc = XtGetGC(w,GCForeground | GCBackground ,&gcval);

	XSetForeground(myDpy,gc,black);
	XSetBackground(myDpy,gc,white);
	for (y = yinc, d= (float) minvalue+dinc; y < 231; y+=yinc,d+=dinc) {
		if (isFloat)
			sprintf(buff,"%-5.3f",d);
		else 
			sprintf(buff,"%-3d",(int) d);
		XDrawString(myDpy,XtWindow(w),gc,
			10, 255-((int)y+yOffset),buff,strlen(buff));
		}
		
/*	sprintf(buff,"%-4.f",maxvalue);
	XDrawString(myDpy,XtWindow(w),gc,
			10,(int)0+yOffset,buff,4);
*/
}


void CBRedrawTest2(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;

	i = (struct IMAGE *) client_data;
	MakeInc(w,i->maxvalue,i->minvalue,i->isFloat,0);

}

UnDrawSelectedArea(image,drawable,gc,x,y,xdim,ydim)
unsigned char	*image;		/* the raster image */
Drawable 	drawable;	/* window to draw on */
GC		gc;		/* gc of window to be undrawn on */
int		x,y;		/* point to undraw selection */
int		xdim,ydim;	/* dimensions of image */
{
int	sx,sy;	/* start x&y */
int	ex,ey;	/* end x&y*/
int	i,j;	/* index */

	sx = (x == 0)? x: x-1;
	sy = (y == 0)? y: y-1;
	ex = (x == xdim)? x:x+1;
	ey = (y == ydim)? y:y+1;

	for (j = sy; j <= ey; j++)
		for (i = sx; i <= ex; i++) {
			XSetForeground(myDpy,gc,image[j*xdim+i]);
/*			printf("i,j = %d,%d color=%d\n",i,j,image[j*xdim+i]);*/
			XSync(myDpy,False);
			XDrawPoint(myDpy,drawable,gc,i,j);
			XSync(myDpy,False);
			}
		
}


void CartHighlightSelectedImage(i,x,y)
struct	IMAGE *i;
int	x,y;
{
GC	gc;
XGCValues gcval;

	if (! i->iws.amIShowing)
		return;

	gcval.foreground = white;
	gcval.line_width = 1;
	gc = XtGetGC(i->iws.box3,GCForeground|GCLineWidth,
			&gcval);
	if (i->iws.data1) { 
			UnDrawSelectedArea(i->ri,XtWindow(i->iws.box3),gc,
					i->iws.data2,i->iws.data3,
					i->xdim,i->ydim);

		if (( x== i->iws.data2) && (y == i->iws.data3)) {
			i->iws.data1 = FALSE;	/* is image selected=FALSE*/
			return;
			}
		}


	if (i->ri[i->xdim*y+x] == white) 	/* yeah, I know I'm lazy...*/
		XSetForeground(myDpy,gc,black); 
	else
		XSetForeground(myDpy,gc,white);
	XDrawRectangle(myDpy,XtWindow(i->iws.box3),
			gc,x-1,y-1,2,2);
	i->iws.data1 = TRUE;
	i->iws.data2 = x;
	i->iws.data3 = y;

	return;

} /* CartHighlightSelectedImage() */

void PolarHighlightSelectedImage(i,x,y)
struct	IMAGE *i;
int	x,y;
{
GC	gc;
XGCValues gcval;

	if (! i->pws.amIShowing)
		return;

	gcval.foreground = white;
	gcval.line_width = 1;
	gc = XtGetGC(i->pws.box3,GCForeground|GCLineWidth,
			&gcval);
	if (i->pws.data1) { 
			UnDrawSelectedArea(i->polarimage,XtWindow(i->pws.box3),
					gc, i->pws.data2,i->pws.data3,
					i->ydim*2,i->ydim*2);

		if (( x== i->pws.data2) && (y == i->pws.data3)) {
			i->pws.data1 = FALSE;	/* is image selected=FALSE*/
			return;
			}
		}


	if (i->polarimage[i->ydim*2*y+x] == white)/*yeah?, so what..I'm lazy.*/
		XSetForeground(myDpy,gc,black); 
	else
		XSetForeground(myDpy,gc,white);
	XDrawRectangle(myDpy,XtWindow(i->pws.box3),
			gc,x-1,y-1,2,2);
	i->pws.data1 = TRUE;
	i->pws.data2 = x;
	i->pws.data3 = y;

	return;

} /* PolarHighlightSelectedImage() */



static void CBCartImageSelected(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;
XButtonPressedEvent *buttonEvent;
char buff[256];
char buff2[256];
int x,y;

	i = (struct IMAGE *) client_data;
	buttonEvent = (XButtonPressedEvent *) call_data;
	x = buttonEvent->x;
	y = buttonEvent->y;
	if ((x < 0) || (x > i->xdim) || (y < 0) || (y > i->ydim))
		return;

	if (i->data_showing) 
		SelectPointFromImage(i,x,y);
	else {
		if (i->isFloat) {
		    sprintf(buff,"Just selected location %d,%d; value=%s\n",
					x,y,i->format);
		    sprintf(buff2,buff,i->fdataset[y*i->xdim+x]);
		    }
		else {
		    sprintf(buff,"Just selected location %d,%d; value=%s\n",
					x,y,i->format);
		    sprintf(buff2,buff,i->ri[y*i->xdim+x]);
		    }
		PrintMesg(buff2);
		}

	CartHighlightSelectedImage(i,x,y);

} /* CBCartImageSelected */



static void CBPolarImageSelected(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IMAGE *i;
XButtonPressedEvent *buttonEvent;
char buff[256];
char buff2[256];
int x,y;
int	yd;	/* ydim  doubled */
int	dx,dy;	/*data set x&y*/
double	r,theta; /* polar coordinates */


	i = (struct IMAGE *) client_data;
	buttonEvent = (XButtonPressedEvent *) call_data;
	x = buttonEvent->x;
	y = buttonEvent->y;

	yd = i->ydim *2;
	if ((x < 0) || (x > yd) || (y < 0) || (y > yd))
		return;	 /* if out of bounds, then ignore it */


	r = sqrt((double) (SQUARE((i->ydim-x)) + SQUARE((i->ydim-y))));
	theta = atan(((double)(y - i->ydim))/((double)(x - i->ydim)));

	dy = ROUND(r);
	dx = ROUND(((double)i->xdim) * ((double) theta/(2.0*PI)));

	/* the following quadrant ajustments should be made on theta*/
	/* before the dx calculations so theta value will be correct */
	/* when printed out ... but I'm lazy...I'll put off til tomorrow*/
	if ( x < i->ydim) /* Q2 & Q3 */
		dx = -dx + i->xdim/2;
	else {
		if (y <= i->ydim)  /* Q1 */
			dx = -dx;
		else /* Q4 */
			dx = -dx + i->xdim;
		}


/*	printf("dx = %d, dy = %d\n",dx,dy);*/

	if ((dx > i->xdim) || (dx < 0)) {
		printf("Error in translation of polar mapping dx =%d\n",dx);
		return;
		}
	if ((dy > i->ydim) || (dy < 0)){
		PrintMesg("Out of Polar data set range\n");
		return;
		}

	if (i->data_showing)
		SelectPointFromImage(i,dx,dy);
	else {
		float rad;
/*		degrees = (int) ((((float) dx) / ((float) i->xdim)) * 360.0);*/
		rad = ((((float) dx) / ((float) i->xdim)) * 2.0*PI);

		if (i->isFloat) {
			sprintf(buff,
		    "Selected location r=%d, theta=%.4f; value=%s\n",
					dy,rad,i->format);
			sprintf(buff2,buff,i->fdataset[dy*i->xdim+dx]);
			}
		else {
			sprintf(buff,
		    "Selected location r=%d, theta=%.4f; value=%s\n",
					dy,rad,i->format);
			sprintf(buff2,buff,i->ri[dy*i->xdim+dx]);
			}
		PrintMesg(buff2);
		}
	PolarHighlightSelectedImage(i,x,y);
}


static void CBInitSetColors(w,client_data,call_data)
/* set palette for the window when exposed */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct IWS *ws;

	ws = (struct IWS *) client_data;
	SetColormap(ws->toplevel,ws->cmap);
        XtRemoveEventHandler(w,ExposureMask,FALSE,
                        CBInitSetColors,ws);
}



void DisplayImage(i,ws,type)
/* Create color display window for cartesian or polar */
struct	IMAGE	*i;
struct	IWS	*ws;
int	type;
{
int	xpos,ypos;
int	s;
int	width,height;

	PlaceWindow(&xpos,&ypos);
	if (type == DISPLAY_POLAR) {
		s = i->ydim << 1 ;
		width = ((s+PAL_WIDTH+65) > 200) ? (s+PAL_WIDTH+65) : 200;
		height = ((s+40)  > 350) ? s+40 : 350;
		}
	else {
		width = ((i->xdim+PAL_WIDTH+65) > 200)?
					(i->xdim+PAL_WIDTH+65): 200;
		height = ((i->ydim+40) > 350)?(i->ydim+40): 350;
		}

	ws->toplevel = MakeATopLevel(i->name,toplevelform,xpos,ypos,
					width,height);
	ws->lockcmap = FALSE;

	if (type == DISPLAY_POLAR) {
		if (myVis->class== PseudoColor) {
		       	ws->cmap = XCreateColormap(myDpy,
				XtWindow(ws->toplevel),
				myVis,AllocAll);
			}
		else {
			if (myVis->class == StaticColor) {
		       		ws->cmap = XCreateColormap(myDpy,
					XtWindow(ws->toplevel),
					myVis,AllocNone);
				}
			else {
/**/	printf("\nNot sure how to create a colormap for this display\n");
/**/		printf("I think I'll die ungracefully\n");
/**/		fflush(stdout);
				}
			}
		if (i->hasPalette) {
			StoreColors(i->palette,FALSE,ws->cmap);
			}
		else
			StoreColors(origccells,FALSE,ws->cmap);

		}

	SetColormap(ws->toplevel,ws->cmap);
		


	Set_Pointer(ws->toplevel,XC_gumby);
	ws->composite = Make_Board(i->name,ws->toplevel,0,0,
					width,height);

        ws->box1 = Make_ButtonBox(ws->composite,5,5,width-50,25);
        ws->label = Make_Label(i->label,ws->box1,2,2,30);
        ws->title = Make_Label(i->name,ws->box1,35,2,width-85);

	ws->box2 = Make_ButtonBox(ws->composite,5,35,
				PAL_WIDTH+50,height-40);
	ws->pal_win = MakeRasterImage("palette",ws->box2,
				2,(height-40)/2 -128,
				palXImage,NULL,NULL);



	if (type == DISPLAY_CART) {
        	b[IMAGE_CDONE] = MakeButton("Done",ws->composite,
                                width-40,5,CBCloseCartImageBox,i,0,0);
		ws->box3 = MakeRasterImage(i->name,ws->composite,
					PAL_WIDTH+60,35,
					i->cimage,CBCartImageSelected,i);
		ws->box4 = MakeWorkSpace("Values",ws->box2,PAL_WIDTH+5,
				(height-40)/2-128,40,256,
				CBRedrawTest2,i,NULL,NULL);
		MakeInc(ws->box4,i->maxvalue,i->minvalue,
				i->isFloat,0);
		
		Make_Toggle("Lock Palette",ws->box2,
				2,(height-40)/2 +140,
				CBLockPaletteCart,i,CBLockPaletteCart,i,
				True,False);
		}
	else {
        	b[IMAGE_PDONE] = MakeButton("Done",ws->composite,
                                width-40,5,CBClosePolarImageBox,i,0,0);
		ws->box3 = MakeRasterImage(i->name,ws->composite,
					PAL_WIDTH+60,35,
					i->pimage,CBPolarImageSelected,i);
		ws->box4 = MakeWorkSpace("Values",ws->box2,PAL_WIDTH+5,
				(height-40)/2-128,40,256,
				CBRedrawTest2,i,NULL,NULL);
		MakeInc(ws->box4,i->maxvalue,i->minvalue,
				i->isFloat,0);
		Make_Toggle("Lock Palette",ws->box2,
				2,(height-40)/2 +140,
				CBLockPalettePolar,i,
				CBLockPalettePolar,i,True,False);
		}


	Set_Pointer(ws->box3,XC_left_ptr);


/*	SetColormap(ws->toplevel,ws->cmap);*/

        XtAddEventHandler(ws->toplevel,ExposureMask,FALSE,
                        CBInitSetColors,ws);
} /* DisplayImage() */


@//E*O*F image.c//
chmod u=rw,g=r,o=r image.c
 
echo x - intensity.c
sed 's/^@//' > "intensity.c" <<'@//E*O*F intensity.c//'
/*  Tensor field plot -- plots a fluctuation grid over a data set, with */
/*  tendencies toward higher data points.  Concept: David Thompson	*/
/*  Written:  David Whittington.					*/

#include	<X11/Xlib.h>
#include	<X11/Intrinsic.h>

#define	SQR(x)	(x)*(x)
#define	INIT_FIELD_STR	2
#define	INIT_INERTIA	5
#define	INIT_X_DENSITY	20
#define	INIT_Y_DENSITY	20

static	int	x,y;
static	int	lastX,lastY;
static	int	xdim,ydim;
static	char	*ri;
static	Display	*disp;
static	Drawable d;
static	GC	the_gc;

static unsigned char data(x,y)
int	x,y;
{
	return(ri[y*xdim + x]);
}

void ForceX(strength,inertia)
int	strength,inertia;
{
int	delta,average,direction;

	delta = 0;
	average = ((int) data(x+1,y) - (int) data(x-1,y))/2;
	direction = (average < 0) ? -1 : 1;
	average = average * direction;
	while ((average - (delta*direction + 1)/strength +
		direction*(lastX - delta - x)/inertia) > 0)
	{
		delta += direction;
		average -= delta * direction / strength;
		if ((x+delta) < 1)
		{
			delta -= direction;
			average = 0;
		}
		else
		if ((x+delta) > (xdim - 1))
		{
			delta -= direction;
			average = 0;
		}
		else
		average += (((int) data(x+delta+1,y)-
			     (int) data(x+delta-1,y))/2)*direction;
	}
	XDrawLine(disp,d,the_gc,lastX,lastY,x+delta,y);
	lastX = x+delta;
	lastY = y;
}

void ForceY(strength,inertia)
int	strength,inertia;
{
int	delta,average,direction;

	delta = 0;
	average = ((int) data(x,y+1) - (int) data(x,y-1))/2;
	direction = (average < 0) ? -1 : 1;
	average = average * direction;
	while ((average - (delta*direction + 1)/strength +
		direction*(lastY - delta - y)/inertia) > 0)
	{
		delta += direction;
		average -= delta * direction / strength;
		if ((y+delta) < 1)
		{
			delta -= direction;
			average = 0;
		}
		else
		if ((y+delta) > (ydim - 1))
		{
			delta -= direction;
			average = 0;
		}
		else
		average += (((int) data(x,y+delta+1)-
			     (int) data(x,y+delta-1))/2)*direction;
	}
	XDrawLine(disp,d,the_gc,lastX,lastY,x,y+delta);
	lastX = x;
	lastY = y+delta;
}

void Updt_Intensity(w,image,xmax,ymax,fore,xorflag)
Widget	w;
char	*image;
int	xmax,ymax;
int	fore,xorflag;
{
XGCValues values;
int	xDensity,yDensity;
int	xStart,yStart;
int	current;

	disp = XtDisplay(w);
	d = XtWindow(w);
	if (xorflag == 0)
	{
		values.foreground = fore;
		the_gc = XtGetGC(w,(GCForeground),&values);
	}
	else
	{
		values.function = GXxor;
		values.foreground = 255;
		the_gc = XtGetGC(w,(GCFunction | GCForeground),&values);
	}

	xdim = xmax;
	ydim = ymax;
	ri = image;
	xDensity = INIT_X_DENSITY;
	yDensity = INIT_Y_DENSITY;
	xStart = (xdim - (xdim / xDensity)*xDensity)/2;
	yStart = (ydim - (ydim / yDensity)*yDensity)/2;
	xStart = (xStart < 1) ? xDensity / 2 : xStart;
	yStart = (yStart < 1) ? yDensity / 2 : yStart;

	for (x = xStart; x < xdim; x += xDensity)
	{
		lastX = x;
		lastY = 0;
		for (y = 1; y < ydim; y++)
			ForceX(INIT_FIELD_STR,INIT_INERTIA);
	}
	for (y = yStart; y < ydim; y += yDensity)
	{
		lastX = 0;
		lastY = y;
		for (x = 1; x < xdim; x++)
			ForceY(INIT_FIELD_STR,INIT_INERTIA);
	}
}

@//E*O*F intensity.c//
chmod u=rw,g=r,o=r intensity.c
 
echo x - main.c
sed 's/^@//' > "main.c" <<'@//E*O*F main.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <X11/Shell.h>

#include "xstuff.h"
#include "ximage.icon"

extern Widget toplevel;
Widget	b[50];			/* Buttons */

static	char whoWroteMe[]="\nNCSA XImage written by Dave Thompson\nContour&Shade routines written by Dave Whittington\n";

main(argc,argv)
int	argc;
char	*argv[];
{
        Arg             argList[2];

        Pixmap  iconPixmap;


	Initialize(argc,argv);

	XtRealizeWidget(toplevel);

	Set_Pointer(toplevel,XC_gumby);

        iconPixmap = XCreateBitmapFromData(XtDisplay(toplevel),
                XtWindow(toplevel), XIMAGE_ICON, XIMAGE_WIDTH, XIMAGE_HEIGHT);
        XtSetArg(argList[0],XtNiconPixmap, iconPixmap);
        XtSetValues(toplevel, argList, 1);

	XtMainLoop();
}

void Quit(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	ReleaseAllImages();
	ClosePaletteBox();
	ReleaseAllAnimations();
	exit(0);
}
@//E*O*F main.c//
chmod u=rw,g=r,o=r main.c
 
echo x - mem.c
sed 's/^@//' > "mem.c" <<'@//E*O*F mem.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

char *XIMalloc(size) 
unsigned int size;
{
/*	return((char *) XtMalloc(size+512));*/
	return((char *) XtMalloc(size));
}

char *XICalloc(nelem,elsize)
unsigned int nelem,elsize;
{
char	*p;
char	*q;
int	x,size;
/*	return(calloc(nelem+10,elsize));*/
	return((char *) XtCalloc(nelem,elsize));

} /* XICalloc() */


void XIFree(ptr)
char *ptr;
{
/*	free(ptr);*/
	XtFree(ptr);

}
@//E*O*F mem.c//
chmod u=rw,g=r,o=r mem.c
 
echo x - notebook.c
sed 's/^@//' > "notebook.c" <<'@//E*O*F notebook.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/cursorfont.h>
#include <X11/Form.h>

#include "xstuff.h"
#include "gr_def.h"
#include "gr_var.h"
#include "notebook.h"

#define	NB_DEF_XDIM	400
#define	NB_DEF_YDIM	600

extern Widget   toplevelform;

/**/	struct NOTEBOOK	n;
/**/	char 	CdevelopFlag = 0;
/**/	char 	SdevelopFlag = 0;

void Notebook();



void CBTestNotebook(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
	Notebook(&n);
}


void CBDoneNotebook(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
struct NOTEBOOK *n;
	n = (struct NOTEBOOK *) client_data;

	XtDestroyWidget(n->topLevel);
}

void CBCalculate(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
	if (!CdevelopFlag) {
		if (SdevelopFlag)
			PrintMesg("Can't calculate from notes yet either\n");
		else 
			PrintMesg("Can't calculate from notes yet\n");
		}
	else
		PrintMesg("Still can't calculate from notes yet\n");
	CdevelopFlag++;
} 

void CBSave(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
	if (!SdevelopFlag) {
		if (CdevelopFlag)
			PrintMesg("Can't save notes yet either\n");
		else 
			PrintMesg("Can't save notes yet\n");
		}
	else
		PrintMesg("Still can't save notes yet\n");

	SdevelopFlag++;
}


void Notebook(n)
struct NOTEBOOK *n;
{
int     xpos,ypos;
Widget	topForm;
Widget	topComp;
Widget	box1;
Widget	vport;
static	Arg setPlace[]={{XtNbottom,(XtArgVal) XtChainBottom},
			{XtNvertDistance,65}};

/**/	CdevelopFlag = 0;
/**/	SdevelopFlag = 0;
        PlaceWindow(&xpos,&ypos);
	n->topLevel = MakeATopLevel("X Image [Notbeook]",toplevelform,
			xpos,ypos,NB_DEF_XDIM,NB_DEF_YDIM);

        Set_Pointer(n->topLevel,XC_gumby);

	topComp= MakeForm("Notebook",n->topLevel,0,0,
				NB_DEF_XDIM,NB_DEF_YDIM,0,0);

	box1 = Make_Board("Notebook ctrls",topComp,0,0,NB_DEF_XDIM-10,30);

	(void) MakeButton("Calculate",box1,5,2,CBCalculate,n,0,0);
	(void) MakeButton("Save",box1,70,2,CBSave,n,0,0);
	(void) MakeButton("Done",box1,NB_DEF_XDIM-60,2,CBDoneNotebook,n,0,0);

	topForm = MakeForm("blabla",topComp,0,65,NB_DEF_XDIM-10,
                        NB_DEF_YDIM-70,setPlace,2);

	vport = MakeVPort("bla",topForm,VERTHORIZ,0,0,NB_DEF_XDIM-10,
			NB_DEF_YDIM-70);


	{
	static char buff[4000];
	gr_MakeText("Notebook edit",vport,
			NOSCROLL,SELECTABLE,STRINGSOURCE,
			buff,5,65,NB_DEF_XDIM-10,
			NB_DEF_YDIM-70);
	}

}



@//E*O*F notebook.c//
chmod u=rw,g=r,o=r notebook.c
 
echo x - palentry.c
sed 's/^@//' > "palentry.c" <<'@//E*O*F palentry.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/cursorfont.h>
#include <Xw/Xw.h>

#include "xstuff.h"
#include "palentry.h"

extern Widget   toplevelform;
/*test*/ extern Colormap fcmap;
extern	void CBInstallCMap();
extern	void CBUnInstallCMap();

#define PEBOX_XDIM	310
#define PEBOX_YDIM	230
#define	MAX_COLORS	256

#define	VCDIM		50	/* View color entry box dimension (sqrt) */
#define	VCDIMX		100
#define	VCDIMY		50	
#define	PAL_WIDTH	30

static	unsigned char viewColor[VCDIMX*VCDIMY];

static	unsigned	char	*palImage;
static	XImage	*palXImage;



int InitPalEntry(dpy)
Display *dpy;
{
Visual *vis;
register int x;
register int y;

        if ( ! (palImage = (unsigned char *) XIMalloc(PAL_WIDTH*256))) {
	    printf("Couldn't allocate enough memory for pal entry editor\n");
            return(0);
            }

        for(x = 0; x < 256; x++)
                for(y = 0; y < PAL_WIDTH; y++)
                        palImage[y*256+ x] = x;
	vis = GetVisual(dpy);
        palXImage = XCreateImage(dpy,vis,8,ZPixmap,0,palImage,
                                256,PAL_WIDTH,8,256);
        return(1);
}


EditPalEntry(ccells,numColors)
XColor  ccells[];
int     numColors;
{
static	struct	PALEDIT p;

	if (numColors > MAX_COLORS) {
		printf("Can't do more than 256 color pals...remember?\n");
		return;
		}
	MakePalEntryEditor(&p,ccells,numColors);
}

void CBEditPalEntry(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	EditPalEntry(client_data,256);
}

static void CBDone(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct PALEDIT *p;
	p = (struct PALEDIT *) client_data;

	XtDestroyWidget((struct PALEDIT *) p->topLevel);
}

static void CBValuator1(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
char    buff[80];
struct PALEDIT *p;
Arg	arglist[2];
int	newVal;

        p = (struct PALEDIT *) client_data;
        newVal = (int) call_data;


	p->ccells[p->entry].red = newVal << 8;
	StoreColors(p->ccells,False,fcmap);

	sprintf(buff,"%d",newVal);
        XtSetArg(arglist[0],XtNlabel,buff);
        XtSetValues(p->val1,arglist,1);

}

static void CBValuator2(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
char    buff[80];
struct PALEDIT *p;
Arg	arglist[2];
int	newVal;

        p = (struct PALEDIT *) client_data;
        newVal = (int) call_data;


	p->ccells[p->entry].green = newVal << 8;
	StoreColors(p->ccells,False,fcmap);

	sprintf(buff,"%d",newVal);
        XtSetArg(arglist[0],XtNlabel,buff);
        XtSetValues(p->val2,arglist,1);

}

static void CBValuator3(w,client_data,call_data)
Widget  w;
caddr_t client_data;
caddr_t call_data;
{
char    buff[80];
struct PALEDIT *p;
Arg	arglist[2];
int	newVal;

        p = (struct PALEDIT *) client_data;
        newVal = (int) call_data;


	p->ccells[p->entry].blue = newVal << 8;
	StoreColors(p->ccells,False,fcmap);

	sprintf(buff,"%d",newVal);
        XtSetArg(arglist[0],XtNlabel,buff);
        XtSetValues(p->val3,arglist,1);

}


CBColorVCE(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
struct PALEDIT *p;
Display *dpy;
	
	dpy = XtDisplay(w);
	p = (struct PALEDIT *) client_data;

	XSetWindowBackground(dpy,XtWindow(p->vce),p->entry);
	XClearArea(dpy,XtWindow(p->vce),0,0,VCDIMX,VCDIMY,False);
}

PalEntryChooser(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Window root, child;
int     root_x,root_y;
int     win_x,win_y;
unsigned int    keys_buttons;
struct	PALEDIT *p;
char	buff[10];
int	v; 

	p = (struct PALEDIT *) client_data;
        if (XQueryPointer(XtDisplay(w),XtWindow(w),&root,&child,
                &root_x,&root_y,&win_x,&win_y,&keys_buttons)) {
                }
        if ((win_x > 255) || ( win_x < 0))
                return;
	p->entry = win_x;

	sprintf(p->dEntryString,"%3d",p->entry);

	CBColorVCE(w,p,0);
	gr_DialogSetValue(p->dEntry,p->dEntryString);

	v = p->ccells[p->entry].red >> 8;
	CBValuator1(w,p,v);
	v = p->ccells[p->entry].green >> 8;
	CBValuator2(w,p,v);
	v = p->ccells[p->entry].blue >> 8;
	CBValuator3(w,p,v);
}


MakePalEntryEditor(p,ccells,numColors)
struct	PALEDIT *p;
XColor	ccells[];
int	numColors;
{
int     xpos,ypos;
int	initE;
Display *dpy;
char	buff[20];
int	v1,v2,v3;
Widget	ebox;

	
	dpy = XtDisplay(toplevelform);
	initE = numColors -1;
	p->ccells = ccells;

	PlaceWindow(&xpos,&ypos);
        p->topLevel = MakeATopLevel("X Image [Palette.PalEntryEditor]",
			toplevelform,
                        xpos,ypos,PEBOX_XDIM,PEBOX_YDIM);

        Set_Pointer(p->topLevel,XC_gumby);

/*#ifdef  NON_ICCCM_WINDOW_MANAGER*/
        XInstallColormap(dpy,fcmap);
        /* Make compatible with Release 2 window managers */
        XtAddEventHandler(p->topLevel,EnterWindowMask,FALSE,
                        CBInstallCMap,NULL);
        XtAddEventHandler(p->topLevel,LeaveWindowMask,FALSE,
                        CBUnInstallCMap,NULL);
/*#else*/

        XSync(dpy,False);
#ifndef DEF_STAT_VISUAL
        {/* Make compatible with Release 3 window managers */
                XSetWindowAttributes attrib;
                attrib.colormap = fcmap;

                XChangeWindowAttributes(dpy,XtWindow(p->topLevel),
                                        CWColormap,&attrib);
                /* aaaaaaarrrrrrrgh */
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
		}
#endif
/*#endif*/

	p->composite = Make_Board("palEntryEditor",
			p->topLevel,0,0,PEBOX_XDIM,PEBOX_YDIM);

	p->composite = Make_Window("X Image [Palette Entry Editor]",
			p->composite,0,0,PEBOX_XDIM,PEBOX_YDIM);


	p->box1 = Make_Board("colors",p->composite,
			2,22,PEBOX_XDIM-10,95);

/*	{
	unsigned char *v;
	int	x;
	for ( x= 0, v = viewColor; x < VCDIMX*VCDIMY ; x++, v++)
		*v = initE;
	}
*/

	/* vce == View Color Entry  */
	p->vce = MakeWorkSpace("vce",p->box1,260-VCDIMX,PAL_WIDTH+10,
			VCDIMX,VCDIMY,CBColorVCE,p,NULL,NULL);

	p->palImage=MakeRasterImage("Palette",p->box1,5,5,palXImage,NULL,NULL);
        XtAddEventHandler(p->palImage,ButtonMotionMask,0,
                                PalEntryChooser,p);

        (void) MakeButton("Done",p->box1,265,5,CBDone,p,0,0);
	
	p->entry = initE;
	sprintf(p->dEntryString,"%d",p->entry);
        ebox = Make_ButtonBox(p->box1,5,PAL_WIDTH+10,PEBOX_XDIM-VCDIMX-60,
				95 - PAL_WIDTH -20);
        p->dEntry = Make_Dialog("name",ebox,"Pal Entry:",p->dEntryString,
                                DSTRINGSIZE,2,2,256-70-VCDIMX,56);
        MakeButton("  Set   ",ebox,95,4,NULL,p,0,0);
/*
	ebox = Make_Board("ebox",p->box1,5,PAL_WIDTH+10,150,27);
	(void) MakeButton("Palette Entry",ebox,2,4,NULL,NULL,0,0);
	p->dEntry = Make_Text(ebox,95,2,50,20,p->dEntryString);
	(void) Make_Toggle("rgb",ebox,5,PAL_WIDTH+47,
			NULL,NULL,NULL,NULL,False);
*/
	

	v1 = p->ccells[initE].red >> 8;
	v2 = p->ccells[initE].green >> 8;
	v3 = p->ccells[initE].blue >> 8;
	p->box2 = Make_Board("colors",p->composite,
			2,122,PEBOX_XDIM-10,PEBOX_YDIM-132);

	p->label1 = Make_Label("red",p->box2,5,10,40);
	p->slide1 = MakeValuator("slide1",p->box2,50,10,210,20,
				False,0,MAX_COLORS+9,v1,10,
				CBValuator1,p,
				CBValuator1,p,
				CBValuator1,p);
	Set_Pointer(p->slide1,XC_sb_h_double_arrow);
	sprintf(buff,"%d",v1);
	p->val1	= Make_Label(buff,p->box2,265,10,30);

	p->label2 = Make_Label("green",p->box2,5,40,40);
	p->slide2 = MakeValuator("slide2",p->box2,50,40,210,20,
				False,0,MAX_COLORS+9,v2,10,
				CBValuator2,p,
				CBValuator2,p,
				CBValuator2,p);
	Set_Pointer(p->slide2,XC_sb_h_double_arrow);

	sprintf(buff,"%d",v2);
	p->val2	= Make_Label(buff,p->box2,265,40,30);

	p->label3 = Make_Label("blue",p->box2,5,70,40);
	p->slide3 = MakeValuator("slide3",p->box2,50,70,210,20,
				False,0,MAX_COLORS+9,v3,10,
				CBValuator3,p,
				CBValuator3,p,
				CBValuator3,p);
	Set_Pointer(p->slide3,XC_sb_h_double_arrow);
	sprintf(buff,"%d",v3);
	p->val3	= Make_Label(buff,p->box2,265,70,30);
	

/*#ifdef  NON_ICCCM_WINDOW_MANAGER*/
        /* Make compatible with Release 2 window managers */
/*        XInstallColormap(dpy,fcmap);
        XtAddEventHandler(p->topLevel,EnterWindowMask,FALSE,
                        CBInstallCMap,NULL);
        XtAddEventHandler(p->topLevel,LeaveWindowMask,FALSE,
                        CBUnInstallCMap,NULL);
*/
/*#else*/

        XSync(dpy,False);
#ifndef DEF_STAT_VISUAL
        {/* Make compatible with Release 3 window managers */
                XSetWindowAttributes attrib;
                attrib.colormap = fcmap;

                XChangeWindowAttributes(dpy,XtWindow(p->topLevel),
                                        CWColormap,&attrib);
                /* aaaaaaarrrrrrrgh */
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
                XSetWindowColormap(dpy,XtWindow(p->topLevel),fcmap);
                XSync(dpy,False);
		}
#endif
/*#endif*/

}
@//E*O*F palentry.c//
chmod u=rw,g=r,o=r palentry.c
 
echo x - palette.c
sed 's/^@//' > "palette.c" <<'@//E*O*F palette.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xatom.h>
#include <X11/Viewport.h>
#include <X11/Form.h>
#include <X11/Label.h>
#include <X11/cursorfont.h>

#include <Xw/Xw.h>
#include <Xw/Toggle.h>

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

#include "buttons.h"
#include "xstuff.h"
#include "paletteP.h"
#include "getfile.h"

#define PALCOMPHEIGHT	100
#define PAL_WIDTH	28

#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

/* copy a color cell */
#define cpccell(a,b)	{\
			a.red = b.red; \
			a.green = b.green; \
			a.blue = b.blue;\
			a.flags = b.flags; \
			a.pad = b.pad;\
			}

#define MAX3(a,b,c) ((a>b)&&(a>c)) ? a : ((b > c)? b : c)
#define MIN3(a,b,c) ((a<b)&&(a<c)) ? a : ((b < c)? b : c)
#define SIGN(a) ((a)?(a/abs(a)):1) /* return 1 if zero */


extern	Widget	toplevelform;			/* The top dude (composite)*/
extern	void CBEditPalEntry();

unsigned long white;
unsigned long black;

static	Display	*myDpy;				/* Display for this program*/
static	Visual	*myVis;
static	Widget	top_pal_ctrl_widget;		/* pal ctrl window ap shell*/
static	Widget	pal_ctrl_widget;		/* composite widget ctrl win*/
static	XWindowAttributes pcw_attrib;		/* window attributes */
static	char	pal_loaded	= FALSE;	/* Is the palette loaded */
/*static*/	Colormap fcmap;
static	char palette_ctrl_window_showing = FALSE;	/* self explanitory */
static	XColor	uccells[256];			/* Undo to these colors*/
static	XColor	bccells[256];			/* Back up copy */
	XColor	rccells[256];			/* current colors */
	XColor	origccells[256];		/* original copy */
static	int	numColors;		/* max num colors on this screen*/

static	char	pal_sfile[80];			/* palette save file name */
static	char	use_entire_palette=FALSE;
static	XImage	*palImage;			/* the palette display XImage*/
static	Widget	pal_image;			/* The palette display window*/
static	crlastx = 0;
static	Widget pal_comp;
static	XImage *pal_comp_image;		/* Stores component pal image*/
static	GC 	pal_comp_gc;
static	int	comp_pen=0;		/* color to draw new component */
static	unsigned long comp_pen_dcolor;	/* color to draw comp pen */
static	int	comp_last_x=0;
static	int	comp_last_y=0;
static	XPoint	rpoints[256];		/*drawn red points(CBDrawComponent)*/
static	XPoint	gpoints[256];		/*drawn green points*/
static	XPoint	bpoints[256];		/*drawn blue points*/
static	XPoint	cpoints[256];		/*drawn cyan  */
static	XPoint	mpoints[256];		/*drawn magenta  */
static	XPoint	ypoints[256];		/*drawn yellow */
static	XPoint	hpoints[256];		/*drawn hue */
static	XPoint	spoints[256];		/*drawn saturation*/
static	XPoint	vpoints[256];		/*drawn value */
static	unsigned int	rgbcmyhsv=0;	/* What's plotted (r=(1<<9),v=(1<<1))*/
static	struct	GetFile	palfile;
static	palRedraw = FALSE;

void	CBInitRotate();
void	CBReset();
void	CBEvalExpr();
void	CBNewLoadPal();
void	CBSetPen();
void	CBUnSetPen();
void	CBPrepChangeComp();
void	CBChangeComponent();
void	CBEndChangeComp();
void	RedrawComponent();
void	CBLoadPal();
void	CBTranspose();
void	TransposeCMap();
void	CBFiddle();
void	CRotate();
char	*Get_Save_Pal();
int	ChooseColor();
void	CBRedrawComponents();
void	CBCompKey();
void	CBPalSave();
void	CBUndo();
void	SaveForUndo();
void	CBSmooth();
void	CBInstallCMap();
void	CBUnInstallCMap();
void	CBDrawComponent();
void	CBUnDrawComponent();



void StoreColors(ccells,redraw,cmap)
/* Store colors in colormap */
XColor	ccells[];	/* colors to be stored */
int	redraw;		/* Should I redraw components */
Colormap cmap;		/* colormap to store colors in */
/* store colors in colormap, except for black & white if 
 * the global variable use_entire_palette is set to false*/
{
Visual *vis;

	vis = myVis;
	if (vis->class == StaticColor) {
		PrintMesg("Can't set colors for this StaticColor display\n");
		return;
		}
	if (vis->class != PseudoColor) {
	    PrintMesg("Can't set colors for this non-PseudoColor display\n");
	    return;
	    }
	if (!use_entire_palette) {
		XColor	inblackcell;
		XColor	inwhitecell;

		inblackcell = ccells[black];
		inwhitecell = ccells[white];

		/* restore black and white */
		ccells[black].red   = (unsigned short) 0;
		ccells[black].blue  = (unsigned short) 0;
		ccells[black].green = (unsigned short) 0;
		ccells[black].flags = DoRed|DoGreen|DoBlue;

		ccells[white].red   = (unsigned short) 65535;
		ccells[white].blue  = (unsigned short) 65535;
		ccells[white].green = (unsigned short) 65535;
		ccells[white].flags = DoRed|DoGreen|DoBlue;

		XStoreColors(myDpy,cmap,ccells,numColors);

		/* take it back out */
		ccells[black]=inblackcell;
		ccells[white]=inwhitecell;
		}
	else
		XStoreColors(myDpy,cmap,ccells,numColors);

	if (redraw)
		RedrawComponent();

	return;
} /* StoreColors() */



static void CBUseEntirePalette(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
static Arg use[]={{XtNlabel,(int)"Use entire palette"},{XtNset,True}};
static Arg dont[]={{XtNlabel,(int)"Don't use entire palette"},{XtNset,True}};

	use_entire_palette = ! use_entire_palette;
	StoreColors(rccells,TRUE,fcmap);

	if (use_entire_palette) {
		/*PrintMesg("Use entire palette\n");*/
		XtSetValues(w,use,2);
		}
	else {
		/*PrintMesg("Don't use entire palette\n");*/
		XtSetValues(w,dont,2);
		}
}


void ClosePaletteBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
/*	XtUnmanageChild(top_pal_ctrl_widget);*/
	if (palette_ctrl_window_showing) {
		CBUnInstallCMap(top_pal_ctrl_widget,NULL,NULL);
		XtDestroyWidget(top_pal_ctrl_widget);
		}


	palette_ctrl_window_showing = FALSE;
}

int InitPalette(dpy)
Display *dpy;
{
int x;
int screen;
int planes;

	myDpy = dpy;
	myVis = GetVisual(dpy);
	screen = DefaultScreen(dpy);
	planes = DisplayPlanes(myDpy,screen);

	white = WhitePixel(dpy,screen);
	black = BlackPixel(dpy,screen);

	numColors = XDisplayCells(dpy,screen);
	if (numColors > 256) {
		numColors = 256;   /* only use max 256 color entries */
		}

	/* Create startup default palette (use X servers) */ 
	for(x=0;x < 256; x++)
		origccells[x].pixel = x;
	XQueryColors(dpy,DefaultColormap(dpy,screen),
			origccells,numColors);
	for(x=0;x < 256; x++) {
		rccells[x].pixel = x;
		cpccell(rccells[x],origccells[x]);
		}

	if (!(palImage = MakePalette(myDpy,PAL_WIDTH,TRUE)))
		return(0);

	return(1); /* initialize ok */
}


void CBInitPal(w,client_data,call_data)
/* This procedure called on exposure of palette control window*/
/* Sets the colormap for the window */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display *dpy;

	w = top_pal_ctrl_widget;
/*	printf("CBInitPal() I've been called\n");*/
	fflush(stdout);
	dpy = XtDisplay(w);
	XSync(dpy,False);
#ifndef DEF_STAT_VISUAL
	XSetWindowColormap(dpy,XtWindow(w),fcmap);
#endif
	XtRemoveEventHandler(w,ExposureMask,0,CBInitPal,NULL);

	/* I don't think this command should be here, but it seems *
	 * to make it work.....oh well... 			   *
	 * Shake up the ICCCM window manager maybe? 		   */
/**/	XInstallColormap(dpy,fcmap);

#ifndef DEF_STAT_VISUAL
	{/* Make compatible with Release 3 window managers */
		/* try this twice since it's not working */
		XSetWindowAttributes attrib;
		attrib.colormap = fcmap;

		XChangeWindowAttributes(dpy,XtWindow(w),
					CWColormap,&attrib);
		XSync(dpy,False);
		XSetWindowColormap(dpy,XtWindow(w),fcmap);
		XSync(dpy,False);
	}
#endif

}


void PaletteBox(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Widget	buttonbox1;
Widget	buttonbox2;
Widget	buttonbox3;
Display *dpy;
Visual	*vis;
int x;
Arg             arglist[10];
Cardinal        i=0;
int	xpos,ypos;

	if (palette_ctrl_window_showing) {
		PrintMesg("Palette window already open\n");
		return;
		}

	dpy = XtDisplay(toplevelform);
	vis = GetVisual(myDpy);
	if (vis->class != PseudoColor) {
		PrintMesg("Can't use X Image Palette on this display.\n");
		PrintMesg("Not a Pseudo Color device\n");
		return;
		}
/*
	if ( DisplayPlanes(dpy,XDefaultScreen(dpy)) != 8 ) {
		PrintMesg("Can't use X Image Palette on this display.\n");
		PrintMesg("Not an 8 bit display\n");
		return;
		}
*/
		

	PrintMesg("Opening Palette Box\n");

	rgbcmyhsv = 0;
	comp_pen = 0;
	comp_last_x = comp_last_y = 0;
	crlastx = 0;

	PlaceWindow(&xpos,&ypos);
	top_pal_ctrl_widget = MakeATopLevel("NCSA X Image [Palette]",
				toplevelform,xpos,ypos,360,285+PALCOMPHEIGHT);
	pal_ctrl_widget = Make_Window("NCSA X Image [Palette]",
				top_pal_ctrl_widget,5,5,360,285+PALCOMPHEIGHT);
/**/	XSync(dpy,False);
	fcmap = XCreateColormap(dpy, XtWindow(top_pal_ctrl_widget),
			GetVisual(dpy),AllocAll);
	for(x=0;x < 256; x++)
		origccells[x].pixel = x;
	XQueryColors(dpy,DefaultColormap(dpy,DefaultScreen(dpy)),
			origccells,numColors);
	for(x=0;x < 256; x++) {
		uccells[x].pixel = rccells[x].pixel = x;
		cpccell(rccells[x],origccells[x]);
		cpccell(uccells[x],origccells[x]);
		}


/*#ifdef	NON_ICCCM_WINDOW_MANAGER*/
	XInstallColormap(dpy,fcmap);
	/* Make compatible with Release 2 window managers */
	XtAddEventHandler(top_pal_ctrl_widget,EnterWindowMask,FALSE,
			CBInstallCMap,NULL);
	XtAddEventHandler(top_pal_ctrl_widget,LeaveWindowMask,FALSE,
			CBUnInstallCMap,NULL);
/*#else*/

	XSync(dpy,False);
	{/* Make compatible with Release 3 window managers */
#ifndef DEF_STAT_VISUAL
		XSetWindowAttributes attrib;
		attrib.colormap = fcmap;

		XChangeWindowAttributes(dpy,XtWindow(top_pal_ctrl_widget),
					CWColormap,&attrib);
		XSetWindowColormap(dpy,XtWindow(top_pal_ctrl_widget),fcmap);
#endif

        XtAddEventHandler(pal_ctrl_widget,ExposureMask,0,CBInitPal,NULL);

	}
	XSync(dpy,False);
/*#endif*/


	buttonbox1 = Make_ButtonBox(pal_ctrl_widget,1,200+PALCOMPHEIGHT,
					355,80);
	b[PAL_LOAD] = MakeButton("Load",buttonbox1,5,1,CBNewLoadPal,NULL,0,0);
	b[PAL_RESET] = MakeButton("Reset",buttonbox1,40,1,CBReset,NULL,0,0);
	(void) MakeButton("Undo",buttonbox1,83,1,CBUndo,NULL,0,0);
	b[PAL_SMOOTH] = MakeButton("Smooth",buttonbox1,300,1,
				CBSmooth,&comp_pen,0,0);
#ifdef UNDER_DEVELOPMENT
	(void) MakeButton("Edit Pal Entry",buttonbox1,142,1,CBEditPalEntry,
					rccells,0,0);
	b[PAL_EVAL] = MakeButton("Eval Expr",buttonbox1,240,1,
				CBEvalExpr,NULL,0,0);
#endif



	b[PAL_SAVE] = MakeButton("Save",buttonbox1,5,30,CBPalSave,NULL,0,0);
	pal_sfile[0]='\0';
	(void)Make_Text_Inp("pal_save_file",buttonbox1,
			pal_sfile,80,45,32,300,20);

	(void)MakeAltToggle("Don't use entire palette",buttonbox1,45,60,
			CBUseEntirePalette,NULL,CBUseEntirePalette,NULL);
/*	(void)MakeAltToggle("Lock in palette",buttonbox1,210,60,
			NULL,NULL,NULL,NULL);
*/

	buttonbox2 = Make_ButtonBox(pal_ctrl_widget,1,60+PALCOMPHEIGHT,
					80,135);
	(void)	Make_Label("Wholistic",buttonbox2,1,1,78);
	b[PAL_FIDDLE] = MakeButton("Fiddle",buttonbox2,5,25,CBFiddle,NULL,0,0);
	b[PAL_INVERT] = MakeButton("Flip",buttonbox2,5,55,CBTranspose,NULL,0,0);
/*b[PAL_T_ROTATE] =MakeButton("Track Rotate",buttonbox2,70,25,
			CBRotate,NULL,0,0);*/
/*	b[PAL_ROTATE] = MakeButton("Rotate",buttonbox2,5,85,NULL,NULL,0,0);*/
	Set_Pointer(buttonbox2,XC_hand2);

	buttonbox3 = Make_ButtonBox(pal_ctrl_widget,85,60+PALCOMPHEIGHT,
					270,135);
	(void)Make_Label("Component Palette Manipulation",buttonbox3,1,1,268);
	b[PAL_PRED] = Make_Toggle("",buttonbox3,5,25,
				CBDrawComponent,CRED,
				CBUnDrawComponent,CRED,True,False);
	b[PAL_RED] = Make_Toggle("Red",buttonbox3,25,25,
				CBSetPen,CRED,CBUnSetPen,CRED,False,False);
	b[PAL_PGREEN] = Make_Toggle("",buttonbox3,5,55,
				CBDrawComponent,CGREEN,
				CBUnDrawComponent,CGREEN,True,False);
	b[PAL_GREEN] = Make_Toggle("Green",buttonbox3,25,55,
				CBSetPen,CGREEN,CBUnSetPen,CGREEN,False,False);
	b[PAL_PBLUE] = Make_Toggle("",buttonbox3,5,85,
				CBDrawComponent,CBLUE,
				CBUnDrawComponent,CBLUE,True,False);
	b[PAL_BLUE] = Make_Toggle("Blue",buttonbox3,25,85,
				CBSetPen,CBLUE,CBUnSetPen,CBLUE,False,False);
	b[PAL_PCYAN] = Make_Toggle("",buttonbox3,80,25,
				CBDrawComponent,CCYAN,
				CBUnDrawComponent,CCYAN,True,False);
	b[PAL_CYAN] = Make_Toggle("Cyan",buttonbox3,100,25,
				CBSetPen,CCYAN,CBUnSetPen,CCYAN,False,False);
	b[PAL_PMAGENTA] = Make_Toggle("",buttonbox3,80,55,
				CBDrawComponent,CMAGENTA,
				CBUnDrawComponent,CMAGENTA,True,False);
	b[PAL_MAGENTA] = Make_Toggle("Magenta",buttonbox3,100,55,
				CBSetPen,CMAGENTA,CBUnSetPen,CMAGENTA,
				False,False);
	b[PAL_PYELLOW] = Make_Toggle("",buttonbox3,80,85,
				CBDrawComponent,CYELLOW,
				CBUnDrawComponent,CYELLOW,True,False);
	b[PAL_YELLOW] = Make_Toggle("Yellow",buttonbox3,100,85,
				CBSetPen,CYELLOW,CBUnSetPen,CYELLOW,
				False,False);
	b[PAL_PHUE] = Make_Toggle("",buttonbox3,170,25,
				CBDrawComponent,CHUE,
				CBUnDrawComponent,CHUE,True,False);
	b[PAL_HUE] = Make_Toggle("Hue",buttonbox3,190,25,
				CBSetPen,CHUE,CBUnSetPen,CHUE,False,False);
	b[PAL_PSATURATION] = Make_Toggle("",buttonbox3,170,55,
				CBDrawComponent,CSATURATION,
				CBUnDrawComponent,CSATURATION,True,False);
	b[PAL_SATURATION] = Make_Toggle("Saturation",buttonbox3,190,55,
				CBSetPen,CSATURATION,CBUnSetPen,CSATURATION,
				False,False);
	b[PAL_PVALUE] = Make_Toggle("",buttonbox3,170,85,
				CBDrawComponent,CVALUE,
				CBUnDrawComponent,CVALUE,True,False);
	b[PAL_VALUE] = Make_Toggle("Value",buttonbox3,190,85,
				CBSetPen,CVALUE,CBUnSetPen,CVALUE,
				False,False);
	Set_Pointer(buttonbox3,XC_hand2);

	b[PAL_DONE]=MakeButton("Done",pal_ctrl_widget,320,25,
				ClosePaletteBox,NULL,0,0);

/*        pal_image = Make_Pal_Window(pal_ctrl_widget,47,23,255,28);*/
	pal_image = MakeRasterImage("PaletteDisplay",pal_ctrl_widget,
				47,23,palImage,NULL,NULL);

	pal_comp = Make_Board("Palette_Components",pal_ctrl_widget,47,55,255,
				PALCOMPHEIGHT+2);
	pal_comp = MakeWorkSpace("Palette Components",pal_ctrl_widget,
				47,55,255,PALCOMPHEIGHT+2,
				CBRedrawComponents,NULL,
				CBCompKey,NULL);
	/*(void) MakeImageWindow("Palette_comp_canvas",&pal_comp_image,white,
				pal_comp,0,0,255,PALCOMPHEIGHT);
	*/
	{
	static XGCValues gcvalues;
	gcvalues.foreground = black;
	gcvalues.background = white;
	pal_comp_gc = XtGetGC(pal_comp,(GCForeground|GCBackground),&gcvalues);
	}

	
	/* Component palette display window drawing */
	XtAddEventHandler(pal_comp,ButtonPressMask,0,
			CBPrepChangeComp,NULL );
        XtAddEventHandler(pal_comp,Button1MotionMask,0,
			CBChangeComponent,NULL );
	XtAddEventHandler(pal_comp,ButtonReleaseMask|LeaveWindowMask,0,
			CBEndChangeComp,NULL );
	Set_Pointer(pal_comp,XC_pencil);


        XtAddEventHandler(pal_image,ButtonPressMask,0,CBInitRotate,NULL );
        XtAddEventHandler(pal_image,Button1MotionMask,0,CRotate,NULL );
        Set_Pointer(pal_image,XC_sb_h_double_arrow);

	XSync(dpy,False);
	StoreColors(rccells,TRUE,fcmap);
	XSync(dpy,False);
	palette_ctrl_window_showing = TRUE;

	return;

} /* PaletteBox() */



static void CBRedrawComponents(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	RedrawComponent();
}

static void CBCompKey(w,client_data,call_data)
/* this routine is suppose to set which component to draw with 
 * but the HP workspace widget doesn't seem to be returning anything
 * meaningful when a key pressed.... either that or I don't know how
 * to use it. 
 */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
/*	printf("Just pressed %d key(call_data)\n",(int) call_data);
	printf("Just pressed %c key(call_data)\n",(char *) call_data);
	printf("Just pressed %d key(client_data)\n",(int) client_data);
*/
	/* will use CBSetPen() */
	/* then set the toggle */
}

static void CBTranspose(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	TransposeCMap();
	return;
}

void CBInstallCMap(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	XInstallColormap(XtDisplay(w),fcmap);
}

void CBUnInstallCMap(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	XUninstallColormap(XtDisplay(w),fcmap);
}

static void CBInitRotate(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Window root, child;
int	root_x,root_y;
int	win_x,win_y;
unsigned int	keys_buttons;

	SaveForUndo(rccells);
	if (XQueryPointer(XtDisplay(w),XtWindow(w),&root,&child,
		&root_x,&root_y,&win_x,&win_y,&keys_buttons)) {
		crlastx = win_x;
		}
}

static void GotPalFile()
{
	CBLoadPal(top_pal_ctrl_widget,NULL,NULL);
	
}

static void DidntGetPalFile()
{
	PrintMesg("Palette load canceled\n");
}

static void CBNewLoadPal(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	palfile.type = FTYPE_PAL;
	palfile.yesfile = GotPalFile;
	palfile.nofile = DidntGetPalFile;
	GetAFile(&palfile);
}



static void CBLoadPal(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display *dpy = XtDisplay(w);
int x;
char fileName[512];

	SaveForUndo(rccells);

        sprintf(fileName,"%s/%s",palfile.directory,*(palfile.file));
	if (! palfile.isHDF) {
		if(! ReadSEQPalette(fileName,origccells))
			return;	/* Error reading Colormap */
		}
	else {
		if(! ReadHDFPalette(fileName,origccells))
			return;	/* Error reading Colormap */
		}

	for(x=0; x < 256 ; x++) {
                rccells[x].pixel = x;
                cpccell(rccells[x],origccells[x]);
                }

        StoreColors(rccells,TRUE,fcmap);


	pal_loaded = TRUE;
	return;

} /* CBLoadPal() */



static void DrawComponent(component)
/* Draw the color components in the component window */
int	component;	/* which component to draw */
{
int x;
int y;
XGCValues	gcval;

        gcval.foreground = ChooseColor(rccells,component);
        XChangeGC(XtDisplay(pal_comp), pal_comp_gc, GCForeground, &gcval);
	switch (component){
		case CRED :
			for (x = 0 ; x < 256 ; x++ ) {
				y = (int) ((float) (rccells[x].red >> 8)* 
						(float) (100.0 / 255.0));
				rpoints[x].x = x;
				rpoints[x].y = 100 - y;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,rpoints,256,CoordModeOrigin);
			break;
		case CGREEN:
			for (x = 0 ; x < 256 ; x++ ) {
				y = (int) ((float) (rccells[x].green >> 8)* 
						(float) (100.0 / 255.0));
				gpoints[x].x = x;
				gpoints[x].y = 100 - y;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,gpoints,256,CoordModeOrigin);
			break;
		case CBLUE:
			for (x = 0 ; x < 256 ; x++ ) {
				y = (int) ((float) (rccells[x].blue >> 8)* 
						(float) (100.0 / 255.0));
				bpoints[x].x = x;
				bpoints[x].y = 100 -y;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,bpoints,256,CoordModeOrigin);
			break;
		case CCYAN:
			for (x = 0 ; x < 256 ; x++ ) {
				y = (int) ((float) (rccells[x].red >> 8)* 
						(float) (100.0 / 255.0));
				cpoints[x].x = x;
				cpoints[x].y = y;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,cpoints,256,CoordModeOrigin);
			break;
		case CMAGENTA:
			for (x = 0 ; x < 256 ; x++ ) {
				y = (int) ((float) (rccells[x].green >> 8)* 
						(float) (100.0 / 255.0));
				mpoints[x].x = x;
				mpoints[x].y = y;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,mpoints,256,CoordModeOrigin);
			break;
		case CYELLOW:
			for (x = 0 ; x < 256 ; x++ ) {
				y = (int) ((float) (rccells[x].blue >> 8)* 
						(float) (100.0 / 255.0));
				ypoints[x].x = x;
				ypoints[x].y = y;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,ypoints,256,CoordModeOrigin);
			break;
		case CHUE: {
			double	h;
			int	r,g,b; 
			int	max,min;
			int	range;
			double	rl,gl,bl; 

			for (x = 0 ; x < 256 ; x++ ) {
			    r = (int) rccells[x].red >> 8;
			    g = (int) rccells[x].green >> 8;
			    b = (int) rccells[x].blue >> 8;
		
			    max = MAX3(r,g,b);
			    min = MIN3(r,g,b);

			    range = max - min;
			    if (range) {
				rl = ((double) (max  - r)) / ((double) range);
				gl = ((double)  (max - g)) / ((double) range);
				bl = ((double) (max - b )) /  ((double) range);

				if ( max == r ) {
					if ( min == g)
						h = 5.0 + bl;
					else
						h = 1.0 - gl;
					}
				else {
					if ( max == g) {
					    if ( min == b)
						h = 1.0 + rl;
					    else
						h = 3.0 - bl;
					    }
					else {
					    if (min == r) 
						h = 3.0 + gl;
					    else
						h = 5.0 - rl;
					    }
					}
				h = h * 60.0;
			
				}

				y = (int) ((double)(h * (100.0 / 360.0)));
		
				hpoints[x].x = x;
				hpoints[x].y = 100 - y;
			} /*for*/


			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,hpoints,256,CoordModeOrigin);
			}
			break; /*CHUE*/
		case CSATURATION: {
			int r,g,b;
			int s;
			int max,min;

			for (x = 0 ; x < 256 ; x++ ) {
				r = (int) (((float) (rccells[x].red >> 8))* 
						(float) (100.0 / 255.0));
				g = (int) (((float) (rccells[x].green >> 8))* 
						(float) (100.0 / 255.0));
				b = (int) (((float) (rccells[x].blue >> 8))* 
						(float) (100.0 / 255.0));

				max = MAX3(r,g,b);
				min = MIN3(r,g,b);

				if (max != 0)
		    		    s=(int)(100.0 *(((float) (max - min)) / 
						((float) max)));
				else
				     s = 0;
		
				spoints[x].x = x;
				spoints[x].y = 100 - s;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,spoints,256,CoordModeOrigin);
			}
			break;
		case CVALUE: {
			int r,g,b;
			int value;
			for (x = 0 ; x < 256 ; x++ ) {
				r = (int) ((float) (rccells[x].red >> 8)* 
						(float) (100.0 / 255.0));
				g = (int) ((float) (rccells[x].green >> 8)* 
						(float) (100.0 / 255.0));
				b = (int) ((float) (rccells[x].blue >> 8)* 
						(float) (100.0 / 255.0));

				value = (int) MAX3(r,g,b);

				vpoints[x].x = x;
				vpoints[x].y = 100 - value;
				}
			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,vpoints,256,CoordModeOrigin);
			}
			break;
		} /* switch */

			
	
	rgbcmyhsv = rgbcmyhsv | component;
	return;
	
} /* DrawComponent() */

static void CBDrawComponent(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	DrawComponent((int) client_data);
}


static void UnDrawComponent(component)
int component;
{
int x;
int y;
XGCValues	gcval;
static	Arg arglist[]={{XtNset,(XtArgVal) True}};

        gcval.foreground = white;
        XChangeGC(XtDisplay(pal_comp), pal_comp_gc, GCForeground, &gcval);
	switch (component) {
		case CRED:
			if ((comp_pen == CRED) && (! palRedraw)){
				XtSetValues(b[PAL_PRED],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,rpoints,256,CoordModeOrigin);
			break;
		case CGREEN:
			if ((comp_pen == CGREEN) && (! palRedraw)){
				XtSetValues(b[PAL_PGREEN],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,gpoints,256,CoordModeOrigin);
			break;
		case CBLUE:
			if ((comp_pen == CBLUE) && (! palRedraw)){
				XtSetValues(b[PAL_PBLUE],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,bpoints,256,CoordModeOrigin);
			break;
		case CCYAN:
			if ((comp_pen == CCYAN) && (! palRedraw)){
				XtSetValues(b[PAL_PCYAN],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,cpoints,256,CoordModeOrigin);
			break;
		case CMAGENTA:
			if ((comp_pen == CMAGENTA) && (! palRedraw)){
				XtSetValues(b[PAL_PMAGENTA],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,mpoints,256,CoordModeOrigin);
			break;
		case CYELLOW:
			if ((comp_pen == CYELLOW) && (! palRedraw)){
				XtSetValues(b[PAL_PYELLOW],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,ypoints,256,CoordModeOrigin);
			break;
		case CHUE:
			if ((comp_pen == CHUE) && (! palRedraw)){
				XtSetValues(b[PAL_PHUE],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,hpoints,256,CoordModeOrigin);
			break;
		case CSATURATION:
			if ((comp_pen == CSATURATION) && (! palRedraw)){
				XtSetValues(b[PAL_PSATURATION],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,spoints,256,CoordModeOrigin);
			break;
		case CVALUE:
			if ((comp_pen == CVALUE) && (! palRedraw)){
				XtSetValues(b[PAL_PVALUE],arglist,1);
				return;
				}

			XDrawPoints(XtDisplay(pal_comp),XtWindow(pal_comp),
				pal_comp_gc,vpoints,256,CoordModeOrigin);
			break;
	} /* switch */

	rgbcmyhsv = rgbcmyhsv ^ (rgbcmyhsv & component) ;
	if (! palRedraw)
		RedrawComponent();

} /* UnDrawComponent() */

static void CBUnDrawComponent(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	UnDrawComponent((int) client_data);
}



static void CBReset(w,client_data,call_data)
/* Set colormap back to last loaded colors */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int x;
	SaveForUndo(rccells);
	for(x=0; x < 256 ; x++) {
		rccells[x].pixel = x;
		cpccell(rccells[x],origccells[x]);
		}
	RedrawComponent();
	StoreColors(rccells,TRUE,fcmap);
} /* CBReset() */


static void CBEvalExpr(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	/* Not working yet, but we'll blame it on the user for
	   not knowing how to use this feature */
	PrintMesg("Bad expression in cut/paste buffer\n");
}


static void TransposeCMap()
/* Flip the colormap:  (0<-> 255, 1<->254, etc.)*/
{
int	x;
XColor	tmp;

	SaveForUndo(rccells);
	for (x=0; x < 128 ;x++) {
		cpccell(tmp,rccells[255-x]);
		cpccell(rccells[255-x],rccells[x]);
		cpccell(rccells[x],tmp);
		}
	StoreColors(rccells,TRUE,fcmap);

	return;

} /* TransposeCMap() */


static void FiddlePalette(w,xdim,ydim,xpos,ypos)
Widget w;
int	xdim,ydim;
int	xpos,ypos;
{
double a,b,b1;
double unit_Theta = (double) 3.14159 / (double) (ydim*2);
double up,down;
register int prej,i,j,k;
int	NUMCOLORS = 256;

	xpos = (((xpos < 0)?0:xpos)>xdim)?xdim:xpos;
	ypos = (((ypos < 0)?0:ypos)>ydim)?ydim:ypos;

	a = (double) tan((double) (unit_Theta * (double) (ydim - ypos)));

	up = 1 + (short) (127.0 * a);
	down = 256 - (short) (128.0 * a);
	if (up > down)
		b = (((double)xpos / (double)xdim) * (double)(up - down))
			 + (double) down;
	else
		b = (((double)xpos / (double)xdim) * (double)(down - up))
			 + (double) up;
	
	prej = 1;

	for ( i = 1 ; i <= NUMCOLORS - 2 ; i++) {
	    j = (short) (a * (double) (i - (NUMCOLORS/2)) + b);
	    if ((j > 0) && (j <= NUMCOLORS-2)) {
		for ( k = prej; k <= j - 1 ; k++)
		   /*if((rccells[k].pixel!=white)&&(rccells[k].pixel!=black))*/
				cpccell(rccells[k],bccells[i]);
		/*if ((rccells[j].pixel!=white)&&(rccells[j].pixel!=black))*/
			cpccell(rccells[j],bccells[i]);
		}
	    else
		if (j >= NUMCOLORS-1) {
			for ( k = prej; k <= NUMCOLORS-2; k++)
				/*if ((rccells[k].pixel!=white)
				    &&(rccells[k].pixel!=black))*/
					cpccell(rccells[k],bccells[i]);
			break;
			}
		else
			continue;

	    prej = j + 1;
 	    }

	for(;j < NUMCOLORS;j++) 
		/*ccells[j].pixel = bccells[255].pixel;*/
		cpccell(rccells[j],bccells[255]);

        StoreColors(rccells,TRUE,fcmap);
}

static void Cfiddle(w,client_data,call_data)
/* Do linear expansion and compression on palette */
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Window root, child;
int	root_x,root_y;
int	win_x,win_y;
unsigned int	keys_buttons;

	if (XQueryPointer(XtDisplay(w),XtWindow(w),&root,&child,
	    &root_x,&root_y,&win_x,&win_y,&keys_buttons)) {
		FiddlePalette(w,pcw_attrib.width,pcw_attrib.height,
			win_x,win_y);
		}

} /* Cfiddle() */


static void CBPrepFiddle(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int	x;
	SaveForUndo(rccells);
	for (x=0; x< 256 ; x++) {
		cpccell(bccells[x],rccells[x]);
		bccells[x].pixel = rccells[x].pixel;
		}
}

static void CBEndFiddle(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Window root, child;
int     root_x,root_y;	/* X & Y coordinates with respect to root */
int     win_x,win_y;	/* X & Y coordinates with respect to window */
unsigned int    keys_buttons;
int	win;

	win = XtWindow(w);

        if (XQueryPointer(XtDisplay(w),win,&root,&child,
                &root_x,&root_y,&win_x,&win_y,&keys_buttons)) {
		XWarpPointer(XtDisplay(w),win,win,win_x,win_y,
		pcw_attrib.width,pcw_attrib.height,30,200);
		}
	XUngrabPointer(XtDisplay(w),CurrentTime);
        XtRemoveEventHandler(pal_ctrl_widget,Button1MotionMask,0,Cfiddle,NULL);
	XtRemoveEventHandler(pal_ctrl_widget,ButtonReleaseMask,0,
			CBEndFiddle,NULL);
} /* CBEndFiddle() */


static void CBFiddle(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int x;

	if(XGrabPointer(XtDisplay(w),XtWindow(pal_ctrl_widget),False,
		PointerMotionMask|ButtonReleaseMask,
		GrabModeAsync,GrabModeSync,
		XtWindow(pal_ctrl_widget),
		XCreateFontCursor(XtDisplay(w),XC_fleur),
		CurrentTime)) {
			PrintMesg("Can't grab pointer for fiddle\n");
			return;
			}

        XtAddEventHandler(pal_ctrl_widget,Button1MotionMask,0,Cfiddle,NULL );
	XtAddEventHandler(pal_ctrl_widget,ButtonReleaseMask,0,
			CBEndFiddle,NULL);

	CBPrepFiddle(pal_ctrl_widget,NULL,NULL);


	XGetWindowAttributes(XtDisplay(w),XtWindow(pal_ctrl_widget),
			&pcw_attrib);
} /* CBFiddle() */

static RotatePalette(w,xdim,ydim,xpos,ypos)
Widget w;
int xdim,ydim;
int xpos,ypos;
{
int offset;
int x;
int i;
int end;
int new;
int	tmp[256];
int	pno;


	if ((crlastx)&& (crlastx != xpos)) {
		for(x = 0;x < 256; x++)
			cpccell(bccells[x],rccells[x]);

		offset = xpos - crlastx;

		for(x=0; x < 256; x++) {
			new = x + offset;
			new = (new > 255) ? (new - 256) : 
					(new < 0) ? (new + 256): new;
			cpccell(rccells[new],bccells[x]);
			}

		StoreColors(rccells,TRUE,fcmap);
		}
	crlastx = xpos;
	return;

} /* RotatePalette() */


static void CRotate(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Window root, child;
int     root_x,root_y;	/* X & Y coordinates with respect to root */
int     win_x,win_y;	/* X & Y coordinates with respect to window */
unsigned int    keys_buttons;

        if (XQueryPointer(XtDisplay(w),XtWindow(w),&root,&child,
                &root_x,&root_y,&win_x,&win_y,&keys_buttons)) {

		if ((win_x <= 255) && (win_x > 0))
	                RotatePalette(w,255,28,win_x,win_y);
                }
}




void Terminate(s)
char *s;
{
        while (*s > ' ')
                s++;
        *s='\0';
	return;
}
static char *Get_Save_Pal()
{
        Terminate(pal_sfile);
        return(pal_sfile);
}


static void RedrawComponent()
{
	palRedraw = TRUE;
	if (rgbcmyhsv & CRED ){
		UnDrawComponent(CRED);
		DrawComponent(CRED);
		}
	if (rgbcmyhsv & CGREEN) {
		UnDrawComponent(CGREEN);
		DrawComponent(CGREEN);
		}
	if (rgbcmyhsv & CBLUE) {
		UnDrawComponent(CBLUE);
		DrawComponent(CBLUE);
		}
	if (rgbcmyhsv & CCYAN) {
		UnDrawComponent(CCYAN);
		DrawComponent(CCYAN);
		}
	if (rgbcmyhsv & CMAGENTA) {
		UnDrawComponent(CMAGENTA);
		DrawComponent(CMAGENTA);
		}
	if (rgbcmyhsv & CYELLOW) {
		UnDrawComponent(CYELLOW);
		DrawComponent(CYELLOW);
		}
	if (rgbcmyhsv & CHUE) {
		UnDrawComponent(CHUE);
		DrawComponent(CHUE);
		}
	if (rgbcmyhsv & CSATURATION) {
		UnDrawComponent(CSATURATION);
		DrawComponent(CSATURATION);
		}
	if (rgbcmyhsv & CVALUE) {
		UnDrawComponent(CVALUE);
		DrawComponent(CVALUE);
		}
	palRedraw = FALSE;
	return;
} /* RedrawComponent() */

static void CBSetPen(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Arg	arglist[10];
Cardinal i=0;

	XtSetArg(arglist[i],XtNset,False);	i++;
	/*****reset old toggle*/
	switch(comp_pen) {
		case CRED:
			XtSetValues(b[PAL_RED],arglist,i);
			break;
		case CGREEN:
			XtSetValues(b[PAL_GREEN],arglist,i);
			break;
		case CBLUE:
			XtSetValues(b[PAL_BLUE],arglist,i);
			break;
		case CCYAN:
			XtSetValues(b[PAL_CYAN],arglist,i);
			break;
		case CMAGENTA:
			XtSetValues(b[PAL_MAGENTA],arglist,i);
			break;
		case CYELLOW:
			XtSetValues(b[PAL_YELLOW],arglist,i);
			break;
		case CHUE:
			XtSetValues(b[PAL_HUE],arglist,i);
			break;
		case CSATURATION:
			XtSetValues(b[PAL_SATURATION],arglist,i);
			break;
		case CVALUE:
			XtSetValues(b[PAL_VALUE],arglist,i);
			break;
		default:
			break;
		} /* switch */
	
	comp_pen = (unsigned short) client_data;

	if (!(comp_pen & rgbcmyhsv)) { /* if not already drawn then draw it*/
		i=0;
	 	XtSetArg(arglist[i],XtNset,True);	i++;
		switch (comp_pen) {
			case CRED:
				DrawComponent(CRED);
				XtSetValues(b[PAL_PRED],arglist,i);
				break;
			case CGREEN:
				DrawComponent(CGREEN);
				XtSetValues(b[PAL_PGREEN],arglist,i);
				break;
			case CBLUE:
				DrawComponent(CBLUE);
				XtSetValues(b[PAL_PBLUE],arglist,i);
				break;
			case CCYAN:
				DrawComponent(CCYAN);
				XtSetValues(b[PAL_PCYAN],arglist,i);
				break;
			case CMAGENTA:
				DrawComponent(CMAGENTA);
				XtSetValues(b[PAL_PMAGENTA],arglist,i);
				break;
			case CYELLOW:
				DrawComponent(CYELLOW);
				XtSetValues(b[PAL_PYELLOW],arglist,i);
				break;
			case CHUE:
				DrawComponent(CHUE);
				XtSetValues(b[PAL_PHUE],arglist,i);
				break;
			case CSATURATION:
				DrawComponent(CSATURATION);
				XtSetValues(b[PAL_PSATURATION],arglist,i);
				break;
			case CVALUE:
				DrawComponent(CVALUE);
				XtSetValues(b[PAL_PVALUE],arglist,i);
				break;
			default:
				break;
			} /* switch */
		} /* if */
} /* CBSetPen() */



static void CBUnSetPen(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	comp_pen = 0;
}



static void SetPenColor(dpy,wingc,color)
/*
 * Set pen color for drawing.
 * Using an 8-bit palette, 0 <= color <= 255
 */
Display		*dpy;
GC		wingc;
unsigned short color;
{
XGCValues	gcval;
        gcval.foreground = color;
        XChangeGC(dpy,wingc, GCForeground, &gcval);
}

		
PlotComp(w,x,y,comp)
Widget w;
int x,y;
int comp;
{
Display	*dpy; 
Window	win;

#ifdef UNICOS
/* Unicos 5.0 C compiler (Cray PCC Version CRAY2 4.1.7 08/23/89)
 * is a little retarted. it gives an internal compiler error when it 
 * gets here.... and I'm tired of trying to work around it, so in 
 * this version, the following just won't work.....oh well.. */

/**/printf("Sorry, this doesn't work under UNICOS 5.0\n");
/**/printf("problem with Cray PCC Version CRAY2 4.1.7 08/23/89 \n");
}
#else
	dpy = XtDisplay(w);
	win = XtWindow(w);

	switch(comp) {
		case CRED:	
			rccells[x].red = (int) ((((float) y)/
					((float) PALCOMPHEIGHT)) * 65535.0);
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,rpoints[x].y);
			rpoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,rpoints[x].y);
			break;
		case CGREEN:	
			rccells[x].green= (int) ((((float)y)/
					((float) PALCOMPHEIGHT)) * 65535.0);
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,gpoints[x].y);
			gpoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,gpoints[x].y);
			break;
		case CBLUE:	
			rccells[x].blue= (int) ((((float) y)/
					((float) PALCOMPHEIGHT)) * 65535.0);
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,bpoints[x].y);
			bpoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,bpoints[x].y);
			break;
		case CCYAN:	
			rccells[x].red = (int) (65535.0 - ((((float) y)/
						((float) PALCOMPHEIGHT))
						 * 65535.0));
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,cpoints[x].y);
			cpoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,cpoints[x].y);
			break;
		case CMAGENTA:	
			rccells[x].green= (int) (65535.0 - ((((float) y)/
						((float) PALCOMPHEIGHT))
						 * 65535.0));
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,mpoints[x].y);
			mpoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,mpoints[x].y);
			break;
		case CYELLOW:	
			rccells[x].blue = (int) (65535.0 - ((((float) y)/
						((float) PALCOMPHEIGHT))
						 * 65535.0));
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,ypoints[x].y);
			ypoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,ypoints[x].y);
			break;
		case CHUE:{
			int max,min;
			double	hue;
			double	saturation;
			int	p1,p2,p3;
			double	frac;
			
			max = MAX3(rccells[x].red,rccells[x].green,
				rccells[x].blue);
			min = MIN3(rccells[x].red,rccells[x].green,
                                rccells[x].blue);

/*			if (max != 0)
				saturation = ((double)(max - min)) 
						/ (double) max;
			else
				saturation = 0;
*/
			saturation = (max)?(((double)(max - min))/(double)max)
					:0;

			hue = ((double) y) 
				* (6.0 / ((double) PALCOMPHEIGHT));

			frac = hue - ((double) ((int) hue));

			p1 = (int) (((double)max) * (1.0 - saturation));
			p2 = (int) (((double)max) * (1.0 - 
				(saturation * frac)));
			p3 = (int) (((double)max) * (1.0 - 
				(saturation * (1.0 - frac))));
			
			switch ( (int) hue) {
				case 0 : 
					rccells[x].red = max;
					rccells[x].green = p3;
					rccells[x].blue = p1;
					break;
				case 1 : 
					rccells[x].red = p2;
					rccells[x].green = max;
					rccells[x].blue = p1;
					break;
				case 2:
					rccells[x].red = p1;
					rccells[x].green = max;
					rccells[x].blue = p3;
					break;
				case 3:
					rccells[x].red = p1;
					rccells[x].green = p2;
					rccells[x].blue = max;
					break;
				case 4:
					rccells[x].red = p3;
					rccells[x].green = p1;
					rccells[x].blue = max;
					break;
				case 5:
					rccells[x].red = max;
					rccells[x].green = p1;
					rccells[x].blue = p2;
					break;
				} /* switch*/
		

			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,hpoints[x].y);
			hpoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,hpoints[x].y);
			
			}
			break;
		case CSATURATION:
			{
			int max;
			int r,g,b;
			double s;

			r = rccells[x].red;
			g = rccells[x].green;
			b = rccells[x].blue;

			max = MAX3(r,g,b);

			s = ((double)y) / ((double) PALCOMPHEIGHT);
			if (max == r) {
/*				rccells[x].green = max - (int) (((double)g)*s);
				rccells[x].blue= max - (int) (((double)b)*s);
*/
				rccells[x].green = ((double)(max - g)) * s
						+ SIGN(((double)g)/65535.0)*g;
				rccells[x].blue= ((double)(max - b)) * s
						+ SIGN(((double)b)/65535.0)*b;
				}
			if (max == g) {
/*				rccells[x].red= max - (int) (((double)r)*s);
				rccells[x].blue= max - (int) (((double)b)*s);
*/
				rccells[x].red= ((double)(max - r)) * s
						+ SIGN(((double)r)/65535.0)*r;
				rccells[x].blue= ((double)(max - b)) * s
						+ SIGN(((double)b)/65535.0)*b;
				}
			if (max == b) {
				rccells[x].red= ((double)(max - r)) * s
						+ SIGN(((double)r)/65535.0)*r;
				rccells[x].green = ((double)(max - g)) * s
						+ SIGN(((double)g)/65535.0)*g;
/*				rccells[x].red= max - (int) (((double)r)*s);
				rccells[x].green= max - (int) (((double)g)*s);
*/
				}
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,spoints[x].y);
			spoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,spoints[x].y);
			
			}
			break;
		case CVALUE: {
			int max;
			double ratio;
			double yval;

			yval = ((double) y) * 
					(65535.0 / ((double)PALCOMPHEIGHT));
			max = MAX3(rccells[x].red,rccells[x].green,
				rccells[x].blue);
			if (max != 0) {
				ratio =((double) rccells[x].red)/(double) max;
				rccells[x].red = (int) (ratio *  yval);
				ratio =((double) rccells[x].green)/(double)max;
				rccells[x].green = (int) (ratio *  yval);
				ratio =((double) rccells[x].blue)/(double) max;
				rccells[x].blue = (int) (ratio *  yval);
				}
			else {
				rccells[x].red = rccells[x].blue = 
					rccells[x].green = yval;
				}
			SetPenColor(dpy,pal_comp_gc,white);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,vpoints[x].y);
			vpoints[x].y = PALCOMPHEIGHT - y;
			SetPenColor(dpy,pal_comp_gc,comp_pen_dcolor);
			XDrawPoint(dpy,win,pal_comp_gc,
					x,vpoints[x].y);
			}
			break;

		default:
			break;
		}
		
	return;
} /* PlotComp() */
#endif



static void CBChangeComponent(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Window root, child;
int     root_x,root_y;
int     win_x,win_y;
unsigned int    keys_buttons;
int	x;
float	y;
float	yinc,ydiff;
Display	*dpy; 
Window	win;

#ifdef UNICOS
/* problem compiling routine PlotComp()... see it for more details */
/**/printf("Sorry, this doesn't work under UNICOS 5.0\n");
/**/printf("problem with Cray PCC Version CRAY2 4.1.7 08/23/89 \n");
}
#else
	if (!comp_pen)		/* No component selected */
		return;

	dpy = XtDisplay(w);
	win = XtWindow(w);
        if (!XQueryPointer(dpy,win,&root,&child,
                &root_x,&root_y,&win_x,&win_y,&keys_buttons)) 
		return;

	win_x = (win_x > 255)? 255 : (win_x <0)? 0 : win_x;
	win_y = (win_y > PALCOMPHEIGHT)? PALCOMPHEIGHT: 
					(win_y < 0)? 0 : win_y;

	win_y = PALCOMPHEIGHT - win_y; /* 4th quadrant -> 1st quadrant */

	if (comp_last_x == 0)
		PlotComp(pal_comp,win_x,win_y,comp_pen);
	else {
		ydiff = (comp_last_x > win_x)?(comp_last_y - win_y):
				(win_y - comp_last_y);

		if (comp_last_x > win_x) {
			yinc = (float) ydiff /((comp_last_x == win_x)?1.0:
					((float)(comp_last_x - win_x)));
			for (x = win_x,y=win_y; x < comp_last_x; x++,y=y+yinc)
				PlotComp(pal_comp,x,(int) y,comp_pen);
			}
		else{
			yinc = (float) ydiff / ((comp_last_x == win_x)?1.0:
					((float)( win_x - comp_last_x)));
			for (x = comp_last_x, y=comp_last_y; x < win_x; x++,y=y+yinc)
				PlotComp(pal_comp,x,(int) y,comp_pen);
			}
		}
	comp_last_x = win_x;
	comp_last_y = win_y;
	StoreColors(rccells,FALSE,fcmap);
} /* CBChangeComponent() */
#endif
			


static void CBPrepChangeComp(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	comp_last_x = 0;
	comp_last_y = 0;
	comp_pen_dcolor = ChooseColor(rccells,comp_pen);
	SaveForUndo(rccells);
	CBChangeComponent(w,client_data,call_data);
}

static void CBEndChangeComp(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	if (comp_last_x || comp_last_y)
		RedrawComponent();
	comp_last_x = 0;
	comp_last_y = 0;
}

static int ChooseColor(ccells,whichone)
/* pick the best entry in the palette to match color */
XColor	ccells[];	/* the palette */
int	whichone;	/* which color to find in palette */
{
int best;
int best_cmpval;
int cmpval;
int x;
int r,b,g;

	best = black;
	best_cmpval = -1 - (1 >> 18);
	switch (whichone) {
	case CRED:	/* find purest red */
		for(x=0; x < 256 ; x++) {
			g = ccells[x].green;
			b = ccells[x].blue;
			cmpval = ccells[x].red - g - b - abs(g-b);
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	case CGREEN:	/* find purest green */
		for(x=0; x < 256 ; x++) {
			r = ccells[x].red;
			b = ccells[x].blue;
			cmpval = ccells[x].green - r - b - abs(r-b);
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	case CBLUE:	/* find purest blue */
		for(x=0; x < 256 ; x++) {
			r = ccells[x].red;
			g = ccells[x].green;
			cmpval = ccells[x].blue - r - g - abs(r-g);
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	case CCYAN:	/* find purest cyan */
		for(x=0; x < 256 ; x++) {
			cmpval = ccells[x].green + ccells[x].blue
						- ccells[x].red;
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	case CMAGENTA:	/* find purest magenta */
		for(x=0; x < 256 ; x++) {
			cmpval = ccells[x].red + ccells[x].blue
						- ccells[x].green;
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	case CYELLOW:	/* find purest yellow */
		for(x=0; x < 256 ; x++) {
			cmpval = ccells[x].red + ccells[x].green
						- ccells[x].blue;
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	case CHUE:	/* find purest orange */
		for(x=0; x < 256 ; x++) {
			r = ccells[x].red;
			b = ccells[x].blue;
			cmpval = r-b - abs(((r+b)>>1) - ccells[x].green);
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	case CSATURATION:	/* find purest purplish color?? */
		for(x=0; x < 256 ; x++) {
			r = ccells[x].red;
			g = ccells[x].green;
			cmpval = b-g - abs(((b+g)>>1) - ccells[x].red);
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	
	case CVALUE:	
	default:
		/* find purest black */
		for(x=0; x < 256 ; x++) {
			cmpval = b-r - abs(((b+r)>>1) - ccells[x].green);
			/*cmpval = 65535 - ((ccells[x].red + ccells[x].green
					+ccells[x].blue)/3);
			*/
			if (cmpval > best_cmpval) {
				best_cmpval = cmpval;
				best = x;
				}
			}
		break;
	} /* switch */

	return(best);
}

static void CBPalSave(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{

	WriteSEQPalette(Get_Save_Pal(),rccells);
}



static void CBUndo(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int	x;
XColor	real_undo[256];

	for(x=0;x < 256; x++) {
		rccells[x].pixel = x;
		cpccell(real_undo[x],uccells[x]);
		}

	SaveForUndo(rccells);

	for(x=0;x < 256; x++) {
		rccells[x].pixel = x;
		cpccell(rccells[x],real_undo[x]);
		}
	StoreColors(rccells,TRUE,fcmap);
}

static void SaveForUndo(rccells)
XColor	rccells[];
{
int	x;

	for(x=0;x < 256; x++) {
		uccells[x].pixel = x;
		cpccell(uccells[x],rccells[x]);
		}
}

static void CBSmooth(w,client_data,call_data)
Widget w;
caddr_t client_data;	/* contains a pointer to the component*/
caddr_t call_data;
{
int x;
int	comp_pen;	/* Drawing color; smooth this one */

	SaveForUndo(rccells);

	comp_pen = *( (int *) client_data);
	if (!comp_pen) {
		PrintMesg("Please select a component to manipulate first\n");
		return;
		}

	switch (comp_pen){
		case CRED:
		case CCYAN:
		    rccells[0].red = (rccells[255].red +rccells[1].red)/2;
		    for(x=1; x< 255; x++)
			rccells[x].red = 
				(rccells[x-1].red + rccells[x+1].red)/2;
		    rccells[255].red = (rccells[254].red +rccells[0].red)/2;
		    break;
		case CGREEN:
		case CMAGENTA:
		    rccells[0].green = 
				(rccells[255].green + rccells[1].green)/2;
		    for(x=1; x< 255; x++)
			rccells[x].green = 
				(rccells[x-1].green + rccells[x+1].green)/2;
		    rccells[255].green = 
				(rccells[254].green + rccells[0].green)/2;
		    break;
		case CBLUE:
		case CYELLOW:
		    rccells[0].blue = 
				(rccells[255].blue + rccells[1].blue)/2;
		    for(x=1; x< 255; x++)
			rccells[x].blue = 
				(rccells[x-1].blue + rccells[x+1].blue)/2;
		    rccells[255].blue = 
				(rccells[254].blue + rccells[0].blue)/2;
		    break;
		case CHUE:
		case CSATURATION:
		case CVALUE:
			/* ick, I'll do this some other time */
		    break;
		} /*switch */
		
	StoreColors(rccells,TRUE,fcmap);
} /* CBSmooth() */
@//E*O*F palette.c//
chmod u=rw,g=r,o=r palette.c
 
echo x - polar.c
sed 's/^@//' > "polar.c" <<'@//E*O*F polar.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Dave Thompson, National Center for Supercomputing Applications
 * davet@ncsa.uiuc.edu
 */
/* Author: Dave Thompson & Dave Whittington*/


#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>

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

#include "xstuff.h"
#include "i.h"

#define	XLOC	400
#define	YLOC	400
#define	PI	3.1415927

struct	POINT {
	short	int	x,y;
	};

extern	int	white;
extern	Widget	toplevelform;

static	XImage	*pimage;


void	CreatePolarImage();
void	CreateInterPolar();


void	DrawPolar(dataset,type,xdim,ydim)
int	*dataset;
int	type;
int	xdim,ydim;
{
Display	*dpy;
Visual	*vis;
char	*imagebuff;
int	x;
int	y;
static	Widget	polarImageWidget;
static	Widget	topPIWidget;
int	ydim_x_2;

/**/	if (dataset== NULL) {
		printf ("DrawPolar(): (Internal error) dataset == nil\n");
		return;
		}

	dpy = XtDisplay(toplevelform);
	vis = GetVisual(dpy);
	if (vis->class != PseudoColor) {
		PrintMesg("Can't use display. Not a Pseudo Color device\n");
		return;
		}

	ydim_x_2 = ydim << 1;
	if(! (imagebuff = (char *) XIMalloc((ydim_x_2)*(ydim_x_2)))) {
		PrintMesg("Couldn't allocate memory for polar image \n");
		return;
		}

	CreateInterPolar(dataset,xdim,ydim,imagebuff);

	/* Draw image */
	topPIWidget = MakeATopLevel("Image Polar Image",toplevelform,
					XLOC,YLOC,(ydim_x_2)+5,(ydim_x_2)+25);

	polarImageWidget = Make_Window("Polar Image",topPIWidget,
					0,0,(ydim_x_2)+5,(ydim_x_2)+25);

	pimage = XCreateImage(dpy,vis,8,ZPixmap,0,imagebuff,
					(ydim_x_2),(ydim_x_2),8,(2*ydim));

	(void) MakeRasterImage("polar image",polarImageWidget,
					2,22,pimage,NULL,NULL);

	return; 
}/* DrawPolar() */

int DrawPolar2(i)
struct IMAGE *i;
/* return NULL if error */
{
int	ydim_x_2;

	ydim_x_2 = i->ydim << 1;
	if(! (i->polarimage = (char *) XIMalloc((ydim_x_2)*(ydim_x_2)))) {
		PrintMesg("Couldn't allocate memory for polar image \n");
		return(NULL);
		}
	
	/* calculate for non float */
	/*CreateInterPolar(i->ri,i->xdim,i->ydim,i->polarimage);*/
	CreatePolarImage(i->ri,i->xdim,i->ydim,i->polarimage);

	return(1);

}

static void CreatePolarImage(dataset,xdim,ydim,imagebuff)
char	dataset[];
int	xdim;
int	ydim;
char	imagebuff[];
{
long	x,y,rad;		/* for stepping trhough dataset */
long	ys,rs;			/* squared value holders	*/
double	angle,radius;		/* cartesian->polar values	*/
double	dx;			/* dataset x & y		*/
int	dy;

	PrintMesg("Generating polar image\n");

	rs = ydim*ydim;		/* actually radius^2 for speed	*/

	for (y = 0; y < 2*ydim; y++)
	{
		ys = (y - ydim) * (y - ydim);
		for (x = 0; x < 2 * ydim; x++)
		{
			rad = (x - ydim)*(x - ydim) + ys;
			if (rad <= rs)
			{
				radius = sqrt((double) rad);
				if (radius < 1.0) angle = 0.0; else
				angle = acos((double) (x - ydim) / radius);
				if (y > ydim) angle = 2.0*M_PI - angle;
				dx = (angle * xdim) / (2.0 * M_PI);
				dy = radius;
				imagebuff[(long)(x + 2*ydim*y)] =
					dataset[(long)(dx + xdim*dy)];
			}
			else
				imagebuff[x + 2*ydim*y] = 0;
		}
	}
}

static void CreateInterPolar(dataset,xdim,ydim,imagebuff)
char	dataset[];
int	xdim;
int	ydim;
char	imagebuff[];
{
long	x,y,rad;		/* for stepping trhough dataset */
long	ys,rs;			/* squared value holders	*/
double	angle,radius;		/* cartesian->polar values	*/
double	dx,dy;			/* dataset x & y		*/
long	lx,ly;
int	data1,data2;

	PrintMesg("Generating polar image\n");

	rs = ydim*ydim;		/* actually radius^2 for speed	*/

	for (y = 0; y < 2*ydim; y++)
	{
		ys = (y - ydim) * (y - ydim);
		for (x = 0; x < 2 * ydim; x++)
		{
			rad = (x - ydim)*(x - ydim) + ys;
			if (rad <= rs)
			{
				radius = sqrt((double) rad);
				if (radius < 1.0) angle = 0.0; else
				angle = acos((double) (x - ydim) / radius);
				if (y > ydim) angle = 2.0*M_PI - angle;
				dx = (angle * xdim) / (2.0 * M_PI);
				dy = radius;
				lx = (long) dx;
				ly = (long) dy;
				dx = dx - (double) lx;
				dy = dy - (double) ly;
				data1 = (dataset[lx+ly*xdim]*(1.0-dx) +
					dataset[lx+1+ly*xdim]*dx);
				ly++;
				data2 = (dataset[lx+ly*xdim]*(1.0-dx) +
					dataset[lx+1+ly*xdim]*dx);
				data1 = data1*(1.0-dy) + data2*dy;
				imagebuff[(long)(x + 2*ydim*y)] =
					data1;
			}
			else
				imagebuff[x + 2*ydim*y] = 0;
		}
	}
}
@//E*O*F polar.c//
chmod u=rw,g=r,o=r polar.c
 
echo x - read.c
sed 's/^@//' > "read.c" <<'@//E*O*F read.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include "i.h"

#include <hdf/df.h>
#include <hdf/dfi.h>
#include <hdf/dfrig.h>
#include <hdf/dfsd.h>

int ReadHDFPalette();

int ReadSEQImage(i)
/* Read in an SEQ image, return size of image read in */
/* return NULL if couldn't find it */
struct IMAGE *i;
{
int     fd;
unsigned char    *imagebuff;
int	length;
int	lengthToRead;
char	msgbuff[256];


	sprintf(msgbuff,"Reading in SEQ image %s\n",i->name);
	PrintMesg(msgbuff);

	if ((fd = open(i->name,O_RDONLY)) < 0 ) {
		sprintf(msgbuff,"Can't open %s\n",i->name);
		PrintMesg(msgbuff);
		return(NULL);
		}

	lengthToRead = i->xdim * i->ydim;
	if ( ! (imagebuff = (unsigned char *) XIMalloc(lengthToRead))) {
		PrintMesg("Couldn't XIMalloc memory for image\n");
		close(fd);
		return(NULL);   /* couldn't get memory */
		}

	if ((length = read(fd,imagebuff,lengthToRead)) != lengthToRead) {
		PrintMesg("Image file is too small for given dimensions\n");
		XIFree(imagebuff);
		return(NULL);
		}

	close(fd);

	i->ri = imagebuff;
	i->isFloat = FALSE;
	i->fdataset = NULL;
	i->format = "%3d";
	i->fwidth = 3;
	i->maxvalue = 255;
	i->minvalue = 0;
	i->hasPalette = FALSE;
	i->palette = (XColor *) NULL;
	
	return(length);

} /* ReadSEQImage() */

int ReadSEQAnimation(fname,imagebuff,xdim,ydim)
/* return NULL on failure */
char	*fname;
char	*imagebuff;
int	xdim,ydim;
{
int	fd;
int	length;
int	lengthToRead;
char	msgbuff[256];

        if ((fd = open(fname,O_RDONLY)) < 0 ) {
		sprintf(msgbuff,"Can't open %s\n",fname);
		PrintMesg(msgbuff);
		return(NULL);
		}

	lengthToRead = xdim * ydim;
	if ((length = read(fd,imagebuff,lengthToRead)) != lengthToRead) {
		sprintf(msgbuff,"%s is too small for given dimensions\n",fname);
		PrintMesg(msgbuff);
		return(NULL);
		}

	close(fd);
	return(length);
}


int ReadHDFImage(i)
struct IMAGE *i;
{
DF *hdf_df;
int     lengthToRead;
int	xdim,ydim;
char	msgbuff[256];

	sprintf(msgbuff,"Reading in HDF image %s\n",i->name);
	PrintMesg(msgbuff);

        lengthToRead = i->xdim * i->ydim;
        if ( ! (i->ri = (unsigned char *) XIMalloc(lengthToRead))) {
                PrintMesg("Couldn't XIMalloc memory for image\n");
                return(NULL);   /* couldn't get memory */
                }
	DFR8restart();
	if (DFR8getimage(i->name,i->ri,i->xdim,i->ydim,NULL) == -1) {
		PrintMesg("Couldn't read in HDF image\n");
		return(NULL);   /* failed */
		}


	i->palette = (XColor  *) NULL;
	i->hasPalette = FALSE;
	if(DFPnpals(i->name) > 0) {
        	if ( ! (i->palette=(XColor *) XICalloc(256,sizeof(XColor)))) {
			PrintMesg("Couldn't XIMalloc memory for palette\n");
			return(NULL);   /* couldn't get memory */
			}
		if (ReadHDFPalette(i->name,i->palette))
			i->hasPalette = TRUE;
		else
			XIFree(i->palette);
		}


	i->isFloat = FALSE;
	i->fdataset = NULL;
	i->format = "%3d";
	i->fwidth = 3;
	i->maxvalue = 255;
	i->minvalue = 0;

	sprintf(msgbuff,"Dimension of this HDF image: %dx%d\n",i->xdim,i->ydim);
	PrintMesg(msgbuff);

	return(i->xdim * i->ydim);	/* return length if ok */
} /* ReadHDFImage() */


MakeHDFImageIndex(file,index,size)
/* make an index table for accessing the images out of HDF*/
char *file;
int index[];
int size;
{
int x;
int32	xdim,ydim;
int	ispalette;

	DFR8restart();
	for(x = 0; x < size; x++)  {
		if ( -1 == DFR8getdims(file,&xdim,&ydim,&ispalette))
			return(0);
		index[x] = DFR8lastref();
		}
	
}


int ReadHDFAnimationImage(file,raster,frameNum)
char *file;
unsigned char *raster;
int	frameNum; /* must be an HDF ref number (see MakeHDFImageIndex()) */
{
/* too slow
int x;
int32	xdim,ydim;
int	ispalette;

	DFR8restart();
	for (x=0;x<frameNum;x++) 
		if ( -1 == DFR8getdims(file,&xdim,&ydim,&ispalette))
			return(0);

	DFR8getimage(file,raster,xdim,ydim,NULL);
	return(xdim*ydim);
*/
/* doesn't do uncompression 
DF *dfile;

	if (!(dfile = DFopen(file,DFACC_READ,1000)))
		return(0);
	if (-1 == DFgetelement(dfile,DFTAG_RI8,frameNum,raster)) {
	    if (-1 == DFgetelement(dfile,DFTAG_CI8,frameNum,raster)) {
		if (-1 == DFgetelement(dfile,DFTAG_II8,frameNum,raster)) {
			DFclose(dfile);
			return(0);
			}
		}
	   }
	DFclose(dfile);
	return(1);
*/
/* just right */
int32	xdim,ydim;
int	ispalette;

	if ( -1 == DFR8readref(file,frameNum))
		return(0);
	if ( -1 == DFR8getdims(file,&xdim,&ydim,&ispalette))
		return(0);
	if (-1 == DFR8getimage(file,raster,xdim,ydim,NULL))
		return(0);

	return(xdim*ydim);
} /* ReadHDFAnimationImage() */



int ReadHDFSDS(i,x,y,z)
struct IMAGE *i;
int	x,y,z;		/* contains dimension of image */
			/* x,y,z: one of these must be set to 1 */
			/* (2D plane along [xyz] must be set to 1) */
/* return 1 if ok */
/* return 0 on failure */
{
DF *hdf_df;
int rank;
int32 sizes[100];
int	maxrank;
char	msgbuff[256];
static 	int32	s1[] = {1,1,1};
int32	s2[3];
int32	dims[3];

	sprintf(msgbuff,"Reading in HDF data set %s\n",i->name);
	PrintMesg(msgbuff);

	DFSDrestart();
/*	DFSDgetdims(i->name,&rank,sizes,maxrank);*/
/*******if (DFSDgetdata(i->name,1,sizes,i->fdataset))*****fill me in **/
	s2[0]=x;
	s2[1]=y;
	s2[2]=z;
	if (x==1) {
		dims[0]=y;
		dims[1]=z;
		}
	else {
		if (y==1) {
			dims[0]=x;
			dims[1]=z;
			}
		else {
			dims[0]=x;
			dims[1]=y;
			}
		}

	if (!(i->fdataset=(float32 *)XIMalloc(dims[0]*dims[1]*sizeof(float32)))){
	    sprintf(msgbuff,"Could not allocate memory for HDF data set%s\n",
			i->name);
	    PrintMesg(msgbuff);
	    return(NULL);
	    }
	
	i->isFloat = TRUE;
	i->xdim = dims[0];
	i->ydim = dims[1];

	if (DFSDgetslice(i->name,s1,s2,i->fdataset,2,dims) == -1 ) {
		PrintMesg("Can't read in HDF data set\n");
		return(NULL);
		}
	
	if (DFSDgetmaxmin(&(i->maxvalue),&(i->minvalue)) == -1) {
		/*max and min not set, scan dataset and set by hand*/
		float max,min;
		register int x,last;
		register float *pf;

		pf = i->fdataset;
		min = max = *(i->fdataset);
		last = i->xdim*i->ydim;

		for (x = 0; x < last ; x++,pf++) {
			min = (*pf < min)? *pf : min;
			max = (*pf > max)? *pf : max;
			}
		i->maxvalue = max;
		i->minvalue = min;
		}
/*	printf("Max = %f, Min= %f",i->maxvalue,i->minvalue);*/
	
	/*if (DFSDgetdatastrs())*/
	/* set format */
	i->format = "% 6.3f";
	i->fwidth = 7;

	i->palette = (XColor *) NULL;
	i->hasPalette = FALSE;
	if(DFPnpals(i->name) > 0) {
        	if ( ! (i->palette=(XColor *) 
				XICalloc(256,sizeof(XColor)))) {
			PrintMesg("Couldn't XIMalloc memory for palette\n");
			return(NULL);   /* couldn't get memory */
			}
		if (ReadHDFPalette(i->name,i->palette))
			i->hasPalette = TRUE;
		else
			XIFree(i->palette);
		}


	/* Create raster image */
	{
	int length;
	int x;
	float range;
	unsigned char *pc;
	float *pf;
	float min;

	length = i->xdim * i->ydim;
	if (! (i->ri = (unsigned char *) XIMalloc(length))) {
	     PrintMesg("Can't allocate memory for image of HDF data slice\n");
	     return(NULL);
	     }
	range = i->maxvalue - i->minvalue;
	min = i->minvalue;
	for (x = 0, pc=i->ri, pf=i->fdataset; x < length; x++,pc++,pf++ ){
		*pc =(unsigned char) ((( *pf - min ) / range) *255.0);
		}
	}
	sprintf(msgbuff,"Dimension of this slice: %dx%d\n",i->xdim,i->ydim);
	PrintMesg(msgbuff);

	return(1); /* return non-NULL if ok */
}




IsItHDF(filename,dimx,dimy,isfloat)
char *filename;
int *dimx,*dimy;
char *isfloat;
/* return null if not HDF */
{
int r;
int32	sizes[3];
int ret;
int ispal;

	ret = DFR8getdims(filename,dimx,dimy,&ispal);
	*isfloat = FALSE;
	if (DFerror == DFE_NOTDFFILE) {
		/* Not HDF file */
		*dimx = *dimy = 0;
		return(0);
		}
	else {
		if (ret == -1) {
			/* Not a DFR8 image, is it a DFSD? */
			ret = DFSDgetdims(filename,&r,sizes,3);
			*dimx=sizes[0];
			*dimy=sizes[1];
			/* dimz=sizes[2]; */
			*isfloat = TRUE;
			}
		}
		
	if (ret == -1) /* if not a DFSD image */
		*dimx = *dimy = 0;

	return(!ret);

} /* IsItHDF() */


int ReadHDFHasPalette(name)
char *name;
/* returns number of pals hdf file has */
/* returns -1 on error */
{
	return(DFPnpals(name));
}

int ReadHDFPalette(name,ccells)
/* return 1 if ok */
/* return 0 on failure */
char	*name;
XColor	ccells[256];
{
DF *hdf_df;
int     lengthToRead;
int	xdim,ydim;
int	isPalette;
unsigned char pal[256*3];
int	x;
char	buff[512];


/*	if (DFR8getimage(name,"garbage",1,1,pal) == -1) {*/
	DFPrestart();
	if (DFPgetpal(name,pal) == -1) {
                sprintf(buff,"Couldn't read in HDF palette %s\n",name);
		PrintMesg(buff);
                return(NULL);   /* failed */
		}

	for (x=0; x < 256;x++) {
		ccells[x].pixel = x;
		ccells[x].red   = (unsigned short) pal[x*3] << 8;
		ccells[x].green = (unsigned short) pal[x*3+1] << 8;
		ccells[x].blue  = (unsigned short) pal[x*3+2] << 8;
		ccells[x].flags = DoRed|DoGreen|DoBlue;
                }

	sprintf(buff,"Just read in HDF palette %s\n",name);
	PrintMesg(buff);
	return(1);
} /* ReadHDFPalette() */






int ReadSEQPalette(name,ccells)
/* Return NULL if could not read SEQ colormap */
char *name;
XColor ccells[256];
{
char	rbuff[256];
char	gbuff[256];
char	bbuff[256];
int	fd;		/* file descriptor */
int	x;
char 	errbuff[260];

	if ((fd = open(name,O_RDONLY,NULL)) < 0) {
		(void) sprintf(errbuff,"Can't open colormap file %s\n",name);
		PrintMesg(errbuff);
		return(NULL);
		}

	if (read(fd,rbuff,256) != 256) {
		sprintf(errbuff,"%s is not a seq colormap\n",name);
		PrintMesg(errbuff);
		return(NULL);
		}
	if (read(fd,gbuff,256) != 256) {
		sprintf(errbuff,"%s is not a seq colormap\n",name);
		PrintMesg(errbuff);
		return(NULL);
		}
	if (read(fd,bbuff,256) != 256) {
		sprintf(errbuff,"%s is not a seq colormap\n",name);
		PrintMesg(errbuff);
		return(NULL);
		}

	(void) close(fd);
	

	for (x = 0; x < 256; x++) {
		ccells[x].pixel = x;
		ccells[x].red   = (unsigned short) rbuff[x] << 8;
		ccells[x].green = (unsigned short) gbuff[x] << 8;
		ccells[x].blue  = (unsigned short) bbuff[x] << 8;
		ccells[x].flags = DoRed|DoGreen|DoBlue;
		}

	return(1);

} /* ReadSEQColormap() */


int HowManyImagesInHDF(file)
char *file;
{
DF *df;
int num;
	if(!(df = DFopen(file,DFACC_READ,0)))
		return(0); /* Can't open file */
	if (!(num = DFnumber(df,DFTAG_RI8)))
		if(!(num = DFnumber(df,DFTAG_CI8)))
			num = DFnumber(df,DFTAG_II8);
/**/	if (num == -1){
/**/	    printf("HowManyImagesInHDF(): Error reading HDF file %s\n",file);
/**/	    printf("HDF error nummber %d\n",DFerrno());
/**/	    }

	DFclose(df);
	return(num);
}

int HowManySDSInHDF(file)
char *file;
{
DF *df;
int num;

	df = DFopen(file,DFACC_READ,0);
	num = DFnumber(file,DFTAG_SD);
	DFclose(df);
	return(num);
}
@//E*O*F read.c//
chmod u=rw,g=r,o=r read.c
 
echo x - shade.c
sed 's/^@//' > "shade.c" <<'@//E*O*F shade.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Dave Thompson, National Center for Supercomputing Applications
 * davet@ncsa.uiuc.edu
 */

/*	ImageTool "Shade" plot   --				*/
/*	makes an n "grey-level" black and white plot of data	*/
/* 	Author: Dave Whittington */

#include	<stdio.h>
#include	<X11/Xlib.h>
#include	<X11/Intrinsic.h>
#include	"patterns.h"

#ifndef	TRUE
#define TRUE 1
#endif
#define FALSE 0
#define	DIVISOR	(8 - SHIFTBITS)
#define DONERTN	((unsigned char) 255)

typedef	struct	{
	int	x;
	int	y;
	int	width;
	int	height;
	} Rect;

extern	unsigned long	black,white;
static	Display	*disp;
static	Drawable d;
static	GC	the_gc;
static	char	*ri;
static	Pixmap	patList[NUMPATTERNS];
static	Rect	plotRect;
static	short	xmax,ymax;
static	float	dimv,dimh;
static	short	lmar,tmar;

static	unsigned char data(x,y)
int	x,y;
{
	return(ri[y*xmax+x]);
}

void PlotRect(r,pat)
Rect	*r;
unsigned char	pat;
{
	XSetStipple(disp,the_gc,patList[pat]);
	XFillRectangle(disp,d,the_gc,r->x,r->y,r->width,r->height);
}

void InitShade(w)
Widget w;
{
	int	count;

	disp = XtDisplay(w);
	d = XtWindow(w);
	for (count = 0; count < NUMPATTERNS; count++)
	patList[count] = XCreateBitmapFromData(disp,d,pats[count],16,16);
}

unsigned char horizontal(y,xl,xr)
short	y,xl,xr;
{
short	count;
unsigned char	old,temp;
Boolean	biff;
Rect	r;

	old = (data(xl,y)>>DIVISOR);
	biff = TRUE;
	for(count = 1; count<(xr-xl); count++)
	{
		temp = (data((xl+count),y)>>DIVISOR);
		if (old != temp) biff = FALSE;
		old = temp;
	}
	if (biff) return(old);
	else
	{
		for(count = 0; count <(xr-xl); count++)
		{
			r.y = ((y-plotRect.y)*dimv + tmar);
			r.height = dimv;
			r.x = ((xl+count-plotRect.x)*dimh + lmar);
			r.width = dimh;
			PlotRect(&r,data((xl,count),y)>>DIVISOR);
		}
		return(DONERTN);
	}
}

unsigned char vertical(x,yt,yb)
short	x,yt,yb;
{
short	count;
unsigned char	old,temp;
Boolean	biff;
Rect	r;

	old = (data(x,yt)>>DIVISOR);
	biff = TRUE;
	for(count = 1; count<(yb-yt); count++)
	{
		temp = (data(x,(yt+count))>>DIVISOR);
		if (old != temp) biff = FALSE;
		old = temp;
	}
	if (biff) return(old);
	else
	{
		for(count = 0; count <(yb-yt); count++)
		{
			r.y = ((yt+count-plotRect.y)*dimv + tmar);
			r.height = dimv;
			r.x = ((x-plotRect.x)*dimh + lmar);
			r.width = dimh;
			PlotRect(&r,data(x,(yt+count))>>DIVISOR);
		}
		return(DONERTN);
	}
}

unsigned char shadePlot(left,top,right,bottom)
short	left,top,right,bottom;
{
short	lwidth,rwidth,theight,bheight;
unsigned char	ul,ur,ll,lr;
Rect	m;

	lwidth = (right-left)/2;
	rwidth = (right-left+1)/2;
	theight = (bottom-top)/2;
	bheight = (bottom-top+1)/2;

	if (lwidth == 1)
	{
		if (theight == 1)
		{
			ul = (data(left,top)>>DIVISOR);
			if (rwidth == 1)
			{
				ur = (data((left+1),top)>>DIVISOR);
				if (bheight == 1)
				{
					ll = (data(left,(top+1))>>DIVISOR);
					lr = (data((left+1),(top+1))>>DIVISOR);
				}
				else
				{
					ll = vertical(left,(top+1),bottom);
					lr = vertical((left+1),(top+1),bottom);
				}
			}
			else
			{
				ur = horizontal(top,(left+1),right);
				if (bheight == 1)
				{
					ll = data(left,(top+1))>>DIVISOR;
					lr = horizontal((top+1),(left+1),right);
				}
				else
				{
					ll = vertical(left,(top+1),bottom);
					lr = shadePlot((left+1),(top+1),right,bottom);
				}
			}
		}
		else
		{
			ul = vertical(left,top,(top+theight));
			ll = vertical(left,(top+theight),bottom);
			if (rwidth != 1)
			{
				ur = shadePlot((left+1),top,right,(top+theight));
				lr = shadePlot((left+1),(top+theight),right,bottom);
			}
			else
			{
				ur = vertical((left+1),top,(top+theight));
				lr = vertical((left+1),(top+theight),bottom);
			}
		}
	}
	else
	{
		if (theight == 1)
		{
			ul = horizontal(top,left,(left+lwidth));
			ur = horizontal(top,(left+lwidth),right);
			if (bheight != 1)
			{
				ll = shadePlot(left,(top+1),(left+lwidth),bottom);
				lr = shadePlot((left+lwidth),(top+1),right,bottom);
			}
			else
			{
				ll = horizontal((top+1),left,(left+lwidth));
				lr = horizontal((top+1),(left+lwidth),right);
			}
		}
		else
		{
			ul = shadePlot(left,top,(left+lwidth),(top+theight));
			ur = shadePlot((left+lwidth),top,right,(top+theight));
			ll = shadePlot(left,(top + theight),(left + lwidth),bottom);
			lr = shadePlot((left+lwidth),(top+theight),right,bottom);
		}
	}

	if ((ll == ul) && (ur == ul) && (lr == ul)) return(ul);
	else
	{
		if (ul != DONERTN)
		{
			m.y = ((top-plotRect.y)*dimv + tmar);
			m.x = ((left-plotRect.x)*dimh + lmar);
			m.width = lwidth*dimh;
			m.height = theight*dimv;
			PlotRect(&m,ul);
		}
		if (ur != DONERTN)
		{
			m.y = ((top-plotRect.y)*dimv + tmar);
			m.x = ((left+lwidth-plotRect.x)*dimh + lmar);
			m.width = (right-left-lwidth)*dimh;
			m.height = theight*dimv;
			PlotRect(&m,ur);
		}
		if (ll != DONERTN)
		{
			m.y = ((top+theight-plotRect.y)*dimv + tmar);
			m.x = ((left-plotRect.x)*dimh + lmar);
			m.width = lwidth*dimh;
			m.height = (bottom-top-theight)*dimv;
			PlotRect(&m,ll);
		}
		if (lr != DONERTN)
		{
			m.y = ((top+theight-plotRect.y)*dimv + tmar);
			m.x = ((left+lwidth-plotRect.x)*dimh + lmar);
			m.width = (right-left-lwidth)*dimh;
			m.height = (bottom-top-theight)*dimv;
			PlotRect(&m,lr);
		}
		return(DONERTN);
	}
}


void Updt_Shaded(w,data,xdim,ydim,lx,ty,rx,by)
Widget w;
char *data;
int xdim,ydim,lx,ty,rx,by;
{
	unsigned char	myPat;
	XGCValues	values;

	xmax = xdim;
	ymax = ydim;
	ri = data;

	disp = XtDisplay(w);
	d = XtWindow(w);
	InitShade(w);

	values.stipple = patList[5];
	values.foreground = black;
	values.background = white;
	the_gc = XCreateGC(disp,d,(GCStipple | GCForeground | GCBackground
		),&values);
	XSetFillStyle(disp,the_gc,FillOpaqueStippled);
	dimv = 1;
	dimh = 1;
	plotRect.x = lx;
	plotRect.y = ty;
	plotRect.width = rx - lx;
	plotRect.height = by - ty;
	if (plotRect.width > xdim - lx) plotRect.width = xdim - lx;
	if (plotRect.width < 0) plotRect.width = 1;
	if (plotRect.height > ydim - ty) plotRect.height = ydim - ty;
	if (plotRect.height < 0) plotRect.height = 1;

	lmar = lx;
	tmar = ty;

	myPat = shadePlot(plotRect.x,plotRect.y,plotRect.x + plotRect.width,
		plotRect.y + plotRect.height);
	if (myPat != DONERTN) PlotRect(&plotRect,myPat);
	XFreeGC(disp,the_gc);
}
 
@//E*O*F shade.c//
chmod u=rw,g=r,o=r shade.c
 
echo x - sliceSDS.c
sed 's/^@//' > "sliceSDS.c" <<'@//E*O*F sliceSDS.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>

#include <Xw/Xw.h>
#include <Xw/Toggle.h>

#include "buttons.h"
#include "xstuff.h"

#define	ARROW_TURN1	1
#define ARROW_FLIP	2
#define ARROW_TURN2	3

#define ROT_CLOCKW	1
#define ROT_FLIP	2
#define ROT_COUNTCW	3

#define	X_AXIS	1
#define Y_AXIS	2
#define Z_AXIS	3

extern  Widget  toplevelform;
extern	unsigned long black,white;

void CBDrawDiagram();
void CBRedrawArrows();
void CBRedrawArrows1();
void CBRedrawArrows2();
void CBRedrawArrows3();
void CBHighlight();
void CBUnhighlight();
void CBRotate();
void CBNewPlane();
void DrawPlane();
void CBOk();

static	int	diagramOrientation;
static	char	flipped;
static	int	axis =Z_AXIS;
static	Widget	diagram;
static	char	isSDSBoxDrawn = FALSE;

DrawSDSBox(name)
char *name;		/* name of file */
{
int	xpos,ypos;
Widget	composite;
Widget	box1,box2,box3;
Widget	toplevel;
static	char	title[256];
Display	*dpy;
int	screen;
Widget	b1,b2,b3;

	if (isSDSBoxDrawn)
		 return;

	sprintf(title,"X Image [SDS Selector]: %s",name);

/*	PlaceWindow(&xpos,&ypos);*/
	dpy = XtDisplay(toplevelform);
	screen = XDefaultScreen(dpy);

	toplevel = MakeATopLevelOverride(title,toplevelform,
				(DisplayWidth(dpy,screen)-305)/2,
				(DisplayHeight(dpy,screen)-180)/2,
				305,180);

	Set_Pointer(toplevel,XC_gumby);
	
/*	composite = Make_Board(title, toplevel, 0,0,305,180);*/
	composite = Make_Window("X Image: [SDS selector]",toplevel,
				0,0,305,180);

/*	(void) Make_Label("X Image: SDS selector",composite,2,2,295);*/

	diagramOrientation = 1;
	flipped = FALSE;
	diagram = MakeWorkSpace("Diagram",composite,2,25,150,150,
				CBDrawDiagram,NULL,
				NULL,NULL);

	box1 = Make_Board("controls",composite,155,25,145,150);

	box2 = Make_Board("plane",box1,2,2,140,50);
	(void) MakeAltToggle("Z Plane",box2,5,30,
			CBNewPlane,NULL,CBNewPlane,NULL);
	axis =Z_AXIS;
	(void) Make_Dialog("plane #",box2,"Plane #","0    ",4,
				75,2,60,45);

	box3 = Make_Board("Orientation",box1,2,55,140,70);
	(void) Make_Label("Orientation",box3,2,2,135);
	b1 = MakeWorkSpace("turn1",box3,2,25,40,40,
				CBRedrawArrows1,ARROW_TURN1,
				NULL,NULL);
	XtAddEventHandler(b1,EnterWindowMask,0,CBHighlight,NULL);
	XtAddEventHandler(b1,LeaveWindowMask,0,CBUnhighlight,NULL);
	XtAddEventHandler(b1,ButtonReleaseMask,0,CBRotate,ROT_CLOCKW);
	Set_Pointer(b1,XC_hand2);

	b2 = MakeWorkSpace("flip",box3,48,25,40,40,
				CBRedrawArrows2,ARROW_FLIP,
				NULL,NULL);
	XtAddEventHandler(b2,EnterWindowMask,0,CBHighlight,NULL);
	XtAddEventHandler(b2,LeaveWindowMask,0,CBUnhighlight,NULL);
	XtAddEventHandler(b2,ButtonReleaseMask,0,CBRotate,ROT_FLIP);
	Set_Pointer(b2,XC_hand2);

	b3 = MakeWorkSpace("turn2",box3,94,25,40,40,
				CBRedrawArrows3,ARROW_TURN2,
				NULL,NULL);
	XtAddEventHandler(b3,EnterWindowMask,0,CBHighlight,NULL);
	XtAddEventHandler(b3,LeaveWindowMask,0,CBUnhighlight,NULL);
	XtAddEventHandler(b3,ButtonReleaseMask,0,CBRotate,ROT_COUNTCW);
	Set_Pointer(b3,XC_hand2);

	(void) MakeButton("          OK          ",box1,2,130,
			CBOk,toplevel,0,0);

	isSDSBoxDrawn = TRUE;
}

void CBDrawSDSBox(w,bla,bla2)
Widget w;
int	bla;
int	bla2;
{
DrawSDSBox("/file/name/goes/here");
}


void CBDrawDiagram(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
int	todraw;

Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
int	xydim = 150;
	
	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = white;
	gc = XtGetGC(w,GCForeground, &gcvalues);
	
	XSetForeground(dpy,gc,white);
	XDrawLine(dpy,win,gc,20,xydim-20,20,50); /*vert */
	XDrawLine(dpy,win,gc,20,xydim-20,xydim-50,xydim-20);
	XDrawLine(dpy,win,gc,20,xydim-20,50,xydim-60); /*diag*/
	XDrawLine(dpy,win,gc,20,xydim-20,20,50);
	XDrawLine(dpy,win,gc,20,50,xydim-50,50);
	XDrawLine(dpy,win,gc,20,50,50,10);
	XDrawLine(dpy,win,gc,xydim-50,xydim-20,xydim-50,50); /*vert */
	XDrawLine(dpy,win,gc,20,50,xydim-50,50); /* horiz*/
	XDrawLine(dpy,win,gc,xydim-50,50,xydim-20,10); /*diag*/
	XDrawLine(dpy,win,gc,xydim-50,xydim-20,xydim-50,50); /*vert */
	XDrawLine(dpy,win,gc,20,xydim-20,xydim-50,xydim-20);
	XDrawLine(dpy,win,gc,xydim-50,xydim-20,xydim-20,xydim-60);

	XDrawString(dpy,win,gc,55,10,"z",1);
	XDrawString(dpy,win,gc,55,xydim-61,"z",1);
	XDrawString(dpy,win,gc,xydim-15,10,"z",1);
	XDrawString(dpy,win,gc,xydim-15,xydim-60,"z",1);
			    XDrawString(dpy,win,gc,xydim-45,xydim-20,"x",1);
			    XDrawString(dpy,win,gc,20,45,"y",1);
			    XDrawString(dpy,win,gc,20,xydim-10,"x",1);
			    XDrawString(dpy,win,gc,xydim-45,50,"y",1);
                            XDrawString(dpy,win,gc,10,50,"x",1);
                            XDrawString(dpy,win,gc,xydim-50,xydim-10,"y",1);
			    XDrawString(dpy,win,gc,xydim-45,50,"x",1);
			    XDrawString(dpy,win,gc,20,xydim-10,"y",1);

			    XDrawString(dpy,win,gc,xydim-45,xydim-20,"y",1);
			    XDrawString(dpy,win,gc,20,45,"x",1);
			    XDrawString(dpy,win,gc,10,50,"y",1);
			    XDrawString(dpy,win,gc,xydim-50,xydim-10,"x",1);
	XSetForeground(dpy,gc,black);

	todraw = diagramOrientation;

	if (flipped) {
		switch (diagramOrientation) {
			case 1: todraw = 2;
			    XDrawString(dpy,win,gc,20,xydim-10,"y",1);
			    XDrawString(dpy,win,gc,xydim-45,50,"x",1);
				break;
			case 2: todraw = 1;
			    XDrawString(dpy,win,gc,xydim-45,xydim-20,"y",1);
			    XDrawString(dpy,win,gc,20,45,"x",1);
				break;
			case 3: todraw = 4;
			    XDrawString(dpy,win,gc,xydim-45,50,"y",1);
			    XDrawString(dpy,win,gc,20,xydim-10,"x",1);
				break;
			case 4: todraw = 3;
			    XDrawString(dpy,win,gc,10,50,"y",1);
			    XDrawString(dpy,win,gc,xydim-50,xydim-10,"x",1);
				break;
			}
		}
	else {
		switch (diagramOrientation) {
			case 1:
			    XDrawString(dpy,win,gc,xydim-45,xydim-20,"x",1);
			    XDrawString(dpy,win,gc,20,45,"y",1);
				break;
			case 2:
			    XDrawString(dpy,win,gc,20,xydim-10,"x",1);
			    XDrawString(dpy,win,gc,xydim-45,50,"y",1);
				break;
			case 3:
			    XDrawString(dpy,win,gc,10,50,"x",1);
			    XDrawString(dpy,win,gc,xydim-50,xydim-10,"y",1);
				break;
			case 4:
			    XDrawString(dpy,win,gc,xydim-45,50,"x",1);
			    XDrawString(dpy,win,gc,20,xydim-10,"y",1);
				break;
		}
		}
	switch(todraw) {
		case 1: 
			XDrawLine(dpy,win,gc,20,xydim-20,20,50); /*vert */
			XDrawLine(dpy,win,gc,20,xydim-20,xydim-50,xydim-20);
			XDrawLine(dpy,win,gc,20,xydim-20,50,xydim-60); /*diag*/
			XDrawString(dpy,win,gc,55,xydim-61,"z",1);
			break;
		case 2:
			XDrawLine(dpy,win,gc,20,xydim-20,20,50);
			XDrawLine(dpy,win,gc,20,50,xydim-50,50);
			XDrawLine(dpy,win,gc,20,50,50,10); /* diag */
			XDrawString(dpy,win,gc,55,10,"z",1);
			break;
		case 3:
			XDrawLine(dpy,win,gc,xydim-50,xydim-20,xydim-50,50);
			XDrawLine(dpy,win,gc,20,50,xydim-50,50); /* horiz*/
			XDrawLine(dpy,win,gc,xydim-50,50,xydim-20,10); /*diag*/
			XDrawString(dpy,win,gc,xydim-15,10,"z",1);
			break;
		case 4:
			XDrawLine(dpy,win,gc,xydim-50,xydim-20,xydim-50,50); 
			XDrawLine(dpy,win,gc,20,xydim-20,xydim-50,xydim-20);
			XDrawLine(dpy,win,gc,xydim-50,xydim-20,
					xydim-20,xydim-60);
			XDrawString(dpy,win,gc,xydim-15,xydim-60,"z",1);
			break;
		}
		DrawPlane(w,axis,black,white);
}

void CBRedrawArrows(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
	
	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = black;
	gcvalues.background = white;
	gc = XtGetGC(w,(GCForeground|GCBackground), &gcvalues);
	
/**/	printf("CBRedrawArrows():I've been called: call_data = %d\n",
/**/				(int)call_data);
	switch ((int) call_data) {
		case ARROW_TURN1:
				XDrawArc(dpy,win,gc,0,0,30,20,
						135/64,225/64);
				break;
		case ARROW_FLIP:
				XDrawLine(dpy,win,gc,20,5,20,15);
				XDrawLine(dpy,win,gc,20,20,20,35);
				break;
		case ARROW_TURN2:
				XDrawArc(dpy,win,gc,0,0,30,20,
						135/64,235/64);
				break;
		}
		
}

void CBRedrawArrows1(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
	
	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = black;
	gcvalues.background = white;
	gc = XtGetGC(w,(GCForeground|GCBackground), &gcvalues);
	
	XDrawArc(dpy,win,gc,15,0,40,40,135*64,90*64);
/*	XDrawLine(dpy,win,gc,22,5,22,9);
	XDrawLine(dpy,win,gc,22,5,18,6);
*/
	XDrawLine(dpy,win,gc,21,6,21,10);
	XDrawLine(dpy,win,gc,21,6,17,7);
}


void CBRedrawArrows2(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
	
	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = black;
	gcvalues.background = white;
	gc = XtGetGC(w,(GCForeground|GCBackground), &gcvalues);
	
	XDrawLine(dpy,win,gc,20,5,20,18);
	XDrawLine(dpy,win,gc,20,5,17,8);
	XDrawLine(dpy,win,gc,20,5,23,8);
	XDrawLine(dpy,win,gc,20,22,20,35);
	XDrawLine(dpy,win,gc,17,33,20,35);
	XDrawLine(dpy,win,gc,23,33,20,35);
}


void CBRedrawArrows3(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
	
	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = black;
	gcvalues.background = white;
	gc = XtGetGC(w,(GCForeground|GCBackground), &gcvalues);
	
	XDrawArc(dpy,win,gc,-15,0,40,40, 315*64,90*64);
	XDrawLine(dpy,win,gc,18,5,18,9);
	XDrawLine(dpy,win,gc,18,5,22,6);
}



void CBHighlight(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
	
	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = black;
	gcvalues.line_width= 3;
	gc = XtGetGC(w,(GCForeground|GCLineWidth), &gcvalues);
	
	XDrawLine(dpy,win,gc,0,0,39,0);
	XDrawLine(dpy,win,gc,0,0,0,39);
	XDrawLine(dpy,win,gc,39,0,39,39);
	XDrawLine(dpy,win,gc,0,39,39,39);
}



void CBUnhighlight(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
	
	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = white;
	gcvalues.line_width= 3;
	gc = XtGetGC(w,(GCForeground|GCLineWidth), &gcvalues);
	
	XDrawLine(dpy,win,gc,0,0,39,0);
	XDrawLine(dpy,win,gc,0,0,0,39);
	XDrawLine(dpy,win,gc,39,0,39,39);
	XDrawLine(dpy,win,gc,0,39,39,39);
}


static void CBRotate(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	switch ((int) client_data) {
		case ROT_CLOCKW:
				if (! flipped) {
				    diagramOrientation++;
				    diagramOrientation = 
						(diagramOrientation >4)?
						1:diagramOrientation;
					}
				else {
				    diagramOrientation--;
				    diagramOrientation = 
						(diagramOrientation < 1)?
						4:diagramOrientation;
				     }
				break;
		case ROT_FLIP:
				flipped = ! flipped;
				break;
		case ROT_COUNTCW:
				if (! flipped) {
				    diagramOrientation--;
				    diagramOrientation = 
						(diagramOrientation < 1)?
						4:diagramOrientation;
					}
				else {
				    diagramOrientation++;
				    diagramOrientation = 
						(diagramOrientation >4)?
						1:diagramOrientation;
				     }
				break;
		}
	
	CBDrawDiagram(diagram,NULL,NULL);
}


void DrawPlane(w,plane,fcolor,bcolor)
Widget w;
int plane; 
unsigned long fcolor,bcolor;	/* foreground and background color */
{
Display	*dpy;
Window	win;
GC	gc;
XGCValues	gcvalues;
static	unsigned char	dashlist[]={(char)3,(char)4,(char)3,(char)1};
int	xydim = 150;

	dpy = XtDisplay(w);
	win = XtWindow(w);

	gcvalues.foreground = fcolor;
	gcvalues.background= bcolor;
	gcvalues.dash_offset = 0;
	gcvalues.dashes = 4;
	gc = XtGetGC(w,(GCForeground|GCBackground|GCDashOffset|GCDashList), 
			&gcvalues);

	XSetDashes(dpy,gc,0,dashlist,4);
	XSetForeground(dpy,gc,fcolor);
	XSetBackground(dpy,gc,bcolor);

	XSync(dpy,False);

	switch (plane) {
	    case X_AXIS: /* X Axis */
		XDrawLine(dpy,win,gc,60,xydim-20,60,50);
		XDrawLine(dpy,win,gc,60,xydim-20,90,xydim-60);
		XDrawLine(dpy,win,gc,60,50,90,10);
		XDrawLine(dpy,win,gc,90,10,90,xydim-60);
		break;
	    case Y_AXIS: /* Y Axis */
		XDrawLine(dpy,win,gc,20,xydim-60,xydim-50,xydim-60); /*front*/
		XDrawLine(dpy,win,gc,20,xydim-60,50,xydim-101);	/*left*/
		XDrawLine(dpy,win,gc,xydim-50,xydim-60,xydim-20,xydim-101); 
		XDrawLine(dpy,win,gc,50,xydim-101,xydim-20,xydim-101); /*back*/
		break;
	    case Z_AXIS: /* Z Axis */
		XDrawLine(dpy,win,gc,40,xydim-47,40,35);
		XDrawLine(dpy,win,gc,xydim-30,xydim-47,xydim-30,35);
		XDrawLine(dpy,win,gc,40,xydim-47,xydim-30,xydim-47);
		XDrawLine(dpy,win,gc,40,35,xydim-30,35);
	    }
}

void CBNewPlane(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
static Arg x_axis[] = {{XtNlabel,(int)"X Plane"},{XtNset,True}};
static Arg y_axis[] = {{XtNlabel,(int) "Y Plane"},{XtNset,True}};
static Arg z_axis[] = {{XtNlabel,(int) "Z Plane"},{XtNset,True}};

	switch (axis) {
		case X_AXIS:
			DrawPlane(diagram,X_AXIS,white,white);
			DrawPlane(diagram,Y_AXIS,black,white);
			axis = Y_AXIS;
			XtSetValues(w,y_axis,2);
			break;
		case Y_AXIS:
			DrawPlane(diagram,Y_AXIS,white,white);
			DrawPlane(diagram,Z_AXIS,black,white);
			axis = Z_AXIS;
			XtSetValues(w,z_axis,2);
			break;
		case Z_AXIS:
			DrawPlane(diagram,Z_AXIS,white,white);
			DrawPlane(diagram,X_AXIS,black,white);
			axis = X_AXIS;
			XtSetValues(w,x_axis,2);
			break;
		}
}


static void CBOk(w,client_data,call_data)
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	XtDestroyWidget((Widget) client_data);
	isSDSBoxDrawn = FALSE;
}
@//E*O*F sliceSDS.c//
chmod u=rw,g=r,o=r sliceSDS.c
 
echo x - write.c
sed 's/^@//' > "write.c" <<'@//E*O*F write.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <stdio.h>
#include <X11/Xlib.h>

int WriteSEQPalette(name,ccells)
char	*name;
XColor	ccells[256];
{
FILE	*fp;
int	x;
char	buff[256];
	if (!(fp = fopen(name,"w"))) {
		sprintf(buff,"Can't open for writing file %s\n",name);
		PrintMesg(buff);
		return(NULL);
		}

	for (x=0; x < 256; x++)
		putc(((char )(ccells[x].red >> 8)),fp);
	for (x=0; x < 256; x++)
		putc(((char )(ccells[x].green >> 8)),fp);
	for (x=0; x < 256; x++)
		putc(((char )(ccells[x].blue >> 8)),fp);

	fclose(fp);

	sprintf(buff,"Palette saved in SEQ format as %s\n",name);
	PrintMesg(buff);

	return(768);
}
@//E*O*F write.c//
chmod u=rw,g=r,o=r write.c
 
echo x - xstuff.c
sed 's/^@//' > "xstuff.c" <<'@//E*O*F xstuff.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/StringDefs.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include <X11/Command.h>
#include <X11/Shell.h>
#include <X11/Box.h>
#include <X11/Form.h>
#include <X11/Label.h>
#include <X11/AsciiText.h>
#include <X11/Dialog.h>
#include <X11/cursorfont.h>
#include <X11/Viewport.h>
#include <X11/List.h>

#include "list.h"

#include <Xw/Xw.h>
#include <Xw/PButton.h>
#include <Xw/BBoard.h>
#include <Xw/Toggle.h>
#include <Xw/SRaster.h>
#include <Xw/Valuator.h>
#include <Xw/TextEdit.h>
#include <Xw/WorkSpace.h>

#define	SCREEN_DEPTH	8
#define LABELFONT	"8x13bold"

void Set_Pointer();

extern Widget toplevelform;

Visual *GetVisual(dpy)
Display *dpy;
{
static char haveIComplainedYet = FALSE;
XVisualInfo vinfo;

	if (!XMatchVisualInfo(dpy,XDefaultScreen(dpy),8,PseudoColor,&vinfo)) {
		if (! haveIComplainedYet) {
/*		PrintMesg("Couldn't get a PseudoColor 8 bit visual\n");*/
			haveIComplainedYet = TRUE;
			}
		return(XDefaultVisual(dpy,XDefaultScreen(dpy)));
		}
	return(vinfo.visual);
}

void PlaceWindow(xpos,ypos)
int	*xpos,*ypos;
{
static	char	start = 20;
static	int	x = 50;
static	int	y = 50;
Display	*dpy;
int	screen;

	*xpos = x;
	*ypos = y;
	x+=100;
	y+=100;

	dpy = XtDisplay(toplevelform);
	screen = XDefaultScreen(dpy);
	if (x > DisplayWidth(dpy,screen)-300){
		x = y = 50 + start;
		start = (start > 100)? 20 :start + 20;
		}
	if (y > DisplayHeight(dpy,screen)-300){
		x = y = 50 + start;
		start = (start > 100)? 20 :start + 20;
		}

	return;
}

static void CBSetInputFocus(w,client_data,call_data)
/* called when on an Enter window event*/
Widget w;
caddr_t client_data;
caddr_t call_data;
{
	XSetInputFocus(XtDisplay(w),XtWindow(w),RevertToNone,CurrentTime);
}


Widget MakeButton(label,parent,xloc,yloc,cbp,client_data,xdim,ydim)
char	*label;			/* Button Label */
Widget	parent;			/* Parent widget of the button */
int	xloc,yloc;		/* Location in Parent widget */
XtCallbackProc cbp;		/* Procedure to call back when button press */
caddr_t	client_data;		/* data for call back */
int	xdim,ydim;		/* dimensions of button; 0 if default */
{
Arg             arglist[10];
Cardinal        i=0;
Widget		the_button;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNlabel,label);	i++;
	if (xdim) {
		XtSetArg(arglist[i],XtNwidth,xdim);	i++;
		}
	if (ydim) {
		XtSetArg(arglist[i],XtNheight,ydim);	i++;
		}
	
	the_button = XtCreateManagedWidget("XIButton", 
			commandWidgetClass, parent, arglist, i);
	if (cbp)
		 XtAddCallback(the_button,"callback",cbp,client_data);
	Set_Pointer(the_button,XC_hand2);

	return(the_button);

} /* Make_Button() */



Widget Make_Window(label,parent,xloc,yloc,width,height)
char	*label;
Widget	parent;
int	xloc,yloc;
int	width,height;
{
XFontStruct	*labelfont;
Widget		the_window;
Arg             arglist[10];
Cardinal        i=0;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	XtSetArg(arglist[i],XtNborderWidth,3);	i++;
	XtSetArg(arglist[i],XtNborder,
            WhitePixel(XtDisplay(parent),DefaultScreen(XtDisplay(parent))));i++;

	the_window = XtCreateManagedWidget("XIWindow",
				XwbulletinWidgetClass, parent, arglist, i);

	labelfont = XLoadQueryFont(XtDisplay(the_window),LABELFONT);
	i=0;
	XtSetArg(arglist[i],XtNx,1);		i++;
	XtSetArg(arglist[i],XtNy,1);		i++;
	XtSetArg(arglist[i],XtNwidth,width-2);	i++;
	XtSetArg(arglist[i],XtNlabel,label);	i++;
	if (labelfont)
		XtSetArg(arglist[i],XtNfont,labelfont); i++;
	(void) XtCreateManagedWidget("XILabel",labelWidgetClass,
				the_window, arglist, i);

	Set_Pointer(the_window,XC_gumby);

	return(the_window);

} /* Make_Window() */


Widget Make_ButtonBox(parent,xloc,yloc,width,height)
Widget	parent;		/* Parent Widget */
int	xloc,yloc;	/* location inside of parent widget */
int	width,height;	/* Size of the box */
{
Widget		the_window;
Arg             arglist[10];
Cardinal        i=0;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	
	the_window = XtCreateManagedWidget("XIWindow",
				/*boxWidgetClass, parent, arglist, i);*/
				XwbulletinWidgetClass, parent, arglist, i);
	return(the_window);

} /* Make_ButtonBox() */

Widget MakeBox(name,parent,xloc,yloc,width,height)
char	*name;
Widget	parent;		/* Parent Widget */
int	xloc,yloc;	/* location inside of parent widget */
int	width,height;	/* Size of the box */
{
Widget		the_window;
Arg             arglist[10];
Cardinal        i=0;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	
	the_window = XtCreateManagedWidget(name,
				boxWidgetClass, parent, arglist, i);
	return(the_window);

} /* MakeBox() */






Widget MakeWorkSpace(name,parent,xloc,yloc,width,height,exp_cbp,exp_param,
							key_cbp,key_param)
char	*name;
Widget	parent;		/* Parent Widget */
int	xloc,yloc;	/* location inside of parent widget */
int	width,height;	/* Size of the box */
XtCallbackProc exp_cbp;	/* expose call back procedure */
caddr_t exp_param;	/* expose call back procedure parameter */
XtCallbackProc key_cbp;	/* key press call back procedure */
caddr_t key_param;	/* key press call back procedure parameter */
{
Widget		w;
Arg             arglist[10];
Cardinal        i=0;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	
	w = XtCreateManagedWidget(name,
				XwworkSpaceWidgetClass, parent, arglist, i);
	if (exp_cbp)
		 XtAddCallback(w,"expose",exp_cbp,exp_param);
	if (key_cbp)
		 XtAddCallback(w,"keyDown",key_cbp,key_param);

	return(w);

} /* MakeWorkSpace() */




Widget Make_Text(parent,xloc,yloc,width,height,string)
Widget	parent;
int	xloc,yloc;
int	width,height;
char	*string;
{
Widget		the_window;
Arg             arglist[10];
Cardinal        i=0;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	XtSetArg(arglist[i],XtNstring,string);	i++;

	
/*	the_window = XtCreateManagedWidget("XIWindow",
				asciiStringWidgetClass, parent, arglist, i);
*/
	the_window = XtCreateManagedWidget("XIWindow",
				XwtexteditWidgetClass, parent, arglist, i);
	return(the_window);

} /* Make_Text() */

Widget Make_Toggle(label,parent,xloc,yloc,cbp,data,cbp2,data2,square,set)
char	*label;			/* Toggle Label */
Widget	parent;			/* Parent widget of the toggle*/
int	xloc,yloc;		/* Location in Parent widget */
XtCallbackProc cbp,cbp2;	/* Procedure to call back when toggled*/
caddr_t	data,data2;
int	square;			/* Should it be a square? */
unsigned char set;		/* should toggle be set? */
{
Arg             arglist[10];
Cardinal        i=0;
Widget		the_toggle;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNlabel,label);	i++;
	XtSetArg(arglist[i],XtNsquare,square);	i++;
	XtSetArg(arglist[i],XtNset,set);	i++;
	
		the_toggle = XtCreateManagedWidget("XIToggle", 
				XwtoggleWidgetClass, parent, arglist, i);
		if (cbp)
			 XtAddCallback(the_toggle,"select",cbp,data);
		if (cbp2)
			 XtAddCallback(the_toggle,"release",cbp2,data2);

	Set_Pointer(the_toggle,XC_hand2);

	return(the_toggle);

} /* Make_Toggle() */

Widget MakeAltToggle(label,parent,xloc,yloc,cbp,data,cbp2,data2)
char	*label;			/* Toggle Label */
Widget	parent;			/* Parent widget of the toggle*/
int	xloc,yloc;		/* Location in Parent widget */
XtCallbackProc cbp,cbp2;	/* Procedure to call back when toggled*/
caddr_t	data,data2;
{
Arg             arglist[10];
Cardinal        i=0;
Widget		the_toggle;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNlabel,label);	i++;
	XtSetArg(arglist[i],XtNsquare,False);	i++;
	XtSetArg(arglist[i],XtNset,True);	i++;
	the_toggle = XtCreateManagedWidget("toggle", 
			XwtoggleWidgetClass, parent, arglist, i);
	if (cbp)
		 XtAddCallback(the_toggle,"select",cbp,data);
	if (cbp2)
		 XtAddCallback(the_toggle,"release",cbp2,data2);

	Set_Pointer(the_toggle,XC_hand2);

	return(the_toggle);
}


Widget Make_Label(label,parent,xloc,yloc,width)
char    *label;
Widget  parent;
int     xloc,yloc;
int	width;
{
Widget          the_label;
Arg             arglist[10];
Cardinal        i=0;

        XtSetArg(arglist[i],XtNx,xloc);         i++;
        XtSetArg(arglist[i],XtNy,yloc);         i++;
        XtSetArg(arglist[i],XtNwidth,width-2);  i++;
        XtSetArg(arglist[i],XtNlabel,label);    i++;

        the_label = XtCreateManagedWidget("XILabel",labelWidgetClass,
                                parent, arglist, i);

	return(the_label);

} /* Make_Label() */


Widget MakeForm(widget_name,parent,xloc,yloc,width,height,moreOps,numOps)
char    *widget_name;
Widget  parent;
int     xloc,yloc;
int	width;
int	height;
Arg	moreOps[];
int	numOps;
{
Widget          w;
Arg             arglist[20];
Cardinal        i=0;
int		x;

	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	if (moreOps)
	    for (x=0; x < numOps; x++) 
		XtSetArg(arglist[i],moreOps[x].name,moreOps[x].value); i++;

	w = XtCreateManagedWidget(widget_name,formWidgetClass,
                                parent, arglist, i);

	return(w);

} /* Make_Form() */




Widget Make_Dialog(widget_name,parent,label,defstring,maxlength,
			x,y,width,height)
char	*widget_name;
Widget	parent;
char	*label;
char	*defstring;
int	maxlength;
int	x,y;
int	width,height;
{
Widget          w;
Arg             arglist[10];
Cardinal        i=0;

	XtSetArg(arglist[i],XtNx,x);		i++;
	XtSetArg(arglist[i],XtNy,y);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	XtSetArg(arglist[i],XtNlabel,label);	i++;
	XtSetArg(arglist[i],XtNvalue,defstring);	i++;
	XtSetArg(arglist[i],XtNmaximumLength,maxlength);i++;
	XtSetArg(arglist[i],XtNsensitive,True);	i++;

	w = XtCreateManagedWidget(widget_name,dialogWidgetClass,
				parent,arglist,i);

	XtAddEventHandler(w,EnterWindowMask,0,CBSetInputFocus,NULL);
	return(w);

}/* Make_Dialog() */

Widget Make_Board(widget_name,parent,x,y,width,height)
Widget parent;
int	x,y;
int	width,height;
{
Widget          w;
Arg             arglist[10];
Cardinal        i=0;

	XtSetArg(arglist[i],XtNx,x);		i++;
	XtSetArg(arglist[i],XtNy,y);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;
	w = XtCreateManagedWidget(widget_name,XwbulletinWidgetClass,
				parent,arglist,i);

	return(w);
}


Widget Make_Text_Inp(widget_name,parent,string,strmaxlen,x,y,width,height)
/* A Null in string deliminates the end of 
 * the prompt and the rest of string space */
char	*widget_name;
Widget	parent;
char	*string;
int	strmaxlen;
int x,y;
int width,height;
{
Widget	w;
Arg	arglist[10];
Cardinal i=0;

	XtSetArg(arglist[i],XtNx,x);			i++;
	XtSetArg(arglist[i],XtNy,y);			i++;
	XtSetArg(arglist[i],XtNheight,height);		i++;
	XtSetArg(arglist[i],XtNwidth,width);		i++;
	XtSetArg(arglist[i],XtNstring,string);		i++;
	XtSetArg(arglist[i],XtNlength,strmaxlen);	i++;
	XtSetArg(arglist[i],XtNeditType,XttextEdit);	i++;

	w = XtCreateManagedWidget(widget_name,asciiStringWidgetClass,
		parent,arglist,i);

	XtAddEventHandler(w,EnterWindowMask,0,CBSetInputFocus,NULL);

	return(w);

} /* Make_Text_Inp() */

void Get_Text_Inp(w,startpos,endpos,string,stringsize)
Widget w;
char *string;
{
int i;

	XwTextReadSubString(w,startpos,endpos,string,stringsize,&i);

	return;

} /* Get_Text_Inp() */


Widget Make_Pal_Window(parent,xloc,yloc,xdim,ydim)
Widget	parent;			/* parent widget */
int	xloc,yloc;		/* location to be placed in parent widget */
int	xdim,ydim;		/* size of widget */
{
static	char	*pbuff;			/* palette image in here */
static	XImage	*pal;			/* palette image struct in here */
Widget	palw;				/* The final product */
int	x,y;
Visual	*vis;		
Arg arglist[5];
Cardinal i;
int	z;
int	xmax;
int	repeat;

/*	xdim = (xdim > 255)?(xdim/255)*255:xdim;
	xmax = (xdim > 255)?255:xdim;
	repeat = xdim / 255;

	pbuff = (char *) XIMalloc(xdim*ydim);

	for(y = 0; y < ydim; y++) {
		for(x = 0; x < xmax; x++)
			for (z = 0 ; z < repeat ; z++)
				pbuff[y*xdim+x*z+z] = x;
		}
*/
	xdim = (xdim > 255)?255:xdim;
	pbuff = (char *) XIMalloc(xdim*ydim);
	for (y = 0; y < ydim ; y++) {
		for(x = 0; x < xdim ; x++)
			pbuff[y*xdim+x]=x;
		}
	
	/* Make palette structure */
	vis = GetVisual(XtDisplay(parent));
	pal = XCreateImage(XtDisplay(parent),vis,SCREEN_DEPTH,ZPixmap,0,
		pbuff,xdim,ydim,8,xdim);

	/* Create a HP Static Raster widget */
	i=0;
        XtSetArg(arglist[i],XtNsRimage,pal);	i++;
	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
        palw = XtCreateManagedWidget("XIWindow",
                        XwsrasterWidgetClass,parent,arglist,i);

	return(palw);

} /* Make_Pal_Window() */


XImage *MakePalette(myDpy,pal_width,isHoriz)
/* Make an XImage of a palette */
Display	*myDpy;
int	pal_width;
char	isHoriz; /* should palette progress 0 to 255 horizontally */
{
Visual *myVis;
register int x;
register int y;
register int z;
int planes;	/* number of planes the default screen has */
int screen;
register int dooda;	 /*number of bytes needed per pixel */
register unsigned char *p;
XImage *palXImage;
unsigned char	*palImage;

	myVis  = GetVisual(myDpy);
	screen = XDefaultScreen(myDpy);
	planes = XDisplayPlanes(myDpy,screen);

	dooda = (planes > 7) ? (planes / 8 + ((planes%8)?1:0)) :1;
	if (dooda >= 3)
		dooda = 4;

	if ( ! (palImage = (unsigned char *) XIMalloc(pal_width*256*dooda))) {
		printf("Couldn't allocate enough memory\n");
		return(0);
		}

	p = palImage;

	if (isHoriz) {
		for(y = 0; y < pal_width; y++)
			for(x = 0; x < 256; x++) {
				for (z = 1; z < dooda; z++) {
					*p = 0;
					p++;
					}
				*p = x;
				p++;
				}
		palXImage = XCreateImage(myDpy,myVis,planes,ZPixmap,0,
				palImage,256,pal_width,8*dooda,
				256*dooda);
		}
	else {
		for(y = 0; y < 256; y++) 
			for(x = 0; x < pal_width; x++){
				for (z = 1; z < dooda; z++) {
					*p = 0;
					p++;
					}
				*p = 255-y;
				p++;
				}
	palXImage = XCreateImage(myDpy,myVis,planes,ZPixmap,0,palImage,
				pal_width,256,8*dooda,pal_width*dooda);
		}


	return(palXImage); 

} /* MakePalette() */




Widget MakeImageWindow(widget_name,ximage,defpixel,parent,xloc,yloc,xdim,ydim)
char	*widget_name;
XImage	**ximage;
unsigned long defpixel;
Widget	parent;			/* parent widget */
int	xloc,yloc;		/* location to be placed in parent widget */
int	xdim,ydim;		/* size of widget */
{
char	*pbuff;	
Widget	w;		
int	x,y;
Visual	*vis;		
Arg arglist[5];
Cardinal i;

	pbuff = (char *) XIMalloc(xdim*ydim);
/*	for (y = 0; y < ydim ; y++) {
		for(x = 0; x < xdim ; x++)
			pbuff[y*xdim+x]=x;
		}
*/
	for(x=0; x < xdim*ydim; x++)
		pbuff[x]=defpixel;
	
	/* Make palette structure */
	vis = GetVisual(XtDisplay(parent));
	*ximage = XCreateImage(XtDisplay(parent),vis,SCREEN_DEPTH,ZPixmap,0,
		pbuff,xdim,ydim,8,xdim);

	/* Create a HP Static Raster widget */
	i=0;
        XtSetArg(arglist[i],XtNsRimage,*ximage);	i++;
	XtSetArg(arglist[i],XtNx,xloc);		i++;
	XtSetArg(arglist[i],XtNy,yloc);		i++;
        w= XtCreateManagedWidget(widget_name,
                        XwsrasterWidgetClass,parent,arglist,i);

	return(w);
}


void Set_Pointer(w,cursorfont)
/* Set pointer to cursorfont if widget has been mapped */
/* (see X11/cursorfont.h for cursorfonts)( */
Widget	w;
int	cursorfont;
{
Cursor  cursor;
Window  win = XtWindow(w);
Display *dpy = XtDisplay(w);

        if(win) {
            cursor = XCreateFontCursor(dpy,cursorfont);
            XDefineCursor(dpy,win,cursor);
            }

        return;

} /* Set_Pointer() */


Widget MakeVPort(shellName,parent,scrollType,x,y,width,height)
char		*shellName;
Widget		parent;
A_Scroll_t	scrollType;
int			x,y;
int			width,height;
{
	Widget		shellWind;
	Arg			argList[10];
	Cardinal	i=0;

	XtSetArg(argList[i],XtNx,x); i++;
	XtSetArg(argList[i],XtNy,y); i++;
	XtSetArg(argList[i],XtNwidth,width); i++;
	XtSetArg(argList[i],XtNheight,height); i++;

	switch (scrollType)
	{
		case NOSCROLL:
			break;
		case VERTONLY:
			XtSetArg(argList[i],XtNallowVert,True); i++;
			XtSetArg(argList[i],XtNforceBars,True); i++;
			break;
		case HORIZONLY:
			XtSetArg(argList[i],XtNallowHoriz,TRUE); i++;
			XtSetArg(argList[i],XtNforceBars,TRUE); i++;
			break;
		case VERTHORIZ:
			XtSetArg(argList[i],XtNallowVert,TRUE); i++;
			XtSetArg(argList[i],XtNallowHoriz,TRUE); i++;
			XtSetArg(argList[i],XtNforceBars,TRUE); i++;
			break;
	}

	shellWind = XtCreateManagedWidget(shellName,viewportWidgetClass,parent,
									  argList,i);

	return(shellWind);
}


Widget MakeList(shellName,parent,scrollType,vportWind,ncols,callBackProc,
			strings,x,y,width,height,nitems,rowspacing)
char		*shellName;
Widget		parent;
A_Scroll_t	scrollType;
Widget 		*vportWind;	/* returned */
char		*strings[];
int			ncols;
XtCallbackProc	callBackProc;
int			x,y;
int			width,height;
int		nitems;
int		rowspacing;
{
	Widget		listWind;
	Arg			argList[15];
	Cardinal	i=0;

	*vportWind = MakeVPort("XTDvport",parent,scrollType,
							 x,y,width,height);
	XtSetArg(argList[i],XtNx,x);	i++;
	XtSetArg(argList[i],XtNy,y);	i++;
/*	XtSetArg(argList[i],XtNwidth,width);	i++; 
	XtSetArg(argList[i],XtNheight,height);	i++;
*/

	XtSetArg(argList[i],XtNdefaultColumns,ncols);	i++;
	XtSetArg(argList[i],XtNforceColumns,TRUE);	i++;
/*	XtSetArg(argList[i],XtNverticalList,True);	i++; */
	XtSetArg(argList[i],XtNpasteBuffer,True);	i++;
	XtSetArg(argList[i],XtNlist,strings);	i++;
	if (nitems) {
		XtSetArg(argList[i],XtNnumberStrings,nitems);	i++;
		}
	if (rowspacing) {
		XtSetArg(argList[i],XtNrowSpacing,rowspacing);	i++;
		}

	listWind = XtCreateManagedWidget(shellName,
				listWidgetClass, *vportWind, argList, i);
						
	if (callBackProc)
		XtAddCallback(listWind,"callback",callBackProc,NULL);

	return(listWind);
} /* MakeList */

Widget MakeATopLevel(widget_name,parent,x,y,width,height)
char	*widget_name;
Widget	parent;
int	x,y;
int	width,height;

{
Arg             arglist[10];
Cardinal        i=0;
Widget		w;

	XtSetArg(arglist[i],XtNx,x);		i++;
	XtSetArg(arglist[i],XtNy,y);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;

/*	w = XtCreateManagedWidget(widget_name, transientShellWidgetClass, */
	w = XtCreateManagedWidget(widget_name, applicationShellWidgetClass,
				parent, arglist, i);

/*	XtAddEventHandler(w,EnterWindowMask,0,CBSetInputFocus,NULL);*/
/*	XtAddEventHandler(w,LeaveWindowMask,0,CBSetInputFocus,NULL);*/
	return(w);
} /* MakeATopLevel() */

Widget MakeATopLevelOverride(widget_name,parent,x,y,width,height)
char	*widget_name;
Widget	parent;
int	x,y;
int	width,height;

{
Arg             arglist[10];
Cardinal        i=0;
Widget		w;

	XtSetArg(arglist[i],XtNx,x);		i++;
	XtSetArg(arglist[i],XtNy,y);		i++;
	XtSetArg(arglist[i],XtNwidth,width);	i++;
	XtSetArg(arglist[i],XtNheight,height);	i++;

	w = XtCreateManagedWidget(widget_name, overrideShellWidgetClass,
				parent, arglist, i);

	XtAddEventHandler(w,EnterWindowMask,0,CBSetInputFocus,NULL);

	return(w);
} /* MakeATopLevelOverride() */


Widget MakeRasterImage(shellName,parent,x,y,image,callBackProc,cbp_param)
char		*shellName;
Widget		parent;
int		x,y;
XImage		*image;
XtCallbackProc	callBackProc;
caddr_t		cbp_param;
{
Widget	w;
Arg	argList[10];
Cardinal i=0;

	XtSetArg(argList[i],XtNx,x);	i++;
	XtSetArg(argList[i],XtNy,y);	i++;
	XtSetArg(argList[i],XtNsRimage,image);	i++;
	XtSetArg(argList[i],XtNinvertOnSelect,False);	i++;
	w = XtCreateManagedWidget(shellName,XwsrasterWidgetClass,
				parent,argList,i);
	if (callBackProc)
		XtAddCallback(w,"select",callBackProc,cbp_param);

	return(w);

} /* MakeRasterImage() */

Widget MakeValuator(shellName,parent,x,y,width,height,vert,min,max,origin,
			extent,
			cbpMoved,mdata,cbpReleased,rdata,cbpSelected,sdata)
char		*shellName;
Widget		parent;
int		x,y;
int		width,height;
char		vert;		/*is it vertical ? */
int		min,max,origin;
XtCallbackProc	cbpMoved;
caddr_t		mdata;
XtCallbackProc	cbpReleased;
caddr_t		rdata;
XtCallbackProc	cbpSelected;
caddr_t		sdata;
{
Widget	w;
Arg	argList[10];
Cardinal i=0;
	XtSetArg(argList[i],XtNx,x);	i++;
	XtSetArg(argList[i],XtNy,y);	i++;
	XtSetArg(argList[i],XtNwidth,width);	i++;
	XtSetArg(argList[i],XtNheight,height);	i++;
	XtSetArg(argList[i],XtNsliderMin,min);	i++;
	XtSetArg(argList[i],XtNsliderMax,max);	i++;
	XtSetArg(argList[i],XtNsliderOrigin,origin);	i++;
	XtSetArg(argList[i],XtNsliderExtent,extent);	i++;
	if (!vert)
		XtSetArg(argList[i],XtNslideOrientation,XwHORIZONTAL);	i++;

	w = XtCreateManagedWidget(shellName,XwvaluatorWidgetClass,
				parent,argList,i);
	if (cbpMoved)
		XtAddCallback(w,"sliderMoved",cbpMoved,mdata);
	if (cbpReleased)
		XtAddCallback(w,"sliderReleased",cbpReleased,rdata);
	if (cbpSelected)
		XtAddCallback(w,"areaSelected",cbpSelected,sdata);

	return(w);

} /* MakeValuator() */



DialogAddTrans(w,trans)
Widget w;
char *trans;
{
XtTranslations	transTable;
	
	transTable = XtParseTranslationTable(trans);
	XtOverrideTranslations(gr_DialogGetTextWind(w),transTable);
}
@//E*O*F xstuff.c//
chmod u=rw,g=r,o=r xstuff.c
 
echo x - xstuff2.c
sed 's/^@//' > "xstuff2.c" <<'@//E*O*F xstuff2.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/StringDefs.h>
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include <X11/Viewport.h>
#include <X11/List.h>

#include <Xw/Xw.h>
#include <Xw/ScrollBar.h>
#include <Xw/List.h>
#include <Xw/Valuator.h>
#include <Xw/SWindow.h>

#include "xstuff.h"
#include "xstuff2.h"

Widget NewMakeVPort(shellName,parent,scrollType,vscrlEv,hscrlEv,grain,
				client_data,
				x,y,width,height)
char		*shellName;
Widget		parent;
A_Scroll_t	scrollType;
XtCallbackProc	vscrlEv,hscrlEv;
caddr_t		client_data;
int		grain;
int		x,y;
int		width,height;
{
Widget		shellWind;
Arg		argList[15];
Cardinal	i=0;

	XtSetArg(argList[i],XtNx,x); i++;
	XtSetArg(argList[i],XtNy,y); i++;
	XtSetArg(argList[i],XtNwidth,width); i++;
	XtSetArg(argList[i],XtNheight,height); i++;
	XtSetArg(argList[i],XtNgranularity,grain); i++;
	XtSetArg(argList[i],XtNinitialDelay,1000); i++;
	XtSetArg(argList[i],XtNrepeatRate,500); i++;
	switch (scrollType)
	{
		case NOSCROLL:
			XtSetArg(argList[i],XtNforceVerticalSB,FALSE); i++;
			XtSetArg(argList[i],XtNforceHorizontalSB,FALSE); i++;
			break;
		case VERTONLY:
			XtSetArg(argList[i],XtNforceVerticalSB,TRUE); i++;
			XtSetArg(argList[i],XtNforceHorizontalSB,FALSE); i++;
			break;
		case HORIZONLY:
			XtSetArg(argList[i],XtNforceVerticalSB,FALSE); i++;
			XtSetArg(argList[i],XtNforceHorizontalSB,TRUE); i++;
			break;
		case VERTHORIZ:
			XtSetArg(argList[i],XtNforceVerticalSB,TRUE); i++;
			XtSetArg(argList[i],XtNforceHorizontalSB,TRUE); i++;
			break;
	}

	shellWind = XtCreateManagedWidget(shellName,
				XwswindowWidgetClass,parent,argList,i);
	if (vscrlEv)
		XtAddCallback(shellWind,"vScrollEvent",vscrlEv,client_data);
	if (hscrlEv)
		XtAddCallback(shellWind,"hScrollEvent",hscrlEv,client_data);
	return(shellWind);
}


Widget NewMakeListSimple(shellName,vportWind,ncols,callBackProc,
			client_data,strings,x,y,width,height)
char		*shellName;
Widget		*vportWind;
int			ncols;
XtCallbackProc	callBackProc;
caddr_t		client_data;
char		*strings[];
int			x,y;
int			width,height;
{
	Widget		listWind;
	Arg			argList[10];
	Cardinal	i=0;

	XtSetArg(argList[i],XtNx,x);	i++;
	XtSetArg(argList[i],XtNy,y);	i++;
	XtSetArg(argList[i],XtNlist,strings);	i++;
	XtSetArg(argList[i],XtNborderWidth,0); i++;
	XtSetArg(argList[i],XtNdefaultColumns,ncols);	i++;
	XtSetArg(argList[i],XtNforceColumns,True);	i++;
	listWind = XtCreateManagedWidget(shellName,
			listWidgetClass, *vportWind, argList, i);
						
	if (callBackProc)
		XtAddCallback(listWind,"callback",callBackProc,client_data);

	return(listWind);
}

Widget NewMakeList(shellName,parent,vportWind,scrollType,ncols,grain,
			vscrlEv,hscrlEv,callBackProc,client_data,
			strings,x,y,width,height)
char		*shellName;
Widget		parent;
Widget		*vportWind; /* returned */
A_Scroll_t	scrollType;
char		*strings[];
int		ncols,grain;
XtCallbackProc	callBackProc,vscrlEv,hscrlEv;
caddr_t		client_data;
int		x,y;
int		width,height;
{
Widget		listWind;

	*vportWind = NewMakeVPort("XTDvport",parent,scrollType,
				 vscrlEv,hscrlEv,grain,client_data,
				 x,y,width,height);

	listWind = NewMakeListSimple(shellName,vportWind,
				 ncols,callBackProc,
				 client_data,strings,1,1,width,height);

	return(listWind);
}


Widget NewMakeListStatic(shellName,parent,vportWind,ncols,callBackProc,
			client_data,strings,x,y,width,height)
char		*shellName;
Widget		parent;
Widget		*vportWind;
char		*strings[];
int		ncols;
XtCallbackProc	callBackProc;
caddr_t		client_data;
int		x,y;
int		width,height;
{
Widget		listWind;

	*vportWind = Make_Board(shellName,parent,x,y,width,height);

	listWind = NewMakeListSimple(shellName,vportWind,
				 ncols,callBackProc,
				 client_data,strings,1,1,width,height);

	return(listWind);
}
@//E*O*F xstuff2.c//
chmod u=rw,g=r,o=r xstuff2.c
 
echo x - xinit.c
sed 's/^@//' > "xinit.c" <<'@//E*O*F xinit.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xatom.h>
#include <X11/Box.h>
#include <Xw/BBoard.h>

#include "xstuff.h"



Widget toplevel;	/* The top dude of everything ...really everything..*/
Widget toplevelform;	/* The top composite widget, parent of all the shells*/

extern void ETDirReturn();
XtActionsRec XIactionTable[] = {{"ETDirReturn",ETDirReturn}};


Initialize(argc,argv)
int argc;
char *argv[];
{
Arg		arglist[10];
Cardinal	i=0;
char		buff[128];
char		buff2[256];
Display		*dpy;
int		screen;
Visual		*myVis;


	toplevel = XtInitialize(argv[0],"XImageTool",NULL,0,&argc,argv);
	toplevelform = XtCreateManagedWidget(argv[0],XwbulletinWidgetClass,
					toplevel,arglist,i);

	XtAddActions(XIactionTable,XtNumber(XIactionTable));

	dpy    = XtDisplay(toplevel);
	screen = DefaultScreen(dpy);

	if (! InitImage(dpy))
		exit(0);
	if (! InitPalette(dpy))
		exit(0);
	if (! InitPalEntry(dpy))
		exit(0);
	if (! InitGetAFile(dpy))
		exit(0);
	if (! InitData(dpy))
		exit(0);
	if (! InitAnimation(dpy))
		exit(0);

	{
	char *garbage;
	garbage = (char *) XIMalloc(1025);
	XIFree(garbage);
	}

	Init_Ctrl_Window(toplevelform);

	/* Print the Display Info*/

  if (8 == DisplayPlanes(dpy,screen)) /* perfectionism at it's wosrt*/
    sprintf(buff,"Display is an %d plane %%s with %d entries in Colormap\n",
			DisplayPlanes(dpy,screen),XDisplayCells(dpy,screen));
  else
    sprintf(buff,"Display is a %d plane %%s with %d entries in Colormap\n",
			DisplayPlanes(dpy,screen),XDisplayCells(dpy,screen));

	myVis = GetVisual(dpy);
	switch (myVis->class) {
		case StaticGray:
			sprintf(buff2,buff,"StaticGray");
			break;
		case GrayScale:
			sprintf(buff2,buff,"GrayScale");
			break;
		case StaticColor:
			sprintf(buff2,buff,"StaticColor");
			break;
		case PseudoColor:
			sprintf(buff2,buff,"PseudoColor");
			break;
		case TrueColor:
			sprintf(buff2,buff,"TrueColor");
			break;
		case DirectColor:
			sprintf(buff2,buff,"DirectColor");
			break;
		}
	PrintMesg(buff2);
	PrintMesg("Done initializing NCSA X Image.\n");

} /* Initialize() */

@//E*O*F xinit.c//
chmod u=rw,g=r,o=r xinit.c
 
echo x - date.c
sed 's/^@//' > "date.c" <<'@//E*O*F date.c//'
/*
 * This NCSA software product is public domain software.  Permission
 * is granted to do whatever you like with it. Should you feel compelled 
 * to make a contribution for the use of this software, please send 
 * comments as to what you like or don't like about the software, 
 * how you use it, how it helps your work, etc. to softdev@ncsa.uiuc.edu.
 *
 * Please send bug reports to bugs@ncsa.uiuc.edu
 *
 * Author: Dave Thompson, National Center for Supercomputing Applications
 *         davet@ncsa.uiuc.edu
 */

#ifndef VERSION
#define VERSION	"NCSA X Image Version 1.0.3"
#endif

#ifndef VERSIONDATE
#define VERSIONDATE "11/29/89"
#endif

static char vinfo[80];
static char vinfo2[80];

char *GetVersionDate()
{

vinfo2[0]='(';
vinfo2[1]='\0';
#ifdef SYSV
	strcat(vinfo2,"System V");
#endif
#ifdef UNICOS
	strcat(vinfo2," UNICOS");
#endif
	strcat(vinfo2,")");

	if (vinfo2[1]==')')
		sprintf(vinfo,"%s %s\n",VERSION,VERSIONDATE);
	else
		sprintf(vinfo,"%s %s %s\n",VERSION,vinfo2,VERSIONDATE);
	return(vinfo);
}

char *GetVersion()
{
	return(VERSION);
}
@//E*O*F date.c//
chmod u=rw,g=r,o=r date.c
 
echo x - animate.h
sed 's/^@//' > "animate.h" <<'@//E*O*F animate.h//'

#define A_STOP	0
#define	A_CFOR	1
#define	A_CREV	2
#define	DSTRINGSIZE	10		/* dialog string size */

struct	ANIMATION {
	Widget	topLevel;
	Widget	composite;
	Widget	pal_win;
	Widget	slidebar;		/* valuator widget */

	char	*name;
	int	xdim,ydim;
	char	isHDF;
	char	isFloat;
	char	*directory;
	char	**files;
	int	frameNum;	/* which frame are we on? */
	int	numFrames;	/* number of frames */
	int	numFiles;
	char	inMemory;	/* images will be stored in pixmaps */
	int	*frameIndex;	/* only used with HDF single file animations*/

	char	ctrl_showing;	/* is animate control window showing? */

	unsigned char *raster;
	unsigned char *expRaster;	/* expanded raster */
	unsigned char isExpanded;	/* is raster expanded */
	XImage	*image;
	Pixmap	*pixmaps;

	char	hasPalette;
	XColor	*palette;	/* XColor[256] (colors for window)*/
	Colormap cmap;
	char	lockcmap;

	char	status;	
	int	skip;		/* what is the skip factor */
	int	delay;
	char	repeat;		/* should repeat */

	Widget	bcrev;	/*button continuous reverse*/
	Widget	bsrev;	/*button single reverse*/
	Widget	bstop;	/*button stop */
	Widget	bsfor;	/*button single forward */
	Widget	bcfor;	/*button continous forward */
	Widget	dFrame;
	char	dFrameString[DSTRINGSIZE];
	Widget	dSkip;
	char	dSkipString[DSTRINGSIZE];
	Widget	dDelay;
	char	dDelayString[DSTRINGSIZE];

	Widget	awin;	/* animation window */
	GC	awinGC;

	Widget	topQbox;	/* top widget for question box */

	struct ANIMATION *next;
	struct ANIMATION *prev;
};

@//E*O*F animate.h//
chmod u=rw,g=r,o=r animate.h
 
echo x - buttons.h
sed 's/^@//' > "buttons.h" <<'@//E*O*F buttons.h//'
extern	Widget	b[];		/* Butttons (b[]) are defined in main.c */

#define	CTRL_IMAGE	0
#define	CTRL_PALETTE	1
#define	CTRL_ANIMATE	2
#define IMAGE_DONE	3
#define CTRL_CALC	4
#define	CTRL_QUIT	5
#define IMAGE_CART	6
#define IMAGE_POLAR	7
#define IMAGE_DATA	8
#define IMAGE_GRAPH	9
#define	IMAGE_CDONE	10
#define IMAGE_PDONE	11
#define PAL_LOAD	12
#define PAL_FIDDLE	13
#define	PAL_INVERT	14
#define	PAL_ROTATE	15
#define PAL_T_ROTATE	16
#define PAL_SAVE	17
#define	PAL_DONE	18
#define	FILE_HDF	19
#define FILE_RASTER	20
#define FILE_SUNRASTER	21
#define	FILE_DONE	22
#define	CTRL_NOTEBOOK	23
#define IMAGE_W_DONE	24
#define PAL_CYAN	25
#define PAL_MAGENTA	26
#define PAL_YELLOW	27
#define PAL_HUE		28
#define	PAL_VALUE	29
#define	PAL_SATURATION	30
#define PAL_RED		31
#define	PAL_BLUE	32
#define PAL_GREEN	33
#define PAL_PCYAN	34
#define PAL_PMAGENTA	35
#define PAL_PYELLOW	36
#define PAL_PHUE	37
#define	PAL_PVALUE	38
#define	PAL_PSATURATION	39
#define PAL_PRED	40
#define	PAL_PBLUE	41
#define PAL_PGREEN	42
#define	PAL_EVAL	43
#define	PAL_RESET	44
#define	PAL_SMOOTH	45
@//E*O*F buttons.h//
chmod u=rw,g=r,o=r buttons.h
 
echo x - getfile.h
sed 's/^@//' > "getfile.h" <<'@//E*O*F getfile.h//'
#define	FTYPE_PAL	1
#define	FTYPE_IMAGE	2

struct GetFile {
/******* Passed to GetAFile ************/
	char	type;		/* What type of file to get */
	void	(*yesfile)();	/* procedure to call when done */
	void	(*nofile)();	/* procededure to call if cancelled */
	char	*param;		/* parameter to pass back */

/******* Returned values ***************/
	char	*directory;	/* directory of file */
	char	*base;		/* unexpanded base name */
	char	**file;		/* list of files */
	int	numFiles;
	char	isHDF;		/* is it an HDF file */
	char	isFloat;
	int	xdim;
	int	ydim;
	};
@//E*O*F getfile.h//
chmod u=rw,g=r,o=r getfile.h
 
echo x - gr_com.h
sed 's/^@//' > "gr_com.h" <<'@//E*O*F gr_com.h//'
/*
 *	File:		gr_com.h
 *	Contents:	Includes all the necessary headers for the
 *				graphics module
 */

#include "gr_def.h"
#include "gr_inc.h"
#include "gr_var.h"
@//E*O*F gr_com.h//
chmod u=rw,g=r,o=r gr_com.h
 
echo x - gr_def.h
sed 's/^@//' > "gr_def.h" <<'@//E*O*F gr_def.h//'
/*
 *	File:		gr_def.h
 *	Contents:	Header file containing all the typedefs and defs used
 *				by the graphics module.
 */

#define STRNG40				40
#define STRNG80				80
#define STRNG160			160

#define MAX_CUBLEV_WINDS	1
#define MAX_DSPLEV_WINDS	1

#define MAX_TOPLEV_WIDTH	400
#define MAX_TOPLEV_HEIGHT	500
#define MAX_CUBLEV_WIDTH	400
#define MAX_CUBLEV_HEIGHT	500

#define DEF_BORDER_WIDTH	3

#define DEF_LABEL_FONT		"8x13bold"

typedef enum {
	CNTRLWIND, CUBEWIND, DSPLWIND
} A_Wind_t;

typedef enum {
	NOSCROLL, VERTONLY, HORIZONLY, VERTHORIZ
} A_Scroll_t;

typedef enum {
	SELECTABLE, NONSELECTABLE
} A_TextSelect_t;

typedef enum {
	FILESOURCE, STRINGSOURCE
} A_TextSource_t;

/*
typedef struct {
	Widget			id;
	char			*label;
	XtCallbackProc	callBackProc;
	int				x,y;
	int				width,height;
} A_Button_t;
*/
@//E*O*F gr_def.h//
chmod u=rw,g=r,o=r gr_def.h
 
echo x - gr_ext.h
sed 's/^@//' > "gr_ext.h" <<'@//E*O*F gr_ext.h//'
/*
 *	File:		gr_ext.h
 *	Contents:	Header file containing all the externs
 *				of the graphics module.
 */

/*
 * Local externs
 */

extern void		gr_BossDisplay();
extern void		gr_BossSetAxes();
extern void		gr_BossSetArb();
extern void		gr_CloseBossLevel();
extern void		gr_CloseCubeLevel();
extern void		gr_CloseDsplLevel();
extern void		gr_CloseTileLevel();
extern void		gr_CubeDisplayAuto();
extern void		gr_CubeDisplaySingle();
extern void		gr_CubeDisplaySelected();
extern void		gr_CubeFlipVert();
extern void		gr_CubeFlipHoriz();
extern void		gr_CubeRotLeft();
extern void		gr_CubeRotRight();
extern void		gr_CubeSetFrame();
extern void		gr_CubeSetInterp();
extern void		gr_CubeSetNonInterp();
extern void		gr_CubeSetXY();
extern void		gr_CubeSetXZ();
extern void		gr_CubeSetYZ();
extern void		gr_DsplListHScroll();
extern void		gr_DsplListVScroll();
extern void		gr_DsplSetVal();
extern void		gr_DsplSliderSelected();
extern void		gr_FileDirAccept();
extern void		gr_FileCheck();
extern void		gr_FileLoad();
extern void		gr_ImageSelect();
extern void		gr_PalletLoad();
extern void		gr_Terminate();
extern void		gr_TileSelect();
extern A_BossWind_t *gr_InitBossLevel();
extern A_BossWind_t *gr_MallocBoss();
extern A_CubeWind_t *gr_InitCubeLevel();
extern A_CubeWind_t *gr_MallocCube();
extern A_DsplWind_t *gr_InitDsplLevel();
extern A_DsplWind_t *gr_MallocDspl();
extern A_TileWind_t *gr_InitTileLevel();
extern A_TileWind_t *gr_MallocTile();
extern Widget	gr_DialogGetTextWind();
extern Widget	gr_MakeBox();
extern Widget	gr_MakeButton();
extern Widget	gr_MakeBulletin();
extern Widget	gr_MakeDialog();
extern Widget	gr_MakeImage();
extern Widget	gr_MakeImageStatic();
extern Widget	gr_MakeList();
extern Widget	gr_MakeListSimple();
extern Widget	gr_MakeListStatic();
extern Widget	gr_MakeRowColumn();
extern Widget	gr_MakeSlider();
extern Widget	gr_MakeText();
extern Widget	gr_MakeTitleBar();
extern Widget	gr_MakeToggle();
extern Widget	gr_MakeVPort();
extern Widget	gr_MakeWindow();
extern Widget	gr_MakeWorkSpace();
extern XImage	*gr_ImageCreate();
extern char		*gr_DialogGetValue();
extern char		*gr_ListgetStruct();
extern char		*gr_TextGetStr();

extern int		gr_CubegetCurIncr();
extern int		gr_CubegetCurPlane();
extern int		gr_CubegetCurScale();
extern int		gr_CubegetCurNumPlanes();
extern short	gr_CubegetCurTile();

/*
 * Inter-module externs
 */

extern char		**td_FileDirStrings();
extern char		*td_CurrentDate();
extern char		*td_getDirName();
extern char		*td_getLogFileName();
extern char		*td_getToolName();
extern char		*td_HdfgetStats();
extern char		*td_HdfgetPixData();
extern char		**td_HdfgetHScale();
extern char		**td_HdfgetVScale();
extern char		**td_HdfgetPlaneData();
extern int		td_HdfgetScale();
extern int		td_HdfgetDim();
extern int		td_HdfCheck();
extern int		td_HdfLoad();
extern double	td_getVersion();
@//E*O*F gr_ext.h//
chmod u=rw,g=r,o=r gr_ext.h
 
echo x - gr_inc.h
sed 's/^@//' > "gr_inc.h" <<'@//E*O*F gr_inc.h//'
/*
 *	File:		gr_inc.h
 *	Contents:	Header file containing all the includes and externs
 *				by the graphics module.
 */

#include <stdio.h>
#include <X11/Xatom.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Box.h>
#include <X11/Command.h>
#include <X11/Dialog.h>
#include <X11/Label.h>
#include <X11/List.h>
#include <X11/Scroll.h>
#include <X11/Shell.h>
#include <X11/Form.h>
#include <X11/AsciiText.h>
#include <X11/Viewport.h>
#include <X11/Cardinals.h>
#include <X11/cursorfont.h>

/*
 * Local externs
 */

extern void		gr_CloseCubeLevel();
extern void		gr_CloseDsplLevel();
extern void		gr_DisplaySetVal();
extern void		gr_DisplayX();
extern void		gr_DisplayY();
extern void		gr_DisplayZ();
extern void		gr_FileDirAccept();
extern void		gr_FileCheck();
extern void		gr_FileLoad();
extern void		gr_Terminate();
extern Widget	gr_InitTopLevel();
extern Widget	gr_InitCubeLevel();
extern Widget	gr_InitDsplLevel();
extern Widget	gr_MakeBox();
extern Widget	gr_MakeButton();
extern Widget	gr_MakeDialog();
extern Widget	gr_MakeList();
extern Widget	gr_MakeText();
extern Widget	gr_MakeVPort();
extern Widget	gr_MakeWindow();
extern char		*gr_TextGetStr();

/*
 * Inter-module externs
 */

extern char		**td_FileDirStrings();
extern char		*td_CurrentDate();
extern char		*td_getDirName();
extern char		*td_getLogFileName();
extern char		*td_getTmpFileName();
extern char		*td_getToolName();
extern char		*td_HdfgetData();
extern char		*td_HdfgetPixMap();
extern char		**td_HdfgetPlaneData();
extern int		td_HdfgetColumns();
extern int		td_HdfgetXDim();
extern int		td_HdfgetYDim();
extern int		td_HdfCheck();
extern int		td_HdfLoad();
extern double	td_getVersion();
@//E*O*F gr_inc.h//
chmod u=rw,g=r,o=r gr_inc.h
 
echo x - gr_var.h
sed 's/^@//' > "gr_var.h" <<'@//E*O*F gr_var.h//'
/*
 *	File:		gr_var.h
 *	Contents:	Header file containing all global variables used
 *				by the graphics module.
 */

Widget		gr_topLevel;
Widget		gr_topLevelForm;
Widget		gr_cubeLevelForm[MAX_CUBLEV_WINDS];
Widget		gr_dsplLevelForm[MAX_DSPLEV_WINDS];
Widget		gr_topMsgWind;
Widget		gr_topFileWind;
Widget		gr_topDirDialog;
Widget		gr_topButtons[2];
Widget		gr_cubMsgWind;
Widget		gr_cubButtons[4];
Widget		gr_cubDialogs[3];
Widget		gr_dspListWind;
Widget		gr_dspViewWind;
Widget		gr_dspViewShell;

short		gr_cubNumWinds;
short		gr_dspNumWinds;
@//E*O*F gr_var.h//
chmod u=rw,g=r,o=r gr_var.h
 
echo x - gr_xwi.h
sed 's/^@//' > "gr_xwi.h" <<'@//E*O*F gr_xwi.h//'
/*
 *	File:		gr_xwi.h
 *	Contents:	Header file containing all the includes and externs
 *				by the X-Windows Athena and HP widget sets.
 */

#include <X11/Xos.h>
#include <X11/AsciiText.h>
#include <X11/Box.h>
#include <X11/Command.h>
#include <X11/Dialog.h>
#include <X11/Label.h>
#include <X11/List.h>
#include <X11/Scroll.h>
#include <X11/Shell.h>
#include <X11/Viewport.h>

#include <Xw/Arrow.h>
#include <Xw/BBoard.h>
#include <Xw/ImageEdit.h>
#include <Xw/List.h>
#include <Xw/PButton.h>
#include <Xw/RCManager.h>
#include <Xw/ScrollBar.h>
#include <Xw/SRaster.h>
#include <Xw/SText.h>
#include <Xw/TextEdit.h>
#include <Xw/TitleBar.h>
#include <Xw/Toggle.h>
#include <Xw/SWindow.h>
#include <Xw/Valuator.h>
#include <Xw/WorkSpace.h>
@//E*O*F gr_xwi.h//
chmod u=rw,g=r,o=r gr_xwi.h
 
echo x - i.h
sed 's/^@//' > "i.h" <<'@//E*O*F i.h//'
#define DISPLAY_CART    1
#define DISPLAY_POLAR   2

struct	IWS {
	int	amIShowing;
	Widget	toplevel;
	Widget	composite;
	Widget	box1;
	Widget	box2;
	Widget	box3;
	Widget	box4;
	Widget	box5;
	Widget	box6;
	Widget	box7;
	Widget	label;
	Widget	title;
	Widget	pal_win;
	Colormap cmap;
	char	lockcmap;
	char	*pdata;
	char	*pdata2;
	char	*pdata3;
	char	*pdata4;
	char	*pdata5;
	char	*pdata6;
	int	data1;
	int	data2;
	int	data3;
	};

struct	IMAGE {
	char	*name;		/* file name of image */
	int	isHDF;		/* file format of image */
	int	xdim,ydim;	/* X and Y dimensions */

	char	label[2];

	char	isFloat;	/* is this IMAGE in float? */
	float	*fdataset;	/* floating point data set */
	float	maxvalue;	/* maximum value only used if float*/
	float	minvalue;	/* minimum value only used if float*/

	char	*format;	/* printf format for printing */
	int	fwidth;		/* format width (maximum # char of output) */

	unsigned char	*ri;	/* raster image data set stored here */
	unsigned char *dExpRI;	/* depth expantion ri (16,24,etc bit)*/
	char	isDExpRI;	/* is ri depth expanded */
	XImage	*cimage;	/* cartesian XImage structure here */

	char	*polarimage;	/* polar image */
	unsigned char *dExpPI;	/* depth expantion polar (16,24,etc bit)*/
	char	isDExpPI;	/* is polar Image depth expanded */
	XImage  *pimage;	/* polar XImage structure here */

	char	plotCartesian;	/* Plot cartesian image */
	char	plotSepWindow;	/* Plot graphs in seperate window */
	unsigned char	*contourLevels;

	struct	IWS	cws;	/* control window widgets */
	struct	IWS	iws;	/* image window widgets */
	struct	IWS	pws;	/* polar window widgets */
	struct	IWS	dws;	/* data window widgets */
	struct	IWS	gws;	/* Graph control box */
	struct	IWS	gcws;	/* graph contour widgets */
	struct	IWS	giws;	/* graph intensity widgets */
	struct	IWS	gsws;	/* graph shaded widgets */
	struct	IWS	ghws;	/* graph histogram widgets */
	char	ctrl_showing;
	char	data_showing;
	char	cart_showing;
	char	polar_showing;
	char	graph_showing;

	char	hasPalette;
	XColor	*palette;

	Widget	pal_win;	/* palette image */
	GC	iwgc;		/* image widget GC */
	Visual	*ivis;		/* image visual */
	XImage	*i;		/* X image struct */
	char	image_loaded;	/* is the image loaded? */
	char	image_showing;	/* is the image window showing? */

	struct IMAGE *prev;	/* next image structure */
	struct IMAGE *next;	/* next image structure */

	};
@//E*O*F i.h//
chmod u=rw,g=r,o=r i.h
 
echo x - list.h
sed 's/^@//' > "list.h" <<'@//E*O*F list.h//'
typedef enum {
	NOSCROLL, VERTONLY, HORIZONLY, VERTHORIZ
} A_Scroll_t;
@//E*O*F list.h//
chmod u=rw,g=r,o=r list.h
 
echo x - notebook.h
sed 's/^@//' > "notebook.h" <<'@//E*O*F notebook.h//'
struct NOTEBOOK {
	Widget topLevel;
};
@//E*O*F notebook.h//
chmod u=rw,g=r,o=r notebook.h
 
echo x - palentry.h
sed 's/^@//' > "palentry.h" <<'@//E*O*F palentry.h//'
#define	DSTRINGSIZE	20

struct PALEDIT {
	Widget	topLevel;
	Widget	composite;
	Widget	box1;
	Widget	box2;
	Widget	slide1;
	Widget	slide2;
	Widget	slide3;
	Widget	label1;
	Widget	label2;
	Widget	label3;
	Widget	val1;
	Widget	val2;
	Widget	val3;
	Widget	palImage;
	
	XColor	*ccells;
	Widget	dEntry;
	char	dEntryString[DSTRINGSIZE];
	int	entry;
	Widget	vce;	/*View color entry */
};
@//E*O*F palentry.h//
chmod u=rw,g=r,o=r palentry.h
 
echo x - paletteP.h
sed 's/^@//' > "paletteP.h" <<'@//E*O*F paletteP.h//'
#define	CRED		(1 << 9)
#define	CGREEN		(1 << 8)
#define	CBLUE		(1 << 7)
#define	CCYAN		(1 << 6)
#define	CMAGENTA	(1 << 5)
#define	CYELLOW		(1 << 4)
#define	CHUE		(1 << 3)
#define	CSATURATION	(1 << 2)
#define	CVALUE		(1 << 1)
#define	CLIGHTNESS	1
@//E*O*F paletteP.h//
chmod u=rw,g=r,o=r paletteP.h
 
echo x - patterns.h
sed 's/^@//' > "patterns.h" <<'@//E*O*F patterns.h//'
/*  XImageTool patterns for stipple creation  --  dsw14feb89  */
/*								*/
/*  Note:  in order to make use of binary shift operations for	*/
/*	   maximum possible speed, the number of patterns below */
/*	   should be some power of two.  Set SHIFTBITS to the	*/
/*	   the power of 2 that you are using.			*/
/* Warning:  If you choose not to implement a 2^n array of	*/
/*	   patterns, the file "Shade.c" will need to be mod	*/
/*	   ified to allow for integer division.  This can be	*/
/*	   considerably slower.					*/

#define	NUMPATTERNS	8
#define	SHIFTBITS	3

static	char	pats[][32] = {
	{
	  0,   0,   0,   0,   0,   0,   0,   0,
	  0,   0,   0,   0,   0,   0,   0,   0,
	  0,   0,   0,   0,   0,   0,   0,   0,
	  0,   0,   0,   0,   0,   0,   0,   0
	},
	{
	128, 128,   0,   0,   0,   0,   0,   0,
	  0,   0,   0,   0,   0,   0,   0,   0,
	128, 128,   0,   0,   0,   0,   0,   0,
	  0,   0,   0,   0,   0,   0,   0,   0
	},
	{
	128, 128,   0,   0,   8,   8,   0,   0,
	128, 128,   0,   0,   8,   8,   0,   0,
	128, 128,   0,   0,   8,   8,   0,   0,
	128, 128,   0,   0,   8,   8,   0,   0
	},
	{
	136, 136,   0,   0,  34,  34,   0,   0,
	136, 136,   0,   0,  34,  34,   0,   0,
	136, 136,   0,   0,  34,  34,   0,   0,
	136, 136,   0,   0,  34,  34,   0,   0
	},
	{
	136, 136,  34,  34, 136, 136,  34,  34,
	136, 136,  34,  34, 136, 136,  34,  34,
	136, 136,  34,  34, 136, 136,  34,  34,
	136, 136,  34,  34, 136, 136,  34,  34,
	},
	{
	170, 170,  85,  85, 170, 170,  85,  85,
	170, 170,  85,  85, 170, 170,  85,  85,
	170, 170,  85,  85, 170, 170,  85,  85,
	170, 170,  85,  85, 170, 170,  85,  85,
	},
	{
	119, 119, 221, 221, 119, 119, 221, 221,
	119, 119, 221, 221, 119, 119, 221, 221,
	119, 119, 221, 221, 119, 119, 221, 221,
	119, 119, 221, 221, 119, 119, 221, 221,
	},
	{
	119, 119, 255, 255, 221, 221, 255, 255,
	119, 119, 255, 255, 221, 221, 255, 255,
	119, 119, 255, 255, 221, 221, 255, 255,
	119, 119, 255, 255, 221, 221, 255, 255,
	} };

@//E*O*F patterns.h//
chmod u=rw,g=r,o=r patterns.h
 
echo x - xstuff.h
sed 's/^@//' > "xstuff.h" <<'@//E*O*F xstuff.h//'
extern Widget MakeButton();
extern Widget Make_Window();
extern Widget Make_ButtonBox();
extern Widget Make_Text();
extern Widget Make_Toggle();
extern Widget Make_Label();
extern Widget Make_Pal_Window();
extern Widget Make_Text_Inp();
extern Widget Make_Dialog();
extern Widget Make_Board();
extern Widget MakeForm();
extern Widget MakeImageWindow();
extern Widget MakeList();
extern Widget MakeATopLevel();
extern Widget MakeATopLevelOverride();
extern Widget MakeRasterImage();
extern Widget MakeWorkSpace();
extern Widget MakeAltToggle();
extern Widget MakeValuator();
extern Widget MakeBox();
extern Widget MakeVPort();

extern XImage *MakePalette();
extern Visual *GetVisual();

extern void Get_Text_Inp();
extern void Set_Pointer();
@//E*O*F xstuff.h//
chmod u=rw,g=r,o=r xstuff.h
 
echo x - xstuff2.h
sed 's/^@//' > "xstuff2.h" <<'@//E*O*F xstuff2.h//'
typedef enum {
        NOSCROLL, VERTONLY, HORIZONLY, VERTHORIZ
} A_Scroll_t;

Widget NewMakeVPort();
Widget NewMakeListSimple();
Widget NewMakeList();
Widget NewMakeListStatic();
@//E*O*F xstuff2.h//
chmod u=rw,g=r,o=r xstuff2.h
 
echo x - ximage.icon
sed 's/^@//' > "ximage.icon" <<'@//E*O*F ximage.icon//'
#define XIMAGE_WIDTH 64
#define XIMAGE_HEIGHT 64
#define XIMAGE_X_HOT -1
#define XIMAGE_Y_HOT -1
static char XIMAGE_ICON[] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0xfc, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0x3f, 0x00, 0x00,
   0x00, 0x00, 0x00, 0xe0, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78,
   0x00, 0xc0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x70, 0x07, 0x00,
   0x00, 0x00, 0x00, 0x0e, 0xf0, 0xff, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x03,
   0xf8, 0xff, 0x18, 0x00, 0x00, 0x00, 0x80, 0x0f, 0xfc, 0xff, 0x30, 0x00,
   0x00, 0x00, 0xc0, 0x0f, 0x0e, 0x70, 0x70, 0x00, 0x00, 0x00, 0xc0, 0x0f,
   0x03, 0x70, 0x60, 0x00, 0x00, 0x00, 0x60, 0x80, 0xf9, 0xff, 0xe0, 0x00,
   0x00, 0x00, 0x60, 0xc0, 0xfc, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x30, 0x40,
   0x02, 0x70, 0xf0, 0x01, 0x00, 0x00, 0x30, 0x40, 0x01, 0x70, 0xf0, 0x01,
   0x06, 0x06, 0x3f, 0xc0, 0xfc, 0xff, 0x70, 0x0b, 0x0e, 0xc6, 0x1f, 0xc0,
   0xfe, 0xff, 0x70, 0x1f, 0x0e, 0xe6, 0x18, 0x40, 0x01, 0x70, 0x70, 0x3f,
   0x1e, 0x66, 0x18, 0xc0, 0x40, 0x00, 0x38, 0x73, 0x16, 0x66, 0x18, 0xc0,
   0xe0, 0x40, 0x38, 0x63, 0x36, 0x66, 0x18, 0x40, 0xe0, 0x60, 0xf8, 0x63,
   0x26, 0x66, 0x18, 0x00, 0x40, 0x60, 0xf8, 0x7f, 0x66, 0x66, 0x18, 0xc0,
   0x01, 0x50, 0xf8, 0x7f, 0x46, 0x66, 0x18, 0xe0, 0xff, 0x6f, 0x18, 0x63,
   0xc6, 0x66, 0x18, 0xe0, 0xff, 0x67, 0x18, 0x63, 0x86, 0x66, 0x30, 0xc0,
   0x01, 0x50, 0x98, 0x61, 0x86, 0xe7, 0x30, 0xc0, 0x01, 0x48, 0x98, 0x61,
   0x06, 0xc7, 0x3f, 0xe0, 0xff, 0x67, 0x98, 0x61, 0x06, 0x06, 0x7f, 0xe0,
   0xff, 0x33, 0xd8, 0x60, 0x00, 0x00, 0x60, 0xc0, 0x01, 0x18, 0xd8, 0x00,
   0x00, 0x00, 0xc0, 0xcf, 0x01, 0x0c, 0x78, 0x00, 0x00, 0x00, 0xc0, 0xef,
   0xff, 0x07, 0x38, 0x00, 0x00, 0x00, 0xc0, 0xef, 0xff, 0x03, 0x38, 0x00,
   0x00, 0x00, 0x60, 0xe3, 0xff, 0x01, 0x18, 0x00, 0x00, 0x00, 0x30, 0xce,
   0x01, 0x00, 0x0e, 0x00, 0x08, 0x00, 0x60, 0x1c, 0x00, 0x00, 0x07, 0x00,
   0x14, 0x00, 0xf0, 0x78, 0x00, 0xc0, 0x03, 0x00, 0x22, 0x00, 0xf8, 0xed,
   0x03, 0xf8, 0x00, 0x00, 0x74, 0x00, 0xec, 0x87, 0xff, 0x3f, 0x00, 0x00,
   0xf8, 0x00, 0xde, 0x02, 0xfc, 0x07, 0x00, 0x00, 0xb0, 0x01, 0x7b, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x60, 0x83, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00,
   0xc0, 0xc6, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xed, 0x0d, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0xbb, 0x07, 0x1f, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x76, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0x01, 0x04,
   0x00, 0x00, 0x00, 0x00, 0x00, 0xde, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,
   0x00, 0xbb, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x80, 0x77, 0x03, 0x04,
   0x00, 0x00, 0x00, 0x00, 0xc0, 0xde, 0x06, 0x44, 0x10, 0x04, 0x7e, 0x7e,
   0xe0, 0x8d, 0x0d, 0xc4, 0x18, 0x0a, 0x01, 0x02, 0xb0, 0x07, 0x1b, 0x44,
   0x15, 0x11, 0x01, 0x02, 0x78, 0x03, 0x16, 0x44, 0x92, 0x3f, 0x79, 0x7e,
   0xf8, 0x01, 0x1c, 0x44, 0x90, 0x20, 0x41, 0x02, 0xf8, 0x00, 0x20, 0x44,
   0x90, 0x20, 0x41, 0x02, 0x78, 0x00, 0x40, 0x5f, 0x90, 0x20, 0x7e, 0x7e,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
@//E*O*F ximage.icon//
chmod u=rw,g=r,o=r ximage.icon
 
echo x - ximage.1
sed 's/^@//' > "ximage.1" <<'@//E*O*F ximage.1//'
@.TH XIMAGE 1 "1 November 1989"
@.SH NAME
NCSA ximage \- interactive data analysis tool
@.SH SYNOPSIS
@.B ximage
@.RB [ " \-options \|.\|.\|." ]
@.LP
@.SH DESCRIPTION
@.IX  ximage  ""  "\fLximage\fR \(em interactive data analysis tool"
@.IP  
ximage is 2D interactive data analysis tool that features displaying
color images of data sets in cartesian and polar form.  It can 
display the actual data values in a spread sheet manner and create
contour plots, shaded images, and histograms.  
@.LP
@.IP
ximage provides functions for dynamically manipulating palettes.  
Palette manipulation may be done by changing the component values in RGB, 
CMY or HSV color models.  In addition, the palette may be changed by 
expansion, compression, rotation or transposition. 
@.LP
@.IP
The user may animate multiple raster images from disk or the X server's memory.
@.LP
@.IP
As input data, ximage takes either 8-bit raster files or HDF files containing 
either 8-bit raster data or 32 bit floating point data.  HDF 
(Hierarchical Data Format) is a standard data format originally developed
at NCSA.  As Input palettes, it takes in HDF palettes, and 8 bit palettes
where the first 256 bytes specify the 256 entries of red, followed by
256 entries of green and then blue.  
@.LP
@.SH SEE ALSO
@.IP
xds(1)	- NCSA XDataSlice
@.LP
@.IP
Full documentation of NCSA XImage is provided along with the distribution.
@.LP
@.SH BUGS
Please send bug reports to bugs@ncsa.uiuc.edu.
@.IP
@.SH ORIGIN
National Center for Supercomputing Applications at the University of Illinois
in Urbana Champaign.
@//E*O*F ximage.1//
chmod u=rwx,g=rx,o=rx ximage.1
 
echo x - Make.noImake
sed 's/^@//' > "Make.noImake" <<'@//E*O*F Make.noImake//'
#########################################################################
#
#  Makefile for X Image Version 1.0.3 11/29/89
#  Before make(ing), set ULIBS, INCLUDES, DEFINES, DESTDIR
#


#################################
#  ULIBS: Where are your libXw.a, libXaw.a, libXt.a, libXmu.a, libX11.a
#  libaries?
#  libXw.a	- 2D HP widget set library.
#  Also libdf.a   - library containing HDF calls (hierarchical data format)
#  If you don't have HDF, you need to get it from anon ftp (128.174.20.50)
#

ULIBS= -L/sdg/netsrc/X.V11R3/lib/lib.sun3.3 -L/usr6/davet/xi/hdf

INCLUDES= -I/sdg/netsrc/X.V11R3/include -I..

#################################
# DEFINES=  possible values listed below 
# for compiling under SysV use: -DSYSV
# for compiling on Cray (UNICOS) use:  -DSYSV -DUNICOS
# for displaying client on servers that have a static color visual,
# 	use -DDEF_STAT_VISUAL   Sun's OpenWindows X/NeWS server and
#	SGI's X/NeWS server set their default Visual to a static color.

DEFINES=


####################################################################
# DESTDIR - final destination of executable
#

DESTDIR = /usr/local/bin


####################################################################
#

CFLAGS= -g $(INCLUDES) $(DEFINES)
#CFLAGS= -O $(INCLUDES) $(DEFINES)


######################################################################
########## You shouldn't need to edit anything below here ############
######################################################################

PROGRAM= ximage
SOURCES= \
			a.c \
			animate.c \
			control.c \
			contour.c \
			ctlcontour.c \
			data.c \
			getfile.c \
			glob.c \
			gr_xwi.c \
			gr_xwi1.c \
			graph.c \
			i.c \
			image.c \
			intensity.c \
			main.c \
			mem.c \
			notebook.c \
			palentry.c \
			palette.c \
			polar.c \
			read.c \
			shade.c \
			sliceSDS.c \
			write.c \
			xstuff.c \
			xstuff2.c \
			xinit.c 

OBJECTS= $(SOURCES:.c=.o)

###########################################
# CURDATE&VERSION used to log compilation date & version No. in module date.c
#
CURDATE = `date '+"%D"'`
#CURDATE = `date '+"%D@%T"'`
VERSION = '"NCSA X Image Version 1.0.3"'


SLIBS= -lXw -lXaw -lXt -lXmu -lX11 -lm -ldf


##########################################

$(PROGRAM):  $(OBJECTS) date.o
	rm -f $@
	$(CC) -o $@ $(CFLAGS) $(OBJECTS) date.o $(ULIBS) $(SLIBS)

backup: $(SOURCES) 
	rm -f backup
	shar README VERSIONLOG $(SOURCES) date.c *.h ximage.icon ximage.1 Make.noImake Imakefile > backup

install: $(PROGRAM)
	install -m 755 $(PROGRAM) $(DESTDIR)
	cp ximage.1 /usr/man/man1

clean:
	rm -f $(PROGRAM) $(OBJECTS) date.o


a.o:		a.c animate.h

animate.o:	animate.c animate.h xstuff.h getfile.h

control.o:	control.c xstuff.h buttons.h gr_def.h gr_var.h

ctlcontour.o:	ctlcontour.c i.h xstuff.h

data.o:		data.c i.h xstuff.h xstuff2.h

getfile.o:	getfile.c xstuff.h getfile.h

graph.o:	graph.c i.h xstuff.h

gr_xwi.o:	gr_xwi.c gr_xwi.h

gr_xwi1.o:	gr_xwi1.c gr_com.h

i.o:		i.c i.h

image.o: 	image.c i.h buttons.h xstuff.h getfile.h

main.o:		main.c xstuff.h ximage.icon

notebook.o:	notebook.c notebook.h xstuff.h

palentry.o:	palentry.c xstuff.h palentry.h

palette.o:	palette.c buttons.h xstuff.h paletteP.h getfile.h

polar.o:	polar.c i.h xstuff.h

read.o:		read.c i.h

shade.o:	shade.c patterns.h

sliceSDS.o:	sliceSDS.c buttons.h xstuff.h

xstuff.o:	xstuff.c list.h

xstuff2.o:	xstuff2.c xstuff.h xstuff2.h

xinit.o:	xstuff.h

date.o: 	$(OBJECTS)
		cc -c $(DEFINES) -DVERSIONDATE=$(CURDATE) -DVERSION=$(VERSION) date.c
@//E*O*F Make.noImake//
chmod u=rwx,g=rwx,o=rwx Make.noImake
 
echo x - Imakefile
sed 's/^@//' > "Imakefile" <<'@//E*O*F Imakefile//'
#################################
#  XWLIB - Where is your 2D HP widgetset library?

XWLIB =/sdg/lib/libXw.a

################################
# XWINCLUDES - Where is your 2D HP widgetset include files?

XWINCLUDES = /sdg/includes

##################################################################
#
#  HDFLIB - Where is your Hierarchical Data Format (HDF) libary?
#           Must be version 2.8 or later.  Most current version
#	    available on anon ftp server ftp.ncsa.uiuc.edu (128.174.20.50).

HDFLIB = ./hdf/libdf.a

##################################################################
# DEFINES=  possible values listed below 
# for compiling under SysV use: -DSYSV
# for compiling on Cray (UNICOS) use:  -DSYSV -DUNICOS
# for displaying client on servers that have a static color visual,
#       use -DDEF_STAT_VISUAL   Sun's OpenWindows X/NeWS server and
#       SGI's X/NeWS server set their default Visual to a static color.

     DEFINES = 

##################################################################
############### Don't make any changes below here ################
##################################################################

    INCLUDES = -I$(TOOLKITSRC) -I$(TOP) -I$(XWINCLUDES) -I..
        SRCS = a.c animate.c control.c contour.c ctlcontour.c \
               data.c getfile.c glob.c gr_xwi.c gr_xwi1.c \
               graph.c i.c image.c intensity.c main.c mem.c \
               notebook.c palentry.c palette.c polar.c read.c shade.c \
               sliceSDS.c write.c xstuff.c xstuff2.c xinit.c 

        OBJS = a.o animate.o control.o contour.o ctlcontour.o \
               data.o getfile.o glob.o gr_xwi.o gr_xwi1.o \
               graph.o i.o image.o intensity.o main.o mem.o \
               notebook.o palentry.o palette.o polar.o read.o shade.o \
               sliceSDS.o write.o xstuff.o xstuff2.o xinit.o 

     PROGRAM = ximage


$(PROGRAM): $(OBJS) date.o $(HDFLIB) $(XWLIB)
	$(CC) -o $@ $(OBJS) date.o $(XAWLIB) $(XWLIB) $(XMULIB) $(XTOOLLIB) \
		$(XLIB) $(HDFLIB) $(LDFLAGS) $(SYSLAST_LIBRARIES) -lm 

relink::
	$(RM) $(PROGRAM)
	$(MAKE) $(MFLAGS) $(PROGRAM)

clean::
	$(RM) $(PROGRAM)

InstallProgram($(PROGRAM), $(BINDIR))
InstallManPage($(PROGRAM), $(MANDIR))

###########################################
# CURDATE&VERSION used to log compilation date & version No. in module date.c
#
CURDATE = `date '+"%D@%T"'`
VERSION = '"NCSA X Image Version 1.0.3"'
##########################################

$(HDFLIB):
	cd hdf; make

a.o:		a.c animate.h

animate.o:	animate.c animate.h xstuff.h getfile.h

control.o:	control.c xstuff.h buttons.h gr_def.h gr_var.h

ctlcontour.o:	ctlcontour.c i.h xstuff.h

data.o:		data.c i.h xstuff.h xstuff2.h

getfile.o:	getfile.c xstuff.h getfile.h

graph.o:	graph.c i.h xstuff.h

gr_xwi.o:	gr_xwi.c gr_xwi.h

gr_xwi1.o:	gr_xwi1.c gr_com.h

i.o:		i.c i.h

image.o: 	image.c i.h buttons.h xstuff.h getfile.h

main.o:		main.c xstuff.h ximage.icon

notebook.o:	notebook.c notebook.h xstuff.h

palentry.o:	palentry.c xstuff.h palentry.h

palette.o:	palette.c buttons.h xstuff.h paletteP.h getfile.h

polar.o:	polar.c i.h xstuff.h

read.o:		read.c i.h

shade.o:	shade.c patterns.h

sliceSDS.o:	sliceSDS.c buttons.h xstuff.h

xstuff.o:	xstuff.c list.h

xstuff2.o:	xstuff2.c xstuff.h xstuff2.h

xinit.o:	xstuff.h

date.o: 	$(OBJS)
		$(CC) -c $(DEFINES) -DVERSIONDATE=$(CURDATE) \
				-DVERSION=$(VERSION) date.c
@//E*O*F Imakefile//
chmod u=rw,g=r,o=r Imakefile
 
exit 0
