/*--------------------------------------------------------------------
 *    The MB-system:	mbedit_callbacks.c	3/28/97
 *    $Id: mbedit_callbacks.c 2227 2015-02-05 21:12:31Z caress $
 *
 *    Copyright (c) 1993-2015 by
 *    David W. Caress (caress@mbari.org)
 *      Monterey Bay Aquarium Research Institute
 *      Moss Landing, CA 95039
 *    and Dale N. Chayes (dale@ldeo.columbia.edu)
 *      Lamont-Doherty Earth Observatory
 *      Palisades, NY 10964
 *
 *    See README file for copying and redistribution conditions.
 *--------------------------------------------------------------------*/
/*
 * MBEDIT is an interactive beam editor for multibeam bathymetry data.
 * It can work with any data format supported by the MBIO library.
 * This version uses the MOTIF toolkit and has been developed using
 * the Builder Xsessory package by ICS.  This file contains
 * the callbacks generated by BX.
 *
 * Author:	D. W. Caress
 * Date:	April 8, 1993
 * Date:	March 28, 1997  GUI recast
 *
 * $Log: mbedit_callbacks.c,v $
 * Revision 5.22  2009/03/13 07:05:58  caress
 * Release 5.1.2beta02
 *
 * Revision 5.21  2008/07/19 07:28:06  caress
 * Fixed scaling for swath widths less than 6 m.
 *
 * Revision 5.20  2006/09/11 18:55:52  caress
 * Changes during Western Flyer and Thomas Thompson cruises, August-September
 * 2006.
 *
 * Revision 5.19  2006/08/09 22:35:32  caress
 * A new edit mode called "grab" has been added to MBedit. In this
 * mode, the user drags a rectangle on the ping display. When the mouse
 * is released, all unflagged beams within that rectangle are flagged.
 *
 * Revision 5.18  2006/08/04 03:56:41  caress
 * Working towards 5.1.0 release.
 *
 * Revision 5.17  2006/06/16 19:30:58  caress
 * Check in after the Santa Monica Basin Mapping AUV Expedition.
 *
 * Revision 5.16  2006/02/08 16:57:36  caress
 * Added #ifdef to let user build mbedit to use orange instead of red.
 *
 * Revision 5.15  2006/01/24 19:12:42  caress
 * Version 5.0.8 beta.
 *
 * Revision 5.14  2005/03/25 04:12:23  caress
 * MBedit now allows alongtrack and acrosstrack views as well as the traditional waterfall display of profiles.
 *
 * Revision 5.13  2004/12/02 06:31:02  caress
 * First cut at adding stacked views from along and across track.
 *
 * Revision 5.12  2004/05/21 23:26:04  caress
 * Moved to new version of BX GUI builder
 *
 * Revision 5.11  2004/02/25 20:48:58  caress
 * Release 5.0.3
 *
 * Revision 5.10  2003/04/17 20:50:01  caress
 * Release 5.0.beta30
 *
 * Revision 5.9  2003/04/17 20:45:42  caress
 * Release 5.0.beta30
 *
 * Revision 5.8  2002/08/30 19:28:21  caress
 * Added time series style plots.
 *
 * Revision 5.7  2002/07/20 20:45:04  caress
 * Release 5.0.beta20
 *
 * Revision 5.6  2001/11/16 01:25:20  caress
 * Added info mode.
 *
 * Revision 5.5  2001/09/17  17:00:48  caress
 * Added local median filter, angle filter, time display toggle.
 *
 * Revision 5.4  2001/07/31  00:40:17  caress
 * Added flagging by beam number and acrosstrack distance.
 *
 * Revision 5.3  2001/07/20  00:30:32  caress
 * Release 5.0.beta03
 *
 * Revision 5.2  2001/06/30  17:39:31  caress
 * Release 5.0.beta02
 *
 * Revision 5.1  2001/01/22  07:40:13  caress
 * Version 5.0.0beta01
 *
 * Revision 5.0  2000/12/01  22:54:35  caress
 * First cut at Version 5.0.
 *
 * Revision 4.11  2000/10/11  01:01:50  caress
 * Convert to ANSI C
 *
 * Revision 4.10  2000/09/30  06:56:36  caress
 * Snapshot for Dale.
 * New version integrated with mbprocess.
 *
 * Revision 4.9  2000/09/08  00:29:20  caress
 * Revision of 7 September 2000.
 *
 * Revision 4.8  2000/03/16  00:35:40  caress
 * Added mode to output edit save file only.
 *
 * Revision 4.7  2000/01/25  01:46:20  caress
 * Altered handling of filenames.
 *
 * Revision 4.6  2000/01/20  00:05:38  caress
 * Added pick mode and two unflag buttons.
 *
 * Revision 4.5  1999/09/15  21:02:07  caress
 * Version label now set from mb_format.h
 *
 * Revision 4.4  1999/07/16  19:21:16  caress
 * Smaller window with new dialogs for Linux.
 *
 * Revision 4.3  1998/10/05 17:45:32  caress
 * MB-System version 4.6beta
 *
 * Revision 4.2  1997/09/15  19:06:10  caress
 * Real Version 4.5
 *
 * Revision 4.1  1997/04/22  19:26:36  caress
 * Fixed startup mode.
 *
 * Revision 4.0  1997/04/21  16:57:14  caress
 * MB-System 4.5 Beta Release.
 *
 * Revision 4.0  1997/04/16  21:31:04  caress
 * Complete rewrite without uid file.
 *
 *
 */
/*
 * README: This file is appended to at file generation time.
 * Edits can be made throughout the file
 */
/*
 * Generated by the ICS Builder Xcessory (BX).
 *
 * Builder Xcessory 4.0
 * Code Generator Xcessory 2.0 (09/09/96)
 *
 */
#include <Xm/Xm.h>


/*
 * Standard includes for builtins.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>

/* X11 includes */
#include <X11/StringDefs.h>
#include <X11/cursorfont.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Intrinsic.h>
#include <X11/keysym.h>
#include <X11/keysymdef.h>
#include <Xm/FileSB.h>
#include <Xm/Text.h>
#include <Xm/TextF.h>
#include <Xm/ToggleB.h>
#include <Xm/List.h>

/* mbedit widget includes */
#include "mbedit_creation.h"
#include "mb_define.h"
#include "mb_status.h"
#include "mb_process.h"
#include "mb_xgraphics.h"
#include "mbedit.h"

/*
 * Macros to make code look nicer between ANSI and K&R.
 */
#ifndef ARGLIST
#if (NeedFunctionPrototypes == 0)
#define PROTOTYPE(p)	()
#define ARGLIST(p)	p
#define ARG(a, b)	a b;
#define GRA(a, b)	a b;
#define UARG(a, b)      a b;
#define GRAU(a, b)      a b;
#else
#define PROTOTYPE(p)	p
#define ARGLIST(p)	(
#define ARG(a, b)	a b,
#define GRA(a, b)	a b)
#ifdef __cplusplus
#define UARG(a, b)      a,
#define GRAU(a, b)      a)
#else
#define UARG(a, b)      a b,
#define GRAU(a, b)      a b)
#endif
#endif
#endif

Widget		BxFindTopShell PROTOTYPE((Widget));
WidgetList	BxWidgetIdsFromNames PROTOTYPE((Widget, char*, char*));

void do_fileselection_list();

/*--------------------------------------------------------------------*/

/* additional widgets */
Widget	fileSelectionList;
Widget	fileSelectionText;

/* global defines and variables */
#define EV_MASK (ButtonPressMask | KeyPressMask | KeyReleaseMask | ExposureMask )
#define xgfont "-misc-fixed-bold-r-normal-*-13-*-75-75-c-70-iso8859-1"

/* Mode value defines */
#define	MODE_TOGGLE	0
#define	MODE_PICK	1
#define	MODE_ERASE	2
#define	MODE_RESTORE	3
#define	MODE_GRAB	4
#define	MODE_INFO	5
#define	VIEW_WATERFALL		0
#define	VIEW_ALONGTRACK		1
#define	VIEW_ACROSSTRACK	2
#define	BEAM_MODE_FLAG		0
#define	BEAM_MODE_DETECT	1
#define	BEAM_MODE_PULSE		2
#define	OUTPUT_MODE_OUTPUT	0
#define	OUTPUT_MODE_EDIT	1
#define	OUTPUT_MODE_BROWSE	2
#define GRAB_START		0
#define GRAB_MOVE		1
#define GRAB_END		2
#define	NUM_FILES_MAX		500

/* global variables */
XtAppContext app_context;
Display *display, *theDisplay;
Screen *screen, *can_screen;
Window can_xid;
Window root_return, child_return;
Colormap theColormap, colormap;
GC gc;
unsigned int theCursorShape;
Cursor theCursor;
XGCValues xgcv;

XFontStruct *fontStruct;

/* Global mbedit definitions */
int	expose_plot_ok = False;
int	plot_size_max;
int	mplot_size;
int	buffer_size_max;
int	buffer_size;
int	hold_size;
int	mformat;
int	step = 5;
int	nloaded;
int	ndumped;
int	nbuffer;
int	ngood;
int	icurrent;
int	mnplot;
int	mexager;
int	mplot_width;
int	mx_interval;
int	my_interval;
int	mode_pick = MODE_TOGGLE;
int	mshow_beammode = BEAM_MODE_FLAG;
int	mshow_flagged = MB_NO;
int	mview_mode = VIEW_WATERFALL;
int	mshow_time = 1;
int	mode_output = OUTPUT_MODE_EDIT;
int	mode_reverse_keys = MB_NO;
int	mode_reverse_mouse = MB_NO;
int	ttime_i[7];
int	f_beams_max;
double	f_distance_max;
int	f_medianspike;
int	f_medianspike_threshold;
int	f_medianspike_xtrack;
int	f_medianspike_ltrack;
int	f_wrongside;
int	f_wrongside_threshold;
int	f_cutbeam;
int	f_cutbeam_begin;
int	f_cutbeam_end;
int	f_cutdistance;
double	f_cutdistance_begin;
double	f_cutdistance_end;
int	f_cutangle;
double	f_cutangle_begin;
double	f_cutangle_end;
int	status;

/* file opening parameters */
int	startup_file = 0;
int	numfiles = 0;
int	currentfile = -1;
int	currentfile_shown = -1;
int	fileformats[NUM_FILES_MAX];
mb_path	filepaths[NUM_FILES_MAX];
int	filelocks[NUM_FILES_MAX];
int	fileesfs[NUM_FILES_MAX];
int	timer_function_set = MB_NO;

static char	input_file[MB_PATH_MAXLINE];
int selected = 0; /* indicates an input file is selected */

void	*can_xgid;		/* XG graphics id */
Cursor myCursor;
XColor closest[2];
XColor exact[2];

int key_g_down = 0;
int key_z_down = 0;
int key_s_down = 0;
int key_a_down = 0;
int key_d_down = 0;

/* Set the colors used for this program here. */
#define NCOLORS 7
XColor colors[NCOLORS];
unsigned int mpixel_values[NCOLORS];
XColor db_color;

/* Set these to the dimensions of your canvas drawing */
/* area, minus 1, located in mbedit.uil.              */
static int mb_borders[4] =
	{ 0, 1016, 0, 525 };

/*--------------------------------------------------------------------*/

/*      Function Name: 	BxUnmanageCB
 *
 *      Description:   	Given a string of the form:
 *		       	"(WL)[widgetName, widgetName, ...]"
 *			BxUnmanageCB attempts to convert the name to a Widget
 *			ID and unmanage the widget.
 *
 *      Arguments:     	Widget	    w:      the widget activating the callback.
 *		       	XtPointer   client: the list of widget names to attempt
 *					    to find and unmanage.
 *		       	XtPointer   call:   the call data (unused).
 *
 *      Notes:        *	This function expects that there is an application
 *		       	shell from which all other widgets are descended.
 */

