#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <dos.h>
#include <fcntl.h>
#include <fctype.h>
#include <sys/stat.h>
#include <exec/types.h>
#include <libraries/dosextens.h>

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

#include <link/io.h>
#include <link/lang.h>

#include <proto/dos.h>
#include <proto/exec.h>
#include <proto/dlg.h>

#include <pragmas/dlg.h>

#define LPswd "PrepArea"

#include <private/Version.h>
#define  ObjRev "1"
const UBYTE version[]="\0$VER: PrepAreas " BUILDVER "." ObjRev " ©" COPYRIGHT " by Digerati Dreams "__AMIGADATE__;

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

void  main        (void);
void  Process_Area(USHORT, long);
void  FixUsers    (long, long);
void _CXBRK       (void);


void main()

{int             fp;
 struct Msg_Area Area;

 sout = Output();
 if (!(DLGBase = OpenLibrary(DLGNAME, DLGVERSION)))  exit(5);
 if (!(SA = getlang(NULL)))                          exit(5);

 AFPrintf(NULL, sout, SA[1710]);
 AFPrintf(NULL, sout, SA[1711]);

 if ((fp=open("MSG:Area.bbs",O_RDONLY))==EOF)
    {AFPrintf(NULL, sout, SA[1712]);
    _CXBRK();
    }

 while((read(fp,&Area,sizeof(Area))) == sizeof(Area))
      {if (Area.Flag&NETMAIL_AREA || Area.Flag&ECHO_AREA)
          {signal(SIGINT, SIG_DFL);
           Chk_Abort();
           signal(SIGINT, SIG_IGN);

           while(EnterArea(Area.Number,MSGLOCK|WRITELOCK)!=RMNOERR)
                 Delay(250L);

           Process_Area(Area.Number, Area.Capacity);
           LeaveArea(Area.Number,MSGLOCK|WRITELOCK);
          }
      }

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


void Process_Area(USHORT number, long cap)

{char   highwater[128];

 long   lomes;
 long   himes;
 long   activity = 0;

 AFPrintf(NULL, sout, SA[1713], number);

 GetHiLowPointers(number, NULL, &lomes, &himes, LPswd);

 ASPrintf(NULL, highwater, "MSG:%d/%d.msg", number, himes);
 AFPrintf(NULL, sout, SA[1714]);

 while(!Exists(highwater)  &&  himes > 1)
      {himes--;
       activity = 1;
       ASPrintf(NULL, highwater,"MSG:%d/%d.msg", number, himes);
      }

 if (!activity)
    {AFPrintf(NULL, sout, SA[1715]);
     return;
    }

 if (himes == 1)
    {lomes = 2;
     himes = 1;
    }

 PutHiLowPointers(number, NULL, lomes, himes, LPswd);
 FixUsers(number, himes);
}


void FixUsers(long number, long himes)

{struct Msg_Log Log;
 int    fp;
 char   filename[80];

 ASPrintf(NULL, filename, "MSG:%d/user.msg", number);

 if ((fp=open(filename,O_RDWR))==EOF)
    {AFPrintf(NULL, sout, SA[1718], filename);
     return;
    }

 while(read(fp,&Log,sizeof(Log))==sizeof(Log))
      {if (Log.High_Mess > himes)
          {Log.High_Mess = himes;
           lseek(fp, (0L-((long)sizeof(Log))), 1);
           write(fp, &Log, sizeof(Log));
          }
      }

 close(fp);
}


void _CXBRK()

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