#!/usr/local/bin/perl -w-- # -*- perl -*-
#
# $Id: check_babyl,v 1.1 1995/11/03 18:21:52 ejb Exp $
# $Source: /home/ejb/scripts/RCS/check_babyl,v $
# $Author: ejb $
#
# Check babyl file for proper format and report errors
#

# This code, from the perl manual page, forces this to be run by perl from 
# perl, sh, or csh.  It must be first.
eval '(exit $?0)' && eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
& eval 'exec /usr/local/bin/perl -S $0 $argv:q'
    if 0;

require 5.001;
use strict;

my $whoami = ($0 =~ m,([^/]*)$,) ? $1 : $0;

undef $/;
(my $file = $ARGV[0]) || die "Usage: $whoami rmail_file\n";

open(FILE, "<$file") || die "$whoami: open $file: $!";
my $buf = <FILE>;
close(FILE);

my (@msgs) = split(/\037/, $buf);
my $offset = length(shift(@msgs)) + 1;
my $i;

for ($i = 1; $i <= scalar(@msgs); $i++)
{
    print "$whoami: checking message $i (offset $offset)\n";
    my $msg = $msgs[$i-1];
    $offset += length($msg) + 1;
    my @lines = split(/\n/, $msg);

    my $st_ff = 0;
    my $st_flags = 1;
    my $st_h1 = 2;
    my $st_eooh = 3;
    my $st_h2 = 4;
    my $st_done = 5;
    my $state = $st_ff;
    for (@lines)
    {
	if ($state == $st_ff)
	{
	    if ($_ ne "\014")
	    {
		warn "$whoami: message $i does not start with a formfeed\n";
		$state = $st_done;
	    }
	    else
	    {
		$state = $st_flags;
	    }
	}
	elsif ($state == $st_flags)
	{
	    if (! m/,,$/)
	    {
		warn "$whoami: line 2 of message $i does not end with ,,\n";
		$state = $st_done;
	    }
	    else
	    {
		$state = $st_h1;
	    }
	}
	elsif ($state == $st_h1)
	{
	    if ($_ eq "")
	    {
		$state = $st_eooh;
	    }		    
	}
	elsif ($state == $st_eooh)
	{
	    if ($_ ne "*** EOOH ***")
	    {
		warn "$whoami: no *** EOOH *** after top headers in " .
		    "message $i\n";
		$state = $st_done;
	    }
	    else
	    {
		$state = $st_h2;
	    }
	}
	elsif ($state == $st_h2)
	{
	    if ($_ eq "")
	    {
		$state = $st_done;
	    }
	}
	else
	{
	    if ($_ eq "*** EOOH ***")
	    {
		warn "$whoami: message $i has superfluous *** EOOH ***\n";
	    }
	}
    }

    if ($state != $st_done)
    {
	warn "$whoami: message $i ends prematurely\n";
    }
}
