#include "HTUtils.h"
#include "tcp.h"
#include "HTInit.h"
#include "HTFile.h"
#include "LYCurses.h"
#include "HTML.h"
#include "HTAccess.h"
#include "LYUtils.h"
#include "LYGlobalDefs.h"
#include "LYSignal.h"
#include "LYGetFile.h"
#include "LYStrings.h"
#include "LYClean.h"
#include "LYCharSets.h"
#include "LYReadCFG.h"
#include "LYrcFile.h"
#include "LYKeymap.h"
#include "HTParse.h"
#ifdef VMS
#include "HTVMSUtils.h"
#endif /* VMS */
#include "LYList.h"
#include "LYJump.h"

#ifndef VMS
#ifdef SYSLOG_REQUESTED_URLS
#include <syslog.h>
#endif /* SYSLOG_REQUESTED_URLS */
#endif /* !VMS */

#ifdef LOCALE
#include<locale.h>
#endif /* LOCALE */

#include "LYexit.h"
#include "LYLeaks.h"

#define FREE(x) if (x) {free(x); x = NULL;}

/* ahhhhhhhhhh!! Global variables :-< */
extern BOOL reloading;    /* For Flushing Cache on Proxy Server (HTTP.c) */
int HTCacheSize = DEFAULT_CACHE_SIZE;  /* number of docs cached in memory */
#if defined(VMS) && defined(VAXC) && !defined(__DECC)
/* Don't dump doc cache unless this size is exceeded */
int HTVirtualMemorySize = DEFAULT_VIRTUAL_MEMORY_SIZE;
#endif /* VMS && VAXC && !_DECC */
char *empty_string = "\0";
int display_lines;  /* number of lines in display */
int www_search_result= -1;
lynx_printer_item_type *printers = NULL;    /* linked list of printers */
lynx_html_item_type *downloaders = NULL;    /* linked list of download options*/
lynx_html_item_type *uploaders = NULL;
int port_syntax = 1;

/* These are declared in cutil.h for current freeWAIS libraries. - FM */
#ifdef DECLARE_WAIS_LOGFILES
char *log_file_name = NULL;	/* for WAIS log file name    in libWWW */
FILE *logfile = NULL;		/* for WAIS log file output  in libWWW */
#endif /* DECLARE_WAIS_LOGFILES */

BOOLEAN LYShowCursor=SHOW_CURSOR; /* to show or not to show */
BOOLEAN LYforce_no_cache=FALSE;
BOOLEAN LYresubmit_forms = ALWAYS_RESUBMIT_FORMS;
BOOLEAN LYUserSpecifiedURL=TRUE;  /* always true the first time */
BOOLEAN LYJumpFileURL=FALSE;	  /* always false the first time */
BOOLEAN jump_buffer=JUMPBUFFER;   /* TRUE if offering default shortcut */
BOOLEAN goto_buffer=GOTOBUFFER;   /* TRUE if offering default goto URL */
BOOLEAN recent_sizechange=FALSE;  /* the window size changed recently? */
BOOLEAN user_mode=NOVICE_MODE;
BOOLEAN dump_output_immediately=FALSE;
BOOLEAN is_www_index=FALSE;
BOOLEAN lynx_mode=NORMAL_LYNX_MODE;
BOOLEAN bold_headers=FALSE;
BOOLEAN bold_H1=FALSE;
BOOLEAN bold_name_anchors=FALSE;
BOOLEAN use_underscore = SUBSTITUTE_UNDERSCORES;
BOOLEAN nolist=FALSE;
BOOLEAN historical_comments=FALSE;
BOOLEAN minimal_comments=FALSE;
BOOLEAN soft_dquotes=FALSE;
BOOLEAN LYValidate=FALSE;
BOOLEAN LYPermitURL=FALSE;
#ifdef REVERSE_CLEAR_SCREEN_PROBLEM
BOOLEAN enable_scrollback=TRUE;
#else
BOOLEAN enable_scrollback=FALSE;
#endif /* REVERSE_CLEAR_SCREEN_PROBLEM */

#ifdef VMS
BOOLEAN UseFixedRecords = USE_FIXED_RECORDS;	/* create FIXED 512 binaries */
#endif /* VMS */

#ifdef DIRED_SUPPORT
BOOLEAN lynx_edit_mode = FALSE;
#ifdef OK_OVERRIDE
BOOLEAN prev_lynx_edit_mode = FALSE;
#endif /* OK_OVERRIDE */
BOOLEAN dir_list_style = MIXED_STYLE;
taglink *tagged = NULL;
#endif /* DIRED_SUPPORT */

#ifdef IGNORE_CTRL_C
BOOLEAN sigint = FALSE;
#endif /* IGNORE_CTRL_C */

BOOLEAN child_lynx = FALSE;
#if defined(EXEC_LINKS) || defined(EXEC_SCRIPTS)
#ifndef NEVER_ALLOW_REMOTE_EXEC
BOOLEAN local_exec = LOCAL_EXECUTION_LINKS_ALWAYS_ON;
#else
BOOLEAN local_exec = FALSE;
#endif /* NEVER_ALLOW_REMOTE_EXEC */
BOOLEAN local_exec_on_local_files = LOCAL_EXECUTION_LINKS_ON_BUT_NOT_REMOTE;
#endif /* EXEC_LINKS || EXEC_SCRIPTS */
BOOLEAN error_logging = MAIL_SYSTEM_ERROR_LOGGING;
BOOLEAN check_mail = CHECKMAIL;
BOOLEAN vi_keys = VI_KEYS_ALWAYS_ON;
BOOLEAN emacs_keys = EMACS_KEYS_ALWAYS_ON;
BOOLEAN keypad_mode = DEFAULT_KEYPAD_MODE;
BOOLEAN case_sensitive = CASE_SENSITIVE_ALWAYS_ON;
BOOLEAN telnet_ok = TRUE;
BOOLEAN news_ok = TRUE;
BOOLEAN rlogin_ok = TRUE;
BOOLEAN ftp_ok = TRUE;
BOOLEAN system_editor = FALSE;
BOOLEAN no_inside_telnet = FALSE;
BOOLEAN no_outside_telnet = FALSE;
BOOLEAN no_telnet_port = FALSE;
BOOLEAN no_inside_news = FALSE;
BOOLEAN no_outside_news = FALSE;
BOOLEAN no_inside_ftp = FALSE;
BOOLEAN no_outside_ftp = FALSE;
BOOLEAN no_inside_rlogin = FALSE;
BOOLEAN no_outside_rlogin = FALSE;
BOOLEAN no_suspend = FALSE;
BOOLEAN no_editor = FALSE;
BOOLEAN no_shell = FALSE;
BOOLEAN no_bookmark = FALSE;
BOOLEAN no_option_save = FALSE;
BOOLEAN no_print = FALSE;
BOOLEAN no_download = FALSE;
BOOLEAN no_disk_save = FALSE;
BOOLEAN no_exec = FALSE;
BOOLEAN no_lynxcgi = FALSE;
BOOLEAN exec_frozen = FALSE;
BOOLEAN no_bookmark_exec = FALSE;
BOOLEAN no_goto = FALSE;
BOOLEAN no_jump = FALSE;
BOOLEAN no_file_url = FALSE;
BOOLEAN no_newspost = FALSE;
BOOLEAN no_mail = FALSE;
BOOLEAN no_dotfiles = NO_DOT_FILES;
BOOLEAN no_statusline = FALSE;
BOOLEAN local_host_only = FALSE;
BOOLEAN override_no_download = FALSE;

#ifdef DIRED_SUPPORT
BOOLEAN no_dired_support = FALSE;
#ifdef OK_PERMIT
#ifdef NO_CHANGE_EXECUTE_PERMS
BOOLEAN no_change_exec_perms = TRUE;
#else
BOOLEAN no_change_exec_perms = FALSE;
#endif /* NO_CHANGE_EXECUTE_PERMS */
#endif /* OK_PERMIT */
#endif /* DIRED_SUPPORT */

BOOLEAN show_dotfiles = FALSE;	/* From rcfile if no_dotfiles is false */

