/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/
#pragma ident	"@(#)xaux_ext_common.c 1.21 99/12/08"

#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

#include <X11/X.h>
#include <X11/Xatom.h>

#include "trace_message.h"

#include "iiimpAux.h"
#include "xaux_common.h"
#include "xaux_ext_common.h"

/* from iiimpAux.c */
size_t
utf16_mb(
        const char **   inbuf,
        size_t *        inbytesleft,
        char **         outbuf,
        size_t *        outbytesleft)
{
        int     r;

        r = IIimpConvertFromUTF16((char *)(*inbuf), *inbytesleft,
                                  outbuf, outbytesleft);
        return (size_t)r;
}

size_t
mb_utf16(
        const char **   inbuf,
        size_t *        inbytesleft,
        char **         outbuf,
        size_t *        outbytesleft)
{
        int     r;

        r = IIimpConvertToUTF16((char *)(*inbuf), *inbytesleft,
                                  outbuf, outbytesleft);
        return (size_t)r;
}


static Bool
xaux_xs_get_sowin(
	xaux_class_t	*xc,
	Display		*display)
{
	size_t		i;


	xc->sowin = XGetSelectionOwner(display, xc->atom_sowin);

	if (xc->sowin == None)
		return False;
	else
		return True;
}

static Bool
xaux_xs_send_property(
	Display *		display,
	xaux_class_t *		xc,
	int			im_id,
	int			ic_id,
	const unsigned char *	p,
	int			len)
{
	if ((xc->sowin == None) &&
		(xaux_xs_get_sowin(xc, display) == False)) {
		return False;
	}

	XChangeProperty(display, xc->sowin,
		xc->atom_xs[xc->atom_xs_idx], XA_STRING,
		8, PropModeReplace, (unsigned char *)p, len);

	if (xaux_xs_send_message(display, xc, im_id, ic_id,
		AUX_EXT_DATA_SETVALUE, xc->atom_xs[xc->atom_xs_idx]) == False) {
			return False;
	}

	/* XFlush() has been called in xaux_xs_send_message() */

	if (++xc->atom_xs_idx == XAUX_XS_NATOMS)
		xc->atom_xs_idx = 1;
	
	return True;
}

Bool
xaux_xs_send_message(
	Display *	display,
	xaux_class_t *	xc,
	int		im_id,
	int		ic_id,
	aux_ext_data_type_t	type,
	Atom		atom)
{
	XClientMessageEvent	event;

	if ((xc->sowin == None) &&
		(xaux_xs_get_sowin(xc, display) == False)) {
		return False;
	}
		
	event.type = ClientMessage;
	event.serial = 0;
	event.send_event = True;
	event.display = display;
	event.window = xc->sowin;
	event.message_type = xc->atom_xs[0];
	event.format = 32;

	event.data.l[0] = xc->atom_classname;
	event.data.l[1] = ((CARD16)im_id << 8) | ((CARD16)ic_id & 0xffff);
	event.data.l[2] = xc->index;
	event.data.l[3] = type;
	if (type == AUX_EXT_DATA_SETVALUE) {
		event.data.l[4] = atom;
	} else {
		event.data.l[4] = 0; /* unused */
	}

	XSendEvent(display, xc->sowin, True, 0, (XEvent *)(&event));

	XFlush(display);

	return True;
}