/* ARGSUSED */
void
BxUnmanageCB ARGLIST((w, client, call))
ARG( Widget, w)
ARG( XtPointer, client)
GRAU( XtPointer, call)
{
    WidgetList		widgets;
    int			i;

    /*
     * This function returns a NULL terminated WidgetList.  The memory for
     * the list needs to be freed when it is no longer needed.
     */
    widgets = BxWidgetIdsFromNames(w, "BxUnmanageCB", (String)client);

    i = 0;
    while( widgets && widgets[i] != NULL )
    {
	XtUnmanageChild(widgets[i]);
	i++;
    }
    XtFree((char *)widgets);
}

/*--------------------------------------------------------------------*/

/*      Function Name: 	BxManageCB
 *
 *      Description:   	Given a string of the form:
 *		       	"(WL)[widgetName, widgetName, ...]"
 *			BxManageCB attempts to convert the name to a Widget
 *			ID and manage the widget.
 *
 *      Arguments:     	Widget	    w:      the widget activating the callback.
 *		       	XtPointer   client: the list of widget names to attempt
 *					    to find and manage.
 *		       	XtPointer   call:   the call data (unused).
 *
 *      Notes:        *	This function expects that there is an application
 *		       	shell from which all other widgets are descended.
 */

/* ARGSUSED */
void
BxManageCB ARGLIST((w, client, call))
ARG( Widget, w)
ARG( XtPointer, client)
GRAU( XtPointer, call)
{
    WidgetList		widgets;
    int			i;

    /*
     * This function returns a NULL terminated WidgetList.  The memory for
     * the list needs to be freed when it is no longer needed.
     */
    widgets = BxWidgetIdsFromNames(w, "BxManageCB", (String)client);

    i = 0;
    while( widgets && widgets[i] != NULL )
    {
	XtManageChild(widgets[i]);
	i++;
    }
    XtFree((char *)widgets);
}
/*--------------------------------------------------------------------*/
/*      Function Name:	BxPopupCB
 *
 *      Description:   	This function accepts a string of the form:
 *			"(WL)[widgetName, widgetName, ...]"
 *			It attempts to convert the widget names to Widget IDs
 *			and then popup the widgets WITHOUT any grab.
 *
 *      Arguments:      Widget		w:	the activating widget.
 *			XtPointer	client:	the string of widget names to
 *						popup.
 *			XtPointer	call:	the call data (unused).
 *
 *      Notes:        * This function expects that there is an application
 *                      shell from which all other widgets are descended.
 *		      * BxPopupCB can only work on Shell widgets.  It will not
 *			work on other object types.  This is because popping up
 *			can only be done to a shell.  A check is made using
 *			XtIsShell() and an appropriate error is output if the
 *			passed object is not a Shell.
 */

/* ARGSUSED */
void
BxPopupCB ARGLIST((w, client, call))
ARG( Widget, w)
ARG( XtPointer, client)
GRAU( XtPointer, call)
{
    WidgetList		widgets;
    int			i;

    /*
     * This function returns a NULL terminated WidgetList.  The memory for
     * the list needs to be freed when it is no longer needed.
     */
    widgets = BxWidgetIdsFromNames(w, "BxPopupCB", (String)client);

    i = 0;
    while( widgets && widgets[i] != NULL )
    {
	if ( XtIsShell(widgets[i]) )
	{
	    XtPopup(widgets[i], XtGrabNone);
	}
	else
	{
	    printf("Callback Error (BxPopupCB):\n\t\
Object %s is not a Shell\n", XtName(widgets[i]));
	}
	i++;
    }
    XtFree((char *)widgets);
}

/*--------------------------------------------------------------------*/

void
do_mbedit_init(int argc, char **argv)
{
    int	i;

    /* make sure expose plots are off */
    expose_plot_ok = False;

    /* get additional widgets */
    fileSelectionList = (Widget)
	XmFileSelectionBoxGetChild(fileSelectionBox,
				    XmDIALOG_LIST);
    fileSelectionText = (Widget)
	XmFileSelectionBoxGetChild(fileSelectionBox,
				    XmDIALOG_TEXT);
    XtAddCallback(fileSelectionList,
	    XmNbrowseSelectionCallback,
	    do_fileselection_list, NULL);

    XtUnmanageChild(
	    (Widget) XmFileSelectionBoxGetChild(
				    fileSelectionBox,
				    XmDIALOG_HELP_BUTTON));

    /* Setup the entire screen. */
    display = XtDisplay(window_mbedit);
    colormap = DefaultColormap(display, XDefaultScreen(display));

    /* Setup just the "canvas" part of the screen. */
    theDisplay = XtDisplay(canvas_mbedit);
    can_screen = DefaultScreenOfDisplay(theDisplay);
    can_xid = XtWindow(canvas_mbedit);
    theColormap = DefaultColormap(display, XDefaultScreen(theDisplay));

    /* Setup the "graphics Context" for just the "canvas" */
    xgcv.background = WhitePixelOfScreen(can_screen);
    xgcv.foreground = BlackPixelOfScreen(can_screen);
    xgcv.line_width = 2;
    gc = XCreateGC(theDisplay,can_xid,GCBackground | GCForeground
	     | GCLineWidth, &xgcv);

    /* Setup the font for just the "canvas" screen. */
    fontStruct = XLoadQueryFont(theDisplay,
	     "-misc-fixed-bold-r-normal-*-13-*-75-75-c-70-iso8859-1");
    XSetFont(theDisplay,gc,fontStruct->fid);

    XSelectInput(theDisplay, can_xid, EV_MASK );

    /* Load the colors that will be used in this program. */
    status = XLookupColor(display,colormap, "white",&db_color,&colors[0]);
    if ((status = XAllocColor(display,colormap,&colors[0])) == 0)
	    fprintf(stderr,"Failure to allocate color: white\n");
    status = XLookupColor(display,colormap, "black",&db_color,&colors[1]);
    if ((status = XAllocColor(display,colormap,&colors[1])) == 0)
	    fprintf(stderr,"Failure to allocate color: black\n");
#ifdef USE_ORANGE
    status = XLookupColor(display,colormap, "orange",&db_color,&colors[2]);
    if ((status = XAllocColor(display,colormap,&colors[2])) == 0)
	    fprintf(stderr,"Failure to allocate color: orange\n");
#else
    status = XLookupColor(display,colormap, "red",&db_color,&colors[2]);
    if ((status = XAllocColor(display,colormap,&colors[2])) == 0)
	    fprintf(stderr,"Failure to allocate color: red\n");
#endif
    status = XLookupColor(display,colormap, "green",&db_color,&colors[3]);
    if ((status = XAllocColor(display,colormap,&colors[3])) == 0)
	    fprintf(stderr,"Failure to allocate color: green\n");
    status = XLookupColor(display,colormap, "blue",&db_color,&colors[4]);
    if ((status = XAllocColor(display,colormap,&colors[4])) == 0)
	    fprintf(stderr,"Failure to allocate color: blue\n");
    status = XLookupColor(display,colormap, "coral",&db_color,&colors[5]);
    if ((status = XAllocColor(display,colormap,&colors[5])) == 0)
	    fprintf(stderr,"Failure to allocate color: coral\n");
    status = XLookupColor(display,colormap, "lightgrey",&db_color,&colors[6]);
    if ((status = XAllocColor(display,colormap,&colors[6])) == 0)
	    fprintf(stderr,"Failure to allocate color: lightgrey\n");
    for (i=0;i<NCOLORS;i++)
	    {
	    mpixel_values[i] = colors[i].pixel;
	    }

    /* Setup initial cursor. This will be changed when changing "MODE". */
    myCursor = XCreateFontCursor(theDisplay, XC_target);
    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
    XDefineCursor(theDisplay,can_xid,myCursor);

    /* initialize graphics */
    xg_init(theDisplay, can_xid, mb_borders, xgfont, &can_xgid);

    status = mbedit_set_graphics(can_xgid, NCOLORS, mpixel_values);
    status = mbedit_set_scaling(mb_borders, mshow_time);

    /* initialize mbedit proper */
    status = mbedit_init(argc,argv, &startup_file);

    /* set up the widgets */
    do_setup_data();
    do_filebutton_on();
    do_nextbutton_off();

    /* set timer for function to keep updating the filelist */
    do_mbedit_settimer();

    /* if startup indicated by num_files > 0 try to open first file */
    if (startup_file == MB_YES && numfiles > 0)
	{
	do_load_specific_file(0);
	}

    /* finally allow expose plots */
    expose_plot_ok = True;
}

/*--------------------------------------------------------------------*/

void
do_parse_datalist( char *file, int form)
{
	void    *datalist;
	int     done;
	double  weight;
	int     filestatus;
	int     fileformat;
	char    fileraw[MB_PATH_MAXLINE];
	char    fileprocessed[MB_PATH_MAXLINE];
	int     datalist_status = MB_SUCCESS;
	int	error = MB_ERROR_NO_ERROR;
	int	format;
	int     verbose = 0;

    	/* try to resolve format if necessary */
	format = form;
	mbedit_get_format(file, &format);

	/* read in a single file */
	if (format > 0 && numfiles < NUM_FILES_MAX)
		{
		strcpy(filepaths[numfiles], file);
		fileformats[numfiles] = format;
		filelocks[numfiles] = -1;
		fileesfs[numfiles] = -1;
		numfiles++;
		}

	/* read in datalist if forma = -1 */
	else if (format == -1)
		{
		error = MB_ERROR_NO_ERROR;
		done = MB_NO;
		if ((datalist_status = mb_datalist_open(verbose, &datalist,
						file, MB_DATALIST_LOOK_NO, &error)) == MB_SUCCESS)
			{
			while (done == MB_NO)
				{
				if ((datalist_status = mb_datalist_read2(verbose, datalist,
						&filestatus, fileraw, fileprocessed, &fileformat, &weight, &error))
						== MB_SUCCESS)
					{
					if (numfiles < NUM_FILES_MAX)
						{
						strcpy(filepaths[numfiles], fileraw);
						fileformats[numfiles] = fileformat;
						filelocks[numfiles] = -1;
						fileesfs[numfiles] = -1;
						numfiles++;
						}
					}
				else
					{
					datalist_status = mb_datalist_close(verbose,&datalist,&error);
					done = MB_YES;
					}
				}
			}
		}
}

/*--------------------------------------------------------------------*/

void
do_editlistselection( Widget w, XtPointer client_data, XtPointer call_data)
{
	Cardinal ac;
	Arg      args[256];
	int	*position_list = NULL;
	int	position_count = 0;
	int	quit;
	int	i;

	/* turn off expose plots */
	expose_plot_ok = False;

	/* get the current selection, if any, from the list */
	ac = 0;
	XtSetArg(args[ac], XmNselectedPositionCount, (XtPointer) &position_count); ac++;
	XtSetArg(args[ac], XmNselectedPositions, (XtPointer) &position_list); ac++;
	XtGetValues(list_filelist, args, ac);

fprintf(stderr,"position_count:%d\n",position_count);
for(i=0;i<position_count;i++)
fprintf(stderr,"  %d %d\n",i,position_list[i]);


	/* if the selected file is different than what's already loaded, unload the old file and load the new one */
	if (position_count > 0 && currentfile != position_list[0] - 1)
		{
		currentfile = position_list[0] - 1;

		status = mbedit_action_done(buffer_size,&ndumped,&nloaded,
			    &nbuffer,&ngood,&icurrent,&quit);
		if (status == 0) XBell(theDisplay,100);

		if (position_count > 0)
			currentfile = position_list[0] - 1;
		if (currentfile < numfiles)
			{
			do_load_specific_file(currentfile);
			}
		}

	/* turn on expose plots */
	expose_plot_ok = True;

	do_setup_data();
}

