use BibTeX::Parser;
use strict;

open( my $fh, $ARGV[1] );
my $bib = BibTeX::Parser->new( $fh );
open OUT, ">$ARGV[0]";
my %sorted;

while ( $_ = $bib->next )
{
    die unless $_->parse_ok;

    my $authors = join ", ", $_->author;
    my $title = $_->cleaned_field( 'title' );
    my $year = $_->{year};
    my $publisher = $_->{publisher};
    my $coll = $_->{"series"};
    $coll = "volume $_->{volume} of $coll" if ( $coll && $_->{volume} );
    my $book = $_->cleaned_field( 'booktitle' );
    my $url = $_->{URL};
    my $note = $_->{note};

    $publisher = "$publisher, " if ( $publisher );
    $coll = ", $coll" if ( $coll );
    $book = "In «$book», " if ( $book );
    $note = " $note" if ( $note );

    $sorted{$year} .= "$authors:\n\$\$html <a href=\"$url\">$title</a>\n. $book$publisher$year$coll.$note\n\n";
}

print OUT "# papers\n\nThis list of papers is also available as a «bibtex file¹».\n¹ ‹./divine.bib›\n\n";

for ( reverse sort (keys %sorted) )
{
    print OUT "# $_\n\n";
    print OUT "$_" for ( $sorted{$_} );
    print OUT "\n";
}
