#include <stdio.h>
#ifdef __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif

#include <X11/Xos.h>
#include <X11/cursorfont.h>
#include <Xm/CascadeB.h>
#include <Xm/FileSB.h>
#include <Xm/MainW.h>
#include <Xm/Form.h>
#include <Xm/Frame.h>
#include <Xm/PushB.h>
#include <Xm/PushBG.h>
#include <Xm/SeparatoG.h>
#include <Xm/RowColumn.h>
#include <Xm/LabelG.h>
#include <Xm/List.h>
#include <Xm/Text.h>
#include <Xm/ToggleBG.h>
#include <Xm/MwmUtil.h>         /* added by rlr */
#include <stdlib.h>
#include <string.h>
#include <ctype.h>		/* isspace */
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>		/* also for getwd on non-POSIX systems */

/*****
* Change this to change the application class of the examples
*****/
#define APP_CLASS		"HTMLDemos"

/*****
* We want to have the full XmHTML instance definition available 
* when debugging this stuff, so include XmHTMLP.h
* Note:
* 	Including XmHTMLP.h normally doesn't pull in any of the internal XmHTML
*	functions. If you want to do this anyway, you need to include *both*
*	XmHTMLP.h and XmHTMLI.h (in that order).
* Note:
*	When being compiled with the provided or imake generated Makefile, the
*	symbol VERSION is defined. This is a private define which must not be used
*	when compiling applications: it sets other defines which pull in
*	other, private, header files normally not present after installation
*	of the library. Therefore we undefine this symbol *before* including
*	the XmHTMLP.h header file. This is not required when XmHTML.h is used.
*****/
#if defined(VERSION)
#undef VERSION
#endif /* VERSION */
#include <XmHTML/XmHTMLP.h>

#include "../src/debug.h"		/* we want to be able to enable debugging */

/* imagecache stuff */
#include "cache.h"

/* catch NULL strdup's for debug builds */
#if defined(DEBUG) && !defined(DMALLOC)
extern char *__rsd_strdup(const char *s1, char *file, int line);
#define strdup(PTR) __rsd_strdup(PTR, __FILE__, __LINE__)
#endif

#ifdef NEED_STRCASECMP
# include <sys/types.h>
extern int my_strcasecmp(const char *s1, const char *s2);
extern int my_strncasecmp(const char *s1, const char *s2, size_t n);
#define strcasecmp(S1,S2) my_strcasecmp(S1,S2)
#define strncasecmp(S1,S2,N) my_strncasecmp(S1,S2,N)
#endif

/*** External Function Prototype Declarations ***/
/* from visual.c */
extern int getStartupVisual(Widget shell, Visual **visual, int *depth,
	Colormap *colormap);

/* can be found in XmHTML */
extern char *my_strcasestr(const char *s1, const char *s2);

/* from misc.c */
extern int parseFilename(char *fullname, char *filename, char *pathname);
extern void XMessage(Widget widget, String msg);

#ifdef DEBUG
extern void _XmHTMLUnloadFonts(XmHTMLWidget);
extern void _XmHTMLAddDebugMenu(Widget, Widget, String);
#endif

/*** Public Variable Declarations ***/

/*** Private Datatype Declarations ****/
#define MAX_HISTORY_ITEMS	100		/* save up to this many links */
#define MAX_PATHS			25		/* size of visited path cache */
#define MAX_IMAGE_ITEMS		512		/* max. no of images per document */
#define MAX_HTML_WIDGETS	10		/* max. no of HTML widgets allowed */

#define FILE_OPEN			1
#define FILE_RELOAD			2
#define FILE_SAVEAS			3
#define FILE_RAISE			5
#define FILE_LOWER			6
#define FILE_INFO			7
#define FILE_VIEW_SOURCE	8
#define FILE_VIEW_FONTCACHE	9
#define FILE_QUIT			10

/* Link defines */
#define LINK_MADE			0
#define LINK_HOMEPAGE		1
#define LINK_TOC			2
#define LINK_INDEX			3
#define LINK_GLOSSARY		4
#define LINK_COPYRIGHT		5
#define LINK_PREVIOUS		6
#define LINK_UP				7
#define LINK_DOWN			8
#define LINK_NEXT			9
#define LINK_HELP			10
#define LINK_LAST			11

/* options menu toggle buttons defines. These may *not* be changed */
#define OPTIONS_ANCHOR_BUTTONS			0
#define OPTIONS_HIGHLIGHT_ON_ENTER		1
#define OPTIONS_ENABLE_STRICT_HTML32	2
#define OPTIONS_ENABLE_BODYCOLORS		3
#define OPTIONS_ENABLE_BODYIMAGES		4
#define OPTIONS_ENABLE_DOCUMENT_COLORS	5
#define OPTIONS_ENABLE_DOCUMENT_FONTS	6
#define OPTIONS_ENABLE_OUTLINING		7
#define OPTIONS_DISABLE_WARNINGS		8
#define OPTIONS_FREEZE_ANIMATIONS		9
#define OPTIONS_AUTO_IMAGE_LOAD			10
#define OPTIONS_FANCY_TRACKING			11
#define OPTIONS_ENABLE_IMAGES			12
#define OPTIONS_LAST					13

/* options menu pushbutton defines */
#define OPTIONS_ANCHOR		20
#define OPTIONS_FONTS		21
#define OPTIONS_BODY		22
#define OPTIONS_IMAGE		23

/* document cache */
typedef struct{
	String path;		/* path to this document */
	String file;		/* full filename of this document */
	int current_ref;	/* last activated hyperlink */
	int nrefs;			/* total no of activated hyperlinks in this document */
	String refs[MAX_HISTORY_ITEMS];	/* list of activated hyperlinks */
	String visited[MAX_HISTORY_ITEMS];	/* list of visited hyperlins */
	int nvisited;		/* total no of visited hyperlinks */
	int nimages;		/* no of images in this document */
	String images[MAX_IMAGE_ITEMS];	/* image urls for this document */
}DocumentCache;

/* List of all HTML widgets (especially for frames) */
typedef struct{
	Boolean active;		/* is this an active frame? */
	Boolean used;		/* is this frame currently being used? */
	String name;		/* name of this frame */
	String src;			/* source file for this frame */
	Widget html;		/* XmHTMLWidget id for this frame */
}HTMLWidgetList;

#define MIME_HTML			0		/* text/html */
#define MIME_HTML_PERFECT	1		/* text/html-perfect */
#define MIME_IMAGE			2		/* image/whatever */
#define MIME_PLAIN			3		/* text/plain/unknown */
#define MIME_IMG_UNSUP		4		/* unsupported image type */
#define MIME_ERR			5		/* some error occured */
  
typedef struct{
	int link_type;		/* 0 = rev, 1 = rel, which means fetch it */
	Boolean have_data;
	String href;
	String title;
}documentLinks;

typedef struct{
	Widget w;
	String name;
	Boolean value;
}optionsStruct;

/*** Private Function Prototype Declarations ****/
static DocumentCache *getDocFromCache(String file);
static void storeDocInCache(String file);
static void storeInHistory(String file, String loc);
static void storeAnchor(String href);
static void removeDocFromCache(int doc);
static void flushImages(Widget w);
static void killImages(void);

static void HelloScreen(char *use_file, Window parent);
void Done(XtPointer client_data, XtIntervalId *id);

/* XmHTMLWidget callbacks */
static void anchorCB(Widget w, XtPointer arg1, XmHTMLAnchorPtr href_data);
static void docCB(Widget w, XtPointer arg1, XmHTMLDocumentPtr cbs);
static void linkCB(Widget w, XtPointer arg1, XmHTMLLinkPtr cbs);
static void frameCB(Widget w, XtPointer arg1, XmHTMLFramePtr cbs);
static String collapseURL(String url);
static void infoCB(Widget parent, Widget popup, XButtonPressedEvent *event);

/* XmHTMLWidget functions */
static XmImageInfo *loadImage(Widget w, String url);
static int testAnchor(Widget w, String href);
static void jumpToFrame(String filename, String loc, String target,
	Boolean store);
static int getImageData(XmHTMLPLCStream *stream, XtPointer buffer);
static void endImageData(XmHTMLPLCStream *stream, XtPointer data, int type,
	Boolean ok);

/* Menu and button bar callbacks */
static void linkButtonCB(Widget w, XtPointer arg1, XtPointer arg2);
static void docInfoCB(Boolean font_only);
static void historyCB(Widget w, int button);
static void progressiveButtonCB(Widget w, int reset);
static void optionsCB(Widget w, int item);
static void showImageInfo(XmImageInfo *info);

/*** Private Variable Declarations ***/
static XtAppContext context;
static Widget back, forward, load_images, label, toplevel = NULL, reload;
static Widget link_button, link_dialog, html32, verified, info_dialog;
static Widget prg_button, image_dialog;
static documentLinks document_links[LINK_LAST];
static XmImage *preview_image;
static Widget link_buttons[LINK_LAST];
static char default_font[128], current_font[128];
static char default_charset[128], current_charset[128];
static String link_labels[LINK_LAST] = {"Mail Author", "Home", "TOC",
	"Index", "Glossary", "Copyright", "Prev", "Up", "Down", "Next",
	"Help"};
static String image_types[] = {"(error occured)", "Unknown Image type",
	"X11 Pixmap", "X11 Bitmap", "CompuServe(C) Gif87a or Gif89a",
	"Animated Gif89a", "Animated Gif89a with NETSCAPE2.0 loop extension",
	"CompuServe(C) Compatible Gzf87a or Gzf89a", "Gif89a Compatible animation",
	"Gif89a compatible animation with NETSCAPE2.0 loop extension",
	"JPEG", "PNG", "Fast Loadable Graphic"};

/*****
* global XmHTML configuration. Elements must be in the same order as the
* OPTIONS_ defines above.
*****/
static optionsStruct html_config[OPTIONS_LAST] = {
	{ NULL, XmNanchorButtons, True },
	{ NULL, XmNhighlightOnEnter, True },
	{ NULL, XmNstrictHTMLChecking, False },
	{ NULL, XmNenableBodyColors, True },
	{ NULL, XmNenableBodyImages, True },
	{ NULL, XmNenableDocumentColors, True },
	{ NULL, XmNenableDocumentFonts, True },
	{ NULL, XmNenableOutlining, True },
	{ NULL, XmNenableBadHTMLWarnings, True },
	{ NULL, XmNfreezeAnimations, False },
	{ NULL, "autoImageLoad", True },
	{ NULL, "fancyMouseTracking", False },
	{ NULL, XmNimageEnable, True },
};

/* Command line options */
static Boolean root_window, noframe, external_client;
static Boolean progressive_images, allow_exec;
static int animation_timeout = 175;
#define MAX_PROGRESSIVE_DATA_SKIP	2048

static int progressive_data_skip = MAX_PROGRESSIVE_DATA_SKIP;
static int progressive_data_inc  = 0;

#ifdef DEBUG
static Boolean debug = False;
#define Debug(MSG) do { \
	if(debug) { printf MSG ; fflush(stdout); } }while(0)
#else
#define Debug(MSG)	/* emtpy */
#endif

static String usage = {"Options:\n"
"\t-allow_exec        : honor href=\"exec:\" or href=\"xexec:\"\n"
"\t-animation_timeout : animation timeout in milliseconds. Default is 175\n"
#ifdef DEBUG
"\t-debug             : enable application debug output\n"
#endif
"\t-images_delayed    : delay image loading\n"
"\t-netscape          : fire netscape for unsupported URL's\n"
"\t-noframe           : don't put a frame around the HTML display area\n"
"\t-root              : act as root window\n"
"\t-progressive       : load images progressively (only GZF for now)\n"
"\t-prg_skip [num]    : progressive data skip. Default is 2048\n"
"\t-prg_inc [num]     : progressive data increment. Resets prg_skip to 256.\n"
"\t                     Using this option overrides any prg_skip value.\n"
"\t-h, --help         : print this help\n"};

/* document cache */
static DocumentCache doc_cache[MAX_HISTORY_ITEMS];
static int current_doc, last_doc;

/*****
* List of all html widgets. The first slot is the toplevel HTML widget and
* is never freed. All other slots are used by frames.
*****/
static HTMLWidgetList html_widgets[MAX_HTML_WIDGETS];

/* visited paths */
static String paths[MAX_PATHS][1024];
static int max_paths;

/* default settings */
static String appFallbackResources[] = {
"*fontList:               *-adobe-helvetica-bold-r-*-*-*-120-*-*-p-*-*-*",
"*useColorObj:            False",
"*usePrivateColormap:     True",
NULL};


static void readPipe( Widget w, char *cmd )
{
    FILE *fd;
    char *buf=NULL;
    int i;
    int val, offset;

    fd = popen(cmd, "r");
    fflush(fd);

    offset = 0;
    val = 0;

    buf = calloc(522, sizeof(char));
    strcpy(buf, "<html><body>\n");
    offset += strlen(buf);
    val = fread(buf+offset, 1, 512, fd);
    offset += 512;

    if (val == 512)
    {
        buf = realloc(buf, offset+512);
        while ((val = fread(buf+offset, 1,512, fd)) == 512)
        {
            offset += 512;
            buf = realloc(buf, offset+512);
        }
    }
    pclose(fd);

    buf = realloc(buf, strlen(buf)+20);
    strcat(buf, "\n</body></html>\n");

    XmHTMLTextSetString(w, buf);
    free(buf);
}


/*****
* Name: 		setBusy
* Return Type: 	void
* Description: 	changes the cursor from or to a stopwatch to indicate we are
*				busy doing something lengthy processing which can't be
*				interrupted.
* In: 
*	state:		True to display the cursor as busy, False to display the
*				normal cursor.
* Returns:
*	nothing.
*****/
static void
setBusy(Boolean state)
{
	static Boolean busy;
	static Cursor cursor;
	Display *display = XtDisplay(toplevel);

	if(!cursor)
	{
		cursor = XCreateFontCursor(display, XC_watch);
		busy = False;
	}
	if(busy != state)
	{
		busy = state;
		if(busy)
			XDefineCursor(display, XtWindow(toplevel), cursor);
		else
			XUndefineCursor(display, XtWindow(toplevel));
	}
	XFlush(display);
}