static Bool
xaux_ext_process_property_update(
	Display	*		display,
	Window			window,
	Atom			atom)
{
	Atom		actual_type_return;
	int		actual_format_return;
	unsigned long	nitem_return;
	unsigned long	bytes_after_return;
	unsigned char *	prop_return;
	int		r;
	int		imid;
	int		size;
	aux_ext_data_t	aux_ext_data_;
	aux_ext_data_t *	aux_ext_data = &(aux_ext_data_);
	unsigned char *	p;
	int		i;
	int		n=0;
	xaux_class_t	*xc = &xaux_class;
	XPoint		point;
	Bool		rv;
	int		type;
	char *		outbuf_ = NULL;

	if (window != xc->extwin && window != xc->sowin) {
		return False;
	}

	r = XGetWindowProperty(display, window,
			       atom, 0, INT_MAX, False,
			       AnyPropertyType, &actual_type_return,
			       &actual_format_return, &nitem_return,
			       &bytes_after_return, &prop_return);

	if (r != Success || actual_type_return == 0) {
		return False;
	}

	type = SX_PROP_TYPE(prop_return);

	/* ClientMessage detoured to property, due to extwin not
	   available yet */
	if (type == AUX_DATA_START || type == AUX_DATA_DONE) {
		aux_ext_data_t	aux_ext_data_;
		aux_ext_data_t	*aux_ext_data = &(aux_ext_data_);
		xaux_class_t	*xc = &xaux_class;

		if (SX_PROP_ATOM_AUX_NAME(prop_return) != xc->atom_classname) {
			return False;
		}

		aux_ext_data->im = SX_PROP_IMID(prop_return);
		aux_ext_data->ic = SX_PROP_ICID(prop_return);
		aux_ext_data->aux_index = SX_PROP_INDEX(prop_return);

		switch (type) {
		case AUX_EXT_DATA_START:
#if defined(DEBUG_XAUX)
			fprintf(stderr, "[%s] received START via property\n",
				xc->classname);
#endif /* defined(DEBUG_XAUX) */
			return xaux_ext_Start(xc, aux_ext_data);
			break;
		case AUX_EXT_DATA_DONE:
#if defined(DEBUG_XAUX)
			fprintf(stderr, "[%s] received DONE via property\n",
				xc->classname);
#endif /* defined(DEBUG_XAUX) */
			return xaux_ext_Done(xc, aux_ext_data);
			break;
		default:
			return False;
		}
	}

	/* header */

	aux_ext_data->type = AUX_EXT_DATA_DRAW;
	aux_ext_data->im = SX_PROP_IMID(prop_return);
	aux_ext_data->ic = SX_PROP_ICID(prop_return);
	aux_ext_data->aux_index = xc->index;
	aux_ext_data->aux_name = (unsigned char *)xc->classname;
	aux_ext_data->aux_name_length =
		strlen((const char *)aux_ext_data->aux_name);

	/* int values */

	aux_ext_data->integer_count = SX_PROP_INT_COUNT(prop_return);

	if (aux_ext_data->integer_count > 0) {
		aux_ext_data->integer_list =
			(int *)SX_PROP_INT_LIST(prop_return);
	} else {
		aux_ext_data->integer_list = NULL;
	}

	/* string values */

	aux_ext_data->string_count = SX_PROP_STR_COUNT(prop_return);

	if (aux_ext_data->string_count > 0) {
		unsigned char * prop_str = SX_PROP_STR_LIST(prop_return);
		char *		outbuf;
		size_t		outbufsiz, c;

		if ((aux_ext_data->string_list =
			(aux_ext_string_t *)malloc(sizeof (aux_ext_string_t) *
				aux_ext_data->string_count)) == NULL) {
				XFree(prop_return);
				return False;
		}

		/*
		 * to make calcuration easier, assume no padding
		 * so allocated area can be larger than needed
		 */
		/* total bytes of the property */
		c  = nitem_return; 
		/* total bytes used for string_values in the property  */
		c -= SX_PROP_STR_LIST(prop_return) - prop_return;
		/* eliminate area for length values */
		c -= aux_ext_data->string_count * sizeof(CARD16);
		/* if all of the area is filled with UTF-16.... */
		c /= sizeof (CARD16);
		/* multiply with MB_CUR_MAX */
		c *= MB_CUR_MAX;
		/* for null termination of each string */
		c += aux_ext_data->string_count;
		outbufsiz = c;

		/* allocate outbuf_ */
		if ((outbuf_ = (char *)malloc(outbufsiz)) == NULL) {
			free(aux_ext_data->string_list);
			XFree(prop_return);
			return False;
		}

		outbuf = &(outbuf_[0]);

		for(i = 0; i < aux_ext_data->string_count; i++) {
			char *		ib;
			char *		ob;
			size_t		ibl;
			size_t		obl = outbufsiz;
			size_t		obl_save;

			/* assign length of a string to ibl */
			ibl = (size_t)*((CARD16 *)(prop_str));
			/* move prop_str to point head of the string */
			prop_str += sizeof(CARD16);
			/* assign head of the string to ib */
			ib = (char *)prop_str;
			/* move prop_str to point lenght of next string */
			prop_str += (ibl + padding[(sizeof(CARD16) + ibl) % 4]);

			ob = outbuf;
			obl_save = obl;

			aux_ext_data->string_list[i].ptr = (unsigned char *)ob;

			utf16_mb((const char **)&ib, &ibl, &ob, &obl);

			aux_ext_data->string_list[i].length = obl_save - obl;
			outbuf = ob + aux_ext_data->string_list[i].length;

			/* null termination */
			*(outbuf++) = '\0';
		}
	} else {
		aux_ext_data->string_list = NULL;
	}

	aux_ext_data->string_ptr = NULL;

	aux_ext_data->clientwin = SX_PROP_CLIENTWIN(prop_return);
	aux_ext_data->point.x = SX_PROP_POSX(prop_return);
	aux_ext_data->point.y = SX_PROP_POSY(prop_return);
	aux_ext_data->focuswin = SX_PROP_FOCUSWIN(prop_return);

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] received DRAW via property\n",
		xc->classname);
