#!/usr/bin/perl -w
#
# Reads in PGG articles and outputs a single file on stdout
# suitable for input into TomeRaider
#
# Syntax:
#     pgg2tr [<FILE>]*
#
# (c) Andrew Flegg 2000. Released under the Artistic Licence.
# v1.00 (14-Jan-2000), see http://www.bleb.org/software/pda/

use strict;

my @articles = ();

my ($title, $subtitle, $author, $date, $story, $seealso);

my $STATE_READINGHEADER    = 1;
my $STATE_READINGBODY      = 2;

my $state = $STATE_READINGHEADER;
while (<>) {
    chomp;

    if ($state == $STATE_READINGHEADER) {
	next if m/^\*/;           # Skip lines starting with *

	if (m/^%t (.*)$/) { $title     = $1; }
	if (m/^%s (.*)$/) { $subtitle  = $1; }
        if (m/^%a (.*)$/) { $author    = $1; }
        if (m/^%d (....)(..)(..)$/) { $date = "$3/$2/$1"; }
	if (m/^%x (.*)$/) { $seealso  .= "$1\n"; }
        if (m/^%i (.*)$/) { &writeStory($1, "", "", "", "See: $title", ""); }

	if (m/^%e/) { $state = $STATE_READINGBODY; next; }

    } elsif ($state == $STATE_READINGBODY) {
	if (m/^%e/) {
	    &writeStory($title, $subtitle, $author, $date, $story, $seealso);
	    $state = $STATE_READINGHEADER;
	    $title = $subtitle = $author = $date = $story = $seealso = "";
            next;
	}

	$story .= "$_\n";
    }
}

@articles = sort { lc($a->{title}) cmp lc($b->{title}) } @articles;

my $i;
foreach $i (@articles) {
    print "*new*$i->{title}\n$i->{body}\n";
}

exit;


# -------------------------------------------------------------
sub writeStory {
    my ($t, $s, $a, $d, $b, $r) = @_;

    my %article;
    $article{title} = $t;
    $article{body}  = $b;

    if ($d) {
	if ($a) {
	    $a .= ", $d";
	} else { $a = $d; }
    }

    if ($a) { $article{body} = "$a\n\n$article{body}"; }
    if ($s) { $article{body} = "$s\n$article{body}"; }

    if ($r) { $article{body} .= "\n\nSEE ALSO:\n$r"; }

    push @articles, \%article ;

    return;
}

