#include "HTUtils.h"
#include "LYCurses.h"
#include "LYSignal.h"
#include "LYUtils.h"
#include "LYClean.h"
#include "LYGlobalDefs.h"
#include "LYEdit.h"
#include "LYStrings.h"
#include "LYSystem.h"
#ifdef VMS
#include <unixio.h>
#include "HTVMSUtils.h"
#endif /* VMS */

#include "LYLeaks.h"

/*
 *  in edit mode invoke either emacs, vi, pico  or the default editor
 *  to display and edit the current file
 *  Both vi, emacs, and pico will open the file to the same line that the
 *  screen cursor is on when editing is invoked
 *  returns FALSE if file uneditable
 */

PUBLIC int edit_current_file ARGS3(char *,newfile, int,cur, int,lineno)
{

	char command[512];
        char *filename = NULL;
	char *colon, *localhost_ptr, *number_sign;
	FILE *fp;
	int url_type = is_url(newfile);

	/* if its a remote file then we can't edit it */
	if(url_type != FILE_URL_TYPE) {
	    _statusline("Lynx cannot currently (E)dit remote WWW files");
	    sleep(2);
	    return FALSE;
	}

	number_sign = strchr(newfile,'#');
	if(number_sign)
	    *number_sign = '\0';
	   
	 /* try and open it as a completely referenced file */
	colon = strchr(newfile,':');
	if((fp = fopen(colon+1,"r")) == NULL) {

	    localhost_ptr = strstr(newfile,"localhost");
	    if(localhost_ptr==NULL || 
#ifdef VMS
	       /* Allow Unix-like or VMS pathspecs */
	       ((fp = fopen(localhost_ptr+10,"r"))==NULL &&
	        (fp = fopen(filename=
			    HTVMS_name("",localhost_ptr+9),"r"))==NULL)) {
#else
	       (fp = fopen(localhost_ptr+9,"r"))==NULL) {
		    
#endif /* VMS */
	        _statusline("Lynx cannot currently edit remote WWW files");
	        sleep(2);
		goto failure;
	    } else {
#ifdef VMS
		if (filename == NULL)
		    filename = localhost_ptr+10;
#else
		filename = localhost_ptr+9;
#endif /* VMS */
	        fclose(fp);
	    }
	} else {
	    filename = colon+1;
	    fclose(fp);
	}
		

#if defined(VMS) || defined(CANT_EDIT_UNWRITABLE_FILES)
        /* Don't allow editing if user lacks write/delete access */
	if (access(filename,2)) {
		_statusline("You are not authorized to edit this file.");
		sleep(2);
		goto failure;
	}
#endif /* VMS || CANT_EDIT_UNWRITABLE_FILES */

#ifdef VMS
        sprintf(command,"%s %s",editor, filename);
#else
	if(strstr(editor,"emacs") || strstr(editor,"vi") ||
	   strstr(editor, "pico") || strstr(editor,"jove")) 
	    sprintf(command,"%s +%d \"%s\"",editor, lineno+links[cur].ly, 
                                                                filename);
	else
	    sprintf(command,"%s \"%s\"",editor, filename);
#endif /* VMS */

	stop_curses();
#ifndef VMS
	signal(SIGINT, SIG_IGN);
#endif /* not VMS */
	system(command);
#ifndef VMS
	signal(SIGINT, cleanup_sig);
#endif /* not VMS */
	start_curses();

	if(number_sign)
	    *number_sign = '#';
	return TRUE;

failure:
	if(number_sign)
	    *number_sign = '#';
	return FALSE;
}