#endif /* defined(DEBUG_XAUX) */
	rv = xaux_ext_Draw(xc, aux_ext_data);

	free(aux_ext_data->string_list);
	if (outbuf_ != NULL) {
		free(outbuf_);
	}
	XFree(prop_return);

	return rv;
}

Bool
xaux_ext_process_client_message(
	Display	*		display,
	XClientMessageEvent *	event)
{
	aux_ext_data_t	aux_ext_data_;
	aux_ext_data_t	*aux_ext_data = &(aux_ext_data_);
	aux_ext_data_type_t	type;
	xaux_class_t	*xc = &xaux_class;

	if (event->data.l[0] != xc->atom_classname) {
		return False;
	}

	if (event->message_type != xc->atom_sx[0]) {
		return False;
	}

	if (event->window != xc->extwin) {
		return False;
	}

	aux_ext_data->im = ((CARD32)(event->data.l[1])) >> 16;
	aux_ext_data->ic = ((CARD32)(event->data.l[1])) & 0xffff;
	aux_ext_data->aux_index = (CARD32)(event->data.l[2]);

	type = (CARD32)(event->data.l[3]);

	switch (type) {
	case AUX_EXT_DATA_START:
#if defined(DEBUG_XAUX)
		fprintf(stderr, "[%s] received START via ClientMessage\n",
			xc->classname);
#endif /* defined(DEBUG_XAUX) */
		return xaux_ext_Start(xc, aux_ext_data);
		break;
	case AUX_EXT_DATA_DRAW:
#if defined(DEBUG_XAUX)
		fprintf(stderr, "[%s] notified DRAW via ClientMessage\n",
			xc->classname);
#endif /* defined(DEBUG_XAUX) */
		return xaux_ext_process_property_update(
			display, xc->extwin, (Atom)(CARD32)(event->data.l[4]));
	case AUX_EXT_DATA_DONE:
#if defined(DEBUG_XAUX)
		fprintf(stderr, "[%s] received DONE via ClientMessage\n",
			xc->classname);
#endif /* defined(DEBUG_XAUX) */
		return xaux_ext_Done(xc, aux_ext_data);
		break;
	default:
		return False;
	}
}

