#!/usr/bin/perl -w
#
# $Revision: 1.2 $ $Date: 2012-07-26 17:11:47-04 $
# $Source: /home/vogelke/bin/RCS/keep-links,v $
# $Host: sys7.com $
# $UUID: faf1e186-3075-32e8-8bca-2abe31d4d95e $
#
#<keep-links: save only used references in a file generated by Lynx.

use strict;

my %num = ();

# Find all numbers in block-quotes before the References.
# Instead of messing around with where we ended a search,
# just split the line into an array.

while (<>) {
    chomp;
    print "$_\n";
    last if /^References$/;

    if (/\[\d+\]/) {
        foreach my $word (split) {
            $num{$1} = 1 if $word =~ /\[(\d+)\]/;
        }
    }
}

die "no References line found\n" if eof;    # Sanity check.

# Keep only references that match what we found above.

while (<>) {
    chomp;
    if (/^\s*(\d+)\.\s/) {
        print "$_\n" if $num{$1};
    }
}

exit(0);