/*--------------------------------------------------------------------*/

void
do_filelist_remove( Widget w, XtPointer client_data, XtPointer call_data)
{
	Cardinal ac;
	Arg      args[256];
	int	*position_list = NULL;
	int	position_count = 0;
	int	i;

	/* turn off expose plots */
	expose_plot_ok = False;

	/* get the current selection, if any, from the list */
	ac = 0;
	XtSetArg(args[ac], XmNselectedPositionCount, (XtPointer) &position_count); ac++;
	XtSetArg(args[ac], XmNselectedPositions, (XtPointer) &position_list); ac++;
	XtGetValues(list_filelist, args, ac);

	/* if the selected file is different than what's already loaded, remove it from the list */
	if (position_count > 0 && currentfile != position_list[0] - 1)
		{
		for (i=position_list[0] - 1;i<numfiles-1;i++)
			{
			strcpy(filepaths[i], filepaths[i+1]);
			fileformats[i] = fileformats[i+1];
			filelocks[i] = filelocks[i+1];
			fileesfs[i] = fileesfs[i+1];
			}
		numfiles--;
		if (currentfile > position_list[0] - 1)
			currentfile--;
		}

	/* turn on expose plots */
	expose_plot_ok = True;

	do_setup_data();

	/* replot the data */
	status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
	if (status == 0) XBell(theDisplay,100);
}

/*--------------------------------------------------------------------*/

void
do_load_specific_file(int i_file)
{
	struct stat file_status;
	int	fstat;
	char    save_file[MB_PATH_MAXLINE];
        int     save_mode = MB_NO;

	/* check the specified file is in the list */
	if (numfiles > 0 && i_file >= 0 && i_file < numfiles)
		{
		/* set current_file */
		currentfile = i_file;

		/* check for edit save file */
		sprintf(save_file, "%s.esf", filepaths[currentfile]);
		fstat = stat(save_file, &file_status);
		if (fstat != 0
			|| (file_status.st_mode & S_IFMT) == S_IFDIR)
			{
			sprintf(save_file, "%s.mbesf", filepaths[currentfile]);
			fstat = stat(save_file, &file_status);
			}

		/* if esf file exists deal with it */
		if (fstat == 0
		    && (file_status.st_mode & S_IFMT) != S_IFDIR)
			{
			/* if save_mode set load data using esf */
			if (save_mode == MB_YES)
                                do_load(MB_YES);

			/* else bring up dialog asking
			if esf should be used */
			else
                                do_checkuseprevious();
			}

		/* else just try to load the data without an esf */
		else
			{
			(void) do_load(MB_NO);
			}
		}
}

/*--------------------------------------------------------------------*/

int do_setup_data()
{
	char value_text[MB_PATH_MAXLINE];

	/* get some default values from mbedit */
	status = mbedit_get_defaults(&plot_size_max,
			&mplot_size,&mshow_beammode,&mshow_flagged,&mshow_time,
			&buffer_size_max,&buffer_size,
			&hold_size,&mformat,
			&mplot_width,&mexager,
			&mx_interval,&my_interval,
			ttime_i,&mode_output);

	/* set about version label */
	sprintf(value_text, ":::t\"MB-System Release %s\":t\"%s\"",
		MB_VERSION, MB_BUILD_DATE);
	set_label_multiline_string(label_about_version, value_text);

	/* set values of number of pings slider */
	XtVaSetValues(slider_number_pings,
			XmNminimum, 1,
			XmNvalue, mplot_size,
			NULL);

	/* set values of number of pings to step slider */
	XtVaSetValues(slider_number_step,
			XmNminimum, 1,
			XmNvalue, step,
			NULL);

	/* set values of buffer size slider */
	XtVaSetValues(slider_buffer_size,
			XmNminimum, 1,
			XmNmaximum, buffer_size_max,
			XmNvalue, buffer_size,
			NULL);

	/* set values of buffer size label */
	sprintf(value_text,"%d",buffer_size_max);
	set_label_string(slider_buffer_size_max_label,
			value_text);

	/* set values of buffer hold size slider */
	XtVaSetValues(slider_buffer_hold,
			XmNminimum, 1,
			XmNmaximum, buffer_size_max,
			XmNvalue, hold_size,
			NULL);

	/* set values of buffer hold size label */
	sprintf(value_text,"%d",buffer_size_max);
	set_label_string(slider_buffer_hold_max_label,
			value_text);

	/* set values of plot width slider */
	XtVaSetValues(slider_scale_x,
			XmNminimum, 1,
			XmNvalue, mplot_width,
			NULL);

	/* set values of vertical exageration slider */
	XtVaSetValues(slider_scale_y,
			XmNdecimalPoints, 2,
			XmNvalue, mexager,
			NULL);

	/* set values of x interval slider */
	XtVaSetValues(slider_x_interval,
			XmNvalue, mx_interval,
			NULL);

	/* set values of y interval slider */
	XtVaSetValues(slider_y_interval,
			XmNvalue, my_interval,
			NULL);

	/* set starting values in go to time widgets */
	sprintf(value_text,"%4.4d",ttime_i[0]);
	XmTextFieldSetString(textfield_year, value_text);

	sprintf(value_text,"%2.2d",ttime_i[1]);
	XmTextFieldSetString(textfield_month, value_text);

	sprintf(value_text,"%2.2d",ttime_i[2]);
	XmTextFieldSetString(textfield_day, value_text);

	sprintf(value_text,"%2.2d",ttime_i[3]);
	XmTextFieldSetString(textfield_hour, value_text);

	sprintf(value_text,"%2.2d",ttime_i[4]);
	XmTextFieldSetString(textfield_minute, value_text);

	sprintf(value_text,"%2.2d",ttime_i[5]);
	XmTextFieldSetString(textfield_second, value_text);

	/* set value of format text item */
	sprintf(value_text,"%2.2d",mformat);
	XmTextFieldSetString(textfield_format, value_text);

	/* set the output mode */
	if (mode_output == OUTPUT_MODE_EDIT)
	    {
	    XmToggleButtonSetState(setting_output_toggle_edit,
			TRUE, TRUE);
	    XmToggleButtonSetState(setting_output_toggle_edit_filelist,
			TRUE, TRUE);
	    }
	else
	    {
	    XmToggleButtonSetState(setting_output_toggle_browse,
			TRUE, TRUE);
	    XmToggleButtonSetState(setting_output_toggle_browse_filelist,
			TRUE, TRUE);
	    }

	/* set the mode toggles */
	XmToggleButtonSetState(setting_mode_toggle_toggle, 0, FALSE);
	XmToggleButtonSetState(setting_mode_toggle_pick, 0, FALSE);
	XmToggleButtonSetState(setting_mode_toggle_erase, 0, FALSE);
	XmToggleButtonSetState(setting_mode_toggle_restore, 0, FALSE);
	XmToggleButtonSetState(setting_mode_toggle_grab, 0, FALSE);
	XmToggleButtonSetState(setting_mode_toggle_info, 0, FALSE);
	if (mode_pick == MODE_TOGGLE)
	    XmToggleButtonSetState(setting_mode_toggle_toggle, 1, FALSE);
	else if (mode_pick == MODE_PICK)
	    XmToggleButtonSetState(setting_mode_toggle_pick, 1, FALSE);
	else if (mode_pick == MODE_ERASE)
	    XmToggleButtonSetState(setting_mode_toggle_erase, 1, FALSE);
	else if (mode_pick == MODE_RESTORE)
	    XmToggleButtonSetState(setting_mode_toggle_restore, 1, FALSE);
	else if (mode_pick == MODE_GRAB)
	    XmToggleButtonSetState(setting_mode_toggle_grab, 1, FALSE);
	else if (mode_pick == MODE_INFO)
	    XmToggleButtonSetState(setting_mode_toggle_info, 1, FALSE);

	/* set the show flagged toggle */
	XmToggleButtonSetState(toggleButton_show_flagged_on, mshow_flagged, FALSE);

	/* turn off all view mode togglebuttons */
	XmToggleButtonSetState(toggleButton_view_waterfall, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_view_alongtrack, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_view_acrosstrack, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_flags, FALSE, FALSE);
	XmToggleButtonSetState(toggleButton_show_detects, FALSE, FALSE);
	XmToggleButtonSetState(toggleButton_show_pulsetypes, FALSE, FALSE);

	/* now turn on the current view mode togglebutton */
	if (mview_mode == 0)
		XmToggleButtonSetState(toggleButton_view_waterfall, MB_YES, FALSE);
	else if (mview_mode == 1)
		XmToggleButtonSetState(toggleButton_view_alongtrack, MB_YES, FALSE);
	else if (mview_mode == 2)
		XmToggleButtonSetState(toggleButton_view_acrosstrack, MB_YES, FALSE);
	if (mshow_beammode == BEAM_MODE_FLAG)
		XmToggleButtonSetState(toggleButton_show_flags, TRUE, FALSE);
	else if (mshow_beammode == BEAM_MODE_DETECT)
		XmToggleButtonSetState(toggleButton_show_detects, TRUE, FALSE);
	else if (mshow_beammode == BEAM_MODE_PULSE)
		XmToggleButtonSetState(toggleButton_show_pulsetypes, TRUE, FALSE);

	/* reset scaling */
	status = mbedit_set_viewmode(mview_mode);

	/* turn off all plot mode togglebuttons */
	XmToggleButtonSetState(toggleButton_show_wideplot, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_time, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_interval, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_lon, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_latitude, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_heading, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_speed, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_depth, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_altitude, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_sonardepth, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_roll, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_pitch, MB_NO, FALSE);
	XmToggleButtonSetState(toggleButton_show_heave, MB_NO, FALSE);

	/* now turn on the current plot mode togglebutton */
	if (mshow_time == 0)
		XmToggleButtonSetState(toggleButton_show_wideplot, MB_YES, FALSE);
	else if (mshow_time == 1)
		XmToggleButtonSetState(toggleButton_show_time, MB_YES, FALSE);
	else if (mshow_time == 2)
		XmToggleButtonSetState(toggleButton_show_interval, MB_YES, FALSE);
	else if (mshow_time == 3)
		XmToggleButtonSetState(toggleButton_show_lon, MB_YES, FALSE);
	else if (mshow_time == 4)
		XmToggleButtonSetState(toggleButton_show_latitude, MB_YES, FALSE);
	else if (mshow_time == 5)
		XmToggleButtonSetState(toggleButton_show_heading, MB_YES, FALSE);
	else if (mshow_time == 6)
		XmToggleButtonSetState(toggleButton_show_speed, MB_YES, FALSE);
	else if (mshow_time == 7)
		XmToggleButtonSetState(toggleButton_show_depth, MB_YES, FALSE);
	else if (mshow_time == 8)
		XmToggleButtonSetState(toggleButton_show_altitude, MB_YES, FALSE);
	else if (mshow_time == 9)
		XmToggleButtonSetState(toggleButton_show_sonardepth, MB_YES, FALSE);
	else if (mshow_time == 10)
		XmToggleButtonSetState(toggleButton_show_roll, MB_YES, FALSE);
	else if (mshow_time == 11)
		XmToggleButtonSetState(toggleButton_show_pitch, MB_YES, FALSE);
	else if (mshow_time == 12)
		XmToggleButtonSetState(toggleButton_show_heave, MB_YES, FALSE);

	/* get filter values and set widgets */
	do_get_filters();

	/* build available file list */
	do_build_filelist();

	return(1);
}

/*--------------------------------------------------------------------*/

