#include "LYCurses.h"
#include "HTUtils.h"
#include "LYSignal.h"
#include "LYClean.h"
#include "LYGlobalDefs.h"

/*
 * Interrupt handler.  Stop curses and exit gracefully.
 */
PUBLIC void cleanup_sig ARGS1(int,sig)
{

    char command[80];

    /* ignore further interrupts */     /*  mhc: 11/2/91 */
    (void) signal (SIGHUP, SIG_IGN);

#ifndef VMS  /* use ttclose() from cleanup() for VMS */
    (void) signal (SIGINT, SIG_IGN);
#endif

    (void) signal (SIGTERM, SIG_IGN);

#ifndef MSDOS
    if (sig != SIGHUP) {
#else
    if (TRUE) {
#endif
	cleanup(); /* <==also calls cleanup_files() */
	printf("\nExiting via interrupt: exit(%d)\n",sig);
	fflush(stdout);
    }

#ifdef TRAVERSAL
    dump_traversal_history();
#endif

#ifdef VMS
    exit(0);
#else
    exit(sig);
#endif VMS
}

/*
 * called by Interrupt handler or at quit time.  
 * Erases the temporary files that lynx created
 * temporary files are:
 * TEMP_SPACE LYNX pid() #
 * TEMP_SPACE LYNXhist pid()
 * TEMP_SPACE LYNX pid() PRINTOPTIONS 
 */
PUBLIC void cleanup_files NOARGS
{
    char filename[120];

	tempname(filename, REMOVE_FILES);
	
	sprintf(filename,"%sLYNX%dPRINTOPTIONS",TEMP_SPACE,getpid());
	remove(filename);
	sprintf(filename,"%sLYNXhist%d",TEMP_SPACE,getpid());
	remove(filename);
	sprintf(filename,"%sLYNXImage%d",TEMP_SPACE,getpid());
	remove(filename);
	sprintf(filename,"%sLYNXprint%d",TEMP_SPACE,getpid());
	remove(filename);
}

PUBLIC void cleanup NOARGS
{
    int lastx=1, lasty=1;
#ifdef VMS
    extern BOOLEAN DidCleanup;
#endif VMS
 
    /* cleanup signals - just in case */
    /* 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

    move(LINES-1, 0);
    clrtoeol();

    stop_bold();
    stop_underline();
    stop_reverse();
    refresh();

    stop_curses();

    cleanup_files();
#ifdef VMS
    ttclose();
    DidCleanup = TRUE;
#endif

   fflush(stdout);
}