BOOLEAN LYforce_HTML_mode = FALSE;
char *homepage = NULL;		    /* home page or main screen */
char *editor = NULL;  		    /* the name of the current editor */
char *jumpfile = NULL;		    /* the name of the default jumps file */
char *jumpprompt = NULL;	    /* the default jumps prompt */
char *bookmark_page = NULL;   	    /* the name of the current bookmark page */
char *startfile = NULL;		    /* the first file */
char *helpfile = NULL; 		    /* the main help file */
char *helpfilepath = NULL; 	    /* the path to the help file set */
char *aboutfilepath = NULL; 	    /* the path to the about lynx file */
char *lynxjumpfile = NULL; 	    /* the current jump file URL */
char *lynxlistfile = NULL; 	    /* the current list file URL */
char *lynxbookfile = NULL; 	    /* the current bookmark file URL */
char *startrealm = NULL; 	    /* the startfile realm */
char *indexfile = NULL;		    /* an index file if there is one */
char *personal_mail_address = NULL; /* the users mail address */
char *display=NULL;		    /* display environment variable */
char *personal_type_map = NULL;	    /* .mailcap */
char *global_type_map = NULL;	    /* global mailcap */
char *global_extension_map = NULL;  /* global mime.types */
char *personal_extension_map = NULL;/* .mime.types */
char *language = NULL;		    /* preferred language */
char *pref_charset = NULL;	    /* preferred character set */
char *inews_path = NULL;	    /* the path for posting to news */
char *system_mail = NULL;	    /* the path for sending mail */
char *lynx_temp_space = NULL;	    /* the prefix for temporary file paths */
char *lynx_save_space = NULL;	    /* the prefix for save to disk paths */
#ifdef VMS
char *mail_adrs = NULL;		    /* the mask for a VMS mail transport */
#endif /* VMS */
char *LYHostName = NULL;	    /* treat as a local host name */
#ifndef VMS
char *NNTPSERVER_putenv_cmd = NULL;   /* lynx.cfg specified NNTPSERVER */
char *http_proxy_putenv_cmd = NULL;   /* lynx.cfg specified http_proxy */
char *https_proxy_putenv_cmd = NULL;  /* lynx.cfg specified https_proxy */
char *ftp_proxy_putenv_cmd = NULL;    /* lynx.cfg specified ftp_proxy */
char *gopher_proxy_putenv_cmd = NULL; /* lynx.cfg specified gopher_proxy */
char *cso_proxy_putenv_cmd = NULL;    /* lynx.cfg specified cso_proxy */
char *news_proxy_putenv_cmd = NULL;   /* lynx.cfg specified news_proxy */
char *snews_proxy_putenv_cmd = NULL;  /* lynx.cfg specified snews_proxy */
char *nntp_proxy_putenv_cmd = NULL;   /* lynx.cfg specified nntp_proxy */
char *wais_proxy_putenv_cmd = NULL;   /* lynx.cfg specified wais_proxy */
char *finger_proxy_putenv_cmd = NULL; /* lynx.cfg specified finger_proxy */
char *no_proxy_putenv_cmd = NULL;     /* lynx.cfg specified no_proxy */
#ifdef SYSLOG_REQUESTED_URLS
char *syslog_txt = NULL;            /* syslog arb text for session */
#endif /* SYSLOG_REQUESTED_URLS */
char *list_format=NULL;		    /* LONG_LIST formatting mask */
#endif /* !VMS */

BOOLEAN clickable_images = MAKE_LINKS_FOR_ALL_IMAGES;
BOOLEAN pseudo_inline_alts = MAKE_PSEUDO_ALTS_FOR_INLINES;

BOOLEAN crawl=FALSE;	     /* Do crawl? */
BOOLEAN traversal=FALSE;     /* Do traversals? */
BOOLEAN check_realm=FALSE;   /* Restrict to the starting realm? */
BOOLEAN more_links=FALSE;    /* Links beyond a displayed page with no links? */ 
int     ccount=0;	     /* Starting number for lnk#.dat files in crawls */
PUBLIC BOOLEAN LYCancelledFetch=FALSE; /* TRUE if cancelled binary fetch */

BOOLEAN keep_mime_headers = FALSE;   /* Include mime headers with source dump */
BOOLEAN no_url_redirection = FALSE;  /* Don't follow URL redirections */
char *form_post_data = NULL;         /* User data for post form */
char *form_get_data = NULL;          /* User data for get form */
char *http_error_file = NULL;        /* Place HTTP status code in this file */
char *authentication_info[2] = {NULL, NULL}; /* Id:Password for protected forms */
BOOLEAN HEAD_request = FALSE;
BOOLEAN scan_for_buried_news_references = TRUE;
int LYlines = 24;
int LYcols = 80;

linkstruct links[MAXLINKS];

histstruct history[MAXHIST];

int nlinks = 0;		/* number of links in memory */
int nhist = 0;		/* number of history entries */
int more = FALSE;	/* is there more text to display? */

PUBLIC enum _kcode {EUC, SJIS, JIS, NONE} kanji_code = KANJI_CODE;
extern BOOL HTJapanese;

PRIVATE void parse_arg PARAMS((char **arg, int *i, int argc));
#ifndef VMS
PRIVATE void FatalProblem PARAMS((int sig));
#endif /* !VMS */
extern int mainloop();

PRIVATE BOOLEAN restrictions_set=FALSE;
PRIVATE BOOLEAN stack_dump=FALSE;
PRIVATE char *terminal=NULL;
PRIVATE char *pgm;
PRIVATE BOOLEAN number_links=FALSE;

PUBLIC int InfoSecs;	/* Seconds to sleep() for Information messages */
PUBLIC int MessageSecs;	/* Seconds to sleep() for important Messages   */
PUBLIC int AlertSecs;	/* Seconds to sleep() for HTAlert() messages   */

#ifdef SOCKS
PUBLIC BOOLEAN socks_flag=TRUE;
#endif /* SOCKS */

PUBLIC BOOLEAN bookmark_start=FALSE;

PUBLIC char * LYUserAgent=NULL;		/* Lynx User-Agent header     */
PUBLIC BOOLEAN LYNoRefererHeader=FALSE;	/* Never send Referer header? */
PUBLIC BOOLEAN LYNoFromHeader=FALSE;	/* Never send From header?    */

BOOLEAN LYListNewsNumbers = LIST_NEWS_NUMBERS;
BOOLEAN LYListNewsDates = LIST_NEWS_DATES;

/*
 * Wow!  Someone wants to start up Lynx.
 */