/*****
* Name: 		addPath
* Return Type: 	void
* Description: 	adds a path to the list of visited paths if it hasn't been
*				stored yet.
* In: 
*	path:		path to be stored;
* Returns:
*	nothing.
*****/
static void
addPath(String path)
{
	int i = 0;

	/* see if the path has already been added */
	for(i = 0; i < max_paths; i++)
		if(!(strcmp((char*)(paths[i]), path)))
			return;

	/* store this path */
	if(max_paths < MAX_PATHS)
	{
		strcpy((char*)(paths[max_paths]), path);
		max_paths++;
	}
}

/*****
* Follow symbolic links (if any) to translate filename into the name of the
* real file that it represents.  Returns TRUE if the call was successful,
* meaning the links were translated successfully, or the file was not 
* linked to begin with (or there was no file).  Returns false if some
* error prevented the call from determining if there were symbolic links
* to process, or there was an error in processing them.  The error
* can be read from the unix global variable errno.
*****/
Boolean
followSymLinks(String filename)
{
	/*****
	* FIXME
	*
	* readlink doesn't seem to do anything at all on Linux 2.0.27,
	* libc 5.3.12
	*****/
	int cc;
	char buf[1024];

	cc = readlink(filename, buf, 1024);
	if (cc == -1) 
	{
#ifdef __sgi
    		if (errno == EINVAL || errno == ENOENT || errno == ENXIO)
#else
    		if (errno == EINVAL || errno == ENOENT)
#endif
/* no error, just not a symbolic link, or no file */
				return(True);
    		else
				return(False);
	} 
	else
	{
		buf[cc] = '\0';
		strcpy(filename, buf);
		return(True); 
	}
}   

/*****
* Name: 		resolveFile
* Return Type: 	String
* Description: 	checks if the given file exists on the local file system
* In: 
*	filename:	file to check
* Returns:
*	a full filename when the file exists. NULL if it doesn't.
* Note:
*	This routine tries three things to check if a file exists on the local
*	file system:
*	1. if "filename" is absolute, it is assumed the file exists and is
*	   accessible;
*	2. checks whether "filename" can be found in the path of the current
*	   document;
*	3. sees if "filename" can be found in the list of stored paths.
*	When a file has been found, it is checked if this is a regular file,
*	and if so it is transformed into a fully qualified pathname (with
*	relative paths fully resolved).
*****/
static String
resolveFile(String filename)
{
	static String ret_val;
	char tmp[1024];

	/* throw out http:// stuff */
	if(!(strncasecmp(filename, "http://", 7)))
		return(NULL);

	Debug(("resolveFile, looking for %s\n", filename));

	ret_val = NULL;

	/*****
	* If this is an absolute path, check if it's really a valid file
	* (or directory). This allows us to recognize chrooted files when
	* browsing the local web directory.
	*****/
	if(filename[0] == '/')
	{
		if(!(access(filename, R_OK)))
			ret_val = strdup(filename); 
		else	/* a fake path, strip of the leading / */
			sprintf(tmp, "%s", &filename[1]);
	}
	else
	{
		strcpy(tmp, filename);
		tmp[strlen(filename)] = '\0';	/* NULL terminate */
	}

	if(ret_val == NULL)
	{
		char real_file[1024];
		int i;

		/*****
		* search the paths visited so far. Do it top to bottom as the
		* last visited path is inserted in the last slot. Quite usefull
		* when looking for images or links in the current document.
		*****/
		for(i = max_paths-1; i >= 0 ; i--)
		{
			sprintf(real_file, "%s%s", (char*)(paths[i]), tmp);

			/* check if we have access to this thing */
			if(!(access(real_file, R_OK)))
			{
				struct stat statb;
				/*****
				* We seem to have some access rights, make sure this
				* is a regular file
				*****/
				if(stat(real_file, &statb) == -1)
				{
					perror(filename);
					break;
				}
				else if(S_ISDIR(statb.st_mode))
				{
					/*****
					* It's a dir. First check for index.html then
					* for Welcome.html.
					*****/
					int len = strlen(real_file)-1;

					strcat(real_file, real_file[len] == '/' ?
						"index.html\0" : "/index.html\0");
					if(!(access(real_file, R_OK)))
					{
						ret_val = strdup(real_file);
						break;
					}
					real_file[len+1] = '\0';
					strcat(real_file, real_file[len] == '/' ?
						"Welcome.html\0" : "/Welcome.html\0");
					if(!(access(real_file, R_OK)))
					{
						ret_val = strdup(real_file);
						break;
					}
					/* no file in here, too bad */
					break;
				}
				else if(!S_ISREG(statb.st_mode))
				{
					fprintf(stderr, "%s: not a regular file\n", filename);
					break;
				}
				ret_val = strdup(real_file);
				break;
			}
		}
	}

	if(ret_val == NULL)
	{
		sprintf(tmp, "%s:\ncannot display: unable to locate file.", filename);
		XMessage(toplevel, tmp);
	}
	else
	{
		/* clean out relative path stuff and add the path to the path index. */
		char fname[1024], pname[1024];

		(void)parseFilename(ret_val, fname, pname);
		addPath(pname);

		/*
		* resolve symbolic links as well (prevents object cache from going
		* haywire by having two different objects with cross-linked
		* mappings)
		*/
#if 0
		(void)followSymLinks(pname);
#endif
		/*****
		* big chance parseFilename compressed relative paths out of ret_val,
		* do it again. We need to reallocate as the size of the fully
		* resolved path can exceed the current length.
		*****/
		ret_val = (String)realloc(ret_val, strlen(pname) + strlen(fname) + 1);
		sprintf(ret_val, "%s%s", pname, fname);
	}

	Debug(("resolveFile, found as %s\n", ret_val ? ret_val : "(not found)"));
	return(ret_val);
}

/*****
* Name: 		getMimeType
* Return Type: 	int
* Description: 	make a guess at the mime type of a document by looking at
*				the extension of the given document.
* In: 
*	file:		file for which to get a mime-type;
* Returns:
*	mime type of the given file.
*****/
static int
getMimeType(String file)
{
	String chPtr;
	unsigned char img_type;

	if((chPtr = strstr(file, ".")) != NULL)
	{
		String start;

		/* first check if this is plain HTML or not */
		for(start = &file[strlen(file)-1]; *start && *start != '.'; start--);

		if(!strcasecmp(start, ".html") || !strcasecmp(start, ".htm"))
			return(MIME_HTML);
		if(!strcasecmp(start, ".htmlp"))
			return(MIME_HTML_PERFECT);
	}

	/* something else then? */
	/* check if this is an image XmHTML knows of */
	if((img_type = XmHTMLImageGetType(file, NULL, 0)) == IMAGE_ERROR)
		return(MIME_ERR);

	/*****
	* Not an image we know of, get first line in file and see if it's
	* html anyway
	*****/
	if(img_type == IMAGE_UNKNOWN)
	{
		FILE *fp;
		char buf[128];

		/* open file */
		if((fp = fopen(file, "r")) == NULL)
			return(MIME_ERR);

		/* read first line in file */
		if((chPtr = fgets(buf, 128, fp)) == NULL)
		{
			/* close again */
			fclose(fp);
			return(MIME_ERR);
		}
		/* close again */
		fclose(fp);

		/* see if it contains any of these strings */
		if(my_strcasestr(buf, "<!doctype") || my_strcasestr(buf, "<html") ||
			my_strcasestr(buf, "<head") || my_strcasestr(buf, "<body") ||
			my_strcasestr(buf, "<!--"))
			return(MIME_HTML);
		/* we don't know it */
		return(MIME_PLAIN);
	}

	/* known imagetype, but check if support is available */
	if((img_type == IMAGE_JPEG && !XmHTMLImageJPEGSupported()) ||
		(img_type == IMAGE_PNG && !XmHTMLImagePNGSupported()) ||
		(img_type == IMAGE_GZF && !XmHTMLImageGZFSupported())) 
		return(MIME_IMG_UNSUP);

	/* we know this image type */
	return(MIME_IMAGE);
}

/*****
* Name: 		loadFile
* Return Type: 	String
* Description: 	loads the contents of the given file.
* In: 
*	filename:	name of the file to load
*	mime_type:		mimetype of file to load, updated upon return.
* Returns:
*	contents of the loaded file.
*****/
static String
loadFile(String filename, String *mime_type)
{
	FILE *file;
	int size, mime;
	static String content;
	XmString xms;
	char buf[1024];

	/* open the given file */
	if((file = fopen(filename, "r")) == NULL)
	{
		sprintf(buf, "%s:\ncannot display: %s", filename, strerror(errno));
		XMessage(toplevel, buf);
		return(NULL);
	}

	mime = getMimeType(filename);
	if(mime == MIME_ERR || mime == MIME_IMG_UNSUP)
	{
		char buf[1024];
		if(mime == MIME_ERR)
			sprintf(buf, "%s:\ncannot display, unable to load file.", filename);
		else
			sprintf(buf, "%s:\ncannot display, support for this image type "
				"not present.", filename);
		XMessage(toplevel, buf);
		return(NULL);
	}

	if(mime == MIME_HTML)
		*mime_type = "text/html";
	else if(mime == MIME_HTML_PERFECT)
		*mime_type = "text/html-perfect";
	else if(mime == MIME_IMAGE)
		*mime_type = "image/";
	else
		*mime_type = "text/plain";

	/* only load contents of file if we need to load something */
	if(mime == MIME_HTML || mime == MIME_HTML_PERFECT || mime == MIME_PLAIN)
	{
		/* see how large this file is */
		fseek(file, 0, SEEK_END);
		size = ftell(file);
		rewind(file);

		/* allocate a buffer large enough to contain the entire file */
		if((content = malloc(size+1)) == NULL)
		{
			fprintf(stderr, "malloc failed for %i bytes\n", size);
			exit(EXIT_FAILURE);
		}

		/* now read the contents of this file */
		if((fread(content, 1, size, file)) != size)
			printf("Warning: did not read entire file!\n");
		content[size] = '\0';	/* sanity */
	}
	else
		content = strdup(filename);

	fclose(file);

	/* set name of current file in the label */
	xms = XmStringCreateLocalized(filename);
	XtVaSetValues(label,
		XmNlabelString, xms,
		NULL);
	XmStringFree(xms);

	/* return contents of this file */
	return(content);
}

/*****
* Name: 		getAndSetFile
* Return Type: 	void
* Description: 	reads the given file, sets the contents of this
*				file in the HTML widget. Also sets the title of the application
*				to the title of the document loaded.
* In: 
*	file:		name of file to load
*	loc			location file file
*	store:		history storage
* Returns:
*	True upon success, False on failure.
*****/
static int
getAndSetFile(String file, String loc, Boolean store)
{
	String buf, title, mime;
	Arg args[5];
	int argc = 0;

	setBusy(True);

	/* load the file */
	if(file == NULL || (buf = loadFile(file, &mime)) == NULL)
	{
		setBusy(False);
		return(False);
	}

	/* kill of any outstanding progressive image loading contexts */
	XmHTMLImageProgressiveKill(html_widgets[0].html);

	/* reset/unmanage progressive image load button */
	if(prg_button)
		progressiveButtonCB(prg_button, 1);

	if(html_config[OPTIONS_ENABLE_IMAGES].value)
		XtSetSensitive(load_images, True);

	/* store this document in the history */
	if(store)
		storeInHistory(file, loc);

	/* set mime type */
	XtSetArg(args[argc], XmNmimeType, mime); argc++;

	/* and set values */
	XtSetValues(html_widgets[0].html, args, argc);

	/*****
	* Now set the text directly into the widget. XmHTMLTextSetString
	* works a lot faster than using XtVaSetValues: it causes a XmHTML widget
	* to update it's display immediatly, and this is the behaviour we want
	* to have: due to the asynchronous behavior of X, the widget might not
	* have parsed and set the text when we want to set or retrieve resources
	* from the new text. Using XmHTMLTextSetString *ensures* that the new
	* text is parsed and loaded before the widget returns control to X.
	* XmUpdateDisplay *might* work also, but that has been untested.
	*****/
	XmHTMLTextSetString(html_widgets[0].html, buf);

	/* free it, XmHTML makes a copy of the text to work with. */
	free(buf);

	/*****
	* See if the current text has got a title.
	* Note that one can also get the document title by using
	* XmHTMLGetHeadAttributes() with the HeadTitle flag set.
	*****/
	if((title = XmHTMLGetTitle(html_widgets[0].html)) != NULL)
	{
		/* it has, set it */
		XtVaSetValues(toplevel,
			XtNtitle, title,
			XtNiconName, title,
			NULL);
		XtFree(title);
	}
	else
	{
		XtVaSetValues(toplevel,
			XtNtitle, "<Untitled>",
			XtNiconName, "<Untitled>",
			NULL);
	}
	XtSetSensitive(reload, True);
	setBusy(False);
	return(True);
}

/*****
* Name: 		getInfoSize
* Return Type: 	int
* Description: 	returns the size of the given XmImageInfo structure.
* In: 
*	call_data:	ptr to a XmImageInfo structure;
*	client_data: data registered when we called initCache.
* Returns:
*	size of the given XmImageInfo structure.
* Note:
*	This function is used both by us and the caching routines.
*****/
static int
getInfoSize(XtPointer call_data, XtPointer client_data)
{
	int size = 0;
	XmImageInfo *frame = (XmImageInfo*)call_data;

	while(frame != NULL)
	{
		size += sizeof(XmImageInfo);
		size += frame->width*frame->height;		/* raw image data */

		/* clipmask size. The clipmask is a bitmap of depth 1 */
		if(frame->clip)
		{
			int clipsize;
			clipsize = frame->width;
			/* make it byte-aligned */
			while((clipsize % 8))
				clipsize++;
			/* this many bytes on a row */
			clipsize /= 8;
			/* and this many rows */
			clipsize *= frame->height;
			size += clipsize;
		}
		/* reds, greens and blues */
		size += 3*frame->ncolors*sizeof(Dimension);
		frame = frame->frame;	/* next frame of this image (if any) */
	}
	return(size);
}

