/**  File gg_helpwin.c
 *
 *  Transcripted from Motif to GTK+ by P. Vincent to
 *   Replace helpwin.c
 */

#include <config.h>
#include <string.h>
#include <gtk/gtk.h>

#include "utils.h"
#include "files.h"


#define NO_HELP "doc/nohelp.html"

#ifdef WITH_LIBHELP
#  include <help.h>
#endif


int force_external_viewer =
#if defined WITH_XMHTML || defined WITH_LIBHELP
    FALSE;
#else
    TRUE;
#endif

/**
 *   Replace (almost identical) HelpCB
 */
void gg_HelpCB (gpointer p)
{
    char *URL, *ha;
    int remote;

    ha = (char *) p;
    
    if (ha == NULL) {
        ha = NO_HELP;
    }
    if (strstr(ha, "http:") || strstr(ha, "ftp:") || strstr(ha, "mailto:")) {
        URL = copy_string(NULL, ha);
        remote = TRUE;
    } else {
        char *p, *pa;
        
        if (ha == strstr(ha, "file:")) {
            p = (ha + 5);
        } else {
            p = ha;
        }

        pa = strchr(p, '#');
        if (pa) {
            char *base = copy_string(NULL, p);
            base[pa - p] = '\0';
            if (force_external_viewer) {
#ifdef HAVE_X11
                URL = copy_string(NULL, "file://");
#else
                URL = copy_string(NULL, "file:///");
#endif
            } else {
                URL = NULL;
            }
            URL = concat_strings(URL, grace_path(base));
            URL = concat_strings(URL, pa);
            xfree(base);
        } else {
            URL = copy_string(NULL, grace_path(p));
        }

        remote = FALSE;
    }
    
    if (remote || force_external_viewer) {
      char *help_viewer, *command ,*exten;
        int i, j, len, urllen, comlen;

	//	exten = rindex (URL ,'.');
	exten = strrchr (URL ,'.');
	if (compare_strings (exten ,".pdf")) {
	  help_viewer = get_pdf_help_viewer ();
	} else {
	  help_viewer = get_help_viewer ();
	}

	printf ("help_viewer = %s \n  URL = %s   exten = %s\n" ,help_viewer ,URL ,exten);

        len = strlen(help_viewer);
        urllen = strlen(URL);
        for (i = 0, comlen = len; i < len - 1; i++) {
    	    if ((help_viewer[i] == '%') && (help_viewer[i + 1] == 's')){
    	        comlen += urllen - 2;
    	        i++;
    	    }
        }
        command = xmalloc((comlen + 1)*SIZEOF_CHAR);
        command[comlen] = '\0';
        for (i = 0, j = 0; i < len; i++) {
    	    if ((help_viewer[i] == '%') && (help_viewer[i + 1] == 's')){
    	        strcpy (&command[j], URL);
    	        j += urllen;
    	        i++;
    	    } else {
    	        command[j++] = help_viewer[i];
    	    }
        }
#ifdef VMS    
        system_spawn(command);
#else
        command = concat_strings (command, "&");    

	printf ("command= %s \n" ,command);

	system_wrap(command);
#endif
        xfree(command);
    } else {
#ifdef WITH_XMHTML
      printf ("gg_create_helper_frame A FAIRE\n");
#endif
#ifdef WITH_LIBHELP
        printf ("gg_get_help A FAIRE\n");
#endif
    }
    
    xfree(URL);
}


