#include <exec/types.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>

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

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

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

void main(int argc, char **argv)

{BPTR             sout;
 int              fp;
 char            *src;
 char            *dst;
 long             len;
 struct Archiver  Arc;
 char             exestring[512];

 struct USER_DATA UserDat;
 struct Ram_File  RStruct;
 char             Ext[4];

 if (argc < 2)                                       exit(5);
 if (!(DLGBase = OpenLibrary(DLGNAME, DLGVERSION)))  exit(5);

 sout = Output();
 len  = strlen(argv[1]);

 if (GetDevName(Ext) == -1)            _CXBRK(5);
 if (!ReadUser(&RStruct,&UserDat,Ext))  _CXBRK(5);
 if (!(ls = GetLang(Ext)))             _CXBRK(5);
 SA = ls->strings;

 if ((fp = open("DLGConfig:Misc/Archivers.bbs",O_RDONLY))==EOF)
    {AFPrintf(&UserDat, sout, SA[2538]);
    _CXBRK(5);
    }

 while(read(fp,&Arc,sizeof(Arc))==sizeof(Arc))
      {if (len <= strlen(Arc.extension))                                 continue;
       if (Stricmp(Arc.extension, argv[1]+(len-strlen(Arc.extension))))  continue; 
       close(fp);

       for(dst = exestring, src = Arc.view; *src; src++)
          {if (*src != '~')
              {*dst++ = *src;
               continue;
              }

           if (*(src+1) != 'd')
              {*dst++ = *src;
               continue;
              }

           strcpy(dst, argv[1]);
           dst += len;
           src++;
          }      

      *dst = 0;
       OverlayProgram(exestring);

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

 AFPrintf(&UserDat, sout, SA[2539]);
 close(fp);
_CXBRK(5);
}


void _CXBRK(int code)

{CloseLibrary(DLGBase);
 exit(code);
}