Bool
xaux_ext_init_classes(
	Display		*display,
	xaux_class_t	*p,
	Window		extwin)
{
	char		buf[1024];
	int		i;

	p->atom_classname = XInternAtom(display, p->classname, False);

	sprintf(buf, "%s%s", p->classname, XAUX_SOWIN_SUFFIX);
	p->atom_sowin = XInternAtom(display, buf, False);

	sprintf(buf, "%s%s", p->classname, XAUX_EXTWIN_SUFFIX);
	p->atom_extwin = XInternAtom(display, buf, False);

	for (i = 0; i < XAUX_SX_NATOMS; i++) {
		sprintf(buf, "%s%s_%d", p->classname, XAUX_SX_SUFFIX, i);
		p->atom_sx[i] = XInternAtom(display, buf, False);
	}

	p->atom_sx_idx = 1;

	for (i = 0; i < XAUX_XS_NATOMS; i++) {
		sprintf(buf, "%s%s_%d", p->classname, XAUX_XS_SUFFIX, i);
		p->atom_xs[i] = XInternAtom(display, buf, False);
	}

	p->atom_xs_idx = 1;

	p->sowin = (Window)0;

	p->extwin = extwin;

	if (XGetSelectionOwner(display, p->atom_extwin) != None) {
#if defined(DEBUG_XAUX)
		fprintf(stderr, "%s: %s already exists.[%s](1)\n",
			ME_EXT, ME_EXT, p->classname);
#endif /* defined(DEBUG_XAUX) */
		return False;
	}

	XSetSelectionOwner(display, p->atom_extwin, p->extwin, CurrentTime);

	if (XGetSelectionOwner(display, p->atom_extwin) != p->extwin) {
#if defined(DEBUG_XAUX)
		fprintf(stderr, "%s: %s already exists.[%s](2)\n",
			ME_EXT, ME_EXT, p->classname);
#endif /* defined(DEBUG_XAUX) */
		XDestroyWindow(display, p->extwin);
		p->extwin = (Window)0;
		return False;
	}

	/* process sx properties which has been put on sowin before
	   extwin is prepared */
	if (xaux_xs_get_sowin(p, display) == True) {
		for (i = p->atom_sx_idx; i < XAUX_SX_NATOMS; i++) {
			if (xaux_ext_process_property_update(
				display, p->sowin, p->atom_sx[i]) == False) {
				break;
			}
		}
	}
	return True;
}

Bool
xaux_ext_SetValue(
	Display		*display,
	xaux_class_t	*xc,
	aux_ext_data_t	*aux_ext_data)
{
	static char	*string_buf = NULL;
	static size_t	bufsize = 0;
	size_t		i;
	size_t		total = 0;
	int		*ip;
	char		*sp;
	Bool		rv = True;

	if (aux_ext_data == NULL) {
		/* reset; free string_buf */
		if (string_buf != NULL) {
			free(string_buf);
			string_buf = NULL;
		}
		bufsize = 0;
		return True;
	}

	total = XS_SIZE_PROP_HEADER_SETVALUE
		+ (sizeof (CARD32) * aux_ext_data->integer_count);

	if (aux_ext_data->string_count > 0) {
		for (i = 0; i < aux_ext_data->string_count; i++) {
			size_t	len;

			len = aux_ext_data->string_list[i].length
				* sizeof (CARD16);
			total += ((sizeof (CARD16) + len + 3) / 4) * 4;
		}

		/*
		 * "+1" is required by mb_utf16() method.
		 * The method uses the area for BOM.
		 */
		total += sizeof (CARD16);
	}

	/* tentatively use realloc(); may replace with malloc() later */
	/* othewise, cleanup (freeing) routine should be provided */
	if (total > bufsize) {
		string_buf = realloc(string_buf, total);
		if (string_buf == NULL) {
			bufsize = 0;
			return False;
		}
		bufsize = total;
	}

	XS_PROP_ATOM_AUX_NAME(string_buf) = xc->atom_classname;
	XS_PROP_IMID(string_buf) = aux_ext_data->im;
	XS_PROP_ICID(string_buf) = aux_ext_data->ic;

	XS_PROP_INT_COUNT(string_buf) = aux_ext_data->integer_count;
	XS_PROP_STR_COUNT(string_buf) = aux_ext_data->string_count;


	ip = (int *)XS_PROP_INT_LIST(string_buf);

	if (aux_ext_data->integer_count > 0) {

		for (i = 0; i < aux_ext_data->integer_count; i++) {
			*ip++ = aux_ext_data->integer_list[i];
		}
	}

	sp = (char *)XS_PROP_STR_LIST(string_buf);

	if (aux_ext_data->string_count > 0) {
		char *	ob;
		size_t	obl;

		ob = sp;
		obl = total - XS_SIZE_PROP_HEADER_SETVALUE
			- (sizeof (CARD16) * aux_ext_data->integer_count);

		for (i = 0; i < aux_ext_data->string_count; i++) {
			char *		ib;
			size_t		ibl;
			size_t		obl_save;
			int		pn;
			CARD16 *	plen;
			int		j;

			ib = (char *)(aux_ext_data->string_list[i].ptr);
			ibl = (size_t)aux_ext_data->string_list[i].length;

			/* remember area for length, then skip the area */
			plen = (CARD16 *)ob;
			ob += sizeof (CARD16);
			obl -= sizeof (CARD16);

			obl_save = obl;

			mb_utf16((const char **)&ib, &ibl, &ob, &obl);

			/* store length */
			*plen = obl_save - obl;

			/* move ob to tail of the string */
			ob += *plen;

			/* padding */
			pn = padding[(sizeof(CARD16) + *plen) % 4];
			for (j = 0; j < pn; j++) {
				*ob++ = 0;
			}
			sp = ob;
		}
	}

#if defined(DEBUG_XAUX)
	fprintf(stderr, "ext_SetValue[%s] im:0x%x ic:0x%x in=%d sn=%d\n",
		xc->classname, aux_ext_data->im, aux_ext_data->ic,
		aux_ext_data->integer_count, aux_ext_data->string_count);
#endif /* defined(DEBUG_XAUX) */

	if (aux_ext_data->integer_count != 0 ||
		aux_ext_data->string_count != 0) {
		rv = xaux_xs_send_property(display, xc,
			aux_ext_data->im, aux_ext_data->ic,
			(unsigned char *)string_buf, (sp - &(string_buf[0])));
	}

	return (rv);
}