/*****
* Name: 		getDocFromCache
* Return Type: 	DocumentCache*
* Description: 	retrieves a document from the document cache.
* In: 
*	file:		filename of document to be retrieved.
* Returns:
*	nothing.
*****/
static DocumentCache*
getDocFromCache(String file)
{
	int i;
	for(i = 0; i < last_doc; i++)
	{
		if(!(strcmp(doc_cache[i].file, file)))
			return(&doc_cache[i]);
	}
	return(NULL);
}

/*****
* Name: 		storeDocInCache
* Return Type: 	void
* Description: 	stores the given document in the document cache.
* In: 
*	file:		filename of document to be stored;
* Returns:
*	nothing.
*****/
static void
storeDocInCache(String file)
{
	char foo[128], pname[1024];

	if(last_doc == MAX_HISTORY_ITEMS)
	{
		int i;
		/* free hrefs */
		for(i = 0; i < doc_cache[0].nrefs; i++)
		{
			if(doc_cache[0].refs[i])
				free(doc_cache[0].refs[i]);
			doc_cache[0].refs[i] = NULL;
		}

		/* free image url's */
		for(i = 0; i < doc_cache[0].nimages; i++)
		{
			free(doc_cache[0].images[i]);
			doc_cache[0].images[i] = NULL;
		}

		/* free visited anchor list */
		for(i = 0; i < doc_cache[0].nvisited; i++)
		{
			if(doc_cache[0].visited[i])
				free(doc_cache[0].visited[i]);
			doc_cache[0].visited[i] = NULL;
		}
		/* free file and path fields */
		free(doc_cache[0].file);
		free(doc_cache[0].path);

		/* move everything downward */
		for(i = 0; i < MAX_HISTORY_ITEMS-1; i++)
			doc_cache[i] = doc_cache[i+1];
		last_doc = MAX_HISTORY_ITEMS - 1;
	}

	Debug(("Storing document %s in document cache\n", file));

	current_doc = last_doc;
	doc_cache[current_doc].nrefs    = 0;
	doc_cache[current_doc].nvisited = 0;
	doc_cache[current_doc].nimages  = 0;
	doc_cache[current_doc].file = strdup(file);

	/* get path to this file */
	(void)parseFilename(file, foo, pname);
	/* and store it */
	doc_cache[current_doc].path = strdup(pname);
	last_doc++;
}

/*****
* Name: 		removeDocFromCache
* Return Type: 	void
* Description: 	removes a document from the document cache
* In: 
*	doc:		id of document to be removed;
* Returns:
*	nothing.
*****/
static void
removeDocFromCache(int doc)
{
	DocumentCache *this_doc;
	int i;

	this_doc = &doc_cache[doc];

	Debug(("Removing document %s from document cache\n", this_doc->file));

	/* remove all document url's */
	for(i = 0; i < this_doc->nrefs; i++)
	{
		if(this_doc->refs[i])
			free(this_doc->refs[i]);
		this_doc->refs[i] = NULL;
	}

	/* free visited anchor list */
	for(i = 0; i < this_doc->nvisited; i++)
	{
		if(this_doc->visited[i])
			free(this_doc->visited[i]);
		this_doc->visited[i] = NULL;
	}

	/* and remove all image url's */
	for(i = 0; i < this_doc->nimages; i++)
	{
		/* remove image cache entry for this image */
		removeURLObjectFromCache(this_doc->images[i]);
		free(this_doc->images[i]);
	}
	/*****
	* Update image cache (clears out all objects with a reference count
	* of zero).
	*****/
	pruneObjectCache();

	this_doc->nrefs    = 0;
	this_doc->nvisited = 0;
	this_doc->nimages  = 0;
	free(this_doc->file);
	free(this_doc->path);
}

/*****
* Name: 		storeInHistory
* Return Type: 	void
* Description: 	stores the given href in the history list
* In: 
*	file:		name of document
*	loc:		value of named anchor in file.
* Returns:
*	nothing.
*****/
static void
storeInHistory(String file, String loc)
{
	int i;
	DocumentCache *this_doc = NULL;

	/* sanity check */
	if(file == NULL && loc == NULL)
		return;

	/* if file is NULL we are for sure in the current document */
	if(file == NULL)
		this_doc = &doc_cache[current_doc];
	else 
	{
		/****
		* This is a new file. If we have any documents on the stack,
		* remove them.
		****/
		if(last_doc)
		{
			for(i = current_doc+1; i < last_doc; i++)
				removeDocFromCache(i);
			last_doc = current_doc+1;
		}
		/* update refs for current document */
		this_doc = &doc_cache[current_doc];
		if(this_doc->nrefs)
		{
			/* remove any existing references above the current one */
			for(i = this_doc->current_ref+1; i < this_doc->nrefs; i++)
			{
				if(this_doc->refs[i])
				{
					free(this_doc->refs[i]);
					this_doc->refs[i] = NULL;
				}
			}
			this_doc->nrefs = this_doc->current_ref + 1;
		}
		if((this_doc = getDocFromCache(file)) == NULL)
		{
			storeDocInCache(file);
			this_doc = &doc_cache[current_doc];
		}
	}

	if(this_doc->nrefs == MAX_HISTORY_ITEMS)
	{
		/* free up the first item */
		if(this_doc->refs[0])
			free(this_doc->refs[0]);
		/* move everything downward */
		for(i = 0; i < MAX_HISTORY_ITEMS - 1; i++)
			this_doc->refs[i] = this_doc->refs[i+1];
		this_doc->nrefs = MAX_HISTORY_ITEMS-1;
	}

	/* sanity check */
	if(loc)
		this_doc->refs[this_doc->nrefs] = strdup(loc);
	this_doc->current_ref = this_doc->nrefs;
	this_doc->nrefs++;

	/* set button sensitivity */
	XtSetSensitive(back, current_doc || this_doc->current_ref ? True : False);
	XtSetSensitive(forward, False);
}

/*****
* Name: 		storeAnchor
* Return Type: 	void
* Description: 	stores the given href in the visited anchor list of current
*				document.
* In: 
*	href:		value to store.
* Returns:
*	nothing.
*****/
static void
storeAnchor(String href)
{
	int i;
	DocumentCache *this_doc = NULL;

	/* sanity check */
	if(href == NULL)
		return;

	/* pick up current document */
	this_doc = &doc_cache[current_doc];

	/* check if this location is already present in the visited list */
	for(i = 0; i < this_doc->nvisited; i++)
		if(!(strcmp(this_doc->visited[i], href)))
			return;
	/* not present yet, store in visited anchor list */

	/* move everything down if list is full */
	if(this_doc->nvisited == MAX_HISTORY_ITEMS)
	{
		/* free up the first item */
		if(this_doc->visited[0])
			free(this_doc->visited[0]);
		/* move everything downward */
		for(i = 0; i < MAX_HISTORY_ITEMS - 1; i++)
			this_doc->visited[i] = this_doc->visited[i+1];
		this_doc->nvisited = MAX_HISTORY_ITEMS-1;
	}
	/* store this item */
	this_doc->visited[this_doc->nvisited] = strdup(href);
	this_doc->nvisited++;
}

/*****
* Name: 		loadOrJump
* Return Type: 	void
* Description: 	checks the given href for a file and a possible jump to
*				a named anchor in this file.
* In: 
*	file:		name of file to load
*	loc:		location in file to jump to.
*	store:		history storage
* Returns:
*	True upon success, False on failure (file load failed)
*****/
static Boolean
loadAndOrJump(String file, String loc, Boolean store)
{
	static String prev_file;

	/* only load a file if it isn't the current one */
	if(prev_file == NULL || (file && strcmp(file, prev_file)))
	{
		/* do nothing more if the load fails */
		if(!(getAndSetFile(file, loc, store)))
			return(False);
	}
	if(prev_file)
		free(prev_file);
	prev_file = strdup(file);

	/* jump to the requested anchor in this file or to top of the document */
	if(loc)
		XmHTMLAnchorScrollToName(html_widgets[0].html, loc);
	else
		XmHTMLTextScrollToLine(html_widgets[0].html, 0);
	return(True);
}

/*****
* Name: 		readFile
* Return Type: 	void
* Description: 	XmNokCallback handler for the fileSelectionDialog: retrieves
*				the entered filename and loads it.
* In: 
*	w:			widget
*	dialog:		widget id of the fileSelectionDialog
*	cbs:		callback data
* Returns:
*	nothing.
*****/
static void
readFile(Widget widget, Widget dialog, XmFileSelectionBoxCallbackStruct *cbs)
{
	String filename, file;
	int item;

	/* remove the fileSelectionDialog */
	XtPopdown(XtParent(dialog));

	/* get the entered filename */
	XmStringGetLtoR(cbs->value, XmSTRING_DEFAULT_CHARSET, &filename);

	/* sanity check */
	if(!filename || !*filename)
	{
		if(filename)
			XtFree(filename);
		return;
	}

	/* get item data */
	XtVaGetValues(dialog, XmNuserData, &item, NULL);

	if(item == FILE_OPEN)
	{
		/* find the file */
		file = resolveFile(filename);
		XtFree(filename);

		if(file == NULL)
			return;

		/* load the file, will also update the document cache */
		loadAndOrJump(file, NULL, True);

		XFlush(XtDisplay(widget));
		free(file);
	}
	else if(item == FILE_SAVEAS)
	{
		FILE *fp;
		/* get parser output */
		String buffer = XmHTMLTextGetString(html_widgets[0].html);

		if(buffer)
		{
			if((fp = fopen(filename, "w")) == NULL)
				perror(filename);
			else
			{
				fputs(buffer, fp);
				fputs("\n", fp);
				fclose(fp);
			}
			XtFree(buffer);
		}
		XtFree(filename);
	}
}


static void
callClient(URLType url_type, String url)
{
	if(external_client)
	{
		char cmd[1024];
		if(url_type == ANCHOR_MAILTO)
			sprintf(cmd, "netscape -remote 'mailto(%s)'", url);
		if(url_type == ANCHOR_NEWS)
			sprintf(cmd, "netscape -remote 'news(%s)'", url);
		else
			sprintf(cmd, "netscape -remote 'openURL(%s)'", url);
		if(!(fork()))
		{
			if(execl("/bin/sh", "/bin/sh", "-c", cmd, NULL) == -1)
			{
				fprintf(stderr, "execl failed (%s)",
					strerror(errno));
				exit(100);
			}
		}
	}
}

