/*************************************************************************
 ***                        system.c                     (JJB TEMPLAR) ***
 *** Date begun: 27/8/89.                                              ***
 *** Last modified: 27/8/89.                                           ***
 *************************************************************************/
/*** Some routines to handle Execute() stuff.                          ***
 *************************************************************************/

#include <exec/types.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>

#include <proto/exec.h>
#include <proto/dos.h>

#include <string.h>

extern char              current_file[];
extern struct DosLibrary *DOSBase;
extern BPTR              file; /* Have to close file so editor can write */

extern void error(char *,int);
extern void bell();
extern void edit(int);         /* To get back, hopefully */
extern void clear();           /* So use real function! */

static char *title = "CON:0/11/640/80/CON: ty1.3 :D/c";

void    newcli();
void    editor();
int     gotenv();

void    newcli() /*======================================================*/
{
register BPTR   con;
    if (!(con = Open(title,MODE_NEWFILE))) {
        error("Failed to open console!",0);
        bell();
    }
    else {
        Execute("",con,0L);
        Close(con);
        error("Welcome back...",0);
    }
}

void    editor() /*======================================================*/
{
register BPTR   con;    /* Also used to open ENV:EDITOR */
register int    len;
char    buf[256];
    if (!gotenv()) goto BADENV;
    if (!(con = Open("ENV:EDITOR",MODE_OLDFILE))) goto BADENV;

    if ((len = Read(con,buf,80)) <= 0) goto BADENV;
    Close(con);
    buf[len] = ' ';     buf[len+1] = 0;
    strcat(buf,current_file);
    if (!(con = Open(title,MODE_NEWFILE))) {
        error("Failed to open console!",0);
        bell();
    }
    else {
        Close(file);    file = NULL;    /* So edit won't try to re-Close */
        clear();    flush();
        Execute(buf,con,con);
        Close(con);
        edit(0);                        /* Zero means current file */
        error("Welcome back...",0);
    }
    return;
BADENV:
    if (con) Close(con);
    error("There's something wrong with ENV:EDITOR!",0);
    bell();
}

int     gotenv() /*======================================================*/
{
register struct DosInfo *di;
register struct DosList *dl;
register char           *name;

    di = (struct DosInfo *)(((struct RootNode *)(DOSBase->dl_Root))->rn_Info << 2);
    dl = (struct DosList *)(di->di_DevInfo << 2);
    while (dl) {
        name = (char *)(dl->dol_Name << 2);
        if (!strnicmp(name+1,"env",3)) break;
        dl = (struct DosList *)(dl->dol_Next << 2);
    }
    return((dl)? 1:0);
}
