#include <exec/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.h>

#include <dlg/resman.h>
#include <dlg/dlg.h>
#include <dlg/user.h>
#include <dlg/menu.h>
#include <dlg/portconfig.h>
#include <dlg/log.h>

#include <link/io.h>

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

#include <pragmas/dlg.h>

#include <private/Version.h>
#define  ObjRev "1"
const UBYTE version[]="\0$VER: Menu " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;


BPTR                   sout;
struct Ram_File        RStruct;
struct USER_DATA       UserDat;

struct Library        *DLGBase;
struct LangStruct     *ls;
char                 **SA;

char  port    [4];
char  menuname[13];

int   HandleBuiltin(UBYTE);
void  CleanUp(char *);
void _CXBRK(void);


main(int argc, char **argv)

{sout = Output();

 DLGBase = OpenLibrary(DLGNAME, DLGVERSION);
 if (!DLGBase)                CleanUp("Unable to open DLG.library");
 if (GetDevName(port)==-1)    CleanUp("Unable to determine port");
 if (!(ls = GetLang(port)))   CleanUp("Unable to access language file");
 SA = ls->strings;
  
 if (!ReadUser(&RStruct, &UserDat, port))  CleanUp(SA[1071]);

 if (argc>1)
     strcpy(menuname, argv[1]);
   else
    {if (*RStruct.menu)
         strcpy(menuname, RStruct.menu);
       else
         strcpy(menuname, "MAIN");
    }

 if (!RStruct.chainflag)
    {ASPrintf(&UserDat, RStruct.Action, SA[1072], menuname);
     WriteRam(&RStruct, port);
    }

 for(;;)
    {if (*RStruct.menu)
         strcpy(menuname, RStruct.menu);
       else
         strcpy(menuname, "MAIN");

     if (MenuInput(menuname,port,"MENU",NULL,0,HandleBuiltin,&UserDat,&RStruct,UserDat.Help_Level,NULL)==MENUNOTFOUND)
         _CXBRK();

     strcpy(RStruct.menu,menuname);
     Chk_Abort();
    }
}


int HandleBuiltin(UBYTE funcnum)

{int retval;

 retval = TRUE;

 switch(funcnum)
       {case 0:  break;

       default: *RStruct.Command_Stack='\0';
                 retval=FALSE;
                 break;
       }

 return(retval);
}


void CleanUp(char *s)

{if (DLGBase)  CloseLibrary(DLGBase);

 if (s)
    {Write(sout,  "\n Error: ", 9);
     Write(sout, s, strlen(s));
     Write(sout, "\n\n", 2);
    }

 exit(s?5:0);
}


void _CXBRK()

{if (DLGBase)  LogOut(&RStruct,&UserDat,port,"Menu");
 CleanUp(SA[1073]);
}
