#include <string.h>
#include <stdlib.h>
#include <exec/types.h>
#include <exec/io.h>
#include <fcntl.h>
#include <stdio.h>
#include <libraries/dosextens.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: TPTQuote " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;

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

char               Ext[4];
struct Library    *DLGBase = NULL;
struct LangStruct *ls;
char             **SA;

SHORT              pfd = EOF;
FILE              *qfp = NULL;


void main(int argc, char **argv)

{BPTR  sout;

 ULONG size   = 0;
 long  offset = 0;

 BYTE  line    [256];
 BYTE  quotename[80];
 BYTE  offname  [80];

 sout = Output();

 if (argc < 2)
    {Write(sout, "\n\n Usage: TPTQuote <quotefile>\n\n", 32);
     exit(5);
    }
 if (!(DLGBase = OpenLibrary(DLGNAME, DLGVERSION)))
    {Write(sout, "\n\n Error: Can't open DLG.Library\n\n", 34);
     exit(5);
    }

 if (GetDevName(Ext)==-1)
    {Write(sout, "\n\nError: Unable to find Handler Port", 36);
    _CXBRK(5);
    }

 if (!(ls = GetLang(Ext)))
    {Write(sout, "\n\nError: Unable to read language file", 37);
    _CXBRK(5);
    }
 SA = ls->strings;

 ASPrintf(NULL, quotename, "DLGCONFIG:text/%.36s.quote", argv[1]);
 ASPrintf(NULL, offname,   "DLGCONFIG:text/%.36s.ofs",   argv[1]);

 if ((pfd = open(offname,O_RDONLY))!=EOF)
     {read(pfd, &offset, 4);
      close(pfd);
      pfd = EOF;
     }

 FileSize(quotename, &size);
 if ((qfp = fopen(quotename,"r"))==NULL)
    {AFPrintf(NULL, sout, SA[2700], quotename);
    _CXBRK(5);
    }

 AFPrintf(NULL, sout, SA[2701]);
 AFPrintf(NULL, sout, SA[2702]);

 if (offset >= size)  offset = 0;
 fseek(qfp, offset, 0);
 for(;;)
    {if (!fgets(line,256,qfp))  break;
     if (!strcmp(line,"%%\n"))  break;

     AFPrintf(NULL, sout, SA[2703], line);
    }
 AFPrintf(NULL, sout, "\n");

 if ((pfd = open(offname, O_WRONLY+O_CREAT))==EOF)
    {AFPrintf(NULL, sout, SA[2704]);
    _CXBRK(5);
    }

 offset = ftell(qfp);
 write(pfd, &offset, 4);

_CXBRK(0);
}


void _CXBRK(int code)

{if (pfd != EOF)  close(pfd);
 if (qfp)         fclose(qfp);

 CloseLibrary(DLGBase);
 exit(code);
}