/*****
* Name: 		anchorCB
* Return Type: 	void
* Description: 	XmNactivateCallback handler for the XmHTML widget
* In: 
*	w:			html widget
*	arg1:		client_data, unused
*	href_data:	anchor data
* Returns:
*	nothing.
*****/
static void
anchorCB(Widget w, XtPointer arg1, XmHTMLAnchorPtr href_data)
{
	/* see if we have been called with a valid reason */
	if(href_data->reason != XmCR_ACTIVATE)
		return;

	switch(href_data->url_type)
	{
		/* a named anchor */
		case ANCHOR_JUMP:
			{
				int id;
				/* see if XmHTML knows this anchor */
				if((id = XmHTMLAnchorGetId(w, href_data->href)) != -1)
				{
					/* store href in history and visited anchor list... */
					storeInHistory(NULL, href_data->href);
					storeAnchor(href_data->href);

					/* ...and let XmHTML jump and mark as visited */
					href_data->doit = True;
					href_data->visited = True;
					return;
				}
				return;
			}
			break;

		/* a local file with a possible ID jump */
		case ANCHOR_FILE_LOCAL:
			{
				String chPtr, file = NULL, loc = NULL;

				/* store href in visited anchor list */
				storeAnchor(href_data->href);

				/* first see if this anchor contains a jump */
				if((chPtr = strstr(href_data->href, "#")) != NULL)
				{
					char tmp[1024];
					strncpy(tmp, href_data->href, chPtr - href_data->href);
					tmp[chPtr - href_data->href] = '\0';
					/* try to find the file */
					file = resolveFile(tmp);
				}
				else
					file = resolveFile(href_data->href);

				if(file == NULL)
					return;

				/*****
				* All members in the XmHTMLAnchorCallbackStruct are
				* *pointers* to the contents of the current document.
				* So, if we will be changing the document, any members of this
				* structure become INVALID (in this case, any jump address to
				* a location in a different file). Therefore we *must* save
				* the members we might need after the document has changed.
				******/
				if(chPtr)
					loc = strdup(chPtr);

				/*****
				* If we have a target, call the frame loader, else call the
				* plain document loader.
				*****/
				if(href_data->target)
					jumpToFrame(file, loc, href_data->target, True);
				else
					loadAndOrJump(file, loc, True); 
				free(file);
				if(loc)
					free(loc);
			}
			break;

		case ANCHOR_PIPE:
			if(root_window || allow_exec)
			{
				char *ptr;
				char *cmd=NULL;

				Debug(("pipe: %s\n", href_data->href));

				if((ptr = strstr(href_data->href, ":")) != NULL)
				{
					ptr++;
					cmd = strdup(ptr);
					cmd[strlen(cmd)] = '\0';
                                        readPipe(html_widgets[0].html, cmd);
					free(cmd);
				}
			}
			break;

		case ANCHOR_EXEC:
			if(root_window || allow_exec)
			{
				char *ptr;
				char *cmd=NULL;

				Debug(("execute: %s\n", href_data->href));

				if((ptr = strstr(href_data->href, ":")) != NULL)
				{
					ptr++;
					cmd = strdup(ptr);
					cmd[strlen(cmd)] = '\0';
					if(!(fork()))
					{
						if(execl("/bin/sh", "/bin/sh", "-c", cmd, NULL) == -1)
						{
							fprintf(stderr, "execl failed (%s)",
								strerror(errno));
							exit(100);
						}
					}
					free(cmd);
				}
			}
			break;

		/* all other types are unsupported */
		case ANCHOR_FILE_REMOTE:
			fprintf(stderr, "fetch remote file: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_FTP:
			fprintf(stderr, "fetch ftp file: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_HTTP:
			fprintf(stderr, "fetch http file: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_GOPHER:
			fprintf(stderr, "gopher: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_WAIS:
			fprintf(stderr, "wais: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_NEWS:
			fprintf(stderr, "open newsgroup: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_TELNET:
			fprintf(stderr, "open telnet connection: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_MAILTO:
			fprintf(stderr, "email to: %s\n", href_data->href);
			callClient(href_data->url_type, href_data->href);
			break;
		case ANCHOR_UNKNOWN:
		default:
			fprintf(stderr, "don't know this type of url: %s\n", 
				href_data->href);
			break;
	}
}

/*****
* Name: 		setFrameText
* Return Type: 	void
* Description: 	loads the given file in the given HTML frame;
* In: 
*	widget:		XmHTML widget id in which to load the file;
*	filename:	file to be loaded;
*	loc:		selected position in the file. If non-NULL this routine will
*				scroll to the given location.
* Returns:
*	nothing.
*****/
static void
setFrameText(Widget frame, String filename, String loc)
{
	setBusy(True);

	if(filename)
	{
		String buf, file, mime;
		file = resolveFile(filename);
		if(file == NULL || (buf = loadFile(file, &mime)) == NULL)
		{
			setBusy(False);
			return;
		}
		/* kill of any outstanding progressive image loading contexts */
		XmHTMLImageProgressiveKill(frame);

		/* set the text in the widget */
		XtVaSetValues(frame,
			XmNvalue, buf,
			XmNmimeType, mime,
			NULL);
		free(buf);
		free(file);
	}

	/* jump to the requested anchor in this file or to top of the document */
	if(loc)
		XmHTMLAnchorScrollToName(frame, loc);
	else
		XmHTMLTextScrollToLine(frame, 0);

	setBusy(False);
}

/*****
* Name: 		jumpToFrame
* Return Type: 	void
* Description:	loads the contents of the given file in a named frame
* In: 
*	filename:	name of file to load;
*	loc:		url of file;
*	target:		name of frame in which to load the file;
*	store:		flag for history storage;
* Returns:
*	nothing.
*****/
static void
jumpToFrame(String filename, String loc, String target, Boolean store)
{
	int i;

	/* html_widgets[0] is the master XmHTML Widget, never framed */
	for(i = 1; i < MAX_HTML_WIDGETS; i++)
	{
		if(html_widgets[i].active && !(strcmp(html_widgets[i].name, target)))
		{
			/*
			* Load new file into frame if it's not the same as the current 
			* src value for this frame.
			*/
			if(html_widgets[i].src && strcmp(html_widgets[i].src, filename))
			{
				free(html_widgets[i].src);
				html_widgets[i].src = strdup(filename);
				setFrameText(html_widgets[i].html, filename, loc);
			}
			else	/* same file, jump to requested location */
				setFrameText(html_widgets[i].html, NULL, loc);
			return;
		}
	}
	/* frame not found, use the toplevel HTML widget */
	if(i == MAX_HTML_WIDGETS)
		loadAndOrJump(filename, loc, store); 
}

/* external gif decoder */
#include "gif_decode.c"

/*****
* Name: 		frameCB
* Return Type: 	void
* Description: 	callback for XmHTML's XmNframeCallback
* In: 
*	w:			widget id;
*	arg1:		client_data, unused;
*	cbs:		data about the frame being created/destroyed/notified of 
*				creation.
* Returns:
*	nothing.
*****/
static void
frameCB(Widget w, XtPointer arg1, XmHTMLFramePtr cbs)
{
	int i;

	if(cbs->reason == XmCR_HTML_FRAME)
	{
		Widget html = cbs->html;

		/* find the first free slot where we can insert this frame */
		for(i = 0; i < MAX_HTML_WIDGETS;i++)
			if(!html_widgets[i].active)
				break;

		/* a frame always has a name */
		html_widgets[i].name = strdup(cbs->name);
		if(cbs->src)
			html_widgets[i].src = resolveFile(cbs->src);

		/* anchor callback */
		XtAddCallback(html, XmNactivateCallback,
			(XtCallbackProc)anchorCB, NULL);

		/* HTML document callback */
		XtAddCallback(html, XmNdocumentCallback, (XtCallbackProc)docCB, NULL);

		/* set other things we want to have */
		XtVaSetValues(html,
			XmNanchorVisitedProc, testAnchor,
			XmNimageProc, loadImage,
			XmNprogressiveReadProc, getImageData,
			XmNprogressiveEndProc, endImageData,
#ifdef HAVE_GIF_CODEC
			XmNdecodeGIFProc, decodeGIFImage,
#endif
			/* propagate current defaults */
			XmNanchorButtons,
				html_config[OPTIONS_ANCHOR_BUTTONS].value,
			XmNhighlightOnEnter,
				html_config[OPTIONS_HIGHLIGHT_ON_ENTER].value,
			XmNenableBadHTMLWarnings,
				html_config[OPTIONS_DISABLE_WARNINGS].value,
			XmNstrictHTMLChecking,
				html_config[OPTIONS_ENABLE_STRICT_HTML32].value,
			XmNenableBodyColors,
				html_config[OPTIONS_ENABLE_BODYCOLORS].value,
			XmNenableBodyImages,
				html_config[OPTIONS_ENABLE_BODYIMAGES].value,
			XmNenableDocumentColors,
				html_config[OPTIONS_ENABLE_DOCUMENT_COLORS].value,
			XmNenableDocumentFonts,
				html_config[OPTIONS_ENABLE_DOCUMENT_FONTS].value,
			XmNenableOutlining,
				html_config[OPTIONS_ENABLE_OUTLINING].value,
			XmNfreezeAnimations,
				html_config[OPTIONS_FREEZE_ANIMATIONS].value,
			XmNimageEnable,
				html_config[OPTIONS_ENABLE_IMAGES].value,
			NULL);

		/* store widget id */
		html_widgets[i].html = html;
		html_widgets[i].active = True;

		/* set source text */
		setFrameText(html_widgets[i].html, html_widgets[i].src, NULL);

		return;
	}
	if(cbs->reason == XmCR_HTML_FRAMECREATE)
	{
		/* see if we have an inactive frame in our frame cache */
		for(i = 0; i < MAX_HTML_WIDGETS;i++)
			if(!html_widgets[i].active && !html_widgets[i].used)
				break;

		/* we have an available slot */
		if(i != MAX_HTML_WIDGETS && html_widgets[i].html != NULL)
		{
			cbs->doit = False;
			cbs->html = html_widgets[i].html;
			/* this slot is being used */
			html_widgets[i].used = True;
		}
		/*
		* this is the appropriate place for doing frame reuse: set
		* the doit field in the callback structure to False and set the
		* id of a *HTML* widget in the html field.
		*/
		return;
	}
	if(cbs->reason == XmCR_HTML_FRAMEDESTROY)
	{
		int freecount = 0;
		/*
		* this is the appropriate place for keeping this widget: just set
		* the doit field to false, update the frame cache (if this frame is
		* going to be reused, it's name and src value will probably change).
		*/
		for(i = 0; i < MAX_HTML_WIDGETS; i++)
		{
			if(!html_widgets[i].active)
				freecount++;
			if(html_widgets[i].html == cbs->html)
			{
				freecount++;
				/* a frame has always got a name */
				free(html_widgets[i].name);
				if(html_widgets[i].src)
					free(html_widgets[i].src);
				html_widgets[i].name = NULL;
				html_widgets[i].src = NULL;
				/* we keep up to three frames in memory */
				if(freecount > 3)
					html_widgets[i].html = NULL;
				html_widgets[i].active = False;
				html_widgets[i].used = False;
				break;
			}
		}
		if(freecount < 4)
			cbs->doit = False;
		return;
	}
	/* do nothing */
	return;
}


/*****
* Name: 		metaListCB
* Return Type: 	void
* Description: 	callback for the list in the document information dialog.
*				Displays the data associated with the selected item in the
*				list.
* In: 
*	w:			list widget id;
*	edit:		widget id of text widget in which data will be displayed.
* Returns:
*	nothing.
*****/
static void
metaListCB(Widget w, Widget edit)
{
	int *pos_list;	/* selected list position */
	int pos_cnt, selected;	/* no of selected items */
	XmHTMLMetaDataPtr meta_data = NULL;

	if(!(XmListGetSelectedPos(w, &pos_list, &pos_cnt)))
		/* no item selected */
		return;

	selected = pos_list[0];
	/* list positions start at 1 instead of zero, so be sure to adjust */
	selected--;

	/* get meta data out of the list's userData */
	XtVaGetValues(w, XmNuserData, &meta_data, NULL);

	/* very serious error */
	if(meta_data == NULL)
	{
		fprintf(stderr, "Could not retrieve meta-data from userData field!\n");
		free(pos_list);
		return;
	}

	/* and put the selected string in the edit field */
	XmTextSetString(edit, meta_data[selected].content);
	free(pos_list);
}

static String
getCharset(String content)
{
	String ptr, start;
	int len = 0;
	static char this_set[128];

	/*
	* We possible have a charset spec in here. Check
	* for it
	*/
	if((ptr = strstr(content, "charset")) != NULL)
	{
		ptr+= 7;	/* move past "charset" */

		/* skip until we hit = */
		for(;*ptr && *ptr != '='; ptr++);
			ptr++;

		/* skip all spaces */
		for(;*ptr && isspace(*ptr); ptr++);

		/*
		* now count how many chars we have. The charset spec is terminated
		* by a a quote
		*/
		start = ptr;
		while(*ptr && *ptr != '\"')
		{
			len++;
			ptr++;
		}
		if(len)
		{
			strncpy(this_set, start, len);
			this_set[len] = '\0'; /* nullify */
			/*
			* if we don't have a - in charset, we *must* append -* to make
			* it a valid XmNcharset spec.
			*/
			if(!(strstr(this_set, "-")))
				strcat(this_set, "-*");

			return(this_set);
		}
	}
	return(NULL);
}

int
#ifdef __STDC__
	my_sprintf(String *dest, int *size, int *max_size, String fmt, ...)
#else /* ! __STDC__ */
	my_sprintf(String *dest, int *size, int *max_size, String fmt, va_list)
	String *dest;
	int *size;
	int *max_size;
    String fmt;
    va_dcl
#endif /* __STDC__ */
{
    int len;
    String s;
#ifdef __STDC__
    va_list	arg_list;
#else
	va_dcl
#endif

    if(*max_size - *size < 1024) 
    {
		*max_size += 1024;
		/* realloc(NULL, size) ain't exactly portable */
		if(*max_size == 1024)
			s = (char *)malloc(*max_size);
		else
			s = (char *)realloc(*dest, *max_size);
		*dest = s;
    }
#ifdef __STDC__
    va_start(arg_list, fmt);
#else
    va_start(arg_list);
#endif
    len = vsprintf(*dest + *size, fmt, arg_list);
    va_end(arg_list);

	/* new size of destination buffer */
    if(len != 0) 
		*size += strlen(*dest + *size);
    return(len);
}


/*****
* Name: 		docInfoCB
* Return Type: 	void
* Description: 	shows a dialog with document information. This routine gets
*				activated when the file->document info menu item is selected.
* In: 
*	font_only:	check only for a possible font spec in the meta information.
* Returns:
*	nothing.
*****/
static void
docInfoCB(Boolean font_only)
{
	static Widget title_label, author_label, base_label, doctype_label;
	static Widget list, edit;
	XmString xms;
	static XmHTMLHeadAttributes head_info;
	Boolean have_info = False;
	String tmp;
	int i, argc = 0;
	Arg args[5];

	if(font_only)
	{
		char this_font[128];
		String this_charset = NULL;

		this_font[0] = '\0';

		/* get meta info for a charset and/or font spec */
		if(XmHTMLGetHeadAttributes(html_widgets[0].html, &head_info, HeadMeta))
		{
			if(head_info.num_meta)
			{
				for(i = 0; i < head_info.num_meta; i++)
				{
					tmp = (head_info.meta[i].http_equiv ? 
						head_info.meta[i].http_equiv : head_info.meta[i].name);

					if(!strcmp(tmp, "font"))
					{
						sprintf(this_font, "*-%s-normal-*",
							head_info.meta[i].content);
					}
					else if(!strcmp(tmp, "content-type") &&
						this_charset == NULL)
					{
						this_charset = getCharset(head_info.meta[i].content);
					}
				}
			}
		}

		/*****
		* have we been told to set a new font?
		* Please note that in a real world application it should be checked
		* if the requested font is available. XmHTML silently ignores this
		* kind of errors.
		*****/
		if(*this_font)
		{
			/* font changed */
			if(strcmp(this_font, current_font))
			{
				strcpy(current_font, this_font);
				current_font[strlen(this_font)] = '\0';

				Debug(("docInfoCB, setting XmNfontFamily to %s\n",
					current_font));
				XtSetArg(args[argc], XmNfontFamily, current_font); argc++;
			}
			/* still the same, don't touch it */
		}
		else if(strcmp(current_font, default_font))
		{
			/* reset default font */
			strcpy(current_font, default_font);
			current_font[strlen(default_font)] = '\0';
			Debug(("docInfoCB, setting XmNfontFamily to %s\n", current_font));
			XtSetArg(args[argc], XmNfontFamily, current_font); argc++;
		}

		/*****
		* have we been told to set a new character set?
		* Please note that a real world app *MUST* check if the requested
		* character set is available. XmHTML silently ignores any errors
		* resulting from an invalid charset, it just falls back to whatever
		* the X server provides.
		* To make these checks really consistent, it should also be verified
		* that the current font family is still valid if the charset is
		* changed. XmHTML's font allocation routines will almost *never*
		* fail on font allocations: if a font can not be found in the requested
		* character set it will use the default charset supplied by the X
		* server. If font allocation still fails after this, it will wildcard
		* the fontfamily and try again (this is done so XmHTML will always have
		* a default font available). If this also fails (which is almost
		* impossible) XmHTML will exit your application: if it can't find
		* any fonts at all, why keep on running?
		*****/
		if(this_charset)
		{
			/* charset changed */
			if(strcmp(current_charset, this_charset))
			{
				/* we currently only known koi8 and iso8859-1 */
				if(strstr(this_charset, "koi8"))
				{
					/* save charset */
					strcpy(current_charset, this_charset);
					current_charset[strlen(this_charset)] = '\0';

					/* koi8 has cronyx for its foundry */
					strcpy(current_font, "cronyx-times-*-*\0");
					argc = 0;		/* overrides a fontspec */

					Debug(("docInfoCB, setting XmNcharset to %s\n",
						current_charset));
					XtSetArg(args[argc], XmNfontFamily, current_font); argc++;
					XtSetArg(args[argc], XmNcharset, current_charset); argc++;
				}
				else if(!strstr(this_charset, "iso8859-1"))
				{
					fprintf(stderr, "Warning: character set %s unsupported\n",
						current_charset);
				}
			}
			/* still the same, don't touch it */
		}
		else if(strcmp(current_charset, default_charset))
		{
			strcpy(current_charset, default_charset);
			current_charset[strlen(default_charset)] = '\0';
			XtSetArg(args[argc], XmNcharset, current_charset); argc++;
		}

		/* plop'em in */
		if(argc)
			XtSetValues(html_widgets[0].html, args, argc);

		/*****
		* Tell XmHTML to clear everything. This is not really required but
		* adviseable since XmHTML will only clear the fields that have
		* been requested. For example, in all subsequent calls to the above
		* XmHTMLGetHeadAttributes call, XmHTML will first clear the stored
		* meta info before filling it again.
		*****/
		XmHTMLGetHeadAttributes(html_widgets[0].html, &head_info, HeadClear);
		return;
	}

	/*****
	* Get <head></head> information from the current document. XmHTML will
	* take care of replacing the requested members when they have been used
	* before. When no <head></head> is available this function returns false
	* Note: the value of the <!DOCTYPE> member is always returned if there
	* is one, even if GetHeadAttributes() returns False.
	*****/
	have_info = XmHTMLGetHeadAttributes(html_widgets[0].html, &head_info,
					HeadDocType|HeadTitle|HeadBase|HeadMeta);

	if(!info_dialog)
	{
		Widget sep, rc1, rc2, fr1, fr2;
		Arg args[20];
		int argc = 0;

		info_dialog = XmCreateFormDialog(toplevel, "documentAttributes",
			NULL, 0);

		XtVaSetValues(XtParent(info_dialog),
			XtNtitle, "Document Attributes",
			NULL);
		fr1 = XtVaCreateManagedWidget("documentTitleForm",
			xmFormWidgetClass, info_dialog,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			NULL);

		sep = XtVaCreateManagedWidget("documentSeperator",
			xmSeparatorGadgetClass, info_dialog,
			XmNorientation, XmHORIZONTAL,
			XmNtopAttachment, XmATTACH_WIDGET,
			XmNtopWidget, fr1,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			XmNleftOffset, 10,
			XmNrightOffset, 10,
			XmNtopOffset, 10,
			NULL);

		fr2 = XtVaCreateManagedWidget("documentTitleForm",
			xmFormWidgetClass, info_dialog,
			XmNtopAttachment, XmATTACH_WIDGET,
			XmNtopWidget, sep,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			XmNbottomAttachment, XmATTACH_FORM,
			NULL);

		rc1 = XtVaCreateManagedWidget("documentTitleLeftRow",
			xmRowColumnWidgetClass, fr1,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_FORM,
			XmNbottomAttachment, XmATTACH_FORM,
			XmNpacking, XmPACK_COLUMN,
			XmNorientation, XmVERTICAL,
			XmNnumColumns, 1,
			XmNtopOffset, 10,
			XmNleftOffset, 10,
			XmNrightOffset, 10,
			NULL);
		XtVaCreateManagedWidget("Document Title:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtVaCreateManagedWidget("Author:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtVaCreateManagedWidget("Document type:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtVaCreateManagedWidget("Base Location:",
			xmLabelGadgetClass, rc1,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);

		rc2 = XtVaCreateManagedWidget("documentTitleRightRow",
			xmRowColumnWidgetClass, fr1,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_WIDGET,
			XmNleftWidget, rc1,
			XmNrightAttachment, XmATTACH_FORM,
			XmNbottomAttachment, XmATTACH_FORM,
			XmNpacking, XmPACK_COLUMN,
			XmNorientation, XmVERTICAL,
			XmNnumColumns, 1,
			XmNtopOffset, 10,
			XmNleftOffset, 10,
			XmNrightOffset, 10,
			NULL);
		title_label = XtVaCreateManagedWidget("docTitle",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		author_label = XtVaCreateManagedWidget("docAuthor",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		doctype_label = XtVaCreateManagedWidget("docType",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		base_label = XtVaCreateManagedWidget("docBase",
			xmLabelGadgetClass, rc2,
			XmNalignment, XmALIGNMENT_BEGINNING,
			NULL);
		XtSetArg(args[argc], XmNlistSizePolicy, XmRESIZE_IF_POSSIBLE); argc++;
		XtSetArg(args[argc], XmNvisibleItemCount, 5); argc++;
		XtSetArg(args[argc], XmNleftAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNtopAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNbottomAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNleftOffset, 10); argc++;
		XtSetArg(args[argc], XmNtopOffset, 10); argc++;
		XtSetArg(args[argc], XmNbottomOffset, 10); argc++;
		list = XmCreateScrolledList(fr2, "metaList", args, argc);

		argc = 0;
		XtSetArg(args[argc], XmNscrollBarDisplayPolicy, XmAS_NEEDED); argc++;
		XtSetArg(args[argc], XmNscrollingPolicy, XmAUTOMATIC); argc++;
		XtSetArg(args[argc], XmNleftAttachment, XmATTACH_WIDGET); argc++;
		XtSetArg(args[argc], XmNleftWidget, list); argc++;
		XtSetArg(args[argc], XmNtopAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNbottomAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNrightAttachment, XmATTACH_FORM); argc++;
		XtSetArg(args[argc], XmNleftOffset, 10); argc++;
		XtSetArg(args[argc], XmNrightOffset, 10); argc++;
		XtSetArg(args[argc], XmNtopOffset, 10); argc++;
		XtSetArg(args[argc], XmNbottomOffset, 10); argc++;
		edit = XmCreateScrolledText(fr2, "metaEdit", args, argc);

		argc = 0;
		XtSetArg(args[argc], XmNeditable, False); argc++;
		XtSetArg(args[argc], XmNcolumns, 35); argc++;
		XtSetArg(args[argc], XmNrows, 5); argc++;
		XtSetArg(args[argc], XmNwordWrap, True); argc++;
		XtSetArg(args[argc], XmNeditMode, XmMULTI_LINE_EDIT); argc++;
		XtSetArg(args[argc], XmNscrollHorizontal, False); argc++;
		XtSetArg(args[argc], XmNscrollVertical, False); argc++;
		XtSetValues(edit, args, argc);

		/* single selection callback on the list */
		XtAddCallback(list, XmNbrowseSelectionCallback,
			(XtCallbackProc)metaListCB, edit);

		XtManageChild(list);
		XtManageChild(edit);
	}

	/* delete all list items */
	XmListDeleteAllItems(list);
	/* clear all text in the edit window */
	XmTextSetString(edit, NULL);

	if(head_info.doctype)
		xms = XmStringCreateLocalized(head_info.doctype);
	else
		xms = XmStringCreateLocalized("<Unspecified>");
	XtVaSetValues(doctype_label, XmNlabelString, xms, NULL);
	XmStringFree(xms);

	if(have_info)
	{
		if(head_info.title)
			xms = XmStringCreateLocalized(head_info.title);
		else
			xms = XmStringCreateLocalized("<Untitled>");
		XtVaSetValues(title_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		if(head_info.base)
			xms = XmStringCreateLocalized(head_info.base);
		else
			xms = XmStringCreateLocalized("<Not specified>");
		XtVaSetValues(base_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);
		xms = NULL;

		/*
		* No need to check for font or charset in meta info, that's
		* already been done from within the documentCallback.
		*/
		if(head_info.num_meta)
		{
			for(i = 0; i < head_info.num_meta; i++)
			{
				tmp = (head_info.meta[i].http_equiv ? 
					head_info.meta[i].http_equiv : head_info.meta[i].name);

				/* pick out author */
				if(!strcmp(tmp, "author"))
					xms = XmStringCreateLocalized(head_info.meta[i].content);
			}
		}
		if(xms == NULL)
			xms = XmStringCreateLocalized("<Unknown>");
		XtVaSetValues(author_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		/* string table */
		if(head_info.num_meta)
		{
			XmStringTable strs;
			strs =(XmStringTable)malloc(head_info.num_meta*sizeof(XmString*));
			
			for(i = 0; i < head_info.num_meta; i++)
			{
				if(head_info.meta[i].http_equiv)
					strs[i] =
						XmStringCreateLocalized(head_info.meta[i].http_equiv);
				else
					strs[i] =
						XmStringCreateLocalized(head_info.meta[i].name);
			}
			XtVaSetValues(list,
				XmNitemCount, head_info.num_meta,
				XmNitems, strs,
				XmNuserData, (XtPointer)head_info.meta,
				NULL);
			for(i = 0; i < head_info.num_meta; i++)
				XmStringFree(strs[i]);
			free(strs);
		}
	}
	else
	{
		xms = XmStringCreateLocalized("<Untitled>");
		XtVaSetValues(title_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		xms = XmStringCreateLocalized("<Unknown>");
		XtVaSetValues(author_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);

		xms = XmStringCreateLocalized("<Not specified>");
		XtVaSetValues(base_label, XmNlabelString, xms, NULL);
		XmStringFree(xms);
	}
	/* put on screen */
	XtManageChild(info_dialog);
	XMapRaised(XtDisplay(info_dialog), XtWindow(info_dialog));
}

/*****
* Name: 		docCB
* Return Type: 	void
* Description: 	displays current document state as given by XmHTML.
* In: 
*	html:		owner of this callback
*	arg1:		client_data, unused
*	cbs:		call_data, documentcallback structure.
* Returns:
*	nothing
* Note:
*	the XmNdocumentCallback is an excellent place for setting several
*	formatting resources: XmHTML triggers this callback when the parser
*	has finished, but *before* doing any formatting. As an example, we
*	check the information contained in the document head for a font
*	specification: we call docInfoCB with the font_only arg set to True.
*****/
static void
docCB(Widget w, XtPointer arg1, XmHTMLDocumentPtr cbs)
{
	XmString xms;
	char doc_label[128];
	Pixel my_pix = (Pixel)0;
	static Pixel red, green;

	/* see if we have been called with a valid reason */
	if(cbs->reason != XmCR_HTML_DOCUMENT)
		return;

	/*
	* If we are being notified of the results of another pass on the loaded
	* document, only check whether the generated parser tree is balanced and
	* don't update the labels since the callback data is the result of a
	* modified document.
	*
	* XmHTML's document verification and repair routines are capable of
	* creating a verified, properly balanced and HTML conforming document
	* from even the most horrible non-HTML conforming documents!
	*
	* And when the XmNstrictHTMLChecking resource has been set to True, these
	* routines are also bound to make the document HTML 3.2 conformant as well.
	*/
	if(cbs->pass_level)
	{
		/*
		* Allow up to two iterations on the current document (remember that
		* the document has already been checked twice when pass_level == 1).
		* XmHTML sets the redo field to True whenever the parser tree is
		* unbalanced, so it needs to be set to False when the allowed number
		* of iterations has been reached.
		*
		* The results of displaying a document with an unbalanced parser tree
		* are undefined however and can lead to some weird markup results.
		*/
		if(!cbs->balanced && cbs->pass_level < 2)
			return;
		cbs->redo = False;

		/* done parsing, check if a font is given in the meta spec. */
		docInfoCB(True);
		return;
	}

	if(!red)
		red = XmHTMLAllocColor((Widget)html_widgets[0].html, "Red",
			BlackPixelOfScreen(XtScreen(toplevel)));

	if(!green)
		green = XmHTMLAllocColor((Widget)html_widgets[0].html, "Green",
			WhitePixelOfScreen(XtScreen(toplevel)));

	if(cbs->html32)
	{
		sprintf(doc_label, "HTML 3.2");
		my_pix = green;
	}
	else
	{
		sprintf(doc_label, "Bad HTML 3.2");
		my_pix = red;
	}
	xms = XmStringCreateLocalized(doc_label);
	XtVaSetValues(html32,
		XmNbackground, my_pix,
		XmNlabelString, xms,
		NULL);
	XmStringFree(xms);

	if(cbs->verified)
	{
		sprintf(doc_label, "Verified");
		my_pix = green;
	}
	else
	{
		sprintf(doc_label, "Unverified");
		my_pix = red;
	}
	xms = XmStringCreateLocalized(doc_label);
	XtVaSetValues(verified,
		XmNbackground, my_pix,
		XmNlabelString, xms,
		NULL);
	XmStringFree(xms);

	/*
	* default processing here. If the parser tree isn't balanced
	* (cbs->balanced == False) and you want to prevent XmHTML from making
	* another pass on the current document, set the redo field to false.
	*/
	if(cbs->balanced)
	{
		/* check meta info for a possible font spec */
		docInfoCB(True);
	}
}

/*****
* Name: 		linkCB
* Return Type: 	void
* Description: 	XmHTML's XmNlinkCallback handler
* In: 
*	w:			widget id;
*	arg1:		client_data, unused;
*	cbs:		link data found in current document.
* Returns:
*	nothing, but copies the link data to an internal structure which is used
*	for displaying a site-navigation bar.
*****/
static void
linkCB(Widget w, XtPointer arg1, XmHTMLLinkPtr cbs)
{
	int i, j;

	/* free previous document links */
	for(i = 0; i < LINK_LAST; i++)
	{
		if(document_links[i].have_data)
		{
			/* we always have a href */
			free(document_links[i].href);
			/* but title is optional */
			if(document_links[i].title)
				free(document_links[i].title);
			document_links[i].href= NULL;
			document_links[i].title = NULL;
		}
		document_links[i].have_data  = False;
	}

	/*****
	* Since this callback gets triggered for every document, this is also
	* the place for updating the info dialog (if it's up that is).
	*****/
	if(info_dialog && XtIsManaged(info_dialog))
		docInfoCB(False);

	/*****
	* if the current document doesn't have any links, unmanage the button
	* and dialog and return.
	*****/
	if(cbs->num_link == 0)
	{
		/* might not have been created yet */
		if(link_dialog != NULL)
			XtUnmanageChild(link_dialog);
		XtUnmanageChild(link_button);
		return;
	}

	/* store links in this document */
	for(i = 0; i < LINK_LAST; i++)
	{
		for(j = 0; j < cbs->num_link; j++)
		{
			/* kludge for the mailto */
			String tmp = (i == 0 ? "made" : link_labels[i]);

			/*****
			* url is mandatory and so is one of rel or rev. Although both
			* of them can be present, we prefer a rel over a rev.
			*****/
			if(!cbs->link[j].url || (!cbs->link[j].rel && !cbs->link[j].rev))
				continue;

			if((cbs->link[j].rel && my_strcasestr(cbs->link[j].rel, tmp)) ||
				(cbs->link[j].rev && my_strcasestr(cbs->link[j].rev, tmp)))
			{
				document_links[i].have_data = True;
				document_links[i].link_type = cbs->link[j].rel ? 1 : 0;
				/* we always have this */
				document_links[i].href = strdup(cbs->link[j].url);
				/* title is optional */
				if(cbs->link[j].title)
					document_links[i].title = strdup(cbs->link[j].title);
			}
		}
	}
	/* if the dialog is already up, update the buttons */
	if(link_dialog && XtIsManaged(link_dialog))
	{
		for(i = 0; i < LINK_LAST; i++)
		{
			if(document_links[i].have_data)
				XtSetSensitive(link_buttons[i], True);
			else
				XtSetSensitive(link_buttons[i], False);
		}
		/* and make sure everything is up and displayed */
		XmUpdateDisplay(link_dialog);
	}
	/* manage the button so user can see the site structure of this doc. */
	XtManageChild(link_button);
}

/*****
* Name: 		collapseURL
* Return Type: 
* Description:	Copies up to 50 chars from the given url and puts in three
*				dots when the given url is larger than fifty chars.
* In: 
*	url:		url to be collapsed or copied;
* Returns:
*	copied url.
*****/
static String
collapseURL(String url)
{
	static char name[51];
	int len;

	if(url == NULL)
		return("");

	len = strlen(url);

	if(len < 50)
	{
		strcpy(name, url);
		name[len] = '\0';	/* NULL terminate */
		return(name);
	}
	/* copy first 11 chars */
	strncpy(name, url, 11);
	/* put in a few dots */
	name[11] = '.';
	name[12] = '.';
	name[13] = '.';
	name[14] = '\0';
	/* copy last 36 chars */
	strcat(name, &url[len - 36]);
	name[50] = '\0';	/* NULL terminate */
	return(name);
}

/*****
* Name: 		infoCB
* Return Type: 	void
* Description: 	ButtonPressed handler for the workArea of a XmHTML widget.
*				In this case, a possible use of the XmHTMLXYToInfo resource
*				is demonstrated.
* In: 
*	w:			widget id;
*	popup:		popup menu widget id
*	event:		location of button press.
* Returns:
*	nothing.
*****/
static void
infoCB(Widget parent, Widget popup, XButtonPressedEvent *event)
{
	XmString xms;
	char tmp[84];	/* max label width */
	XmHTMLInfoPtr info;
	WidgetList children;
	Widget html_w;

	XUngrabPointer(XtDisplay(parent), CurrentTime);

	/* only button 3 */
	if(event->button != 3)
		return;

	html_w = XtParent(parent);

	if(html_w == NULL || !XmIsHTML(html_w))
	{
		fprintf(stderr, "%s parent gotten from XtParent(%s)\n",
			html_w == NULL ? "NULL" : "Invalid", XtName(parent));
		return;
	}

	/* get the info for the selected position */
	info = XmHTMLXYToInfo(html_w, event->x, event->y);

	/* no popup if no image and anchor */
	if(info == NULL || (info->image == NULL && info->anchor == NULL))
		return;

	XtVaGetValues(popup, XmNchildren, &children, NULL);

	/* unmanage all buttons */
	XtUnmanageChild(children[0]);
	XtUnmanageChild(children[1]);
	XtUnmanageChild(children[2]);
	XtUnmanageChild(children[3]);

	/*****
	* Note on how to convey the href or image url's to the popup callbacks:
	*
	* All strings provided in the anchor and/or image field of this callback
	* are internal to XmHTML and are guarenteed to exist as long as the
	* current document is up. Knowing this, we can safely store these strings
	* in the userData field of the popup menu buttons.
	****/

	/* if we have an anchor, we copy the url to the label */
	if(info->anchor)
	{
		sprintf(tmp, "Follow this link (%s)", collapseURL(info->anchor->href));
		xms = XmStringCreateLocalized(tmp);
		XtVaSetValues(children[0],
			XmNlabelString, xms,
			XmNuserData, info->anchor->href,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[0]);
	}
	if(info->image)
	{
		sprintf(tmp, "Open this image (%s)", collapseURL(info->image->url));
		xms = XmStringCreateLocalized(tmp);
		XtVaSetValues(children[1],
			XmNlabelString, xms,
			XmNuserData, info->image->url,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[1]);

		xms = XmStringCreateLocalized("View Image details");
		XtVaSetValues(children[2],
			XmNlabelString, xms,
			XmNuserData, info->image,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[2]);

		/* set proper string for fancy image tracking */
		if(html_config[OPTIONS_FANCY_TRACKING].value)
			xms = XmStringCreateLocalized("Disable Anchored Image Tracking");
		else
			xms = XmStringCreateLocalized("Enable Anchored Image Tracking");
		XtVaSetValues(children[3],
			XmNlabelString, xms,
			NULL);
		XmStringFree(xms);

		/* manage it */
		XtManageChild(children[3]);
	}
	/* set correct menu position */
	XmMenuPosition(popup, event);
	/* and show it */
	XtManageChild(popup);
}

/*****
* Name: 		navCB
* Return Type: 	void
* Description: 	callback for the buttons in the link dialog (displayed 
*				by the linkButtonCB routine)
* In: 
*	w:			widget id of selected button;
*	item:		id of selected item;
* Returns:
*	nothing.
* Note:
*	This routine simply creates a XmHTMLAnchorCallbackStruct and calls
*	the anchorCB routine to let it handle navigation of the document
*	(which can include loading a new local or remote document, call a mail
*	application to mail something, download something, whatever).
*****/
static void
navCB(Widget w, int item)
{
	static XmHTMLAnchorCallbackStruct cbs;

	/*****
	* We just compose a XmHTMLAnchorCallbackStruct and let anchorCB do the
	* loading.
	*****/
	cbs.reason = XmCR_ACTIVATE;
	cbs.event  = NULL;
	cbs.url_type = XmHTMLGetURLType(document_links[item].href);
	cbs.href   = document_links[item].href;
	cbs.title  = document_links[item].title;
	cbs.line   = 0;
	cbs.target = NULL;
	cbs.doit   = False;
	cbs.visited= False;
	if(document_links[item].link_type == 0)
	{
		cbs.rev = link_labels[item];
		cbs.rel = NULL;
	}
	else
	{
		cbs.rel = link_labels[item];
		cbs.rev = NULL;
	}

	/* and call the activate callback */
	anchorCB(html_widgets[0].html, NULL, &cbs);
}

/*****
* Name: 		linkButtonCB
* Return Type: 	void
* Description: 	displays a dialog with buttons to allow navigation of a
*				document using the information contained in the <link></link>
*				section of a HTML document.
* In: 
*	w:			widget id, unused;
*	arg1:		client_data, unused;
*	arg2:		call_data, unused;
* Returns:
*	nothing.
*****/
static void
linkButtonCB(Widget w, XtPointer arg1, XtPointer arg2)
{
	int i;

	if(!link_dialog)
	{
		Widget rc;
		link_dialog = XmCreateFormDialog(toplevel, "Preview", NULL, 0);
		
		XtVaSetValues(XtParent(link_dialog),
			XtNtitle, "Site Structure",
			NULL);

		/* a rowcol for the buttons */
		rc = XtVaCreateManagedWidget("rowColumn",
			xmRowColumnWidgetClass, link_dialog,
			XmNtopAttachment, XmATTACH_FORM,
			XmNleftAttachment, XmATTACH_FORM,
			XmNrightAttachment, XmATTACH_FORM,
			XmNspacing, 0,
			XmNpacking, XmPACK_COLUMN,
			XmNorientation, XmVERTICAL,
			XmNnumColumns, 1,
			NULL);
		/* all buttons */
		for(i = 0; i < LINK_LAST; i++)
		{
			link_buttons[i] = XtVaCreateManagedWidget(link_labels[i],
				xmPushButtonWidgetClass, rc,
				NULL);
			XtAddCallback(link_buttons[i], XmNactivateCallback,
				(XtCallbackProc)navCB, (XtPointer)i);
		}
	}
	/* Now see what buttons to activate. */
	for(i = 0; i < LINK_LAST; i++)
	{
		if(document_links[i].have_data)
			XtSetSensitive(link_buttons[i], True);
		else
			XtSetSensitive(link_buttons[i], False);
	}
	/* 
	* Keep the focus on the html widget so the navigation keys always
	* work.
	*/
	XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);

	/* put on screen */
	XtManageChild(link_dialog);
	XMapRaised(XtDisplay(link_dialog), XtWindow(link_dialog));

	/* and make sure everything is up and displayed */
	XmUpdateDisplay(link_dialog);
}

/*****
* Name: 		historyCB
* Return Type: 	void
* Description: 	XmNactivateCallback handler for the back & forward buttons.
*				moves back or forward in the history.
* In: 
*	w:			widget
*	button:		button the triggered this callback.
* Returns:
*	nothing.
*****/
static void
historyCB(Widget w, int button)
{
	DocumentCache *this_doc = &doc_cache[current_doc];

	/* back button has been pressed */
	if(button == 0)
	{
		if(!XtIsSensitive(back))
			return;

		/* current_ref == 0 -> top of file */
		if(this_doc->current_ref)
			this_doc->current_ref--;
		/* reached bottom of current document, move to the previous one */
		else
		{
			current_doc--;
			this_doc = &doc_cache[current_doc];
		}
		if(loadAndOrJump(this_doc->file, this_doc->refs[this_doc->current_ref],
			False))
		{
			XtSetSensitive(forward, True);
			XtSetSensitive(back, 
				current_doc || this_doc->current_ref ? True : False);
		}
		else
		{
			if(current_doc)
			{
				current_doc--;
				historyCB(w, button);
			}
		}
	}
	/* forward button has been pressed */
	else
	{
		if(!XtIsSensitive(forward))
			return;

		this_doc->current_ref++;
		/* reached max of this document, move to the next doc */
		if(this_doc->current_ref == this_doc->nrefs)
		{
			this_doc->current_ref--;
			current_doc++;
			this_doc = &doc_cache[current_doc];
		}

		if(loadAndOrJump(this_doc->file, this_doc->refs[this_doc->current_ref],
			False))
		{
			XtSetSensitive(back, True);

			if(current_doc == last_doc - 1 && 
				this_doc->current_ref == this_doc->nrefs - 1)
				XtSetSensitive(forward, False);
		}
		else
		{
			if(current_doc != last_doc-1)
			{
				current_doc++;
				historyCB(w, button);
			}
		}
	}
	/* 
	* Keep the focus on the html widget so the navigation keys always
	* work.
	*/
	XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);
}

/*****
* Name: 		destroyCacheObject
* Return Type: 	void
* Description: 	gets called by the object caching routines when it wants to
*				destroy a cached object.
* In: 
*	call_data:	object to be destroyed;
*	client_data:data we registered ourselves when we made the initObjectCache
*				call.
* Returns:
*	nothing.
*****/
static void
destroyCacheObject(XtPointer call_data, XtPointer client_data)
{
	Debug(("destroyCacheObject, called for %s\n",
		((XmImageInfo*)call_data)->url));

	XmHTMLImageFreeImageInfo((Widget)client_data, (XmImageInfo*)call_data);
}

/*****
* Name: 		loadAnimation
* Return Type: 	XmImageInfo
* Description: 	load an animation consisting of multiple images
* In: 
*	names:		comma separated list of images
* Returns:
*	a list of XmImageInfo composing the animation
* Note:
*	this is a fairly simple example on how to add support for images
*	that are not supported by the XmHTMLImageDefaultProc convenience
*	function.
*****/
XmImageInfo*
loadAnimation(char *names)
{
	static XmImageInfo *all_frames;
	XmImageInfo *frame = NULL;
	String chPtr, name_buf, filename;
	int nframes = 0;

	name_buf = strdup(names);
	for(chPtr = strtok(name_buf, ","); chPtr != NULL; 
		chPtr = strtok(NULL, ","))
	{
		if((filename = resolveFile(chPtr)) == NULL)
		{
			free(name_buf);
			return(NULL);
		}
		if(nframes)
		{
			frame->frame = XmHTMLImageDefaultProc(html_widgets[0].html,
				filename, NULL, 0);
			frame = frame->frame;
		}
		else
		{
			all_frames = XmHTMLImageDefaultProc(html_widgets[0].html,
				filename, NULL, 0);
			frame = all_frames;
		}
		frame->timeout = animation_timeout;
		nframes++;
		free(filename);
	}
	free(name_buf);

	/* nframes is total no of frames in this animation */
	all_frames->nframes = nframes;
	all_frames->timeout = animation_timeout;
	return(all_frames);
}

/*****
* Name: 		flushImages
* Return Type: 	void
* Description: 	flushes all images (normal *and* delayed) to the currently
*				loaded document.
* In: 
*	w:			widget id, unused;
* Returns:
*	nothing.
* Note:
*	This routine simply flushes all images in the currently loaded document.
*	When it finds an image that has been delayed, it loads the real image and
*	replaces the delayed image in the current document with the real image.
*	When all images have been updated, it calls XmHTMLRedisplay to force
*	XmHTML to do a re-computation of the document layout.
*****/
static void 
flushImages(Widget w)
{
	int i;
	static XmImageInfo *image, *new_image;
	String url, filename;
	DocumentCache *this_doc;
	XmImageStatus status = XmIMAGE_OK, retval = XmIMAGE_OK;
	
	setBusy(True);

	/* get current document */
	this_doc = &doc_cache[current_doc];

	for(i = 0; i < this_doc->nimages; i++)
	{
		url = this_doc->images[i];

		/* get image to update */
		if((image = (XmImageInfo*)getURLObjectFromCache(url)) == NULL)
			continue;

		/* only do this when the image hasn't been loaded yet */
		if(image->options & XmIMAGE_DELAYED &&
			(filename = resolveFile(url)) != NULL)
		{
			if(strstr(url, ","))
				new_image = loadAnimation(url); 
			else
			{
				new_image = XmHTMLImageDefaultProc(html_widgets[0].html,
					filename, NULL, 0);
				free(filename);
			}
			if(new_image)
			{
				/* don't let XmHTML free it */
				new_image->options &= ~(XmIMAGE_DEFERRED_FREE) &
					~(XmIMAGE_DELAYED);
				/*****
				* Replace it. XmHTMLImageReplace returns a statuscode 
				* indicating success of the action. If XmIMAGE_OK is returned,
				* no call to XmHTMLRedisplay is necessary, the dimensions are
				* the same as specified in the document. It returns
				* XmIMAGE_ALMOST if a recomputation of document layout is
				* necessary, and something else if an error occured:
				* XmIMAGE_ERROR: the widget arg is not a XmHTML widget or
				*	pixmap creation failed;
				* XmIMAGE_BAD if image and/or new_image is NULL;
				* XmIMAGE_UNKNOWN if image is unbound to an internal image.
				*****/
				retval = XmHTMLImageReplace(html_widgets[0].html, image,
					new_image);

				/* update private cache */
				replaceObjectInCache((XtPointer)image, (XtPointer)new_image);

				/* and destroy previous image data */
				XmHTMLImageFreeImageInfo((Widget)html_widgets[0].html, image);
			}
		}
		else	/* same note as above applies */
			retval = XmHTMLImageUpdate(html_widgets[0].html, image);

		/* store return value of ImageReplace and/or ImageUpdate */
		if(retval == XmIMAGE_ALMOST)
			status = retval;
	}
	/* force a reformat and redisplay of the current document if required */
	if(status == XmIMAGE_ALMOST)
		XmHTMLRedisplay(html_widgets[0].html);

	/* keep focus on the html widget */
	XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);

	setBusy(False);
}

/*****
* Name: 		killImages
* Return Type: 	void
* Description: 	kills all images (normal *and* delayed) of all documents.
*				Should be called at exit.
* In: 
*	nothing.
* Returns:
*	nothing.
*****/
static void 
killImages(void)
{
	setBusy(True);

	destroyObjectCache();

	setBusy(False);
}

static void
progressiveButtonCB(Widget w, int reset)
{
	int curr_state = 0;
	String label;
	XmString xms;

	if(reset)
	{
		if(XtIsManaged(prg_button))
			XtUnmanageChild(prg_button);

		/* set new label and global PLC state */
		xms = XmStringCreateLocalized("Suspend Image Load");
		XtVaSetValues(prg_button,
			XmNlabelString, xms,
			XmNuserData, (XtPointer)STREAM_OK,
			NULL);
		XmStringFree(xms);
		return;
	}

	/* get current progressive image loading state */
	XtVaGetValues(w, XmNuserData, &curr_state, NULL);

	switch(curr_state)
	{
		case STREAM_OK:
			XmHTMLImageProgressiveSuspend(html_widgets[0].html);
			curr_state = STREAM_SUSPEND;
			label = "Continue Image Load";
			break;
		case STREAM_SUSPEND:
			XmHTMLImageProgressiveContinue(html_widgets[0].html);
			curr_state = STREAM_OK;
			label = "Suspend Image Load";
			break;
		default:
			fprintf(stderr, "Oops, unknown button state in "
				"progressiveButtonCB\n");
			return;
	}

	/* set new label and global PLC state */
	xms = XmStringCreateLocalized(label);
	XtVaSetValues(prg_button,
		XmNlabelString, xms,
		XmNuserData, (XtPointer)curr_state,
		NULL);
	XmStringFree(xms);
}

/*****
* Name:			getImageData
* Return Type: 	int
* Description: 	XmHTMLGetDataProc method. Called when we are to
*				load images progressively.
* In: 
*	stream:		Progressive Load Context stream object
*	buffer:		destination buffer.
* Returns:
*	STREAM_END when we have run out of data, number of bytes copied into the
*	buffer otherwise.
* Note:
*	This routine is an example implementation of how to write a
*	XmHTMLGetDataProc method. As this program doesn't have networking
*	capabilities, we mimic a connection by providing the data requested in
*	small chunks (which is a command line option: prg_skip [number of bytes]).
*	The stream argument is a structure containing a minimum and maximum byte
*	count (the min_out and max_out fields), a number representing the number
*	of bytes used by XmHTML (the total_in field) and user_data registered
*	with the object that is being loaded progressively.
*
*	If this routine returns data, it must *always* be a number between
*	min_out and max_out (including min_out and max_out). Returning less is
*	not an advisable thing to do (it will cause an additional call immediatly)
*	and returning more *can* cause an error (by overflowing the buffer).
*
*	You can let XmHTML expand it's internal buffers by setting the max_out
*	field to the size you want the buffer to have and returning STREAM_RESIZE.
*	XmHTML will then try to resize its internal buffers to the requested size
*	and call this routine again immediatly. When a buffer has been resized, it
*	is very likely that XmHTML will backtrack to an appropriate starting point,
*	so be sure to check and use the total_in field of the stream arg when 
*	returning data.
*
*	If you want to abort progressive loading, you can return STREAM_ABORT.
*	This will cause XmHTML to terminate the progressive load for the given
*	object (which involves a call to any installed XmHTMLProgressiveEndData
*	method). Example use of this could be an ``Abort'' button. An alternative
*	method is to use the XmHTMLImageProgressiveKill() convenience routine as
*	shown in the getAndSetFile() routine above.
*
*	Also note that returning 0 is equivalent to returning STREAM_END (which
*	is defined as being 0).
*
*	As a final note, XmHTML will ignore any bytes copied into the buffer
*	if you return any of the STREAM_ codes.
*****/
static int
getImageData(XmHTMLPLCStream *stream, XtPointer buffer)
{
	ImageBuffer *ib = (ImageBuffer*)stream->user_data;
	int len;

	Debug(("getImageData, request made for %s\n", ib->file));
	Debug(("getImageData, XmHTML already has %i bytes\n", stream->total_in));

	/* no more data available, everything has been copied */
	if(ib->next >= ib->size)
		return(STREAM_END);

	/*
	* Maximum no of bytes we can return. ib->size contains the total size of
	* the image data, and total_in contains the number of bytes that have
	* already been used by XmHTML so far.
	* total_in may differ from ib->next due to backtracking of the calling PLC.
	*/
	len = ib->size - stream->total_in;

	/*
	* If you want to flush all data you've got to XmHTML but max_out is too
	* small, you can do something like this:
	* if(len > stream->max_out)
	* {
	*	stream->max_out = len;
	*	return(STREAM_RESIZE);
	* }
	* As noted above, XmHTML will then resize it's internal buffers to fit
	* the requested size and call this routine again. Before I forget, the
	* default size of the internal buffers is 2K.
	* And no, setting max_out to 0 will not cause XmHTML to choke. It will
	* simply ignore it (and issue a blatant warning message accusing you of
	* being a bad programmer :-).
	*/
	if(progressive_data_inc)
	{
		/* increment if not yet done for this pass */
		if(!ib->may_free)
		{
			progressive_data_skip += progressive_data_inc;

			Debug(("getImageData, incrementing buffer size to %i bytes\n",
				progressive_data_skip));

			stream->max_out = progressive_data_skip;
			ib->may_free = True;
			return(STREAM_RESIZE);
		}
		else	/* already incremented, copy data for this pass */
			ib->may_free = False;
	}

	/* provide the minimum if our skip is too small */
	if(len < stream->min_out || progressive_data_skip < stream->min_out)
		len = stream->min_out;
	else
		len = progressive_data_skip;

	/* final sanity */
	if(len + stream->total_in > ib->size)
		len = ib->size - stream->total_in;

	/* more bytes available than minimally requested, we can copy */
	if(len >= stream->min_out)
	{
		/* but don't exceed the maximum allowable amount to return */
		if(len > stream->max_out)
			len = stream->max_out;

		Debug(("getImageData, returning %i bytes (min_out = %i, "
			"max_out = %i)\n", len, stream->min_out, stream->max_out));

		memcpy((char*)buffer, ib->buffer + stream->total_in, len);
		ib->next = stream->total_in + len;
		return(len);
	}
	/*
	* some sort of error, XmHTML requested data beyond the end of the file,
	* so we just return STREAM_END here and let XmHTML decide what to do.
	*/
	return(STREAM_END);
}

static void
endImageData(XmHTMLPLCStream *stream, XtPointer data, int type, Boolean ok)
{
	XmImageInfo *image = (XmImageInfo*)data;
	ImageBuffer *ib;

	/*
	* XmHTML signals us that there are no more images being loaded
	* progressively. Remove ``Suspend Image Load'' button.
	* Beware: this is the only case in which stream is NULL.
	*/
	if(type == XmPLC_FINISHED)
	{
		XtSetSensitive(prg_button, False);
		XtUnmanageChild(prg_button);
		return;
	}

 	ib = (ImageBuffer*)stream->user_data;

	/*
	* To keep the cache size in sync, we update the cached image by replacing
	* it. As we will be replacing the same object, the only effect this call
	* will have is that the sizeObjectProc will be called.
	*/
	if(ok)
		replaceObjectInCache((XtPointer)image, (XtPointer)image);
	else
	{
		/* incomplete image, remove it from the image cache */
		removeObjectFromCache(ib->file);
		cleanObjectCache();
	}

	Debug(("endImageData, called for %s, ok = %s\n", ib->file,
		ok ? "True" : "False"));

	free(ib->file);
	free(ib->buffer);
	free(ib);
}

/*****
* Name: 		loadImage
* Return Type: 	XmImageInfo
* Description: 	XmHTMLimageProc handler
* In: 
*	w:			HTML widget id
*	url:		src value of an img element.
* Returns:
*	return value from the HTML widget imageDefaultProc
* Note:
*	this is a very simple example of how to respond to requests for images:
*	XmHTML calls this routine with the name (or location or whatever the
*	src value is) of an image to load. All you need to do is get the full
*	name of the image requested and call the imageDefaultProc and let XmHTML
*	handle the actual loading.
*	This is also the place to fetch remote images, implement an imagecache
*	or add support for images not supported by the imageDefaultProc.
*****/
static XmImageInfo*
loadImage(Widget w, String url)
{
	String filename = NULL;
	XmImageInfo *image = NULL;
	DocumentCache *this_doc;
	int i;

	/* get current document */
	this_doc = &doc_cache[current_doc];

	Debug(("Requested to load image %s\n", url));

	/*****
	* get full path for this url. The "," strstr is used to check if this
	* image is an animation consisting of a list of comma-separated images
	* (see examples/test-pages/animation?.html for an example)
	*****/
	if((filename = resolveFile(url)) == NULL)
		if(!strstr(url, ","))
			return(NULL);

	/* 
	* add this image to this document's image list.
	* First check if we haven't got it already, can only happen when the 
	* document is reloaded (XmHTML doesn't load identical images).
	* Use original URL for this.
	*/
	for(i = 0; i < this_doc->nimages; i++)
	{
		if(!(strcmp(this_doc->images[i], url)))
			break;
	}
	/* don't have it yet */
	if(i == this_doc->nimages)
	{
		/* see if it can hold any more images */
		if(this_doc->nimages != MAX_IMAGE_ITEMS)
		{
			this_doc->images[this_doc->nimages++] = strdup(url);
			i = this_doc->nimages;
		}
		else
		{
			char buf[128];
			sprintf(buf, "This document contains more than %i images,\n"
				"Only the first %i will be shown.", MAX_IMAGE_ITEMS,
  				MAX_IMAGE_ITEMS);
			XMessage(toplevel, buf);
			return(NULL);
		}
	}

	/* now check if we have this image already available */
	if((image = (XmImageInfo*)getObjectFromCache(filename, url)) != NULL)
	{
		/*
		* If i isn't equal to the current no of images for the current
		* document, the requested image has already been loaded once for this
		* document, so we do not have to store it again.
		*/
		/* call storeImage again as we might be using a different URL */
		if(i == this_doc->nimages)
			storeObjectInCache((XtPointer)image,
				filename ? filename : url, url);
		if(filename)
			free(filename);
		return(image);
	}

	if(filename || (strstr(url, ",")) != NULL)
	{
		/* test delayed image loading */
		if(html_config[OPTIONS_AUTO_IMAGE_LOAD].value)
		{
			if(strstr(url, ","))
				image = loadAnimation(url);
			else
			{
				if(!progressive_images)
					image = XmHTMLImageDefaultProc(w, filename, NULL, 0);
				else
				{
					unsigned char img_type;

					img_type = XmHTMLImageGetType(filename, NULL, 0);

					if(img_type != IMAGE_ERROR && img_type != IMAGE_UNKNOWN &&
						img_type != IMAGE_XPM && img_type != IMAGE_PNG)
					{
						FILE *file;
						static ImageBuffer *ib;

						/* open the given file */
						if((file = fopen(filename, "r")) == NULL)
						{
							perror(filename);
							return(NULL);
						}

						/*
						* We load the image data into an ImageBuffer (which
						* we will be using in the get_data() function.
						*/
						ib = (ImageBuffer*)malloc(sizeof(ImageBuffer));
						ib->file = strdup(filename);
						ib->next = 0;

						/* see how large this file is */
						fseek(file, 0, SEEK_END);
						ib->size = ftell(file);
						rewind(file);

						/* allocate a buffer to contain the entire image */
						ib->buffer = malloc(ib->size+1);

						/* now read the contents of this file */
						if((fread(ib->buffer, 1, ib->size, file)) != ib->size)
							printf("Warning: did not read entire file!\n");
						ib->buffer[ib->size] = '\0';	/* sanity */

						/* create an empty ImageInfo */
						image = (XmImageInfo*)malloc(sizeof(XmImageInfo));
						memset(image, 0, sizeof(XmImageInfo));

						/* set the Progressive bit and allow scaling */
						image->options =XmIMAGE_PROGRESSIVE|XmIMAGE_ALLOW_SCALE;
						image->url = strdup(filename);

						/* set file buffer as user data for this image */
						image->user_data = (XtPointer)ib;

						/* make the progressive image loading button visible */
						if(!XtIsManaged(prg_button))
							XtManageChild(prg_button);

						XtSetSensitive(prg_button, True);

						/* all done! */
					}
					else
						image = XmHTMLImageDefaultProc(w, filename, NULL, 0);
				}
			}
			/* failed, too bad */
			if(!image)
				return(NULL);

			/* don't let XmHTML free it */
			image->options &= ~(XmIMAGE_DEFERRED_FREE);
		}
		else
		{
			image = (XmImageInfo*)malloc(sizeof(XmImageInfo));
			memset(image, 0, sizeof(XmImageInfo));
			image->options = XmIMAGE_DELAYED|XmIMAGE_ALLOW_SCALE;
			image->url = strdup(filename ? filename : url);
		}
		/* store in the cache */
		storeObjectInCache((XtPointer)image, filename ? filename : url, url);
	}
	if(filename)
		free(filename);
	
	return(image);
}

/*****
* Name: 		testAnchor
* Return Type: 	int
* Description: 	XmNanchorVisitedProc procedure
* In: 
*	w:			widget
*	href:		href to test
* Returns:
*	True when the given href has already been visited, false otherwise.
* Note:
*	This is quite inefficient. In fact, the whole history scheme is 
*	inefficient, but then again, this is only an example and not a full 
*	featured browser ;-)
*****/
static int
testAnchor(Widget w, String href)
{
	int i, j;

	/* walk each document */
	for(i = 0 ; i < last_doc; i++)
	{
		/* and walk the history list of each document */
		for(j = 0; j < doc_cache[i].nvisited; j++)
			if(doc_cache[i].visited[j] &&
				!strcmp(doc_cache[i].visited[j], href))
				return(True);
	}
	/* we don't know it */
	return(False);
}

/*****
* Name: 		aboutCB
* Return Type: 	void
* Description: 	displays an ``About'' dialog when the help->about menu item
*				is selected.
* In: 
*	widget:		menubutton widget id
*	client_data:	unused
*	call_data:	unused
* Returns:
*	nothing
*****/
static void
aboutCB(Widget widget, XtPointer client_data, XtPointer call_data)
{
	char label[256];
  
	sprintf(label, "A Simple HTML browser using\n"
		"%s\n", XmHTMLVERSION_STRING);
  
	XMessage(toplevel, label);
}

static void
optionsCB(Widget w, int item)
{
	XmString label;
	Boolean set = False;
	int i, argc = 0;
	Arg args[4];

	switch(item)
	{
		/*
		* These are seven XmHTML On/Off resources so we can treat them
		* all in the same manner
		*/
		case OPTIONS_ANCHOR_BUTTONS:
		case OPTIONS_HIGHLIGHT_ON_ENTER:
		case OPTIONS_ENABLE_STRICT_HTML32:
		case OPTIONS_ENABLE_BODYCOLORS:
		case OPTIONS_ENABLE_BODYIMAGES:
		case OPTIONS_ENABLE_DOCUMENT_COLORS:
		case OPTIONS_ENABLE_DOCUMENT_FONTS:
		case OPTIONS_ENABLE_IMAGES:
		case OPTIONS_ENABLE_OUTLINING:
		case OPTIONS_DISABLE_WARNINGS:
		case OPTIONS_FREEZE_ANIMATIONS:

			/* get value */
			XtVaGetValues(w, XmNset, &set, NULL);

			/* check if changed */
			if(set == html_config[item].value)
				break;

			/* store new value */
			html_config[item].value = set;

			Debug(("optionsCB, setting value for resource %s to %s\n",
				html_config[item].name, set ? "True" : "False"));

			/* set new value */
			XtSetArg(args[argc], html_config[item].name,
				html_config[item].value);
			argc++;

			/*
			* if global image support has been toggled, toggle other buttons
			* as well.
			*/
			if(item == OPTIONS_ENABLE_IMAGES)
			{
				XtSetSensitive(html_config[OPTIONS_ENABLE_BODYIMAGES].w, set);
				XtSetSensitive(html_config[OPTIONS_AUTO_IMAGE_LOAD].w, set);
				XtSetSensitive(load_images, set);

				/* set corresponding resources */
				XtSetArg(args[argc],
					html_config[OPTIONS_ENABLE_BODYIMAGES].name,
					set ? html_config[OPTIONS_ENABLE_BODYIMAGES].value:False);
				argc++;
			}

			/* propagate changes down to all active HTML widgets */
			for(i = 0; i < MAX_HTML_WIDGETS; i++)
			{
				if(html_widgets[i].active)
					XtSetValues(html_widgets[i].html, args, argc);
			}
			break;

		case OPTIONS_AUTO_IMAGE_LOAD:
		case OPTIONS_FANCY_TRACKING:
			/* get value */
			XtVaGetValues(w, XmNset, &set, NULL);

			/* check if changed */
			if(set == html_config[item].value)
				break;

			/* store new value */
			html_config[item].value = set;

			Debug(("optionsCB, setting value for %s to %s\n",
				html_config[item].name, set ? "True" : "False"));

			/* change label as well */
			if(set)
				label = XmStringCreateLocalized("Reload Images");
			else
				label = XmStringCreateLocalized("Load Images");
			XtVaSetValues(load_images,
				XmNlabelString, label,
				NULL);
			XmStringFree(label);
			break;

		case OPTIONS_ANCHOR:
			fprintf(stderr, "Configure anchor appearance (not ready)\n");
			break;
		case OPTIONS_FONTS:
			fprintf(stderr, "Configure document fonts (not ready).\n");
			break;
		case OPTIONS_BODY:
			fprintf(stderr, "Configure default body settings (not ready).\n");
			break;
		case OPTIONS_IMAGE:
			fprintf(stderr, "Configure default image settings (not ready).\n");
			break;
		default:
			fprintf(stderr, "optionsCB: impossible menu selection "
				"(item = %i)\n", item);
	}
}

/*****
* Name:			Main
* Return Type:	int
* Description:	main for example 2
* In:
*	argc:		no of command line arguments
*	argv:		array of command line arguments
* Returns:
*	EXIT_FAILURE when an error occurs, EXIT_SUCCESS otherwise
*****/
int
main(int argc, char **argv)
{
    char *filename;
    Display *display;
    Widget topLevel;
    XEvent event;
    XtAppContext app_context;
    XSetWindowAttributes setAttrib;
    XClassHint *classhint;
    Atom property;
    Window parent;
    int timeout = 5;
    XtIntervalId TimeoutID;

    filename = strdup(argv[1]);

    topLevel = XtVaAppInitialize(&app_context, NULL, NULL, 0,
                0, NULL, NULL, NULL, NULL);
    display = XtDisplay(topLevel);
    XtVaSetValues(topLevel, XmNoverrideRedirect, True, XmNx,0, XmNy,0,
                  XmNwidth,1,XmNheight,1,NULL);
    XtRealizeWidget(topLevel);

    parent = XtWindow(topLevel);

    setpgrp();

    if (!fork())
    {
        HelloScreen(filename, parent);
        exit(0);
    }

    setAttrib.event_mask = SubstructureNotifyMask;
    XChangeWindowAttributes ( display,
                              XDefaultRootWindow(display),
                              CWEventMask,
                              &setAttrib);
    setAttrib.event_mask = PropertyChangeMask;
    XChangeWindowAttributes ( display,
                              parent,
                              CWEventMask,
                              &setAttrib);

    TimeoutID = XtAppAddTimeOut(app_context,
                                (unsigned long)60000,
                                Done,
                                NULL);

    property = XInternAtom (display, "_XA_CLIENT_TIMEOUT", False);

    for (;;)
    {
        XtAppNextEvent(app_context, &event);

        if ( event.type == PropertyNotify &&
             event.xproperty.window == parent &&
             event.xproperty.state == PropertyNewValue &&
             event.xproperty.atom == property)
        {
             XtRemoveTimeOut(TimeoutID);
             XtAppAddTimeOut(app_context,
                             (unsigned long)5000,
                             Done,
                             NULL);
        }
        else XtDispatchEvent(&event);
    }

}

void Done(XtPointer client_data, XtIntervalId *id)
{
    exit(0);
}



static void HelloScreen(char *use_file, Window parent)
{

    XEvent event;
    XSetWindowAttributes setAttrib;
    Display *display = NULL; /* shutup compiler */
    Visual *visual = NULL;
    int depth = 0;
    Colormap colormap = 0;

    root_window = False;
    progressive_images = False;

/* set current working directory as the first path to search */
#ifdef _POSIX_SOURCE
    getcwd((char*)(paths[0]), sizeof(paths[0]));
#else
    getwd((char*)(paths[0]));
#endif
    strcat((char*)(paths[0]), "/");
    max_paths = 1;

    toplevel = XtVaAppInitialize(&context, APP_CLASS, NULL, 0,
                                 0, NULL, appFallbackResources, NULL, NULL);
    display = XtDisplay(toplevel);

    /* check if visual, depth or colormap have been given */
    if (getStartupVisual(toplevel, &visual, &depth, &colormap))
    {
        XtVaSetValues(toplevel, XmNvisual, visual, XmNdepth, depth,
                      XmNcolormap, colormap, NULL);

        XInstallColormap(display, colormap);
    }

    XtVaSetValues(toplevel, XmNmwmDecorations, MWM_DECOR_BORDER, 
                  XmNx, 0, XmNy, 0,
                  XmNheight, DisplayHeight(display, DefaultScreen(display)),
                  XmNwidth, DisplayWidth(display, DefaultScreen(display)),
                  NULL);

    html_widgets[0].html = 
        XtVaCreateManagedWidget("html", xmHTMLWidgetClass, toplevel,
                                XmNanchorVisitedProc, testAnchor,
                                XmNimageProc, loadImage,
                                XmNimageEnable, True,
                                XmNprogressiveReadProc, getImageData,
                                XmNprogressiveEndProc, endImageData,
#ifdef HAVE_GIF_CODEC
                                XmNdecodeGIFProc, decodeGIFImage,
#endif
                                XmNheight, 
                                DisplayHeight(display, DefaultScreen(display)),
                                XmNwidth, 
                                DisplayWidth(display, DefaultScreen(display)),
                                XtVaTypedArg, XmNforeground, 
                                XmRString, "white", 6,
                                XtVaTypedArg, XmNbackground, 
                                XmRString, "black", 6,
                                NULL);



    html_widgets[0].active = True;
    html_widgets[0].used   = True;

    /* anchor activation callback */
    XtAddCallback(html_widgets[0].html, XmNactivateCallback,
                  (XtCallbackProc)anchorCB, NULL);

    /* HTML frame callback */
    XtAddCallback(html_widgets[0].html, XmNframeCallback,
                (XtCallbackProc)frameCB, NULL);

    /* set the HTML document callback */
    XtAddCallback(html_widgets[0].html, XmNdocumentCallback,
               (XtCallbackProc)docCB, NULL);

    /* link callback for site structure */
    XtAddCallback(html_widgets[0].html, XmNlinkCallback,
                (XtCallbackProc)linkCB, NULL);

    initCache(5*1024*1024, (cleanObjectProc)destroyCacheObject,
              (sizeObjectProc)getInfoSize, (XtPointer)html_widgets[0].html);

    XtRealizeWidget(toplevel);

    XRaiseWindow(XtDisplay(toplevel), XtWindow(toplevel));

    /* The HTML widget has the focus */
    XmProcessTraversal(html_widgets[0].html, XmTRAVERSE_CURRENT);

    /* if we have a file, load it */
    if (use_file)
    {
        String filename;

        /* get full filename */
        if ((filename = resolveFile(use_file)) != NULL)
        {
            /* load the file, will also update the document cache */
            loadAndOrJump(filename, NULL, True);
            free(filename);
        }
    }

    setAttrib.event_mask = StructureNotifyMask;
    XChangeWindowAttributes(display,
                            XtWindow(toplevel),
                            CWEventMask,
                            &setAttrib);

    XChangeProperty(display,
                    parent,
                    XInternAtom (display, "_XA_CLIENT_TIMEOUT", False),
                    XA_STRING,
                    8,
                    PropModeReplace,
                    (unsigned char *)"client",
                    7);

    XFlush(display);
    XSync(display, False);

    /* enter the event loop */
    for (;;) 
    {
        XtAppNextEvent(context, &event);
        if (event.type == ReparentNotify &&
            event.xreparent.window == XtWindow(toplevel))
        {
            XtDestroyApplicationContext(context);
            exit(0);
        }
        else XtDispatchEvent(&event);
    }

    /* never reached, but keeps compiler happy */
    exit(EXIT_SUCCESS);
}

