#!/usr/bin/perl
# Core Modules
use strict;
use warnings;
use utf8;
use Encode;
use IO::Handle;
use Getopt::Long;
use Pod::Usage;
# CPAN Modules

# Argument Parsing
my $file;
my $in_coding  = 'ISO-8859-15';
my $out_coding = 'UTF-8';
my $seperator  = "\@footnote:\n";
my $temp;
my $verbose;
my $help;

GetOptions(
   'file=s'  => \$file,
   'in=s'    => \$in_coding,
   'out=s'   => \$out_coding,
   'temp'    => \$temp,
   'verbose' => \$verbose,
   'help'    => \$help,
);

# Print Usage if filename not supplied
# or -h | --help is called.
if ( $help || !defined $file ) {
   pod2usage({
       -exitval  => 1,
       -verbose  => 99,
       -sections => 'NAME|SYNOPSIS'
   });
}

# Load Berkeley DB Modul and File::Temp Modul
# if user want a temp file.
if ( $temp ) {
   require DB_File;
   require File::Temp;
}

# open file
open my $fh, '<', $file
   or die "Cannot open file '$file': $!\n";

# skip anything until footnote
LINE:
while ( my $line = <$fh> ) {
   $line = decode($in_coding, $line, Encode::FB_CROAK);
   next LINE if $line ne $seperator;
   last LINE;
}

# variable that holds the mapping
my $db;
my %mapping;

# if user want temp file, then use a berkeley db
if ( $temp ) {
   $db = File::Temp->new();
   tie %mapping, 'DB_File', $db->filename;

   # Install Handler that fetches SIGINT (CTRL-C),
   # SIGTERM and SIGQUIT. It deletes the temp file
   # before ending.
   $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = sub {
       unlink $db->filename or
           warn sprintf "Cannot delete file '%s': $!\n",
               $db->filename;
       exit 0;
   };
}

# Build mapping (old number => new number)
my $counter = 1;
while ( my $line = <$fh> ) {
   $line = decode($in_coding, $line, Encode::FB_CROAK);
   if ( $line =~ m/ \A \s* \[ ( [0-9]+? ) \] /xms ) {
       $mapping{$1} = $counter++;
   }
}

# Seek to beginning of file
seek($fh, 0, 0)
   or die "Cannot seek in file '$file': $!\n";
$fh->input_line_number(0);

# go through each line and replace old number with new number
while ( my $line = <$fh> ) {
   $line = decode($in_coding, $line, Encode::FB_CROAK);
   # replace number with new one
   $line =~ s{ \[ ( [0-9]+? ) \] }{
       if ( exists $mapping{$1} ) {
           '[' . $mapping{$1} . ']'
       }
       else {
           if ( $verbose ) {
               warn sprintf "There is no target for reference '%d' at line %d.\n",
                   $1,
                   $fh->input_line_number;
           }
           "[$1]"
       }
   }xmsge;
   # print it out
   print encode($out_coding, $line, Encode::FB_CROAK);
}

close $fh or die "Cannot close file '$file': $!\n";

__END__
=head1 NAME

Call this progam <whatever> you want.

=head1 SYNOPSIS

<whatever> has following arguments.

-f  --file     Name of the file to process.
-i  --in       Input Encoding of the file.     Default: ISO-8859-1
-o  --out      Output Encoding of the program. Default: UTF-8
-v  --verbose  Print warning if a reference has no target.
-t  --temp     Uses a Berkeley DB as a temp file. Use this if you
               have really large files, or low memory.
-h  --help     Something you would not expect.

=head1 ENVIRONMENT

No environment variables are used.

=head1 AUTHOR

David Raab

=head1 LICENSE

Copyright (c) <2008> <David Raab>

MIT - License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.