#ifdef  USE_CDE_HELP

#if defined(USE_DTACTIONINVOKE)
#include <Dt/Dt.h>
#include <Dt/Action.h>

static void DbReloadProc(XtPointer cd);

#else /* defined(USE_DTACTIONINVOKE) */

#define DTACTION_CMD    "/usr/dt/bin/dtaction"

static int help_available = 0;
static char tmp_file[256];

void
HelpCleanup()
{
    if (help_available) {
        unlink(tmp_file);
    }
}

void
HelpSinalHandler(int unused)
{
    HelpCleanup();
    exit(1);
}

int
HelpXIOErrorHandler(Display * dpy)
{
    HelpCleanup();
    return 0;
}
#endif /* defined(USE_DTACTIONINVOKE) */

typedef struct _RmDatabase {
    char *help_basepath;
} RmDatabase;

static RmDatabase rdb;

static XtResource rdb_items[] = {
  {"helpBasepath", "HelpBasepath", XtRString, sizeof(char*),
   offsetof(RmDatabase, help_basepath), XtRString,
   (XPointer)DEFAULT_HELP_PATH
   },
};

void
HelpInit(
	Widget shell,
        char *ApplicationClass,
	int argc,
	char **argv
)
{
#if defined(USE_DTACTIONINVOKE)
    if (DtInitialize(XtDisplay(shell), shell, argv[0], ApplicationClass)==False) {
        /* DtInitialize() has already logged an appropriate error msg */
        exit(-1);
    }

    /* Load the filetype/action databases */
    DtDbLoad();

    /* Notice changes to the database without needing to restart application */
    DtDbReloadNotify(DbReloadProc, NULL);
#else /* defined(USE_DTACTIONINVOKE) */
    int i;
    char *tmp_dir;
    char tmp_tmp_file[256];

    if (help_available) {
        return;
    }
    XtGetApplicationResources(shell,
                              &rdb, rdb_items, 1,
                              NULL, 0);

    if (access(DTACTION_CMD, X_OK) != 0) {
        return;
    }
    tmp_dir = getenv("HOME");
    if (!tmp_dir) {
        return;
    }

    /* check tmp file exists or not */
    for(i=0;i<10;i++){
        sprintf(tmp_tmp_file, "%s/.dt/tmp/%s.%s", tmp_dir,
            strrchr(ApplicationClass, '.') + 1, "XXXXXX");
        mktemp(tmp_tmp_file);
        if (access(tmp_tmp_file, F_OK) != 0) {
            strcpy(tmp_file, tmp_tmp_file);
	    help_available = 1;
            break;
        }
    }

    if(!help_available){
	return;
    }

    /* At shoutdown of user session */
    XSetIOErrorHandler(HelpXIOErrorHandler);

    signal(SIGKILL, HelpSinalHandler);
    signal(SIGTERM, HelpSinalHandler);
    signal(SIGHUP, HelpSinalHandler);
#endif /* defined(USE_DTACTIONINVOKE) */

    XtGetApplicationResources(shell,
                                &rdb, rdb_items, 1,
                                NULL, 0);

#if defined(DEBUG_XAUX)
   printf("basepath = %s\n", rdb.help_basepath);
#endif /* defined(DEBUG_XAUX) */
}