PUBLIC int main ARGS2(int,argc, char **,argv)
{
    int  i;	/* indexing variable */
    int status=0;	/* exit status */
    char *lynx_cfg_file=NULL;
    char *lynx_version_putenv_command=NULL;
    char *cp;
    FILE *fp;

    pgm = argv[0];
    if ((cp = strrchr(pgm, '/')) != NULL) {
	pgm = cp + 1;
    }

#ifdef ULTRIX
    terminal = getenv("TERM");
    if ((terminal == NULL) || !strcmp(terminal, "xterm"))
        terminal = "vt100";
#endif /* ULTRIX */

#ifdef LY_FIND_LEAKS
    /*
     *	Register the final function to be executed when being exited.
     *	Will display memory leaks if LY_FIND_LEAKS is defined.
     */
    atexit(LYLeaks);
#endif /* LY_FIND_LEAKS */

#ifdef LOCALE
    /* LOCALE support for international characters. */
    setlocale(LC_ALL, "");
#endif /* LOCALE */

    /* initialize some variables */
    /* zero the links and history struct array */
    memset((void *)links, 0, sizeof(linkstruct)*MAXLINKS);
    memset((void *)history, 0, sizeof(histstruct)*MAXHIST);

#ifndef VMS
#ifdef SYSLOG_REQUESTED_URLS
    openlog("lynx", LOG_PID, LOG_LOCAL5);
#endif /* SYSLOG_REQUESTED_URLS */
    StrAllocCopy(list_format, LIST_FORMAT);
#endif /* !VMS */

    InfoSecs    = (int)INFOSECS;
    MessageSecs = (int)MESSAGESECS;
    AlertSecs   = (int)ALERTSECS;

    StrAllocCopy(helpfile, HELPFILE);
    StrAllocCopy(startfile, STARTFILE);
    StrAllocCopy(jumpprompt, JUMP_PROMPT);
#ifdef JUMPFILE
    StrAllocCopy(jumpfile, JUMPFILE);
    {
        char *temp = (char *)malloc(strlen(jumpfile) + 10);
	if (!temp) {
	    outofmem(__FILE__, "main");
	} else {
	    sprintf(temp, "JUMPFILE:%s", jumpfile);
	    if (!LYJumpInit(temp)) {
		if (TRACE)
		    fprintf(stderr, "Failed to register %s\n", temp);
	    }
	    FREE(temp);
	}
    }
#endif /* JUMPFILE */
    StrAllocCopy(indexfile, DEFAULT_INDEX_FILE);
    StrAllocCopy(global_type_map, GLOBAL_MAILCAP);
    StrAllocCopy(personal_type_map, PERSONAL_MAILCAP);
    StrAllocCopy(global_extension_map, GLOBAL_EXTENSION_MAP);
    StrAllocCopy(personal_extension_map, PERSONAL_EXTENSION_MAP);
    StrAllocCopy(language, PREFERRED_LANGUAGE);
    StrAllocCopy(pref_charset, PREFERRED_CHARSET);
    StrAllocCopy(inews_path, INEWS);
    StrAllocCopy(system_mail, SYSTEM_MAIL);
    if ((cp=getenv("LYNX_TEMP_SPACE")) != NULL)
        StrAllocCopy(lynx_temp_space, cp);
    else
        StrAllocCopy(lynx_temp_space, TEMP_SPACE);
    if ((cp = strchr(lynx_temp_space, '~'))) {
	char *temp = NULL;
	int len;

	*(cp++) = '\0';
	StrAllocCopy(temp, lynx_temp_space);
	if ((len=strlen(temp)) > 0 && temp[len-1] == '/')
	    temp[len-1] = '\0';
#ifdef VMS
	StrAllocCat(temp, HTVMS_wwwName((char *)Home_Dir()));
#else
	StrAllocCat(temp, Home_Dir());
#endif /* VMS */
	StrAllocCat(temp, cp);
	StrAllocCopy(lynx_temp_space, temp);
	FREE(temp);
    }
    StrAllocCopy(LYUserAgent, LYNX_NAME);
    StrAllocCat(LYUserAgent, " ");
    StrAllocCat(LYUserAgent, LYNX_VERSION);
    if (HTLibraryVersion) {
        StrAllocCat(LYUserAgent, "  libwww-FM/");
	StrAllocCat(LYUserAgent, HTLibraryVersion);
    }
#ifdef VMS
    for (i = 0; lynx_temp_space[i]; i++)
        lynx_temp_space[i] = TOLOWER(lynx_temp_space[i]);
    if (strchr(lynx_temp_space, '/') != NULL) {
        char *temp = NULL;
	int len = strlen(lynx_temp_space);

	if (len == 1) {
	    StrAllocCopy(lynx_temp_space, "sys$scratch:");
	} else {
	    if (lynx_temp_space[len-1] != '/')
	        StrAllocCat(lynx_temp_space, "/");
            StrAllocCopy(temp, HTVMS_name("", lynx_temp_space));
	    StrAllocCopy(lynx_temp_space, temp);
	    FREE(temp);
	}
    }
    if (strchr(lynx_temp_space, ':') == NULL &&
	strchr(lynx_temp_space, ']') == NULL) {
	StrAllocCat(lynx_temp_space, ":");
    }
#else
    {
        int len = strlen(lynx_temp_space);

	if (len > 1 && lynx_temp_space[len-1] != '/') {
	    StrAllocCat(lynx_temp_space, "/");
	}
    }
#endif /* VMS */
#ifdef VMS
    StrAllocCopy(mail_adrs, MAIL_ADRS);
#endif /* VMS */
#ifdef LYNX_HOST_NAME
    StrAllocCopy(LYHostName, LYNX_HOST_NAME);
#else
    StrAllocCopy(LYHostName, HTHostName());
#endif /* LYNX_HOST_NAME */

#ifdef UNIX
    StrAllocCopy(lynx_version_putenv_command,"LYNX_VERSION=");
    StrAllocCat(lynx_version_putenv_command,LYNX_VERSION);
    putenv(lynx_version_putenv_command);
#endif /* UNIX */

    HTJapanese = JAPANESE;

    /* set up trace, if requested, and an alternate
     * configuration file, if specified, now
     */
    for (i=1; i<argc; i++) {
#ifdef SOCKS
	if (strncmp(argv[i], "-nosocks", 8) == 0) {
	    socks_flag = FALSE;
        } else
#endif /* SOCKS */
	if (strncmp(argv[i], "-trace", 6) == 0) {
	    WWW_TraceFlag = TRUE;
	} else if (strncmp(argv[i], "-cfg", 4) == 0) {
	    if ((cp=strchr(argv[i],'=')) != NULL)
                StrAllocCopy(lynx_cfg_file, cp+1);
            else {
                StrAllocCopy(lynx_cfg_file, argv[i+1]);
                i++;
            }
	} else if (strncmp(argv[i], "-help", 5) == 0) {
	    parse_arg(&argv[i], &i, argc);
	}
    }
#ifdef SOCKS
    if (socks_flag)
        SOCKSinit(argv[0]);
#endif /* SOCKS */

    /*
     * If no alternate configuration file was specified on
     * the command line, see if it's in the environment.
     */
    if (!lynx_cfg_file) {
        if (((cp=getenv("LYNX_CFG")) != NULL) ||
	    (cp=getenv("lynx_cfg")) != NULL)
	    StrAllocCopy(lynx_cfg_file, cp);
    }

    /*
     * If we still don't have a configuration file,
     * use the userdefs.h definition.
     */
    if (!lynx_cfg_file)
    	StrAllocCopy(lynx_cfg_file, LYNX_CFG_FILE);

    /*
     * Convert a '~' in the configuration file path to $HOME.
     */
    if ((cp = strchr(lynx_cfg_file, '~'))) {
	char *temp = NULL;
	int len;

	*(cp++) = '\0';
	StrAllocCopy(temp, lynx_cfg_file);
	if ((len=strlen(temp)) > 0 && temp[len-1] == '/')
	    temp[len-1] = '\0';
#ifdef VMS
	StrAllocCat(temp, HTVMS_wwwName((char *)Home_Dir()));
#else
	StrAllocCat(temp, Home_Dir());
#endif /* VMS */
	StrAllocCat(temp, cp);
	StrAllocCopy(lynx_cfg_file, temp);
	FREE(temp);
    }

    /*
     * If the configuration file is not available,
     * inform the user and exit.
     */
    if ((fp = fopen(lynx_cfg_file, "r")) == NULL) {
        fprintf(stderr, "\nConfiguration file %s is not available.\n\n",
			lynx_cfg_file);
	exit(-1);
    }
    fclose(fp);

    /*
     * Make sure we have the character sets declared. - FM
     */
    if (!LYCharSetsDeclared()) {
        fprintf(stderr, "\nLynx character sets not declared.\n\n");
	exit(-1);
    }

    /*
     * Make sure we have the edit map declared. - FM
     */
    if (!LYEditmapDeclared()) {
        fprintf(stderr, "\nLynx edit map not declared.\n\n");
	exit(-1);
    }

#ifdef USE_SLANG
    /*
     * Set up default foreground and background colors.
     */
    lynx_setup_colors();
#endif /* USE_SLANG */

    /*
     * Process the configuration file.
     */
    read_cfg(lynx_cfg_file);
    FREE(lynx_cfg_file);

    /*
     * Check for a save space path in the environment.
     * If one was set in the configuration file, that
     * one will be overridden. - FM
     */
    if ((cp=getenv("LYNX_SAVE_SPACE")) != NULL)
        StrAllocCopy(lynx_save_space, cp);

    /*
     * We have a save space path, make sure it's valid. - FM
     */
    if (lynx_save_space && *lynx_save_space == '\0') {
        FREE(lynx_save_space);
    }
    if (lynx_save_space) {
        if ((cp = strchr(lynx_save_space, '~')) != NULL) {
	    char *temp = NULL;
	    int len;

	    *(cp++) = '\0';
	    StrAllocCopy(temp, lynx_save_space);
	    if ((len=strlen(temp)) > 0 && temp[len-1] == '/')
	        temp[len-1] = '\0';
#ifdef VMS
	    StrAllocCat(temp, HTVMS_wwwName((char *)Home_Dir()));
#else
	    StrAllocCat(temp, Home_Dir());
#endif /* VMS */
	    StrAllocCat(temp, cp);
	    StrAllocCopy(lynx_save_space, temp);
	    FREE(temp);
        }
#ifdef VMS
        for (i = 0; lynx_save_space[i]; i++)
            lynx_save_space[i] = TOLOWER(lynx_save_space[i]);
        if (strchr(lynx_save_space, '/') != NULL) {
            char *temp = NULL;
	    int len = strlen(lynx_save_space);

	    if (len == 1) {
	        StrAllocCopy(lynx_save_space, "sys$scratch:");
	    } else {
	        if (lynx_save_space[len-1] != '/')
	            StrAllocCat(lynx_save_space, "/");
                StrAllocCopy(temp, HTVMS_name("", lynx_save_space));
	        StrAllocCopy(lynx_save_space, temp);
	        FREE(temp);
	    }
        }
	if (strchr(lynx_save_space, ':') == NULL &&
	    strchr(lynx_save_space, ']') == NULL) {
	    StrAllocCat(lynx_save_space, ":");
	}
#else
    {
        int len = strlen(lynx_save_space);

	if (len > 1 && lynx_save_space[len-1] != '/') {
	    StrAllocCat(lynx_save_space, "/");
	}
    }
#endif /* VMS */
    }

    /*
     * Set up the file extension and mime type maps from
     * src/HTInit.c and the global and personal mime.types
     * and mailcap files.  These will override any SUFFIX
     * or VIEWER maps in userdefs.h or the configuration
     * file, if they overlap.
     */
    HTFormatInit();
    HTFileInit();

    /*
     * Get WWW_HOME environment variable if it exists)
     */
    if ((cp = getenv("WWW_HOME")) != NULL)
	StrAllocCopy(startfile, cp);

    /*
     * Process arguments - with none, look for the database in STARTDIR,
     * starting with STARTFILE.
     *
     * If a pathname is given, use it as the starting point.  Split it
     * into directory and file components, 'cd' to the directory, and
     * view the file.
     *
     * If the only argument is '-' then we expect to see the arguments on
     * stdin, this is to allow for the potentially very long command line that
     * can be associated with post or get data.
     */
    if (argc == 2 && strcmp(argv[1], "-") == 0) {
	char buf[1025];
	char *argv[2];
 
	argv[0] = buf;
	argv[1] = NULL;
 
	while (fgets(buf, sizeof(buf) - 1, stdin)) {
	    int j;
     
	    for (j = strlen(buf) - 1; j > 0 && 
		(buf[j] == CR || buf[j] == LF); j--) {
		buf[j] = '\0';
	    }
	    parse_arg(argv, NULL, -1);
	}
    } else {
	for (i=1; i<argc; i++) {
	    parse_arg(&argv[i], &i, argc);
	}
    }

#ifndef VMS
#ifdef SYSLOG_REQUESTED_URLS
    if (syslog_txt) {
	syslog(LOG_INFO, "Session start:%s", syslog_txt);
    } else {
	syslog(LOG_INFO, "Session start");
    }
#endif /* SYSLOG_REQUESTED_URLS */
#endif /* !VMS */

    /* read the rc file */
    read_rc();
#if defined(EXEC_LINKS) || defined(EXEC_SCRIPTS)
#ifdef NEVER_ALLOW_REMOTE_EXEC
    if (local_exec) {
        local_exec = FALSE;
	local_exec_on_local_files=TRUE;
    }
#endif /* NEVER_ALLOW_REMOTE_EXEC */
#endif /* EXEC_LINKS || EXEC_SCRIPTS */


    if (emacs_keys)
        set_emacs_keys();
 
    if (vi_keys)
        set_vi_keys();
 
    if (number_links)
	keypad_mode = LINKS_ARE_NUMBERED;
    if (keypad_mode == NUMBERS_AS_ARROWS)
        set_numbers_as_arrows();

    /* disable news posting if no posting command */
    if (*inews_path == '\0' || !strcasecomp(inews_path,"none"))
        no_newspost = TRUE;

#ifdef VMS
    set_vms_keys();
#endif /* VMS */


    /* trap interrupts */    
    if (!dump_output_immediately)
        (void) signal (SIGHUP, cleanup_sig);
    (void) signal (SIGTERM, cleanup_sig);
#ifdef SIGWINCH
    (void) signal (SIGWINCH, size_change);
#endif /* SIGWINCH */
#ifndef VMS
    if (!TRACE && !dump_output_immediately && !stack_dump) {
        (void) signal (SIGINT, cleanup_sig);
#ifndef __linux__
        (void) signal (SIGBUS, FatalProblem);
#endif /* !__linux__ */
        (void) signal (SIGSEGV, FatalProblem);
        (void) signal (SIGILL, FatalProblem);
        /*
	 * Since we're doing lots of TCP, just ignore SIGPIPE altogether.
	 *
	 * HTTCP.c should deal with a broken pipe for servers.
	 * Rick Mallet's check after c = GetChar() in LYStrings.c should
	 *  deal with a disconnected terminal.
	 * So the runaway CPU time problem on Unix should not occur any
	 *  more.
	 */
        (void) signal (SIGPIPE, SIG_IGN);
    }
#endif /* !VMS */

    /* set up the proper character set */
    HTMLUseCharacterSet(current_char_set);

    /*
     * If startfile is a file URL and the host is defaulted,
     * force in "//localhost".  We need this until all the
     * other Lynx code which performs security checks based
     * on the "localhost" string is changed to assume
     * "//localhost" when a host field is not present in file
     * URLs - FM
     */
    if (!strncmp(startfile, "file:", 5)) {
	char *temp=NULL;
        if (startfile[5] == '\0') {
            StrAllocCat(startfile, "//localhost");
        } else if (!strcmp(startfile, "file://")) {
            StrAllocCat(startfile, "localhost");
        } else if (!strncmp(startfile, "file:///", 8)) {
	    StrAllocCopy(temp, (startfile+7));
	    StrAllocCopy(startfile, "file://localhost");
	    StrAllocCat(startfile, temp);
	    FREE(temp);
        } else if (!strncmp(startfile, "file:/", 6) && startfile[6] != '/') {
	    StrAllocCopy(temp, (startfile+5));
	    StrAllocCopy(startfile, "file://localhost");
	    StrAllocCat(startfile, temp);
	    FREE(temp);
	}
    }

    /*
     * No path in a file://localhost URL for startfile means
     * a directory listing for the current default. - FM
     */
    if (!strcmp(startfile, "file://localhost")) {
#ifdef VMS
	StrAllocCat(startfile, HTVMS_wwwName(getenv("PATH")));
#else
        char curdir[DIRNAMESIZE];
#ifdef NO_GETCWD
      	getwd (curdir);
#else
    	getcwd (curdir, DIRNAMESIZE);
#endif /* NO_GETCWD */
	StrAllocCat(startfile, curdir);
#endif /* VMS */
    }

#ifdef VMS
    /*
     * On VMS, a file://localhost/ URL for startfile
     * means a listing for the login directory. - FM
     */
    if (!strcmp(startfile, "file://localhost/"))
	StrAllocCat(startfile, (HTVMS_wwwName((char *)Home_Dir())+1));
#endif /* VMS */

    /*
     * If it is not a URL then make it one.
     */
    if (!is_url(startfile)) {
	if (TRACE)
	    fprintf(stderr, "STARTFILE '%s' is not a URL\n", startfile);
        LYConvertToURL(&startfile);
    }

    /*
     * If homepage is a file URL and the host is defaulted,
     * force in "//localhost".  We need this until all the
     * other Lynx code which performs security checks based
     * on the "localhost" string is changed to assume
     * "//localhost" when a host field is not present in file
     * URLs - FM
     */
    if (homepage && !strncmp(homepage, "file:", 5)) {
	char *temp=NULL;
        if (homepage[5] == '\0') {
            StrAllocCat(homepage, "//localhost");
        } else if (!strcmp(homepage, "file://")) {
            StrAllocCat(homepage, "localhost");
        } else if (!strncmp(homepage, "file:///", 8)) {
	    StrAllocCopy(temp, (homepage+7));
	    StrAllocCopy(homepage, "file://localhost");
	    StrAllocCat(homepage, temp);
	    FREE(temp);
        } else if (!strncmp(homepage, "file:/", 6) && homepage[6] != '/') {
	    StrAllocCopy(temp, (homepage+5));
	    StrAllocCopy(homepage, "file://localhost");
	    StrAllocCat(homepage, temp);
	    FREE(temp);
	}
    }

    /*
     * No path in a file://localhost URL for homepage means
     * a directory listing for the current default. - FM
     */
    if (homepage && !strcmp(homepage, "file://localhost")) {
#ifdef VMS
	StrAllocCat(homepage, HTVMS_wwwName(getenv("PATH")));
#else
        char curdir[DIRNAMESIZE];
#ifdef NO_GETCWD
      	getwd (curdir);
#else
    	getcwd (curdir, DIRNAMESIZE);
#endif /* NO_GETCWD */
	StrAllocCat(homepage, curdir);
#endif /* VMS */
    }

#ifdef VMS
    /*
     * On VMS, a file://localhost/ URL for homepage
     * means a listing for the login directory. - FM
     */
    if (homepage && !strcmp(homepage, "file://localhost/"))
	StrAllocCat(homepage, (HTVMS_wwwName((char *)Home_Dir())+1));
#endif /* VMS */

    /*
     * If it is not a URL then make it one.
     */
    if (homepage && !is_url(homepage)) {
	if (TRACE)
	    fprintf(stderr, "HOMEPAGE '%s' is not a URL\n", homepage);
        LYConvertToURL(&homepage);
    }

    /*
     * If we don't have a homepage specified,
     * set it to startfile.
     */
    if (!homepage)
	homepage = startfile;

    /*
     * anonymous may already be set above by command line options.
     * so this just sets the correct options.
     */
#ifndef VMS
#ifdef NO_CUSERID
    if (STREQ(((char *)getlogin()==NULL ? " " : getlogin()) , ANONYMOUS_USER)) {
#else
    if (STREQ((char *)cuserid((char *) NULL), ANONYMOUS_USER)) {
#endif /* NO_CUSERID */
	if (!restrictions_set)
	    parse_restrictions("default");
    }
#endif /* !VMS */

    if (inlocaldomain()) {
#if defined(NO_UTMP) || defined(VMS) /* not selective */
        telnet_ok = !no_inside_telnet && !no_outside_telnet && telnet_ok;
	news_ok = !no_inside_news && !no_outside_news && news_ok;
	ftp_ok = !no_inside_ftp && !no_outside_ftp && ftp_ok;
	rlogin_ok = !no_inside_rlogin && !no_outside_rlogin && rlogin_ok;
#else
	if (TRACE)
	   fprintf(stderr,"LYMain.c: User in Local domain\n");
        telnet_ok = !no_inside_telnet && telnet_ok;
	news_ok = !no_inside_news && news_ok;
	ftp_ok = !no_inside_ftp && ftp_ok;
	rlogin_ok = !no_inside_rlogin && rlogin_ok;
#endif /* NO_UTMP || VMS */
    } else {
	if (TRACE)
	   fprintf(stderr,"LYMain.c: User in REMOTE domain\n");
        telnet_ok = !no_outside_telnet && telnet_ok;
	news_ok = !no_outside_news && news_ok;
	ftp_ok = !no_outside_ftp && ftp_ok;
	rlogin_ok = !no_outside_rlogin && rlogin_ok;
    }

#ifdef SIGTSTP
    if (no_suspend)
	signal(SIGTSTP,SIG_IGN);
#endif /* SIGTSTP */

    /*
     * here's where we do all the work
     */
    if (HEAD_request && strncmp(startfile, "http", 4)) {
        fprintf(stderr,
 "The '-head' switch is for http HEAD requests and cannot be used for\n'%s'.\n",
		startfile);
        (void) signal (SIGHUP, SIG_IGN);
        (void) signal (SIGTERM, SIG_IGN);
        (void) signal (SIGINT, SIG_IGN);
	exit(-1);
    }
    if (keep_mime_headers && strncmp(startfile, "http", 4)) {
        fprintf(stderr,
 "The '-mime_header' switch is for http URLs and cannot be used for\n'%s'.\n",
		startfile);
        (void) signal (SIGHUP, SIG_IGN);
        (void) signal (SIGTERM, SIG_IGN);
        (void) signal (SIGINT, SIG_IGN);
	exit(-1);
    }
    if (traversal && strncmp(startfile, "http", 4)) {
        fprintf(stderr,
 "The '-traversal' switch is for http URLs and cannot be used for\n'%s'.\n",
		startfile);
        (void) signal (SIGHUP, SIG_IGN);
        (void) signal (SIGTERM, SIG_IGN);
        (void) signal (SIGINT, SIG_IGN);
	exit(-1);
    }
    StrAllocCopy(helpfilepath, helpfile);
    if ((cp=strrchr(helpfilepath, '/')) != NULL)
        *cp = '\0';
    StrAllocCopy(aboutfilepath, helpfilepath);
    if ((cp=strrchr(aboutfilepath, '/')) != NULL) {
        *cp = '\0';
	StrAllocCat(aboutfilepath, "/about_lynx/");
    }
    StrAllocCat(helpfilepath, "/");
    if (!bookmark_page || *bookmark_page == '\0')
        StrAllocCopy(bookmark_page, "lynx_bookmarks.html");
    if (dump_output_immediately) {
        if (crawl && !number_links) {
	    keypad_mode = NUMBERS_AS_ARROWS;
	} else if (!nolist) {
	    keypad_mode = LINKS_ARE_NUMBERED;
	}
	status = mainloop();
        if (!nolist && keypad_mode == LINKS_ARE_NUMBERED)
	    printlist(stdout,FALSE);
        (void) signal (SIGHUP, SIG_IGN);
        (void) signal (SIGTERM, SIG_IGN);
        (void) signal (SIGINT, SIG_IGN);
    } else {
 	if (setup(terminal)) {
	    status = mainloop();
	    cleanup();
	}
    }
 
    exit(status);
}

/* Called by HTAccessInit to register any protocols supported by lynx.
 * Protocols added by lynx:
 *   LYNXKEYMAP, lynxcgi, LYNXIMGMAP
 */
#ifdef GLOBALREF_IS_MACRO
extern GLOBALREF (HTProtocol,LYLynxKeymap);
extern GLOBALREF (HTProtocol,LYLynxCGI);
extern GLOBALREF (HTProtocol,LYLynxIMGmap);
#else
GLOBALREF  HTProtocol LYLynxKeymap;
GLOBALREF  HTProtocol LYLynxCGI;
GLOBALREF  HTProtocol LYLynxIMGmap;
#endif /* GLOBALREF_IS_MACRO */

PUBLIC void LYRegisterLynxProtocols NOARGS
{
    HTRegisterProtocol(&LYLynxKeymap);
    HTRegisterProtocol(&LYLynxCGI);
    HTRegisterProtocol(&LYLynxIMGmap);
}

/*
 * Parse one argument, optionally picking up the next entry in argv (if
 * appropriate).
 */

PRIVATE char * scan3D ARGS2(char **,argv, int *,i)
{
    char *result;

    if ((result=strchr(argv[0],'=')) != NULL)
        return result+1;
    if (argv[1] && i)
        (*i)++; /* Let master know we've stolen an argument */
    return argv[1];
}

PRIVATE void parse_arg ARGS3(char **, argv, int *, i, int, argc)
{
    char *cp;
#define nextarg ((cp=scan3D(&argv[0], i))!=NULL)

    if (strncmp(argv[0], "-anonymous", 10) == 0) {
	if (!restrictions_set)
	    parse_restrictions("default");
	
    } else if (strncmp(argv[0], "-restrictions", 13) == 0) {
	if ((cp=strchr(argv[0],'=')) != NULL)
	    parse_restrictions(cp+1);
	else
	    {
		/* print help */
		printf("\n\
   USAGE: lynx -restrictions=[option][,option][,option]\n\
   List of Options:\n\
   all             restricts all options.\n");
	        printf("\
   bookmark        disallow changing the location of the bookmark file.\n\
   bookmark_exec   disallow execution links via the bookmark file\n");
#if defined(DIRED_SUPPORT) && defined(OK_PERMIT)
	        printf("\
   change_exec_perms  disallow changing the eXecute permission on files\n\
                   (but still allow it for directories) when local file\n\
		   management is enabled.\n");
#endif /* DIRED_SUPPORT && OK_PERMIT */
	        printf("\
   default         same as commandline option -anonymous.  Disables\n\
                   default services for anonymous users.  Currently set to,\n\
                   all restricted except for: inside_telnet, outside_telnet,\n\
                   inside_news, inside_ftp, outside_ftp, inside_rlogin,\n\
		   outside_rlogin, goto, jump and mail.  Defaults\n\
                   are settable within userdefs.h\n");
#ifdef DIRED_SUPPORT
	        printf("\
   dired_support   disallow local file management\n");
#endif /* DIRED_SUPPORT */
	        printf("\
   disk_save       disallow saving binary files to disk in the download menu\n\
   dotfiles        disallow access to, or creation of, hidden (dot) files\n\
   download        disallow downloaders in the download menu\n\
   editor          disallow editing\n\
   exec            disable execution scripts\n\
   exec_frozen     disallow the user from changing the execution link\n\
   file_url        disallow using G)oto to go to file: URL's\n\
   goto            disable the 'g' (goto) command\n");
#if defined(NO_UTMP) || defined(VMS) /* not selective */
	        printf("\
   inside_ftp      disallow ftps for people coming from inside your\n\
                   domain (utmp required for selectivity)\n\
   inside_news     disallow USENET news posting for people coming from\n\
                   inside your domain (utmp required for selectivity)\n\
   inside_rlogin   disallow rlogins for people coming from inside your\n\
                   domain (utmp required for selectivity)\n\
   inside_telnet   disallow telnets for people coming from inside your\n\
                   domain (utmp required for selectivity)\n");
#else
	        printf("\
   inside_ftp      disallow ftps for people coming from inside your domain\n\
   inside_news     disallow USENET news posting for people coming from inside\n\
                   your domain\n\
   inside_rlogin   disallow rlogins for people coming from inside your domain\n\
   inside_telnet   disallow telnets for people coming from inside your domain\n");
#endif /* NO_UTMP || VMS */
	        printf("\
   jump            disable the 'j' (jump) command\n\
   mail            disallow mail\n\
   news_post       disallow USENET News posting setting in the O)ptions menu\n\
   option_save     disallow saving options in .lynxrc\n");
#if defined(NO_UTMP) || defined(VMS) /* not selective */
	        printf("\
   outside_ftp     disallow ftps for people coming from outside your\n\
                   domain (utmp required for selectivity)\n\
   outside_news    disallow USENET news posting for people coming from\n\
                   outside your domain (utmp required for selectivity)\n\
   outside_rlogin  disallow rlogins for people coming from outside your\n\
                   domain (utmp required for selectivity)\n\
   outside_telnet  disallow telnets for people coming from outside your\n\
                   domain (utmp required for selectivity)\n");
#else
		printf("\
   outside_ftp     disallow ftps for people coming from outside your domain\n\
   outside_news    disallow USENET news posting for people coming from outside\n\
                   your domain\n\
   outside_rlogin  disallow rlogins for people coming from outside your domain\n\
   outside_telnet  disallow telnets for people coming from outside your domain\n");
#endif /* NO_UTMP || VMS */
		printf("\
   print           disallow most print options\n\
   shell           disallow shell escapes, and lynxexec, lynxprog or lynxcgi\n\
                   G)oto's\n\
   suspend         disallow Control-Z suspends with escape to shell\n\
   telnet_port     disallow specifying a port in telnet G)oto's\n");
		exit(0);
	    }

    } else if (strncmp(argv[0], "-homepage", 9) == 0) {
	if (nextarg)
	    StrAllocCopy(homepage,cp);
	
    } else if (strncmp(argv[0], "-editor", 7) == 0) {
	if (nextarg)
	    StrAllocCopy(editor,cp);
	system_editor = TRUE;
	
#ifndef VMS
#ifdef SYSLOG_REQUESTED_URLS
    } else if (strncmp(argv[0], "-syslog", 7) == 0) {
	if (nextarg) 
	    StrAllocCopy(syslog_txt,cp);
#endif /* SYSLOG_REQUESTED_URLS */
#endif /* !VMS */
	
    } else if (strncmp(argv[0], "-display", 8) == 0) {
	
	char *putenv_command;
	
	if (nextarg)
	    display = cp;
	
#ifdef UNIX
	StrAllocCopy(putenv_command,"DISPLAY=");
	StrAllocCopy(putenv_command,display);
	putenv(putenv_command);
#endif /* UNIX */
	
    } else if (strncmp(argv[0], "-index", 6) == 0) {
	if (nextarg)
	    StrAllocCopy(indexfile, cp);
	
    } else if (strncmp(argv[0], "-cfg", 4) == 0) {
	/* already read the alternate configuration file 
	 * so just check whether we need to increment i
	 */
	if (nextarg)
	    ; /* do nothing */
	
    } else if (strncmp(argv[0], "-stack_dump", 11) == 0) {
	stack_dump = TRUE;
	
    } else if (strncmp(argv[0], "-cache", 6) == 0) {
	if (nextarg)
	    HTCacheSize = atoi(cp);
	
	/* limit size */
	if (HTCacheSize < 2) HTCacheSize = 2;
	
    } else if (strncmp(argv[0], "-vikeys", 7) == 0) {
	vi_keys = TRUE;
	
    } else if (strncmp(argv[0], "-emacskeys", 10) == 0) {
	emacs_keys = TRUE;
	
    } else if (strncmp(argv[0], "-version", 8) == 0) {
	printf("\n%s Version %s\n(c)GNU General Public License\n\
<URL:http://www.nyu.edu/pages/wsn/subir/lynx.html>\n\n",
		LYNX_NAME, LYNX_VERSION);
	exit(0);
	
    } else if (strncmp(argv[0], "-case", 5) == 0) {
	case_sensitive = TRUE;
	
    } else if (strncmp(argv[0], "-dump", 5) == 0) {
	dump_output_immediately = TRUE;
	LYcols=80;
	
    } else if (strncmp(argv[0], "-nofrom", 7) == 0) {
	LYNoFromHeader = TRUE;
	
    } else if (strncmp(argv[0], "-nolist", 7) == 0) {
	nolist = TRUE;
	
    } else if (strncmp(argv[0], "-noreferer", 10) == 0) {
	LYNoRefererHeader = TRUE;
	
    } else if (strncmp(argv[0], "-crawl", 6) == 0) {
	crawl = TRUE;
	LYcols=80;

    } else if (strncmp(argv[0], "-historical", 11) == 0) {
        if (historical_comments)
	    historical_comments = FALSE;
	else
	    historical_comments = TRUE;

    } else if (strncmp(argv[0], "-minimal", 11) == 0) {
        if (minimal_comments)
	    minimal_comments = FALSE;
	else
	    minimal_comments = TRUE;

    } else if (strncmp(argv[0], "-soft_dquotes", 13) == 0) {
        if (soft_dquotes)
	    soft_dquotes = FALSE;
	else
	    soft_dquotes = TRUE;

    } else if (strncmp(argv[0], "-enable_scrollback", 18) == 0) {
        if (enable_scrollback)
	    enable_scrollback = FALSE;
	else
	    enable_scrollback = TRUE;

    } else if (strncmp(argv[0], "-link", 5) == 0) {
        if (nextarg)
	    ccount = atoi(cp);

    } else if (strncmp(argv[0], "-traversal", 10) == 0) {
	traversal = TRUE;
	LYcols=999;

    } else if (strncmp(argv[0], "-realm", 6) == 0) {
	check_realm = TRUE;

    } else if (strncmp(argv[0], "-source", 7) == 0) {
	dump_output_immediately = TRUE;
	HTOutputFormat = HTAtom_for("www/dump");
	LYcols=999;
	
    } else if (strncmp(argv[0], "-reload", 7) == 0) {
        reloading = TRUE;

    } else if (strncmp(argv[0], "-force_html", 11) == 0) {
	LYforce_HTML_mode = TRUE;
	
#ifdef SOCKS	
    } else if (strncmp(argv[0], "-nosocks", 8) == 0) {
	socks_flag = FALSE;
#endif /* SOCKS */

    } else if (strncmp(argv[0], "-trace", 6) == 0) {
	WWW_TraceFlag = TRUE;
	
    } else if (strncmp(argv[0], "-number_links", 9) == 0) {
        number_links = TRUE;
	
    } else if (strncmp(argv[0], "-image_links", 12) == 0) {
	if (clickable_images)
	    clickable_images = FALSE;
	else
	    clickable_images = TRUE;

    } else if (strncmp(argv[0], "-pseudo_inlines", 15) == 0) {
	if (pseudo_inline_alts)
	    pseudo_inline_alts = FALSE;
	else
	    pseudo_inline_alts = TRUE;

    } else if (strncmp(argv[0], "-resubmit_forms", 14) == 0) {
	if (LYresubmit_forms)
	    LYresubmit_forms = FALSE;
	else
	    LYresubmit_forms = TRUE;

    } else if (strncmp(argv[0], "-underscore", 15) == 0) {
	if (use_underscore)
	    use_underscore = FALSE;
	else
	    use_underscore = TRUE;

    } else if (strncmp(argv[0], "-localhost", 10) == 0) {
	local_host_only = TRUE;
	
    } else if (strncmp(argv[0], "-nobrowse", 9) == 0) {
	HTDirAccess = HT_DIR_FORBID;
	
    } else if (strncmp(argv[0], "-selective", 10) == 0) {
	HTDirAccess = HT_DIR_SELECTIVE;
	
    } else if (strncmp(argv[0], "-noprint", 8) == 0) {
	no_print=TRUE;
	
    } else if (strncmp(argv[0], "-print", 6) == 0) {
	no_print=FALSE;
	
#if defined(EXEC_LINKS) || defined(EXEC_SCRIPTS)
    } else if (strncmp(argv[0], "-exec", 5) == 0) {
#ifndef NEVER_ALLOW_REMOTE_EXEC
	local_exec=TRUE;
#else
	local_exec_on_local_files=TRUE;
#endif /* NEVER_ALLOW_REMOTE_EXEC */
	
    } else if (strncmp(argv[0], "-locexec", 8) == 0) {
	local_exec_on_local_files=TRUE;
	
    } else if (strncmp(argv[0], "-noexec", 7) == 0) {
	local_exec=FALSE;
#endif /* EXEC_LINKS || EXEC_SCRIPTS */
	
    } else if (strncmp(argv[0], "-child", 6) == 0) {
	child_lynx=TRUE;
	no_disk_save=TRUE;
	
    } else if (strncmp(argv[0], "-nolog", 6) == 0) {
	error_logging=FALSE;
	
    } else if (strncmp(argv[0], "-nostatus", 9) == 0)	{
	no_statusline = TRUE;
	
    } else if (strncmp(argv[0], "-show_cursor", 12) == 0) {
	LYShowCursor = TRUE;
	
    } else if (strncmp(argv[0], "-term", 5) == 0) {
	if (nextarg)
	    terminal = cp;
	
    } else if (strncmp(argv[0], "-telnet", 7) == 0) {
	telnet_ok=FALSE;
	
    } else if (strncmp(argv[0], "-ftp", 4) == 0) {
	ftp_ok=FALSE;
	
    } else if (strncmp(argv[0], "-rlogin", 7) == 0) {
	rlogin_ok=FALSE;
	
#ifdef USE_SLANG
    } else if (strncmp(argv[0], "-color", 6) == 0) {
        Lynx_Color_Flags |= SL_LYNX_USE_COLOR;

    } else if (strncmp(argv[0], "-blink", 6) == 0) {
        Lynx_Color_Flags |= SL_LYNX_USE_BLINK;
#endif /* USE_SLANG */

    } else if (strncmp(argv[0], "-fileversions", 13) == 0) {
#ifdef VMS
	HTVMSFileVersions=TRUE;
#else
	return;
#endif /* VMS */
	
    } else if (strcmp(argv[0], "-post_data") == 0 ||
 	       strcmp(argv[0], "-get_data") == 0) { 	/* User data for post
 							   or get form. */
	char **post_data;
	char buf[1024];

        /* -post_data and -get_data conflict with curses when interactive
         * so let's force them to dump.  - CL
	 *
	 * On VMS, mods have been made in LYCurses.c to deal with
	 * potential conflicts, so don't force them to dump here. - FM
         */
#ifndef VMS
	dump_output_immediately = TRUE;
        LYcols = 80;
#endif /* VMS */
        
	if (strcmp(argv[0], "-get_data") == 0) {
	    StrAllocCopy(form_get_data, "?");   /* Prime the pump */
	    post_data = &form_get_data;
	} else {
	    post_data = &form_post_data;
	}
	
	/* Build post data for later. Stop reading when we see a line with
	 * "---" as its first three characters.
	 */
	while (fgets(buf, sizeof(buf), stdin) && strncmp(buf, "---", 3) != 0) {
	    int j;
	    
	    for (j = strlen(buf) - 1; j >= 0 && /* Strip line terminators */
		(buf[j] == CR || buf[j] == LF); j--) {
		buf[j] = '\0';
	    }
	    StrAllocCat(*post_data, buf);
	}
	
    } else if (strcmp(argv[0], "-head") == 0) {/* Return mime headers */
	HEAD_request = TRUE;
	
    } else if (strcmp(argv[0], "-book") == 0) {/* Use bookmarks as startfile */
	bookmark_start = TRUE;
	
    } else if (strcmp(argv[0], "-buried_news") == 0) {
        /* Toggle scans for buried news references */
        if (scan_for_buried_news_references)
	    scan_for_buried_news_references = FALSE;
	else
	    scan_for_buried_news_references = TRUE;
	
    } else if (strcmp(argv[0], "-mime_header") == 0) {
        /* Include mime headers and force source dump */
	keep_mime_headers = TRUE;
	dump_output_immediately = TRUE;
	LYcols=999;

    } else if (strncmp(argv[0], "-error_file", 11) == 0) { /* Output return
							      (success/failure)
							      code of an HTTP
							      transaction */
	if (nextarg)
	    http_error_file = cp;

	
    } else if (strncmp(argv[0], "-auth", 5) == 0) { /* Authentication
						       information for
						       protected forms */
	char *auth_info = NULL;
	
	if (nextarg) {
	    StrAllocCopy(auth_info, cp);
	    memset(cp, ' ', strlen(cp));/* Let's not show too much */
	}
        if (auth_info != NULL)  {
	    if ((cp = strchr(auth_info, ':')) != NULL) { /* Pw */
		*cp++ = '\0';	/* Terminate ID */
		authentication_info[1] = HTUnEscape(cp);
	    }
	    authentication_info[0] = HTUnEscape(auth_info); /* Id */
	}
	
    } else if (strcmp(argv[0], "-noredir") == 0) { /* Don't follow URL
						      Redirections */
	no_url_redirection = TRUE;
	 
    } else if (strcmp(argv[0], "-validate") == 0) { /* Follow only http URLs */
	LYValidate = TRUE;
	parse_restrictions("all");

    } else if (strncmp(argv[0], "-jpn", 4) == 0) {
	if (HTJapanese) {
	   HTJapanese = FALSE;
	} else {
	   HTJapanese = TRUE;
	}

    } else if (strncmp(argv[0], "-euc", 4) == 0) {
	kanji_code=EUC;

    } else if (strncmp(argv[0], "-sjis", 5) == 0) {
	kanji_code=SJIS;

    } else if (strncmp(argv[0], "-ascii", 6) == 0) {
	kanji_code=NONE;

    } else if (strncmp(argv[0], "-", 1) == 0) {
	if (strncmp(argv[0], "-help", 5) != 0) 
#ifdef VMS
	    printf(" LYNX: Invalid Option: %s\n", argv[0]);
	printf("USAGE: lynx [options] [file]\n");
#else
	    printf("%s: Invalid Option: %s\n", pgm, argv[0]);
	printf("USAGE: %s [options] [file]\n",pgm);
#endif /* VMS */
	printf("Options are:\n");
	printf("    -                receive the arguments from stdin (enclose\n");
	printf("                     in double-quotes (\"-\") on VMS)\n");
	printf("    -anonymous       used to specify the anonymous account\n");
	printf("    -ascii           disable kanji code translation\n");
 	printf("    -auth=id:pw      authentication information for protected forms\n");
 	printf("    -book            use the bookmark page as the startfile\n");
 	printf("    -buried_news     toggles scanning of news articles for buried references\n");
	printf("    -cache=NUMBER    NUMBER of documents cached in memory (default is %d)\n",DEFAULT_CACHE_SIZE);
	printf("    -case            enable case sensitive user searching\n");
	printf("    -cfg=FILENAME    specifies a lynx.cfg file other than the default\n");
	printf("    -child           exit on left-arrow in startfile, and disable save to disk\n");
#ifdef USE_SLANG
	printf("    -color           force color mode on with standard bg colors\n");
	printf("    -blink           force color mode on with high intensity bg colors\n");
#endif /* USE_SLANG */
	printf("    -crawl           with -traversal, output each page to a file\n");
	printf("                     with -dump, format output as with -traversal, but to stdout\n");
	printf("    -display=DISPLAY set the display variable for X execed programs\n");
	printf("    -dump            dump the first file to stdout and exit\n");
	printf("    -editor=EDITOR   enable edit mode with specified editor\n");
	printf("    -emacskeys       enable emacs-like key movement\n");
	printf("    -enable_scrollback  toggle compatibility with comm programs' scrollback\n");
	printf("                        keys (may be incompatible with some curses packages)\n");
 	printf("    -error_file=FILE write the HTTP status code here\n");
	printf("    -euc             set kanji code to EUC\n");
#if defined(EXEC_LINKS) || defined(EXEC_SCRIPTS)
#ifndef NEVER_ALLOW_REMOTE_EXEC
	printf("    -exec            enable local program execution\n");
#endif /* !NEVER_ALLOW_REMOTE_EXEC */
	printf("    -locexec         enable local program execution from local files only\n");
	printf("    -noexec          disable local program execution (DEFAULT)\n");
#endif /* EXEC_LINKS || EXEC_SCRIPTS */
	printf("    -fileversions    include all versions of files in local VMS directory\n");
	printf("                     listings\n");
	printf("    -force_html      forces the first document to be interpreted as HTML\n");
	printf("    -ftp             disable ftp access\n");
 	printf("    -get_data        user data for get forms, read from stdin,\n");
        printf("                     terminated by '---' on a line\n");
 	printf("    -head            send a HEAD request\n");
	printf("    -help            print this usage message\n");
	printf("    -historical      toggles use of '>' or '-->' as a terminator for comments\n");
	printf("    -homepage=URL    set homepage separate from start page\n");
	printf("    -image_links     toggles inclusion of links for all images\n");
	printf("    -index=URL       set the default index file to URL\n");
	printf("    -jpn             toggle Japanese character translations\n");
	printf("    -link=NUMBER     starting count for lnk#.dat files produced by -crawl\n");
	printf("    -localhost       disable URLs that point to remote hosts\n");
 	printf("    -mime_header     include mime headers and force source dump\n");
	printf("    -minimal         toggles minimal versus valid comment parsing\n");
	printf("    -nobrowse        disable directory browsing\n");
	printf("    -nofrom          disable transmissions of From headers\n");
	printf("    -nolist          disable the link list feature in dumps\n");
	printf("    -nolog           disable mailing of error messages to document owners\n");
	printf("    -noprint         disable print functions\n");
 	printf("    -noredir         don't follow Location: redirection\n");
	printf("    -noreferer       disable transmissions of Referer headers\n");
#ifdef SOCKS
	printf("    -nosocks         don't use SOCKS proxy for this session\n");
#endif /* SOCKS */
	printf("    -nostatus        disable the miscellaneous information messages\n");
	printf("    -number_links    force numbering of links\n");
 	printf("    -post_data       user data for post forms, read from stdin,\n");
        printf("                     terminated by '---' on a line\n");
	printf("    -print           enable print functions (DEFAULT)\n");
	printf("    -pseudo_inlines  toggles pseudo-ALTs for inlines with no ALT string\n");
	printf("    -realm           restricts access to URLs in the starting realm\n");
	printf("    -reload          flushes the cache on a proxy server\n");
	printf("                     (only the first document affected)\n");
	printf("    -restrictions=[options]  use -restrictions to see list\n");
	printf("    -resubmit_forms  toggles forced resubmissions (no_cache) of forms\n");
	printf("    -rlogin          disable rlogins\n");
	printf("    -selective       require .www_browsable files to browse directories\n");
	printf("    -show_cursor     don't hide the curser in the lower right corner\n");
	printf("    -sjis            set kanji code to Shift JIS\n");
	printf("    -soft_dquotes    toggles emulation of the old Netscape and Mosaic bug which\n");
	printf("                     treated '>' as a co-terminator for double-quotes and tags\n");
	printf("    -source          dump the source of the first file to stdout and exit\n");
#ifndef VMS
#ifdef SYSLOG_REQUESTED_URLS
	printf("    -syslog=text     information for syslog call\n");
#endif /* SYSLOG_REQUESTED_URLS */
#endif /* !VMS */
	printf("    -telnet          disable telnets\n");
	printf("    -term=TERM       set terminal type to TERM\n");
	printf("    -trace           turns on WWW trace mode\n");
	printf("    -traversal       traverse all http links derived from startfile\n");
	printf("    -underscore      toggles use of _underline_ format in dumps\n");
	printf("    -validate        accept only http URLs (for validation)\n");
	printf("    -version         print Lynx version information\n");
	printf("    -vikeys          enable vi-like key movement\n");
	if (strncmp(argv[0], "-help", 5) != 0)
	    exit(-1);
	exit(0);
    } else {	/* alternate database path */
	
	StrAllocCopy(startfile, argv[0]);
    }
}

#ifndef VMS
static void FatalProblem ARGS1(int,sig)
{
    fprintf (stderr, "\r\n\
A Fatal error has occurred in %s Ver. %s\r\n", LYNX_NAME, LYNX_VERSION);

    fprintf(stderr, "\r\n\
Please notify your system administrator to confirm a bug, and\r\n\
if confirmed, to notify the lynx-dev list.  Bug reports should\r\n\
have concise descriptions of the command and/or URL which causes\r\n\
the problem, the operating system name with version number, the\r\n\
TCPIP implementation, and any other relevant information.\r\n");

    fprintf(stderr, "\r\n\
Do NOT mail the core file if one was generated.\r\n");

    fprintf(stderr, "\r\n\
Lynx now exiting with signal:  %d\r\n\r\n", sig);

    /* ignore further interrupts */     /*  mhc: 11/2/91 */
    (void) signal (SIGHUP, SIG_IGN);
    (void) signal (SIGTERM, SIG_IGN);
#ifndef VMS  /* use ttclose() from cleanup() for VMS */
    (void) signal (SIGINT, SIG_IGN);
#endif /* !VMS */
#ifndef __linux__
     (void) signal (SIGBUS, SIG_IGN);
#endif /* !__linux__ */
     (void) signal (SIGSEGV, SIG_IGN);
     (void) signal (SIGILL, SIG_IGN);

  cleanup_sig(0);
#ifndef __linux__
  signal (SIGBUS, 0);
#endif /* !__linux__ */
  signal (SIGSEGV, 0);
  signal (SIGILL, 0);
  abort();  /* exit and dump core */
}
#endif /* !VMS */