void
do_build_filelist()
{
	int	update_filelist;
	Cardinal ac;
	Arg      args[256];
	int	item_count;
	int	*position_list = NULL;
	int	position_count = 0;
	int	selection;
	char value_text[MB_PATH_MAXLINE];
    	XmString *xstr;
	char	*lockstrptr;
	char	*lockedstr   = "<Locked>";
	char	*unlockedstr = "        ";
	char	*loadedstr   = "<loaded>";
	char	*esfstrptr;
	char	*esfyesstr   = "<esf>";
	char	*esfnostr    = "     ";
	int     verbose = 0;
	int	i;

	/* swath file locking variables */
	int	lock_status;
	int	lock_error = MB_ERROR_NO_ERROR;
	int	locked;
	int	lock_purpose;
	mb_path	lock_program;
	mb_path lock_cpu;
	mb_path lock_user;
	char	lock_date[25];

	/* esf file checking variables */
	int	esf_exists;
	struct stat file_status;
	int	fstat;
	char    save_file[MB_PATH_MAXLINE];

	/* check to see if anything has changed */
	update_filelist = MB_NO;

	/* check for change in number of files */
	ac = 0;
	XtSetArg(args[ac], XmNitemCount, (XtPointer) &item_count); ac++;
	XtGetValues(list_filelist, args, ac);
	if (item_count != numfiles)
		update_filelist = MB_YES;

	/* check current file shown vs loaded */
	if (currentfile != currentfile_shown)
		{
		currentfile_shown = currentfile;
		update_filelist = MB_YES;
		}

	/* check for change in lock status or esf status */
	for (i=0;i<numfiles;i++)
		{
		/* check for locks */
		lock_status = mb_pr_lockinfo(verbose, filepaths[i], &locked,
				&lock_purpose, lock_program, lock_user, lock_cpu,
				lock_date, &lock_error);
		if (locked != filelocks[i])
			{
			filelocks[i] = locked;
			update_filelist = MB_YES;
			}

		/* check for edit save file */
		sprintf(save_file, "%s.esf", filepaths[i]);
		fstat = stat(save_file, &file_status);
		if (fstat == 0
		    && (file_status.st_mode & S_IFMT) != S_IFDIR)
			esf_exists = MB_YES;
		else
			esf_exists = MB_NO;
		if (esf_exists != fileesfs[i])
			{
			fileesfs[i] = esf_exists;
			update_filelist = MB_YES;
			}
		}

	/* only rebuild the filelist if necessary */
	if (update_filelist == MB_YES)
		{
		/* get the current selection, if any, from the list */
		ac = 0;
		XtSetArg(args[ac], XmNitemCount, (XtPointer) &item_count); ac++;
		XtSetArg(args[ac], XmNselectedPositionCount, (XtPointer) &position_count); ac++;
		XtSetArg(args[ac], XmNselectedPositions, (XtPointer) &position_list); ac++;
		XtGetValues(list_filelist, args, ac);
		if (position_count > 0)
			selection = position_list[0];

		/* build available file list */
		XmListDeleteAllItems(list_filelist);
		if (numfiles > 0)
			{

			/* allocate array of x strings */
			xstr = (XmString *) malloc(numfiles * sizeof(XmString));
			for (i=0;i<numfiles;i++)
				{
				/* check for locks */
				if (currentfile == i)
					lockstrptr = loadedstr;
				else if (filelocks[i] == MB_YES)
					lockstrptr = lockedstr;
				else
					lockstrptr = unlockedstr;

				/* check for edit save file */
				if (fileesfs[i] == MB_YES)
					esfstrptr = esfyesstr;
				else
					esfstrptr = esfnostr;

				/* build x string item */
				sprintf(value_text,"%s %s %s %3d",
					lockstrptr,
					esfstrptr,
					filepaths[i],
					fileformats[i]);
   				xstr[i] = XmStringCreateLocalized(value_text);

				/* print out list of files */
				/* if (currentfile == i)
					fprintf(stderr," *** %s %d %s %d\n",lockstrptr,i+1,filepaths[i],fileformats[i]);
				else
					fprintf(stderr,"     %s %d %s %d\n",lockstrptr,i+1,filepaths[i],fileformats[i]); */
 				}
    			XmListAddItems(list_filelist,xstr,numfiles,0);
			for (i=0;i<numfiles;i++)
				{
    				XmStringFree(xstr[i]);
    				}
    			free(xstr);

			/* reinstate selection if the number of items is the same as before */
			if (item_count == numfiles && position_count > 0)
				{
    				XmListSelectPos(list_filelist,selection,False);
				}
			}
		}
	}
/*--------------------------------------------------------------------*/

void
do_get_filters()
{

	/* get some default values from mbedit */
	status = mbedit_get_filters(&f_beams_max, &f_distance_max,
			&f_medianspike,
			&f_medianspike_threshold,
			&f_medianspike_xtrack,
			&f_medianspike_ltrack,
			&f_wrongside,
			&f_wrongside_threshold,
			&f_cutbeam,
			&f_cutbeam_begin, &f_cutbeam_end,
			&f_cutdistance,
			&f_cutdistance_begin, &f_cutdistance_end,
			&f_cutangle,
			&f_cutangle_begin, &f_cutangle_end);

	/* set values of median spike filter widgets */
 	XmToggleButtonSetState(toggleButton_filters_medianspike,
 					f_medianspike, FALSE);
	XtVaSetValues(scale_filters_medianspike,
			XmNminimum, 1,
			XmNmaximum, 100,
			XmNvalue, f_medianspike_threshold,
			NULL);
	XtVaSetValues(scale_median_local_xtrack,
			XmNminimum, 1,
			XmNmaximum, f_beams_max,
			XmNvalue, f_medianspike_xtrack,
			NULL);
	XtVaSetValues(scale_median_local_ltrack,
			XmNminimum, 1,
			XmNmaximum, f_beams_max,
			XmNvalue, f_medianspike_ltrack,
			NULL);

	/* set values of wrong side filter widgets */
 	XmToggleButtonSetState(toggleButton_filters_wrongside,
 					f_wrongside, FALSE);
	XtVaSetValues(scale_filters_wrongside,
			XmNminimum, 0,
			XmNmaximum, f_beams_max,
			XmNvalue, f_wrongside_threshold,
			NULL);

	/* set values of cut by beam number filter widgets */
 	XmToggleButtonSetState(toggleButton_filters_cutbeam,
 					f_cutbeam, FALSE);
	XtVaSetValues(scale_filters_cutbeamstart,
			XmNminimum, 0,
			XmNmaximum, f_beams_max,
			XmNvalue, f_cutbeam_begin,
			NULL);
	XtVaSetValues(scale_filters_cutbeamend,
			XmNminimum, 0,
			XmNmaximum, f_beams_max,
			XmNvalue, f_cutbeam_end,
			NULL);

	/* set values of cut by distance filter widgets */
 	XmToggleButtonSetState(toggleButton_filters_cutdistance,
 					f_cutdistance, FALSE);
	XtVaSetValues(scale_filters_cutdistancestart,
			XmNminimum, (int)(-100 * f_distance_max - 0.5),
			XmNmaximum, (int)(100 * f_distance_max + 0.5),
			XmNvalue, (int)(100 * f_cutdistance_begin + 0.5),
			NULL);
	XtVaSetValues(scale_filters_cutdistanceend,
			XmNminimum, (int)(-100 * f_distance_max - 0.5),
			XmNmaximum, (int)(100 * f_distance_max + 0.5),
			XmNvalue, (int)(100 * f_cutdistance_end + 0.5),
			NULL);

	/* set values of cut by angle filter widgets */
 	XmToggleButtonSetState(toggleButton_filters_cutangle,
 					f_cutangle, FALSE);
	XtVaSetValues(scale_filters_cutanglestart,
			XmNminimum, -9000,
			XmNmaximum, 9000,
			XmNvalue, (int)(100 * f_cutangle_begin + 0.5),
			NULL);
	XtVaSetValues(scale_filters_cutangleend,
			XmNminimum, -9000,
			XmNmaximum, 9000,
			XmNvalue, (int)(100 * f_cutangle_end + 0.5),
			NULL);
}

/*--------------------------------------------------------------------*/

void
do_file_selection_cancel( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
}

/*--------------------------------------------------------------------*/

void
do_expose( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    /* replot the data */
    if (expose_plot_ok == True)
	    status = mbedit_action_plot(mplot_width, mexager,
		    mx_interval, my_interval,
		    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
		    &nbuffer, &ngood, &icurrent, &mnplot);
}

/*--------------------------------------------------------------------*/

void
do_mode_toggle( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_pick = MODE_TOGGLE;

    myCursor = XCreateFontCursor(theDisplay, XC_target);
    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
    XDefineCursor(theDisplay,can_xid,myCursor);
}

/*--------------------------------------------------------------------*/

void
do_mode_pick( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_pick = MODE_PICK;

    myCursor = XCreateFontCursor(theDisplay, XC_target);
    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
    XDefineCursor(theDisplay,can_xid,myCursor);
}

/*--------------------------------------------------------------------*/

void
do_mode_erase( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_pick = MODE_ERASE;

    myCursor = XCreateFontCursor(theDisplay, XC_exchange);
    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
    XDefineCursor(theDisplay,can_xid,myCursor);
}

/*--------------------------------------------------------------------*/

void
do_mode_restore( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_pick = MODE_RESTORE;

    myCursor = XCreateFontCursor(theDisplay, XC_exchange);
    XAllocNamedColor(theDisplay,colormap,"green",&closest[0],&exact[0]);
    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
    XDefineCursor(theDisplay,can_xid,myCursor);
}

/*--------------------------------------------------------------------*/

void
do_mode_grab( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_pick = MODE_GRAB;

    myCursor = XCreateFontCursor(theDisplay, XC_target);
    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
    XDefineCursor(theDisplay,can_xid,myCursor);
}

/*--------------------------------------------------------------------*/

void
do_mode_info( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_pick = MODE_INFO;

    myCursor = XCreateFontCursor(theDisplay, XC_target);
    XAllocNamedColor(theDisplay,colormap,"blue",&closest[0],&exact[0]);
    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
    XDefineCursor(theDisplay,can_xid,myCursor);
}
/*--------------------------------------------------------------------*/

void
do_scale_y( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    int	maxx;
    char	label[10];

    mexager = acs->value;

    /* if slider set to minimum value, half the value range;
	    if slider set to maximum value,  double the range */
    XtVaGetValues(slider_scale_y,
		    XmNmaximum, &maxx,
		    NULL);
    if (mexager == 1 || mexager == maxx)
	    {
	    if (mexager == 1)
		    maxx = maxx/2;
	    else
		    maxx = 2*maxx;
	    if (maxx < 2)
		    maxx = 2;
	    XtVaSetValues(slider_scale_y,
		    XmNmaximum, maxx,
		    NULL);
	    sprintf(label, "%.2f", (double)(maxx/100.));
	    set_label_string(slider_scale_y_max_label,
			    label);
	    }

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
    if (status == 0) XBell(theDisplay,100);

}

/*--------------------------------------------------------------------*/

void
do_fileselection_list( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    static char selection_text[MB_PATH_MAXLINE];
    int	form;
    char	value_text[10];

    /* get selected text */
    get_text_string(fileSelectionText, selection_text);

    /* get output file */
    if((int)strlen(selection_text) > 0)
	    {
	    /* look for MB suffix convention */
	    form = mformat;
	    if ((status = mbedit_get_format(selection_text,
			    &form)) == MB_SUCCESS)
		{
		mformat = form;
		sprintf(value_text,"%d",mformat);
		XmTextFieldSetString(
		    textfield_format,
		    value_text);
		}
	    }
}

/*--------------------------------------------------------------------*/

