#!/usr/bin/perl -w

=head1 NAME

marclint - MARC record dump utility

=head1 SYNOPSIS

B<marclint> [options] file(s)

=over 4

=item options

=over 4

=item --help

Print a summary of commands

=item --[no]stats

Print a statistical summary by file at the end.  (Default: on)

=back

=back

=cut

use warnings;
use strict;
use integer;

use lib qw( /home/alester/marc/lib );
use MARC::Record;
use MARC::Lint;
use Getopt::Long;

use constant USAGE => <<"END";
Usage: marclint [options] file(s)
    options
        --help
	    Print a summary of commands
	--[no]quiet
	    Suppress status messages
        --[no]stats
            Print a statistical summary by file at the end
END

my $stats = 1;
my $help = 0;
my $quiet = 0;

my $rc = GetOptions(
	"stats!" => \$stats,
	"quiet!" => \$quiet,
	"help"   => \$help,
	);

my @files = @ARGV;

die USAGE if $help or (not $rc) or (@files == 0);

my $linter = new MARC::Lint;
my %counts;
my %errors;
for my $IN ( @files ) {
	$counts{$IN} = 0;
	$errors{$IN} = 0;

	warn "$IN\n" unless $quiet;
	open( IN, "<", $IN ) or die "Couldn't open $IN: $!\n";

	while ( !eof(IN) ) {
		my $marc = MARC::Record::next_from_file( *IN );
		if ( not $marc ) {
			warn $MARC::Record::ERROR;
			++$errors{$IN};
		}

	        $linter->check_record( $marc );

		if ( $linter->warnings ) {
			print join( "\n",
				$marc->title,
				$linter->warnings,
				"",
				"",
			);
			++$errors{$IN};
		}
	} # while
	close IN;
} # for 

if ( $stats ) {
	print "\n\n";
	print " Recs  Errs Filename\n";
	print "----- ----- --------\n";
	for my $key ( sort keys %counts ) {
		printf( "%5d %5d %s\n", $counts{$key}, $errors{$key}, $key );
	} # for
} # if stats

