#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <dialog/msg.h>

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

extern struct Library  *DLGBase;
extern char           **SA;
extern struct USER_DATA StUser;

BOOL AlignAreas(struct Msg_Area *ainfo,char mode)

{char   filename[64];
 char   userfile[72];
 ULONG  size;
 struct Msg_Log *uarray;
 int    fp;
 int    up;
 long   level;
 long   counter;
 long   uindex;
 BPTR   sout;

 if (!(ainfo->Flag&AUTO_ACCESS_AREA))  return(TRUE);

 ASPrintf(NULL, filename, "%s:%d/User.%s",mode?"FILE":"MSG",ainfo->Number, mode?"file":"msg");

 /* Load users into an array */
 if (FileSize(filename, &size)==-1)                         return(FALSE);
 if (!(uarray=(struct Msg_Log *)malloc(size)))              return(FALSE);
 if (GetFirstStruct(filename, (char *)uarray, size) == -1)  return(FALSE);

 DeleteFile(filename);

 sout = Output();

 if ((fp=open(filename,O_RDWR+O_CREAT))==EOF)
    {AFPrintf(&StUser, sout, SA[3398],filename);
     return(FALSE);
    }

 counter = size / sizeof(struct Msg_Log);
 for(uindex=0; uindex < counter; uindex++)
    {AFPrintf(&StUser,  sout, SA[3399], (uarray+uindex)->Name);
     ASPrintf(NULL, userfile, "USER:%s/User.data", (uarray+uindex)->Name);
     UnderScore(userfile);

     if ((up=open(userfile,O_RDONLY))==EOF)
        {AFPrintf(&StUser, sout, SA[3400]);
         continue;
        }

     lseek(up,80L,0);
     read(up,&level,2);
     AFPrintf(&StUser, sout, SA[3401],level);
     close(up);

     if ((level<ainfo->llevel || level>ainfo->ulevel) &&
       !((uarray+uindex)->special) && !((uarray+uindex)->uflag) && level!=255)
        {AFPrintf(&StUser, sout, SA[3402]);
         continue;
        }

     Upper((uarray+uindex)->Name);
     write(fp,(uarray+uindex),sizeof(struct Msg_Log));
     AFPrintf(&StUser, sout, SA[3403]);
    }

 close(fp);
 free(uarray);
 AFPrintf(NULL, sout, "\n");
 return(TRUE);
}