void
do_scale_x( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    int	maxx;
    char	label[10];

    mplot_width = acs->value;

    /* if slider set to minimum value, half the value range;
	    if slider set to maximum value,  double the range */
    XtVaGetValues(slider_scale_x,
		    XmNmaximum, &maxx,
		    NULL);
    if (mplot_width == 1 || mplot_width == maxx)
	    {
	    if (mplot_width == 1)
		    maxx = maxx/2;
	    else
		    maxx = 2*maxx;
	    if (maxx < 2)
		    maxx = 2;
	    XtVaSetValues(slider_scale_x,
		    XmNmaximum, maxx,
		    NULL);
	    sprintf(label, "%d", maxx);
	    set_label_string(slider_scale_x_max_label,
			    label);
	    }

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
    if (status == 0) XBell(theDisplay,100);

}

/*--------------------------------------------------------------------*/

int do_reset_scale_x(int pwidth, int maxx, int xntrvl, int yntrvl)
{
	char	label[10];

	mplot_width = pwidth;

	/* check max value */
	if (pwidth > maxx - 1)
		{
		maxx = 2 * pwidth;
		if (maxx < 2)
			maxx = 2;
		}
	mx_interval = xntrvl;
	my_interval = yntrvl;

	/* set values of plot width slider */
	XtVaSetValues(slider_scale_x,
			XmNvalue, mplot_width,
			XmNmaximum, maxx,
			NULL);
	sprintf(label, "%d", maxx);
	set_label_string(slider_scale_x_max_label,
			label);

	/* set values of x interval slider */
	XtVaSetValues(slider_x_interval,
			XmNvalue, mx_interval,
			NULL);

	/* set values of y interval slider */
	XtVaSetValues(slider_y_interval,
			XmNvalue, my_interval,
			NULL);

	return(1);

}

/*--------------------------------------------------------------------*/

void
do_output_edit( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmToggleButtonCallbackStruct *acs=(XmToggleButtonCallbackStruct*)call_data;

    /* set values if needed */
    if (acs->reason == XmCR_VALUE_CHANGED && acs->set)
	    {
	    mode_output = OUTPUT_MODE_EDIT;
	    XmToggleButtonSetState(setting_output_toggle_edit_filelist,
			TRUE, TRUE);
	    }
}

/*--------------------------------------------------------------------*/

void
do_output_browse( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmToggleButtonCallbackStruct *acs=(XmToggleButtonCallbackStruct*)call_data;

    /* set values if needed */
    if (acs->reason == XmCR_VALUE_CHANGED && acs->set)
	    {
	    mode_output = OUTPUT_MODE_BROWSE;
	    XmToggleButtonSetState(setting_output_toggle_browse_filelist,
			TRUE, TRUE);
	    }
}

/*--------------------------------------------------------------------*/


void
do_output_edit_filelist( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmToggleButtonCallbackStruct *acs=(XmToggleButtonCallbackStruct*)call_data;

    /* set values if needed */
    if (acs->reason == XmCR_VALUE_CHANGED && acs->set)
	    {
	    mode_output = OUTPUT_MODE_EDIT;
	    XmToggleButtonSetState(setting_output_toggle_edit,
			TRUE, TRUE);
	    }
}

/*--------------------------------------------------------------------*/


void
do_output_browse_filelist( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmToggleButtonCallbackStruct *acs=(XmToggleButtonCallbackStruct*)call_data;

    /* set values if needed */
    if (acs->reason == XmCR_VALUE_CHANGED && acs->set)
	    {
	    mode_output = OUTPUT_MODE_BROWSE;
	    XmToggleButtonSetState(setting_output_toggle_browse,
			TRUE, TRUE);
	    }
}

/*--------------------------------------------------------------------*/

void
do_x_interval( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    int	maxx;
    char	label[10];

    mx_interval = acs->value;

    /* if slider set to minimum value, half the value range;
	    if slider set to maximum value,  double the range */
    XtVaGetValues(slider_x_interval,
		    XmNmaximum, &maxx,
		    NULL);
    if (mx_interval == 1 || mx_interval == maxx)
	    {
	    if (mx_interval == 1)
		    maxx = maxx/2;
	    else
		    maxx = 2*maxx;
	    if (maxx < 2)
		    maxx = 2;
	    XtVaSetValues(slider_x_interval,
		    XmNmaximum, maxx,
		    NULL);
	    sprintf(label, "%d", maxx);
	    set_label_string(slider_x_max_interval_label,
			    label);
	    }

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
    if (status == 0) XBell(theDisplay,100);
}

/*--------------------------------------------------------------------*/

void
do_y_interval( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    int	maxx;
    char	label[10];

    my_interval = acs->value;

    /* if slider set to minimum value, half the value range;
	    if slider set to maximum value,  double the range */
    XtVaGetValues(slider_y_interval,
		    XmNmaximum, &maxx,
		    NULL);
    if (my_interval == 1 || my_interval == maxx)
	    {
	    if (my_interval == 1)
		    maxx = maxx/2;
	    else
		    maxx = 2*maxx;
	    if (maxx < 2)
		    maxx = 2;
	    XtVaSetValues(slider_y_interval,
		    XmNmaximum, maxx,
		    NULL);
	    sprintf(label, "%d", maxx);
	    set_label_string(slider_y_max_interval_label,
			    label);
	    }

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
    if (status == 0) XBell(theDisplay,100);
}

/*--------------------------------------------------------------------*/

void
do_load(int save_mode)
{

    /* turn off expose plots */
    expose_plot_ok = False;

    /* only load valid file */
    if (currentfile >= 0)
    	{
	/* process input file name */
	status = mbedit_action_open(filepaths[currentfile],
    			fileformats[currentfile],
			currentfile,
			numfiles,
			save_mode,
			mode_output,
			mplot_width, mexager, mx_interval,
			my_interval, mplot_size, mshow_beammode, mshow_flagged, mshow_time,
			&buffer_size, &buffer_size_max,
			&hold_size,
			&ndumped, &nloaded, &nbuffer,
			&ngood, &icurrent, &mnplot);
	if (status == MB_FAILURE)
		{
		XBell(theDisplay,100);
		currentfile = -1;
		}
	}

    /* display data from chosen file */
    if (status == MB_SUCCESS)
    	{
	status = mbedit_action_plot(mplot_width, mexager,
		mx_interval, my_interval,
		mplot_size, mshow_beammode, mshow_flagged, mshow_time,
		&nbuffer, &ngood, &icurrent, &mnplot);
	if (status == 0) XBell(theDisplay,100);
	}

    /* set widget values */
    do_setup_data();

    /* turn on expose plots */
    expose_plot_ok = True;

}
/*--------------------------------------------------------------------*/

void
do_load_ok( Widget w, XtPointer client_data, XtPointer call_data)
{
    /* load the current file without using edit save file */
    do_load(MB_NO);
}
/*--------------------------------------------------------------------*/

void
do_load_ok_with_save( Widget w, XtPointer client_data, XtPointer call_data)
{
    /* load the current file using edit save file */
    do_load(MB_YES);
}

/*--------------------------------------------------------------------*/

void
do_load_check( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmFileSelectionBoxCallbackStruct *acs=(XmFileSelectionBoxCallbackStruct*)call_data;

    char    *input_file_ptr;
    static  char format_text[40];
    int		format;
    int		numfilessave;
    int		quit;

    /* read the input file name */
    if(!XmStringGetLtoR(acs->value,
	XmSTRING_DEFAULT_CHARSET,
	&input_file_ptr))
	{
	fprintf(stderr,"\nno input multibeam file selected\n");
	}
    else
	{
	/* turn off expose plots */
	expose_plot_ok = False;

	/* close out previously open file */
	status = mbedit_action_done(buffer_size,&ndumped,&nloaded,
		    &nbuffer,&ngood,&icurrent,&quit);
	if (status == 0) XBell(theDisplay,100);
	currentfile = -1;

	/* read the input file name */
	numfilessave = numfiles;
	strncpy(input_file, input_file_ptr, MB_PATH_MAXLINE);
	XtFree(input_file_ptr);

	/* read the mbio format number from the dialog */
	get_text_string(textfield_format, format_text);
	sscanf(format_text, "%d", &format);

	/* try to parse the selection */
	do_parse_datalist(input_file, format);

	/* load first new file in the list */
	if (numfiles > 0 && numfilessave < numfiles)
	    {
	    currentfile = numfilessave;
	    do_load_specific_file(numfilessave);
	    }

	/* turn on expose plots */
	expose_plot_ok = True;
	}
}

/*--------------------------------------------------------------------*/

void
do_checkuseprevious( )
{
    XtManageChild(bulletinBoard_editsave);
}

/*--------------------------------------------------------------------*/

void
do_filebutton_on()
{
	Boolean  argok = False;
        XmString    tmp0;

	XtVaSetValues(pushButton_file,
		XmNsensitive, True,
		NULL);

	XtVaSetValues(pushButton_done,
		XmNsensitive, False,
		NULL);
        tmp0 = (XmString) BX_CONVERT(pushButton_done, (char *)"Done",
                			XmRXmString, 0, &argok);
	XtVaSetValues(pushButton_done,
		XmNlabelString, tmp0,
		NULL);
        XmStringFree((XmString)tmp0);

	XtVaSetValues(pushButton_forward,
		XmNsensitive, False,
		NULL);
	XtVaSetValues(pushButton_reverse,
		XmNsensitive, False,
		NULL);
	XtVaSetValues(pushButton_start,
		XmNsensitive, False,
		NULL);
	XtVaSetValues(pushButton_end,
		XmNsensitive, False,
		NULL);
}

/*--------------------------------------------------------------------*/

void
do_filebutton_off()
{
	Boolean  argok = False;
        XmString    tmp0;

	XtVaSetValues(pushButton_file,
		XmNsensitive, True,
		NULL);
	XtVaSetValues(pushButton_done,
		XmNsensitive, True,
		NULL);
	if (numfiles > 0 && currentfile >= 0 && currentfile < numfiles - 1)
		{
        	tmp0 = (XmString) BX_CONVERT(pushButton_done, (char *)"Next File",
                				XmRXmString, 0, &argok);
		XtVaSetValues(pushButton_done,
			XmNlabelString, tmp0,
			NULL);
        	XmStringFree((XmString)tmp0);
		}
	else
		{
        	tmp0 = (XmString) BX_CONVERT(pushButton_done, (char *)"Done",
                				XmRXmString, 0, &argok);
		XtVaSetValues(pushButton_done,
			XmNlabelString, tmp0,
			NULL);
        	XmStringFree((XmString)tmp0);
		}
	XtVaSetValues(pushButton_forward,
		XmNsensitive, True,
		NULL);
	XtVaSetValues(pushButton_reverse,
		XmNsensitive, True,
		NULL);
	XtVaSetValues(pushButton_start,
		XmNsensitive, True,
		NULL);
	XtVaSetValues(pushButton_end,
		XmNsensitive, True,
		NULL);
}
/*--------------------------------------------------------------------*/

void
do_nextbutton_on()
{
		XtVaSetValues(pushButton_next,
			XmNsensitive, True,
			NULL);
}

/*--------------------------------------------------------------------*/

void
do_nextbutton_off()
{
		XtVaSetValues(pushButton_next,
			XmNsensitive, False,
			NULL);
}

/*--------------------------------------------------------------------*/

