#!/usr/bin/perl
# parsenews 1.0 by John Gotts <jgotts@engin.umich.edu>

# Copyright 1996, John Gotts.

# I hereby release this program under the GNU General Public License.  Don't
# sue me for it.

# Usage: parsenews [-v] [-d] <filename> [<filename> <filename> ...]

# -v verbose output.
# -d include the date in output files.

require "getopts.pl";

&Getopts(':vd');

print "parsenews 1.0, a news/mail beautifier, by John Gotts <jgotts\@engin.umich.edu>.\n\n" if $opt_v;

if ($#ARGV < 0) {
   print "Usage: $0 [-v] [-d] <filename> [<filename> <filename> ...]\n";
   print "\n";
   print "-v verbose output.\n";
   print "-d include the date in output files.\n";
   exit;
}

print "Filenames:" if $opt_v;

$count = 0;

foreach $article (@ARGV) {
   if (! open(ARTICLE, $article)) {
      print STDERR "Cannot open $article.\n";
      next;
   }
   if (! -T $article) {
      print STDERR "$article is not a text file.\n";
      next;
   }

   $author = "";
   $newsgroups = "";
   $subject = "";
   $date = "";
   while (<ARTICLE>) {
      if ($_ !~ /^$/) {
         if (/^From: (.*)/) {
            $author = $1;
         }
         elsif (/^Newsgroups: (.*)/) {
            $newsgroups = $1;
         }
         elsif (/^Subject: (.*)/) {
            $subject = $1;
         }
         elsif (/^Date: (.*)/) {
            $date = $1;
         }
         if (eof) {
            print STDERR "$article does not contain a distinct header.\n";
         }
      } else {
         if (! $author) {
            print STDERR "Cannot find \"From\" field in $article; skipped.\n";
            seek (ARTICLE, 0, 2);
         } else {
            $count++;
            open (TEMP, "> /tmp/parsenews.pl.$$") || die "Can't open /tmp/parsenews.pl.$$: $!\n";
            if ($newsgroups) {
               print TEMP "Newsgroups: $newsgroups\n";
            }
            print TEMP "Subject:    $subject\n";
            print TEMP "Author:     $author\n";
            if ($opt_d) {
               print TEMP "Date:       $date\n";
            }
            print TEMP "\n";
            while (<ARTICLE>) {print TEMP "$_"};
            close (TEMP);
            close (ARTICLE);
            system ("/bin/cp -f /tmp/parsenews.pl.$$ \"$article\"");
            if ($opt_v) {
               if ($count > 1) {
                  print ", $article";
               } else {
                  print " $article";
               }
            }
         }
      }
   }
}

if ($opt_v) {
   if ($count) {
      print ".\n";
   } else {
      print " None.\n";
   }
}
