/*
 * validate pop file format
 *
 * Usage: reap <file1> <file2>...
 *
 * Tom Coppeto
 * 1/16/90
 *
 * $Source: /afs/net.mit.edu/tools/src/grim/RCS/popreap.c,v $
 * $Author: tjcoppet $
 * $Log:	popreap.c,v $
 * Revision 1.2  90/01/16  15:56:10  tjcoppet
 * hello
 * 
 */

#ifndef lint
static char rcsid[]="$Header: /afs/net.mit.edu/tools/src/grim/RCS/popreap.c,v 1.2 90/01/16 15:56:10 tjcoppet Exp Locker: tom $";
#endif


#include <stdio.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/dir.h>

/*
 * Each Mail file is separted by this
 */

#define POP_SEP "\001\001\001\001"

char *prog;
void validate();


main(argc, argv)
     int argc;
     char *argv[];
{
  int i;
  DIR *dirp;
  struct direct *dp;

  prog = argv[0];

  if(argv[1])
    for(i = 1; i < argc; i++)
      validate(argv[i]);
  else
    {
      if(!(dirp = opendir(".")))
	{
	  fprintf(stderr, "%s: cannot open current directory.\n", prog);
	  exit(1);
	}
      for (dp = readdir(dirp); dp ; dp = readdir(dirp))
	validate(dp->d_name);
    }
}


/*
 * Function:    validate()
 * Description: Loops through each message in the file
 */

void
validate(file)
     char *file;
{
  FILE *fp;
  char buf[BUFSIZ];
  int pcount = 0;
  int msgcount = 0;
  int line = 0;
  int open;

  fp = fopen(file, "r");
  if(fp == NULL)
    {
      perror(prog);
      fprintf(stderr, "%s: unable to open file %s.\n", prog, file);
      return;
    }
  
  open = 0;
  while(fgets(buf, sizeof(buf), fp))
    {
      ++line;
      if(strncmp(buf, POP_SEP, 4) == 0)
	{
	  ++pcount;
	  if(open)
	    {
	      open = 0;
	      continue;
	    }
	  msgcount++;
	  open = 1;
	  continue;
	}

      if(!open)
	{
	  fprintf(stderr, "%s: garbage after message %d, line %d\n", 
		  file, msgcount, line);
	  break;
	}
    }

  if(open)
    fprintf(stderr, "%s: never closed\n", file);

  printf("%s: done\n", file);
  (void) fclose(fp);
  return;
}