#if defined(USE_DTACTIONINVOKE)
static void DbReloadProc(XtPointer cd)
{
    /* Pick up any dynamic changes to the database files */
    DtDbLoad();
}
#endif /* defined(USE_DTACTIONINVOKE) */

void
HelpInvoke(
	Widget toplevel,
	char *path_
)
{
#if defined(USE_DTACTIONINVOKE)
    DtActionArg *ap = NULL;
    int nap = 0;
    DtActionInvocationID actionId;
    char path[256];

    sprintf(path, "%s%s", rdb.help_basepath, path_);

#if defined(DEBUG_XAUX)
    printf("actual path = %s\n", path);
#endif /* defined(DEBUG_XAUX) */

    if (path != NULL){
        ap = (DtActionArg*) XtCalloc(1, sizeof(DtActionArg));

        ap[0].argClass = DtACTION_BUFFER;
        ap[0].u.buffer.bp = (void*)path;
        ap[0].u.buffer.size = strlen(path);
        ap[0].u.buffer.type = NULL;
        ap[0].u.buffer.name = NULL;
        ap[0].u.buffer.writable = False;

        nap = 1;
    }

    /* Invoke the specified action */
    actionId = DtActionInvoke(toplevel,"SDtWebClient",ap,nap,NULL,NULL,NULL,True,NULL,NULL);
#else /* defined(USE_DTACTIONINVOKE) */
    FILE *fp;
    pid_t pid;

    if (!help_available) {
        return;
    }
    if (!path_) {
        return;
    }
    if ((fp = fopen(tmp_file, "w")) == NULL) {
        return;
    }
    fprintf(fp, "%s%s\n", rdb.help_basepath, path_);
    fclose(fp);

    pid = fork1();

    if (pid == (pid_t) (-1)) {
        return;
    } else if (0 == pid) {
        execl(DTACTION_CMD, "dtaction",
              "SDtWebClient", tmp_file, NULL);
        _exit(1);
    }
    return;
#endif /* defined(USE_DTACTIONINVOKE) */
}

#else /* USE_CDE_HELP */

void
HelpInvoke(
        char *path
)
{
    char *browser;
    char *basepath;

    pid_t pid, pid2;

    if (!path) {
      return;
    }

#ifdef linux
    pid = fork();
#else
    pid = fork1();
#endif

    if (getenv("HTT_HELP_BROWSER")){
      browser = getenv("HTT_HELP_BROWSER");
    } else {
      browser = "/usr/bin/netscape";
    }

    if (getenv("HTT_HELP_PATH")){
      basepath = getenv("HTT_HELP_PATH");
    } else {
      basepath = DEFAULT_HELP_PATH;
    }

    if (pid == (pid_t) (-1)) {
        return;
    } else if (0 == pid) {
        pid2 = fork();
        if(pid2 == -1) {
            _exit(1);
        } else if(pid2 == 0) {
	    char *help = (char*)malloc(strlen(basepath) + strlen(path) +1 );
	    sprintf(help, "%s%s", basepath, path);
	    execl(browser, browser, help, NULL);
	    free(help);
            _exit(1);
        } else {
            _exit(0);
        }
    } else {
        waitpid(pid, NULL, 0);
    }
    return;
}

#endif /* USE_CDE_HELP */

#if !defined(USE_ICONV) && !defined(USE_CSCONV)
#if defined(sun)
#define USE_ICONV
#else
#define USE_CSCONV
#endif
#endif

#ifdef USE_ICONV
#include <iconv.h> 
#endif

#include <locale.h>
#include <langinfo.h>
#include <strings.h>
#if !defined(USE_CSCONV)
#include <errno.h>
#endif /* !USE_CSCONV */
#if 0
#include "iiimpIM.h"
#include "iiimp.h"
#include "iiimpReq.h"
#endif

#define UTF16_STRLEN	4096

#ifdef USE_CSCONV
#include <dlfcn.h>
#include "csconv.h"
#define CSC_OPEN_LOCALE	"csconv_open_locale"
#define CSC_OPEN	"csconv_open"
#define CSC_CONV	"csconv"
#define CSC_CLOSE	"csconv_close"

typedef csconv_t	(* csc_open_locale_t)(const char *,
					      const char *, const char *);
