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

#include <dlg/dlg.h>
#include <dlg/menu.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: SetMenuPri " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;

void  main(int, char **);
void _CXBRK(void);

BPTR                 sout;
struct Library      *DLGBase = NULL;
struct SearchCookie *sc      = NULL;
SHORT                fp      =  0;

void main(int argc, char **argv)

{char                *searchname;
 char                 infile[128];

 struct MenuEntry     MenuEnt;
 struct MenuHeader    MenuHeader;
 SHORT                priority;

 /* if no arguments, set to -127, otherwise set to argument */
 sout = Output();
 if (!(DLGBase = OpenLibrary(DLGNAME, DLGVERSION)))  exit(5);

 if (argc<2)
    {AFPrintf(NULL, sout, "\nSetting menu priorities to DEFAULT\n\n");
     priority = -127;
    }
  else
    {AFPrintf(NULL, sout, "\nSetting menu priorities to %d\n\n", atoi(argv[1]));
     priority = atoi(argv[1]);
    }

 /* Loop through the menu directory for each menu file */
 sc = SearchStart("DLGConfig:Menu", "*.menun");
 while(searchname = SearchNext(sc))
      {ASPrintf(NULL, infile, "DLGConfig:Menu/%s", searchname);

       AFPrintf(NULL, sout, "Converting %s... ",searchname);

       if ((fp=open(infile,O_RDWR))!=EOF)
          {/* Seek past the header */
           lseek(fp,(long)sizeof(MenuHeader),0);

           /* If priority is different than what we are setting it to, set it, backup, and write it */
           while(read(fp,&MenuEnt,sizeof(MenuEnt))==sizeof(MenuEnt))
                {if (MenuEnt.priority != priority)
                    {MenuEnt.priority = priority;
                     lseek(fp, 0-(long)sizeof(MenuEnt), 1);
                     write(fp,&MenuEnt,sizeof(MenuEnt));
                    }
                }

           close(fp);
           fp = 0;
           AFPrintf(NULL, sout, "done\n");
          }
      }


 AFPrintf(NULL, sout, "\n");
_CXBRK();
}


void _CXBRK(void)

{if (sc)  SearchEnd(sc);
 if (fp)  close(fp);

 CloseLibrary(DLGBase);
 exit(0);
}