void
do_end( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;
fprintf(stderr,"do_end\n");

    status = mbedit_action_step(nbuffer-icurrent-1,mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
    if (status == 0) XBell(theDisplay,100);

}

/*--------------------------------------------------------------------*/

void
do_forward( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    if (key_g_down == 0)
	{
	status = mbedit_action_step(step,mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
	if (status == 0) XBell(theDisplay,100);
	}
    else
	{
	status = mbedit_action_step(nbuffer-icurrent-1,mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
	if (status == 0) XBell(theDisplay,100);
	}

}

/*--------------------------------------------------------------------*/

void
do_reverse( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    if (key_g_down == 0)
	{
	status = mbedit_action_step(-step,mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
	if (status == 0) XBell(theDisplay,100);
	}
    else
	{
	status = mbedit_action_step(-icurrent,mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
	if (status == 0) XBell(theDisplay,100);
	}

}

/*--------------------------------------------------------------------*/

void
do_start( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;
fprintf(stderr,"do_start\n");

    status = mbedit_action_step(-icurrent,mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
    if (status == 0) XBell(theDisplay,100);

}

/*--------------------------------------------------------------------*/

void
do_quit( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    status = mbedit_action_quit(buffer_size,&ndumped,&nloaded,
		    &nbuffer,&ngood,&icurrent);
    if (status == 0) XBell(theDisplay,100);

    exit(0);

}

/*--------------------------------------------------------------------*/

void
do_event( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmDrawingAreaCallbackStruct *acs=(XmDrawingAreaCallbackStruct*)call_data;
    static Position x_loc, y_loc;

    XEvent  *event = acs->event;

    KeySym keysym;
    char buffer[1];
    int actual;
    int root_x_return, root_y_return,win_x,win_y;
    unsigned int mask_return;
    int doit;
    int	grab_mode;

    /* check for data file loaded at startup */
    if (startup_file)
	    {
	    startup_file = 0;
	    status = mbedit_action_plot(mplot_width, mexager,
		    mx_interval, my_interval,
		    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
		    &nbuffer, &ngood, &icurrent, &mnplot);
	    if (status == 0) XBell(theDisplay,100);
	    } /* end startup file */

    /* If there is input in the drawing area */
    if (acs->reason == XmCR_INPUT)
    {
      /* deal with expose events by replotting the mbedit view */
      if (event->xany.type == Expose || event->xany.type == GraphicsExpose)
		status = mbedit_action_plot(mplot_width, mexager,
				    mx_interval, my_interval,
				    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
				    &nbuffer, &ngood, &icurrent, &mnplot);

      /* Deal with KeyPress events */
      if(event->xany.type == KeyPress)
      {
      /* Get key pressed - buffer[0] */
      actual = XLookupString((XKeyEvent *)event,
		    buffer, 1, &keysym, NULL);

      /* process events */
      switch (buffer[0])
	    {
	    case 'G':
	    case 'g':
		    key_g_down = 1;
		    break;
	    case 'M':
	    case 'm':
	    case 'Z':
	    case 'z':
		    status = mbedit_action_bad_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    key_z_down = 1;
		    key_s_down = 0;
		    key_a_down = 0;
		    key_d_down = 0;
		    break;
	    case 'K':
	    case 'k':
	    case 'S':
	    case 's':
		    status = mbedit_action_good_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    key_z_down = 0;
		    key_s_down = 1;
		    key_a_down = 0;
		    key_d_down = 0;
		    break;
	    case 'J':
	    case 'j':
	    case 'A':
	    case 'a':
		    if (mode_reverse_keys == MB_NO)
			status = mbedit_action_left_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    else
			status = mbedit_action_right_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    key_z_down = 0;
		    key_s_down = 0;
		    key_a_down = 1;
		    key_d_down = 0;
		    break;
	    case 'L':
	    case 'l':
	    case 'D':
	    case 'd':
		    if (mode_reverse_keys == MB_NO)
			status = mbedit_action_right_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    else
			status = mbedit_action_left_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    key_z_down = 0;
		    key_s_down = 0;
		    key_a_down = 0;
		    key_d_down = 1;
		    break;
	    case '<':
	    case ',':
	    case 'X':
	    case 'x':
		    status = mbedit_action_flag_view(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    break;
	    case '>':
	    case '.':
	    case 'C':
	    case 'c':
		    status = mbedit_action_unflag_view(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    break;
	    case '!':
		    status = mbedit_action_zero_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    break;
	    case 'U':
	    case 'u':
	    case 'Q':
	    case 'q':
			    {
			    mode_pick = MODE_TOGGLE;
			    XmToggleButtonSetState(setting_mode_toggle_toggle, 1, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_pick, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_erase, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_restore, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_grab, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_info, 0, FALSE);

			    myCursor = XCreateFontCursor(theDisplay, XC_target);
			    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
			    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
			    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
			    XDefineCursor(theDisplay,can_xid,myCursor);
			    }
		    break;
	    case 'I':
	    case 'i':
	    case 'W':
	    case 'w':
			    {
			    mode_pick = MODE_PICK;
			    XmToggleButtonSetState(setting_mode_toggle_toggle, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_pick, 1, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_erase, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_restore, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_grab, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_info, 0, FALSE);

			    myCursor = XCreateFontCursor(theDisplay, XC_target);
			    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
			    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
			    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
			    XDefineCursor(theDisplay,can_xid,myCursor);
			    }
		    break;
	    case 'O':
	    case 'o':
	    case 'E':
	    case 'e':
			    {
			    mode_pick = MODE_ERASE;
			    XmToggleButtonSetState(setting_mode_toggle_toggle, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_pick, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_erase, 1, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_restore, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_grab, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_info, 0, FALSE);

			    myCursor = XCreateFontCursor(theDisplay, XC_exchange);
			    XAllocNamedColor(theDisplay,colormap,"red",&closest[0],&exact[0]);
			    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
			    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
			    XDefineCursor(theDisplay,can_xid,myCursor);
			    }
		    break;
	    case 'P':
	    case 'p':
	    case 'R':
	    case 'r':
			    {
			    mode_pick = MODE_RESTORE;
			    XmToggleButtonSetState(setting_mode_toggle_toggle, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_pick, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_erase, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_restore, 1, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_grab, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_info, 0, FALSE);

			    myCursor = XCreateFontCursor(theDisplay, XC_exchange);
			    XAllocNamedColor(theDisplay,colormap,"green",&closest[0],&exact[0]);
			    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
			    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
			    XDefineCursor(theDisplay,can_xid,myCursor);
			    }
		    break;
	    case '{':
	    case '[':
	    case 'T':
	    case 't':
			    {
			    mode_pick = MODE_GRAB;
			    XmToggleButtonSetState(setting_mode_toggle_toggle, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_pick, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_erase, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_restore, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_grab, 1, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_info, 0, FALSE);

			    myCursor = XCreateFontCursor(theDisplay, XC_target);
			    XAllocNamedColor(theDisplay,colormap,"blue",&closest[0],&exact[0]);
			    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
			    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
			    XDefineCursor(theDisplay,can_xid,myCursor);
			    }
		    break;
	    case '}':
	    case ']':
	    case 'Y':
	    case 'y':
			    {
			    mode_pick = MODE_INFO;
			    XmToggleButtonSetState(setting_mode_toggle_toggle, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_pick, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_erase, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_restore, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_grab, 0, FALSE);
			    XmToggleButtonSetState(setting_mode_toggle_info, 1, FALSE);

			    myCursor = XCreateFontCursor(theDisplay, XC_target);
			    XAllocNamedColor(theDisplay,colormap,"blue",&closest[0],&exact[0]);
			    XAllocNamedColor(theDisplay,colormap,"coral",&closest[1],&exact[1]);
			    XRecolorCursor(theDisplay,myCursor,&closest[0],&closest[1]);
			    XDefineCursor(theDisplay,can_xid,myCursor);
			    }
		    break;
	    case '2':
	    case '@':
			    {
			    /* set the view mode */
			    mview_mode = VIEW_WATERFALL;
			    mbedit_set_viewmode(mview_mode);
			    XmToggleButtonSetState(toggleButton_view_waterfall, MB_YES, FALSE);
			    XmToggleButtonSetState(toggleButton_view_alongtrack, MB_NO, FALSE);
			    XmToggleButtonSetState(toggleButton_view_acrosstrack, MB_NO, FALSE);

			    /* replot the data */
			    status = mbedit_action_plot(mplot_width, mexager,
				    mx_interval, my_interval,
				    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
				    &nbuffer, &ngood, &icurrent, &mnplot);
			    }
		    break;
	    case '3':
	    case '#':
			    {
			    /* set the view mode */
			    mview_mode = VIEW_ALONGTRACK;
			    mbedit_set_viewmode(mview_mode);
			    XmToggleButtonSetState(toggleButton_view_waterfall, MB_NO, FALSE);
			    XmToggleButtonSetState(toggleButton_view_alongtrack, MB_YES, FALSE);
			    XmToggleButtonSetState(toggleButton_view_acrosstrack, MB_NO, FALSE);

			    /* replot the data */
			    status = mbedit_action_plot(mplot_width, mexager,
				    mx_interval, my_interval,
				    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
				    &nbuffer, &ngood, &icurrent, &mnplot);
			    }
		    break;
	    case '4':
	    case '$':
			    {
			    /* set the view mode */
			    mview_mode = VIEW_ACROSSTRACK;
			    mbedit_set_viewmode(mview_mode);
			    XmToggleButtonSetState(toggleButton_view_waterfall, MB_NO, FALSE);
			    XmToggleButtonSetState(toggleButton_view_alongtrack, MB_NO, FALSE);
			    XmToggleButtonSetState(toggleButton_view_acrosstrack, MB_YES, FALSE);

			    /* replot the data */
			    status = mbedit_action_plot(mplot_width, mexager,
				    mx_interval, my_interval,
				    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
				    &nbuffer, &ngood, &icurrent, &mnplot);
			    }
		    break;
	    default:
		    break;
	    } /* end of key switch */
       } /* end of key press events */

      /* Deal with KeyRelease events */
      if(event->xany.type == KeyRelease)
      {
      /* Get key pressed - buffer[0] */
      actual = XLookupString((XKeyEvent *)event,
		    buffer, 1, &keysym, NULL);

      /* process events */
      switch (buffer[0])
	    {
	    case 'G':
	    case 'g':
		    key_g_down = 0;
		    break;
	    case 'M':
	    case 'm':
	    case 'Z':
	    case 'z':
		    key_z_down = 0;
		    break;
	    case 'K':
	    case 'k':
	    case 'S':
	    case 's':
		    key_s_down = 0;
		    break;
	    case 'J':
	    case 'j':
	    case 'A':
	    case 'a':
		    key_a_down = 0;
		    break;
	    case 'L':
	    case 'l':
	    case 'D':
	    case 'd':
		    key_d_down = 0;
		    break;
	    default:
		    break;
	    } /* end of key switch */
       } /* end of key release events */

      /* Check for mouse pressed and not pressed and released. */
      if(event->xany.type == ButtonPress)
      {
	  /* If left mouse button is pushed then toggle, pick, erase, restore, grab, or info. */
	  if ((event->xbutton.button == 1 && mode_reverse_mouse == MB_NO)
		|| (event->xbutton.button == 3 && mode_reverse_mouse == MB_YES))
	    {
	    x_loc = event->xbutton.x;
	    y_loc = event->xbutton.y;
	    grab_mode = GRAB_START;

	    doit = 1;
	    while (doit)
		{

		if (mode_pick == MODE_TOGGLE)
		    status = mbedit_action_mouse_toggle(
			    x_loc, y_loc,
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		else if (mode_pick == MODE_PICK)
		    status = mbedit_action_mouse_pick(
			    x_loc, y_loc,
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		else if (mode_pick == MODE_ERASE)
		    status = mbedit_action_mouse_erase(
			    x_loc, y_loc,
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		else if (mode_pick == MODE_RESTORE)
		    status = mbedit_action_mouse_restore(
			    x_loc, y_loc,
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		else if (mode_pick == MODE_GRAB)
		    {
		    status = mbedit_action_mouse_grab(
		    	    grab_mode,
			    x_loc, y_loc,
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    if (status == MB_SUCCESS)
		    	grab_mode = GRAB_MOVE;
		    else
		    	grab_mode = GRAB_START;
		    }
		else if (mode_pick == MODE_INFO)
		    status = mbedit_action_mouse_info(
			    x_loc, y_loc,
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		if (status == 0)
			XBell(theDisplay,100);
		else if (key_z_down)
		    {
		    status = mbedit_action_bad_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    }
		else if (key_s_down)
		    {
		    status = mbedit_action_good_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    }
		else if (key_a_down)
		    {
		    if (mode_reverse_keys == MB_NO)
			status = mbedit_action_left_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    else
			status = mbedit_action_right_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    }
		else if (key_d_down)
		    {
		    if (mode_reverse_keys == MB_NO)
			status = mbedit_action_right_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    else
			status = mbedit_action_left_ping(
			    mplot_width,mexager,
			    mx_interval,my_interval,
			    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
			    &nbuffer,&ngood,&icurrent,&mnplot);
		    }

		    status = XQueryPointer(theDisplay,can_xid,
			    &root_return,&child_return,&root_x_return,
			    &root_y_return, &win_x, &win_y, &mask_return);

		    x_loc = win_x;
		    y_loc = win_y;

		    /* If the button is still pressed then read the location */
		    /* of the pointer and run the action mouse function again */
		    if (mode_reverse_mouse == MB_NO)
			{
			if ((mask_return & 256) == 256
			    && mode_pick != MODE_TOGGLE
			    && mode_pick != MODE_PICK)
			    doit = 1;
			else
			    doit = 0;
			}
		    else if (mode_reverse_mouse == MB_YES)
			{
			if ((mask_return & 1024) == 1024
			    && mode_pick != MODE_TOGGLE
			    && mode_pick != MODE_PICK)
			    doit = 1;
			else
			    doit = 0;
			}
		    else
		       doit = 0;

		    /* if grab on but mouse released, end grab */
		    if (grab_mode == GRAB_MOVE && doit == 0)
			{
			status = mbedit_action_mouse_grab(
		    		GRAB_END,
				x_loc, y_loc,
				mplot_width,mexager,
				mx_interval,my_interval,
				mplot_size,mshow_beammode, mshow_flagged,mshow_time,
				&nbuffer,&ngood,&icurrent,&mnplot);
			grab_mode = GRAB_START;
			}
		}

	    } /* end of left button events */

	    /* If middle mouse button is pushed then scroll in reverse. */
	    if(event->xbutton.button == 2)
	    {
	    if (key_g_down == 0)
	    	{
		    status = mbedit_action_step(-step,mplot_width,mexager,
				    mx_interval,my_interval,
				    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
				    &nbuffer,&ngood,&icurrent,&mnplot);
		    if (status == 0) XBell(theDisplay,100);
		}
	    else
	    	{
		    status = mbedit_action_step(-icurrent,mplot_width,mexager,
				    mx_interval,my_interval,
				    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
				    &nbuffer,&ngood,&icurrent,&mnplot);
		    if (status == 0) XBell(theDisplay,100);
		}
	    } /* end of middle button events */

	    /* If right mouse button is pushed then scroll forward. */
	  if ((event->xbutton.button == 3 && mode_reverse_mouse == MB_NO)
		|| (event->xbutton.button == 1 && mode_reverse_mouse == MB_YES))
	    {
	    if (key_g_down == 0)
	    	{
		    status = mbedit_action_step(step,mplot_width,mexager,
				    mx_interval,my_interval,
				    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
				    &nbuffer,&ngood,&icurrent,&mnplot);
		    if (status == 0) XBell(theDisplay,100);
		}
	    else
	    	{
		    status = mbedit_action_step(nbuffer-icurrent-1,mplot_width,mexager,
				    mx_interval,my_interval,
				    mplot_size,mshow_beammode,mshow_flagged,mshow_time,
				    &nbuffer,&ngood,&icurrent,&mnplot);
		    if (status == 0) XBell(theDisplay,100);
		}
	    } /* end of right button events */
      } /* end of button pressed events */
    } /* end of inputs from window */
} /* end do_event function */

/*--------------------------------------------------------------------*/

void
do_flag_view( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    status = mbedit_action_flag_view(
	    mplot_width,mexager,
	    mx_interval,my_interval,
	    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
	    &nbuffer,&ngood,&icurrent,&mnplot);
}

/*--------------------------------------------------------------------*/

void
do_unflag_view( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    status = mbedit_action_unflag_view(
	    mplot_width,mexager,
	    mx_interval,my_interval,
	    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
	    &nbuffer,&ngood,&icurrent,&mnplot);
}

/*--------------------------------------------------------------------*/

void
do_unflag_all( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    status = mbedit_action_unflag_all(
	    mplot_width,mexager,
	    mx_interval,my_interval,
	    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
	    &nbuffer,&ngood,&icurrent,&mnplot);
}

/*--------------------------------------------------------------------*/

void
do_next_buffer( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    int	    quit;

    /* turn off expose plots */
    expose_plot_ok = False;

    /* get next buffer */
    status = mbedit_action_next_buffer(hold_size,buffer_size,
		    mplot_width,mexager,
		    mx_interval,my_interval,
		    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
		    &ndumped,&nloaded,&nbuffer,
		    &ngood,&icurrent,&mnplot,&quit);
    if (status == 0) XBell(theDisplay,100);

    /* set widget values */
    do_setup_data();

    /* turn on expose plots */
    expose_plot_ok = True;

    /* quit if in GUI mode */
    if (quit)
	    exit(0);

}

/*--------------------------------------------------------------------*/

void
do_number_step( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    int	maxx;
    char	label[10];

    step = acs->value;

    /* if slider set to minimum value, half the value range;
	    if slider set to maximum value,  double the range */
    XtVaGetValues(slider_number_step,
		    XmNmaximum, &maxx,
		    NULL);
    if (step == 1 || step == maxx)
	    {
	    if (step == 1)
		    maxx = maxx/2;
	    else
		    maxx = 2*maxx;
	    if (maxx > plot_size_max)
		    maxx = plot_size_max;
	    if (maxx < 2)
		    maxx = 2;
	    XtVaSetValues(slider_number_step,
		    XmNmaximum, maxx,
		    NULL);
	    sprintf(label, "%d", maxx);
	    set_label_string(slider_number_max_step_label,
			    label);
	    }
}

/*--------------------------------------------------------------------*/

void
do_show_flagged( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mshow_flagged = XmToggleButtonGetState(toggleButton_show_flagged_on);

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
}

/*--------------------------------------------------------------------*/

void
do_view_mode( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    /* turn off all togglebuttons */
    XmToggleButtonSetState(toggleButton_view_waterfall, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_view_alongtrack, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_view_acrosstrack, MB_NO, FALSE);

    /* turn on the one that was clicked */
    XmToggleButtonSetState(w, MB_YES, FALSE);

    /* now set the data type id */
    if (w == toggleButton_view_waterfall)
	mview_mode = 0;
    else if (w == toggleButton_view_alongtrack)
	mview_mode = 1;
    else if (w == toggleButton_view_acrosstrack)
	mview_mode = 2;
    else
    	mview_mode = 0;

    /* reset scaling */
    status = mbedit_set_viewmode(mview_mode);

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
}

/*--------------------------------------------------------------------*/

void
do_show_time( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    /* turn off all togglebuttons */
    XmToggleButtonSetState(toggleButton_show_wideplot, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_time, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_interval, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_lon, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_latitude, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_heading, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_speed, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_depth, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_altitude, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_sonardepth, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_roll, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_pitch, MB_NO, FALSE);
    XmToggleButtonSetState(toggleButton_show_heave, MB_NO, FALSE);

    /* turn on the one that was clicked */
    XmToggleButtonSetState(w, MB_YES, FALSE);

    /* now set the data type id */
    if (w == toggleButton_show_wideplot)
	mshow_time = 0;
    else if (w == toggleButton_show_time)
	mshow_time = 1;
    else if (w == toggleButton_show_interval)
	mshow_time = 2;
    else if (w == toggleButton_show_lon)
	mshow_time = 3;
    else if (w == toggleButton_show_latitude)
	mshow_time = 4;
    else if (w == toggleButton_show_heading)
	mshow_time = 5;
    else if (w == toggleButton_show_speed)
	mshow_time = 6;
    else if (w == toggleButton_show_depth)
	mshow_time = 7;
    else if (w == toggleButton_show_altitude)
	mshow_time = 8;
    else if (w == toggleButton_show_sonardepth)
	mshow_time = 9;
    else if (w == toggleButton_show_roll)
	mshow_time = 10;
    else if (w == toggleButton_show_pitch)
	mshow_time = 11;
    else if (w == toggleButton_show_heave)
	mshow_time = 12;
    else
    	mshow_time = 0;

    /* reset scaling */
    status = mbedit_set_scaling(mb_borders, mshow_time);

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
}

/*--------------------------------------------------------------------*/

void
do_reverse_mouse( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_reverse_mouse = XmToggleButtonGetState(toggleButton_reverse_mouse);
}

/*--------------------------------------------------------------------*/

void
do_reverse_keys( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mode_reverse_keys = XmToggleButtonGetState(toggleButton_reverse_keys);
}

/*--------------------------------------------------------------------*/

void
do_show_flags( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mshow_beammode = BEAM_MODE_FLAG;
    XmToggleButtonSetState(toggleButton_show_flags, TRUE, FALSE);
    XmToggleButtonSetState(toggleButton_show_detects, FALSE, FALSE);
    XmToggleButtonSetState(toggleButton_show_pulsetypes, FALSE, FALSE);

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	mx_interval, my_interval,
	mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	&nbuffer, &ngood, &icurrent, &mnplot);
}

/*--------------------------------------------------------------------*/

void
do_show_detects( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mshow_beammode = BEAM_MODE_DETECT;
    XmToggleButtonSetState(toggleButton_show_flags, FALSE, FALSE);
    XmToggleButtonSetState(toggleButton_show_detects, TRUE, FALSE);
    XmToggleButtonSetState(toggleButton_show_pulsetypes, FALSE, FALSE);

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	mx_interval, my_interval,
	mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	&nbuffer, &ngood, &icurrent, &mnplot);
}

/*--------------------------------------------------------------------*/

void
do_show_pulsetypes( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    mshow_beammode = BEAM_MODE_PULSE;
    XmToggleButtonSetState(toggleButton_show_flags, FALSE, FALSE);
    XmToggleButtonSetState(toggleButton_show_detects, FALSE, FALSE);
    XmToggleButtonSetState(toggleButton_show_pulsetypes, TRUE, FALSE);

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	mx_interval, my_interval,
	mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	&nbuffer, &ngood, &icurrent, &mnplot);
}


/*--------------------------------------------------------------------*/

void
do_buffer_hold( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    hold_size = acs->value;
}

/*--------------------------------------------------------------------*/

void
do_buffer_size( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    buffer_size = acs->value;

}

/*--------------------------------------------------------------------*/

void
do_done( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    int	quit;

    /* turn off expose plots */
    expose_plot_ok = False;

    /* close the file */
    status = mbedit_action_done(buffer_size,&ndumped,&nloaded,
		    &nbuffer,&ngood,&icurrent,&quit);
    if (status == 0) XBell(theDisplay,100);

    /* if there is another file in the list open it */
    if (currentfile >= 0 && currentfile < numfiles - 1)
    	{
	do_load_specific_file(currentfile + 1);
	}

    /* else do not open a file */
    else
    	{
	currentfile = -1;
	}

    /* turn on expose plots */
    expose_plot_ok = True;

    if (quit)
	    exit(0);

    /* set widget values */
    do_setup_data();
}


/*--------------------------------------------------------------------*/

void
do_number_pings( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmScaleCallbackStruct *acs=(XmScaleCallbackStruct*)call_data;

    int	maxx;
    char	label[10];

    /* Read the value of the slider bar for number of pings displayed */
    mplot_size = acs->value;

    /* if slider set to minimum value, half the value range;
	    if slider set to maximum value,  double the range */
    XtVaGetValues(slider_number_pings,
		    XmNmaximum, &maxx,
		    NULL);
    if (mplot_size == 1 || mplot_size == maxx)
	    {
	    if (mplot_size == 1)
		    maxx = maxx/2;
	    else
		    maxx = 2*maxx;
	    if (maxx > plot_size_max)
		    maxx = plot_size_max;
	    if (maxx < 2)
		    maxx = 2;
	    XtVaSetValues(slider_number_pings,
		    XmNmaximum, maxx,
		    NULL);
	    sprintf(label, "%d", maxx);
	    set_label_string(slider_num_pings_max_label,
			    label);
	    }

    /* replot the data */
    status = mbedit_action_plot(mplot_width, mexager,
	    mx_interval, my_interval,
	    mplot_size, mshow_beammode, mshow_flagged, mshow_time,
	    &nbuffer, &ngood, &icurrent, &mnplot);
    if (status == 0) XBell(theDisplay,100);
}

/*--------------------------------------------------------------------*/

void
do_goto_apply( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

    char    value_text[MB_PATH_MAXLINE];

    get_text_string(textfield_year, value_text);
    sscanf(value_text, "%d", &ttime_i[0]);

    get_text_string(textfield_month, value_text);
    sscanf(value_text, "%d", &ttime_i[1]);

    get_text_string(textfield_day, value_text);
    sscanf(value_text, "%d", &ttime_i[2]);

    get_text_string(textfield_hour, value_text);
    sscanf(value_text, "%d", &ttime_i[3]);

    get_text_string(textfield_minute, value_text);
    sscanf(value_text, "%d", &ttime_i[4]);

    get_text_string(textfield_second, value_text);
    sscanf(value_text, "%d", &ttime_i[5]);

    ttime_i[6] = 0;

    /* turn off expose plots */
    expose_plot_ok = False;

    status = mbedit_action_goto(ttime_i,hold_size,buffer_size,
		    mplot_width,mexager,
		    mx_interval,my_interval,
		    mplot_size,mshow_beammode, mshow_flagged,mshow_time,
		    &ndumped,&nloaded,&nbuffer,
		    &ngood,&icurrent,&mnplot);
    if (status == 0) XBell(theDisplay,100);

    /* turn on expose plots */
    expose_plot_ok = True;
}
/*--------------------------------------------------------------------*/

void
do_set_filters( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;
	int	ival;

	/* get values of median spike filter widgets */
 	f_medianspike = XmToggleButtonGetState(toggleButton_filters_medianspike);
	XtVaGetValues(scale_filters_medianspike,
		XmNvalue, &f_medianspike_threshold,
		NULL);
	XtVaGetValues(scale_median_local_xtrack,
		XmNvalue, &f_medianspike_xtrack,
		NULL);
	XtVaGetValues(scale_median_local_ltrack,
		XmNvalue, &f_medianspike_ltrack,
		NULL);

	/* get values of wrong side filter widgets */
 	f_wrongside = XmToggleButtonGetState(toggleButton_filters_wrongside);
	XtVaGetValues(scale_filters_wrongside,
		XmNvalue, &f_wrongside_threshold,
		NULL);

	/* get values of cut by beam number filter widgets */
 	f_cutbeam = XmToggleButtonGetState(toggleButton_filters_cutbeam);
	XtVaGetValues(scale_filters_cutbeamstart,
		XmNvalue, &f_cutbeam_begin,
		NULL);
	XtVaGetValues(scale_filters_cutbeamend,
		XmNvalue, &f_cutbeam_end,
		NULL);

	/* get values of cut by distance filter widgets */
 	f_cutdistance = XmToggleButtonGetState(toggleButton_filters_cutdistance);
	XtVaGetValues(scale_filters_cutdistancestart,
		XmNvalue, &ival,
		NULL);
	f_cutdistance_begin = 0.01 * ival;
	XtVaGetValues(scale_filters_cutdistanceend,
		XmNvalue, &ival,
		NULL);
	f_cutdistance_end = 0.01 * ival;

	/* get values of cut by angle filter widgets */
 	f_cutangle = XmToggleButtonGetState(toggleButton_filters_cutangle);
	XtVaGetValues(scale_filters_cutanglestart,
		XmNvalue, &ival,
		NULL);
	f_cutangle_begin = 0.01 * ival;
	XtVaGetValues(scale_filters_cutangleend,
		XmNvalue, &ival,
		NULL);
	f_cutangle_end = 0.01 * ival;

	/* set some values in mbedit */
	status = mbedit_set_filters(f_medianspike,
			f_medianspike_threshold,
			f_medianspike_xtrack,
			f_medianspike_ltrack,
			f_wrongside,
			f_wrongside_threshold,
			f_cutbeam,
			f_cutbeam_begin, f_cutbeam_end,
			f_cutdistance,
			f_cutdistance_begin, f_cutdistance_end,
			f_cutangle,
			f_cutangle_begin, f_cutangle_end);

    	status = mbedit_action_filter_all(
	     	mplot_width,mexager,
	    	mx_interval,my_interval,
	    	mplot_size,mshow_beammode, mshow_flagged,mshow_time,
	    	&nbuffer,&ngood,&icurrent,&mnplot);
}

/*--------------------------------------------------------------------*/

void
do_reset_filters( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

	/* get filter values and set widgets */
	do_get_filters();
}

/*--------------------------------------------------------------------*/

void
do_check_median_xtrack( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

	XtVaGetValues(scale_median_local_xtrack,
		XmNvalue, &f_medianspike_xtrack,
		NULL);
	if (f_medianspike_xtrack %2 == 0)
	    f_medianspike_xtrack++;
	XtVaSetValues(scale_median_local_xtrack,
			XmNvalue, f_medianspike_xtrack,
			NULL);
}

/*--------------------------------------------------------------------*/

void
do_check_median_ltrack( Widget w, XtPointer client_data, XtPointer call_data)
{
    XmAnyCallbackStruct *acs;
    acs = (XmAnyCallbackStruct*)call_data;

	XtVaGetValues(scale_median_local_ltrack,
		XmNvalue, &f_medianspike_ltrack,
		NULL);
	if (f_medianspike_ltrack % 2 == 0)
	    f_medianspike_ltrack++;
	XtVaSetValues(scale_median_local_ltrack,
			XmNvalue, f_medianspike_ltrack,
			NULL);
}

/*--------------------------------------------------------------------*/
/*--------------------------------------------------------------------*/

int
do_wait_until_viewed(XtAppContext app)
{
    Widget  topshell;
    Window  topwindow;
    XWindowAttributes	xwa;
    XEvent  event;

    /* set app_context */
    app_context = app;

    /* find the top level shell */
    for (topshell = window_mbedit;
	    !XtIsTopLevelShell(topshell);
	    topshell = XtParent(topshell))
	;

    /* keep processing events until it is viewed */
    if (XtIsRealized(topshell))
	{
	topwindow = XtWindow(topshell);

	/* wait for the window to be mapped */
	while (XGetWindowAttributes(
			XtDisplay(window_mbedit),
			topwindow, &xwa)
		&& xwa.map_state != IsViewable)
	    {
	    XtAppNextEvent(app_context, &event);
	    XtDispatchEvent(&event);
	    }
	}

    XmUpdateDisplay(topshell);

    return(1);

}
/*------------------------------------------------------------------------------*/

int do_mbedit_settimer()
{
	int	status = MB_SUCCESS;
	int	timer_timeout_time = 1000;
	int	id;

	/* set timer function if none set for this instance */
	if (timer_function_set == MB_NO)
		{
		id =  XtAppAddTimeOut(app_context,
				(unsigned long) timer_timeout_time,
				(XtTimerCallbackProc)do_mbedit_workfunction,
				(XtPointer) -1);
		if (id > 0)
			timer_function_set = MB_YES;
		else
			status = MB_FAILURE;
		}

/* else
fprintf(stderr,"do_mbedit_settimer: FUNCTION ALREADY SET!!\n"); */

	return(status);
}

/*------------------------------------------------------------------------------*/

int do_mbedit_workfunction(XtPointer client_data)
{
	int	status = MB_SUCCESS;

	timer_function_set = MB_NO;

	/* reset filelist */
	if (numfiles > 0 && expose_plot_ok == True)
		{
		do_build_filelist();
		}

	/* reset the timer function */
	do_mbedit_settimer();

	return(status);
}

/*--------------------------------------------------------------------*/
/* Message and error dialogs */
/*--------------------------------------------------------------------*/

int
do_message_on(char *message)
{
    Widget  diashell, topshell;
    Window  diawindow, topwindow;
    XWindowAttributes	xwa;
    XEvent  event;

    set_label_string(label_message, message);
    XtManageChild(bulletinBoard_message);

    /* force the label to be visible */
    for (diashell = label_message;
	    !XtIsShell(diashell);
	    diashell = XtParent(diashell))
	;
    for (topshell = diashell;
	    !XtIsTopLevelShell(topshell);
	    topshell = XtParent(topshell))
	;
    if (XtIsRealized(diashell) && XtIsRealized(topshell))
	{
	diawindow = XtWindow(diashell);
	topwindow = XtWindow(topshell);

	/* wait for the dialog to be mapped */
	while (XGetWindowAttributes(display, diawindow, &xwa)
		&& xwa.map_state != IsViewable)
	    {
	    if (XGetWindowAttributes(display, topwindow, &xwa)
		    && xwa.map_state != IsViewable)
		break;

	    XtAppNextEvent(app_context, &event);
	    XtDispatchEvent(&event);
	    }
	}

    XmUpdateDisplay(topshell);

    return(1);
}

/*--------------------------------------------------------------------*/

int
do_message_off()
{
    XtUnmanageChild(bulletinBoard_message);
    XSync(XtDisplay(bulletinBoard_message), 0);
    XmUpdateDisplay(window_mbedit);

    return(1);
}

/*--------------------------------------------------------------------*/

int
do_error_dialog(char *s1, char *s2, char *s3)
{
    set_label_string(label_error_one, s1);
    set_label_string(label_error_two, s2);
    set_label_string(label_error_three, s3);
    XtManageChild(bulletinBoard_error);
    XBell(theDisplay,100);
/* fprintf(stderr,"do_error_dialog:\n\t%s\n\t%s\n\t%s\n",s1,s2,s3); */

    return(1);
}

/*--------------------------------------------------------------------*/
/* Change label string cleanly, no memory leak */
/*--------------------------------------------------------------------*/

void set_label_string(Widget w, String str)
{
    XmString xstr;

    xstr = XmStringCreateLocalized( str );
    if ( xstr != NULL )
	XtVaSetValues(w,
	    XmNlabelString, xstr,
	    NULL);
    else
	XtWarning("Failed to update labelString");

    XmStringFree( xstr );
}
/*--------------------------------------------------------------------*/
/* Change multiline label string cleanly, no memory leak */
/*--------------------------------------------------------------------*/

void set_label_multiline_string(Widget w, String str)
{
    XmString xstr;
    Boolean      argok;

    xstr = (XtPointer)BX_CONVERT(w, str, XmRXmString, 0, &argok);
    if ( xstr != NULL && argok)
        XtVaSetValues(w,
            XmNlabelString, xstr,
            NULL);
    else
        XtWarning("Failed to update labelString");

    XmStringFree( xstr );
}
/*--------------------------------------------------------------------*/
/* Get text item string cleanly, no memory leak */
/*--------------------------------------------------------------------*/

void get_text_string(Widget w, String str)
{
    char	*str_tmp;

    str_tmp = (char *) XmTextGetString(w);
    strcpy(str, str_tmp);
    XtFree(str_tmp);
}

/*--------------------------------------------------------------------*/