typedef csconv_t	(* csc_open_t)(const char *, const char *);
typedef size_t		(* csc_conv_t)(csconv_t, const char **, size_t *,
				       char **, size_t *);
typedef int		(* csc_close_t)(csconv_t);

static void *			csc_handle;	
static csc_open_locale_t	csc_open_locale;
static csc_open_t		csc_open;
static csc_conv_t		csc_conv;
static csc_close_t		csc_close;

static char *current_locale = 0;
#endif

#ifdef USE_ICONV
static iconv_t i_conv1 = NULL;
static iconv_t i_conv2 = NULL;
static Bool skip_native_to_utf8_conv = False;
#endif

#ifdef USE_CSCONV
static void
dlopen_csconv()
{
      csc_handle = dlopen(CSC_PATH, RTLD_LAZY);
      if (NULL == csc_handle) {
        csc_handle = (void *)(-1);
	return;
      }

      csc_open_locale = (csc_open_locale_t)dlsym(csc_handle, CSC_OPEN_LOCALE);
      csc_open = (csc_open_t)dlsym(csc_handle, CSC_OPEN);
      csc_conv = (csc_conv_t)dlsym(csc_handle, CSC_CONV);
      csc_close = (csc_close_t)dlsym(csc_handle, CSC_CLOSE);

      if ((NULL == csc_open_locale) || (NULL == csc_open) ||
	  (NULL == csc_conv) || (NULL == csc_close)) {
        dlclose(csc_handle);
	csc_handle = (void *)(-1);
	return;
      }
}
#endif

int
IIimpConvertToUTF16(char *from_buf, size_t from_left,
		    char **to_buf, size_t *to_left) {
  size_t src_len, dst_len;
  char *src, *dst;
#ifndef USE_CSCONV
  const char *ip;
  size_t ileft;
  char *op;
  size_t oleft;
  char buffer[UTF16_STRLEN];		/* Fix me! */
#endif /* !USE_CSCONV */
  const size_t buf_len = UTF16_STRLEN;
  size_t ret = 0;
#ifdef USE_CSCONV
  static csconv_t csconv_cd = NULL;

#endif

#ifdef USE_CSCONV
  if (current_locale == NULL){
    current_locale = (char*)strdup(setlocale(LC_CTYPE, NULL));
  }

  do {
    if (((void *)(-1) == csc_handle) ||
	((csconv_t)(-1) == csconv_cd)) {
      continue;
    }
    if (NULL == csc_handle) {
      dlopen_csconv();
      if ((void *)(-1) == csc_handle) {
	continue;
      }
    }
    if (NULL == csconv_cd) {

      csconv_cd = (csc_open_locale)(current_locale, "UTF-16", "MultiByte");
      
      if ((csconv_t)(-1) == csconv_cd) {
	continue;
      }
    }

    dst = *((char **)to_buf);

    ret = csc_conv(csconv_cd,
		   (const char **)&from_buf, &from_left,
		   &dst, to_left);
    return ret;
  } while (0);
#endif

#ifdef USE_ICONV
  if (i_conv1 == (iconv_t)-1 || i_conv2 == (iconv_t)-1){
    goto done;
  }

  if (i_conv1 == NULL && !skip_native_to_utf8_conv) {
    char *encoding = nl_langinfo(CODESET);
    if (!strcmp(encoding, "UTF-8")) {
      skip_native_to_utf8_conv = True;
    } else {
      if ((i_conv1 = iconv_open("UTF-8", encoding))
	  == (iconv_t)-1) {
	goto done;
      }
    }
  }

  if (i_conv2 == NULL){
    if ((i_conv2 = iconv_open("UCS-2",
			      "UTF-8")) == (iconv_t)-1)
      goto done;
  }

  if (!skip_native_to_utf8_conv) {
    ip = (const char *)from_buf;
    ileft = from_left;

    op = *((char **)to_buf);
    oleft = *to_left;

    while ((0 < ileft) && (0 < oleft)) {
      dst = buffer;
      dst_len = buf_len;
      ret = iconv(i_conv1, &ip, &ileft, (char**)&dst, &dst_len);
      if ((ret != 0) && (E2BIG != errno)) {
	goto done;
      }

      src = buffer;
      src_len = buf_len - dst_len;

      ret = iconv(i_conv2, (const char**)&src, &src_len, &op, &oleft);
      if (ret != 0) goto done;
    }

    dst_len = oleft;

  } else {
    src = from_buf;
    src_len = from_left;
    dst = *to_buf;
    dst_len = *to_left;

    ret = iconv(i_conv2, (const char**)&src, &src_len, (char**)&dst, &dst_len);
  }

  if (0xFEFF == **((CARD16 **)to_buf)) {
    memmove(*to_buf, *to_buf + 2, *to_left - dst_len - 2);
    *to_left = (dst_len + 2);
  } else {
    *to_left = dst_len;
  }
done:
#endif /* USE_ICONV */
  return(ret);
}

