#include <exec/types.h>
#include <exec/exec.h>
#include <stdio.h>
#include <stdlib.h>
#include "dh0:code/code20/defines.h"

struct MailStat MS;
char conf[200];
BOOL UPDATE=FALSE;
void NullStats();
int TLock(char *str);
void sr(char *str);
char temp[200];
main(int argc,char *argv[])
{
  FILE *fi;
  if(argc<2 || argc >3)
  {
    printf("MailStats version 1.0 written by Joseph Hodge\n");
    printf("Usage: MailStats <conference path> [UPDATE]\n");
    printf("   ie: MailStats BBS:PD\n");
    printf("\n\n");
    printf("This is an AmiExpress 1.1w+ utility\n");
    printf("\n");
    exit(0);
  }
  
  strcpy(conf,argv[1]);
  sr(conf);
  if(!TLock(conf))
  {
     printf("Can't locate conference location %s\n",conf);
     printf("\n");
     exit(0);
  }
  if(argc==3)
  {
    UPDATE=TRUE;
  }
  strcat(conf,"/MsgBase/MailStats");
  NullStats();
  if(TLock(conf))
  {
    fi=fopen(conf,"rb");
    if(fi==NULL)
    {
      printf("Error! can't open file %s\n",conf);
      exit(0);
    }
    fread((APTR)&MS,sizeof(struct MailStat),1,fi);
    fclose(fi);
    printf("Current MailStats\n");
    printf("\n");
    printf("LowestKey    :%ld\n",MS.LowestKey);
    printf("HighMsgNum   :%ld\n",MS.HighMsgNum);
    printf("LowestNotDel :%ld\n",MS.LowestNotDel);
    printf("\n\n");
  }
  else
  {
    if(!UPDATE)
    {
      printf("Error!, MailStats does not exist for this conference\n");
      printf("This is normal if the message base has not been used\n");
      printf("But if the message base has been used then please run\n");
      printf("this utility with the UPDATE option\n");
      printf("\n\n");
      exit(0);
    }
  }
  if(UPDATE)
  {
    printf("Enter New LowestKey    >:");
    gets(temp);
    MS.LowestKey=atol(temp);
    printf("Enter New HighMsgNum   >:");
    gets(temp);
    MS.HighMsgNum=atol(temp);
    printf("Enter New LowestNotDel >:");
    gets(temp);
    MS.LowestNotDel=atol(temp);
    fi=fopen(conf,"wb");
    if(fi==NULL)
    {
      printf("Error!, can't create MailStats file\n");
      printf("\n\n");
      exit(0);
    }
    fwrite((APTR)&MS,sizeof(struct MailStat),1,fi);
    fclose(fi);
  }
  
}
void sr(char *str)
{
  register int i;
  i=strlen(str)-1;
  while(i>-1)
  {
    if(*(str+i)<=32) *(str+i)='\0'; else break;
    i--; 
  }
}
#define ACCESS_READ -2
int TLock(char *str)
{
  long lock;
  if(lock=Lock(str,ACCESS_READ))
  {
    UnLock(lock); return(1);
  }
  return(0);
}
void NullStats()
{
  MS.LowestKey=0L;
  MS.HighMsgNum=0L;
  MS.LowestNotDel=0L;
  strcpy(MS.Pad,"     ");
}