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

#include <dlg/dlg.h>
#include <dlg/resman.h>
#include <dlg/user.h>
#include <dlg/msg.h>
#include <dlg/misc.h>

#include <link/io.h>
#include <link/lang.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: UNet2DLG " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;

#define TFILE "T:unet2dlg.tmp"

void                main(int, char **);
BOOL                DoMsg(void);
BOOL                KeepEm = FALSE;
long                ReadArtPointer(char *);
BOOL                WriteArtPointer(char *, long);
void                CheckForBreak(void);
void                _CXBRK(void);
void                CleanUp(char *);

BPTR                sout;
char              **SA;
struct Library     *DLGBase = NULL;

long                high;
long                artnum;
ULONG               bsize = 0;
UBYTE              *mybuf = NULL;

UBYTE               pflag = FALSE;
UBYTE               inarea = FALSE;

struct Msg_Header   header;
struct Msg_Area     area;
struct fido         fido;
struct MsgStruct    ms = {&header, NULL, NULL, 0, &area, 0};

int                 afd = EOF;
int                 rfd = EOF;
FILE               *pfp = NULL;
FILE               *fp = NULL;

void                main(int argc, char **argv)
{
   long                len;

   UBYTE               fflag;
   UBYTE               tflag;

   char                buf[256];
   char                filename[256];
   char                tempbuf[10];


   sout = Output();

   if (!(DLGBase = OpenLibrary(DLGNAME, DLGVERSION)))
      CleanUp("Unable to open DLG.Library");
   if (!(SA = getlang(NULL)))
      CleanUp("Can't read language file");

   if(argc > 1)
   {
      if(!Stricmp(argv[1],"-K"))
      {
         KeepEm = TRUE;
      }
   }

   AFPrintf(NULL, sout, SA[3313]);

   if (GetFirstStruct("DLGConfig:Port/FidoNet.Settings", (char *) &fido, sizeof(fido)))
   {
      fido.net = 0;
      fido.origin[0] = 0;
   }

   if ((afd = open("MSG:Area.bbs", O_RDONLY)) == EOF)
      CleanUp(SA[3314]);

   strcpy(header.To, "All");

   while (read(afd, &area, sizeof(struct Msg_Area)) == sizeof(struct Msg_Area))
   {
      int                 i;
      char               *newsdir;

      if (!(area.Flag & NEWSGROUP_AREA))
         continue;

      newsdir = strdup(area.origin);

      for (i = 0; i < strlen(newsdir); i++)
      {
         if (newsdir[i] == '.')
         newsdir[i] = '/';
      }

      tempbuf[0] = 0;
      AFPrintf(NULL, sout, SA[3315], area.Number, area.Name);

      EnterArea(area.Number, MSGLOCK & ENTERPEND);
      inarea = TRUE;

      artnum = ReadArtPointer(newsdir);
      pflag = TRUE;

      while (artnum < high)
      {
         ASPrintf(NULL, filename, "UUNews:%s/%ld", newsdir, artnum);

         if (!(fp = fopen(filename, "r")))
         {
            artnum++;
            continue;
         }

         if (!(*tempbuf))
            AFPrintf(NULL, sout, SA[3316]);

         AFPrintf(NULL, sout, SA[3317], artnum);

         if ((rfd = open(TFILE, O_WRONLY + O_CREAT)) == EOF)
            CleanUp(SA[3318]);

         header.TimesRead = 0;
         header.DestNode = 0;
         header.OrigNode = 0;
         header.Cost = 0;
         header.OrigNet = 0;
         header.DestNet = 0;
         header.ReplyTo = 0;
         header.Attribute = 0;
         header.NextReply = 0;
         header.From[0] = 0;
         header.Title[0] = 0;

         fflag = FALSE;
         tflag = FALSE;

         while (fgets(buf, 254, fp))
         {
            len = strlen(buf) - 1;
            buf[len] = 0;

            if (!fflag)
            {
               if (!strncmp(buf, "From:", 5))
               {
                  fflag = TRUE;
                  strncpy(header.From, buf + 6, 35);
                  header.From[35] = '\0';
               }
            }

            if (!tflag)
            {
               if (!strncmp(buf, "Subject:", 8))
               {
                  tflag = TRUE;
                  strncpy(header.Title, buf + 9, 71);
                  header.Title[71] = '\0';
               }
            }

            write(rfd, buf, len);
            write(rfd, "\x0d", 1);
         }

         fclose(fp);
         fp = NULL;
         close(rfd);
         rfd = EOF;

         if(!KeepEm)
            DeleteFile(filename);

         ASPrintf(NULL, tempbuf, "%ld", artnum);
         artnum++;
         DoMsg();
         AFPrintf(NULL, sout, "\033[%dD", strlen(tempbuf));
      }

      LeaveArea(area.Number, MSGLOCK);
      inarea = FALSE;

      if (*tempbuf)
         AFPrintf(NULL, sout, "\033[%dC", strlen(tempbuf));

      AFPrintf(NULL, sout, SA[3319]);

      WriteArtPointer(newsdir, artnum);
      pflag = FALSE;
   }

   AFPrintf(NULL, sout, SA[3320]);
   CleanUp(NULL);
}

BOOL                DoMsg(void)
{
   ULONG               size;

   FileSize(TFILE, &size);

   if (bsize < size + 256)
   {
      if (bsize)
      {
         free(mybuf);
         bsize = 0;
      }

      mybuf = malloc(size + 256);

      if (!mybuf)
      {
         DeleteFile(TFILE);
         return (FALSE);
      }

      bsize = size + 256;
   }

   if (GetFirstStruct(TFILE, mybuf, size))
   {
      DeleteFile(TFILE);
      return (FALSE);
   }

   *(mybuf + size) = 0;

   MDate(header.Date);
   ms.body = mybuf;
   SendPublicMsg(&ms, &fido, "UNet2DLG", "NOL");

   DeleteFile(TFILE);
   Chk_Abort();

   return (TRUE);
}

long                ReadArtPointer(char *dirname)
{
   long                ptr;
   char                pointerfile[256];

   ASPrintf(NULL, pointerfile, "UUNews:%s/.next", dirname);

   if (!(pfp = fopen(pointerfile, "r")))
      high = 1;
   else
   {
      fscanf(pfp, "%d", &high);
      fclose(pfp);
      pfp = 0;
   }

   ASPrintf(NULL, pointerfile, "UUNews:%s/.DLG", dirname);

   if (!(pfp = fopen(pointerfile, "r")))
      ptr = 1;
   else
   {
      fscanf(pfp, "%ld", &ptr);
      fclose(pfp);
      pfp = 0;
   }

   ptr = (ptr > high) ? high : ptr;
   return (ptr);
}

BOOL                WriteArtPointer(char *dirname, long ptr)
{
   char                pointerfile[256];

   ASPrintf(NULL, pointerfile, "UUNews:%s/.DLG", dirname);
   pfp = fopen(pointerfile, "w");

   if (!pfp)
      return (FALSE);

   fprintf(pfp, "%d\n", ptr);
   fclose(pfp);
   pfp = 0;

   return (TRUE);
}

void                _CXBRK(void)
{
   CleanUp(SA[3321]);
}

void                CleanUp(char *s)
{
   if (inarea)
      LeaveArea(area.Number, MSGLOCK);

   if (afd != EOF)
      Close(afd);

   if (rfd != EOF)
      Close(rfd);

   if (fp)
      fclose(fp);

   if (pfp)
      fclose(pfp);

   if (pflag)
      WriteArtPointer(area.origin, artnum);

   if (bsize)
      free(mybuf);

   DeleteFile(TFILE);

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