#ifdef USE_ICONV
static iconv_t i_conv1_FromUTF16 = NULL;
static iconv_t i_conv2_FromUTF16 = NULL;
#endif

/* Used when transfering data from AUX to IM,
   do data conversion from UCS2 to EUC */
int
IIimpConvertFromUTF16(char *from_buf, size_t from_left,
		      char **to_buf, size_t * to_left) {
  size_t src_len, dst_len;
  char *src, *dst;
#ifndef USE_CSCONV
  const char *ip;
  size_t ileft;
  char *op;
  size_t oleft;
  char buffer[UTF16_STRLEN];	/* Fix me! */
#endif /* !USE_CSCONV */
  const size_t buf_len = UTF16_STRLEN;
  size_t ret = 0;

#ifdef USE_CSCONV
  static csconv_t csconv_cd = NULL;
#endif

#ifdef USE_CSCONV
  if (current_locale == NULL){
    current_locale = (char*)strdup(setlocale(LC_CTYPE, NULL));
  }
  do {
    if (((void *)(-1) == csc_handle) ||
	((csconv_t)(-1) == csconv_cd)) {
      continue;
    }
    if (NULL == csc_handle) {
      dlopen_csconv();
      if ((void *)(-1) == csc_handle) {
	continue;
      }
    }
    if (NULL == csconv_cd) {

      csconv_cd = (csc_open_locale)(current_locale, "MultiByte", "UTF-16");
      
      if ((csconv_t)(-1) == csconv_cd) {
	continue;
      }
    }

    dst = *((char **)to_buf);

    ret = csc_conv(csconv_cd,
		   (const char **)&from_buf, &from_left, &dst, to_left);
    return ret;
  } while (0);
#endif

#ifdef USE_ICONV
  if (i_conv1_FromUTF16 == (iconv_t)-1 ||
      i_conv2_FromUTF16 == (iconv_t)-1) {
    goto done;
  }

  if (i_conv2_FromUTF16 == NULL && !skip_native_to_utf8_conv) {
    char *encoding = nl_langinfo(CODESET);
    if (!strcmp(encoding, "UTF-8")) {
      skip_native_to_utf8_conv = True;
    } else {
      if ((i_conv2_FromUTF16 = iconv_open(encoding, "UTF-8"))
	  == (iconv_t) - 1) {
	goto done;
      }
    }
  }
  if (i_conv1_FromUTF16 == NULL) {
    if ((i_conv1_FromUTF16 = iconv_open("UTF-8", "UCS-2"))
	== (iconv_t) - 1) {
      goto done;
    }
  }

  if (skip_native_to_utf8_conv) {
    src = from_buf;
    src_len = from_left;	/* don't stop at '\0' in case of ascii */
    dst = *((char **) to_buf);

    ret = iconv(i_conv1_FromUTF16, (const char**)&src, &src_len,
		(char**)&dst, to_left);
  } else {
    ip = (const char *)from_buf;
    ileft = from_left;

    op = *((char **)to_buf);
    oleft = *to_left;

    while ((0 < ileft) && (0 < oleft)) {
      dst = buffer;
      dst_len = buf_len;
      ret = iconv(i_conv1_FromUTF16, &ip, &ileft, (char**)&dst, &dst_len);
      if ((ret != 0) && (E2BIG != errno)) {
	goto done;
      }

      src = buffer;
      src_len = buf_len - dst_len;

      ret = iconv(i_conv2_FromUTF16, (const char**)&src, &src_len,
		  &op, &oleft);
      if (ret != 0) goto done;
    }

    *to_left = oleft;
  }
done:
#endif /* USE_ICONV */
  return(ret);
}
