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

#include <dlg/dlg.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>

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


void  main(void);
void _CXBRK(int);


BPTR            sout    = NULL;
struct Library *DLGBase = NULL;
char           *buffer  = NULL;
long            bsize   =  0;
char          **SA;

void main(void)

{BPTR                  lock;
 BPTR                  fp;
 struct FileInfoBlock  fib;

 char                 *cbuffer;
 char                 *ebuffer;
 char                 *pbuffer;
 char                  tempstring[36];

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

 AFPrintf(NULL, sout, SA[580]);
 AFPrintf(NULL, sout, SA[581]);

 if (!(lock = Lock("User:", ACCESS_READ)))
    {AFPrintf(NULL, sout, SA[582]);
    _CXBRK(5);
    }

 if (!Examine(lock, &fib))
    {AFPrintf(NULL, sout, SA[583]);
    _CXBRK(5);
    }

 while(ExNext(lock, &fib))
      {if (fib.fib_DirEntryType < 0)  continue;
       bsize += 36;
       Chk_Abort();
      }

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

 if (!(buffer = malloc(bsize)))
    {AFPrintf(NULL, sout, SA[585]);
     UnLock(lock);
    _CXBRK(5);
    }


 if (!Examine(lock, &fib))
    {AFPrintf(NULL, sout, SA[583]);
    _CXBRK(5);
    }

 cbuffer = buffer;
 while(ExNext(lock, &fib))
      {if (fib.fib_DirEntryType < 0)  continue;

       memset(tempstring, 0, sizeof(tempstring));
       strcpy(tempstring, fib.fib_FileName);
       tempstring[35] = 0;

       DeScore(tempstring);
       Upper(tempstring);

       movmem(tempstring, cbuffer, 36);
       cbuffer += 36;
       Chk_Abort();
      }

 UnLock(lock);

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

 for(cbuffer=buffer+36, ebuffer=buffer+bsize; cbuffer < ebuffer; cbuffer += 36)
    {pbuffer = cbuffer - 36;
     if (strcmp(cbuffer, pbuffer) < 0)
        {movmem(pbuffer,    &tempstring, 36);
         movmem(cbuffer,     pbuffer,    36);
         movmem(&tempstring, cbuffer,    36);
         if (cbuffer > buffer+36)  cbuffer -= 72;
        }
     Chk_Abort();
    }

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

 DeleteFile("DLGCONFIG:Misc/Users.bbs");
 if (!(fp = Open("DLGCONFIG:Misc/Users.bbs", MODE_NEWFILE)))
    {AFPrintf(NULL, sout, SA[588]);
    _CXBRK(5);
    }

 Write(fp, buffer, bsize);
 Close(fp);

 AFPrintf(NULL, sout, SA[589]);
_CXBRK(0);
}


void _CXBRK(int code)

{if (buffer)   free(buffer);
 CloseLibrary(DLGBase);
 exit(code);
}
