#include <stdlib.h>
#include <string.h>
#include <exec/types.h>
#include <ctype.h>

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

void main   (int, char **);
void Usage  (char *);
void CleanUp(char *);

BPTR            sout;
struct Library *DLGBase = NULL;


void main(int argc, char **argv)

{long  retval;
 char *name    =  NULL;
 char *passwd  = "DIALOG";

 sout    = Output();
 DLGBase = OpenLibrary(DLGNAME,DLGVERSION);
 if (!DLGBase) CleanUp("Unable to open dlg.library");

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

 while(--argc>0)
      {char *s;

       s = *++argv;
       if (*s++=='-')
          {while(*s)
                {switch(toupper(*s))
                       {case 'N': if (!--argc)  break;
                                  name = *++argv;
                                  break;

                        case 'K': if (!--argc)  break;
                                  passwd = *++argv;
                                  break;
                       }

                 s++;
                }
          }
      }

 if (!name)  Usage("You must specify the name of a resource");

 retval = FreeResource(name, passwd);

 if (retval == RMNOERR)
     AFPrintf(NULL, sout, " Resource released successfully\n");
   else
     if (retval == NORM)
         CleanUp("TPTRM is not installed");
       else
         if (retval == NOTLOCKED)
             CleanUp("You do not have a lock on that resource");
           else
             if (retval==BADRES)
                 CleanUp("Resource is not locked");
               else
                 CleanUp("Failed to free resource");

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


void Usage(char *string)

{AFPrintf(NULL, sout, " %s\n\n",string);
 AFPrintf(NULL, sout, " Usage:  FreeResource -n <name> [-k <password>]\n\n");

 CleanUp(NULL);
}


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);
}
