#!/usr/bin/perl
#
# Written by Kirk Hilliart, <kirk@debian.org>
# Adapted by Thomas Petazzoni, <thomas.petazzoni@enix.org> for dict-revo
use strict;

my @b64 = (('A'..'Z'), ('a'..'z'), (0..9), '+', '\\');
sub B64 {
    my($x) = @_;
    my $s;
    while(($s.=$b64[$x%64]),$x>>=6) {}
    scalar reverse $s;
}

@ARGV != 3 or die "$0: Error: Incorrect argument count\n";
$ARGV[0] !~ /\.dz$/ or die "$0: Error: database may not be compressed\n";
stat $ARGV[0] or die "$0: Error: Can't stat file $ARGV[0]: $!\n";

open (DATABASE, $ARGV[0]) or die "$0: Error: Can't open file $ARGV[0]: $!\n";
open (NEWENTRY, $ARGV[1]) or die "$0: Error: Can't open file $ARGV[1]: $!\n";

my $offset = (stat(DATABASE))[7];
my $length = (stat(NEWENTRY))[7];
close DATABASE;
my $start = -1;
my $headword;
my $lines = 0;

while (<NEWENTRY>) {
    if (/^\S/) { # found headword
        chomp ($headword = $_);
        $start = $offset;
    }
    $offset += length;
    $lines = $lines + 1;
}

if ($lines != 2)
{
    print "Error in file $ARGV[1]! ($lines)\n";
    exit 1;
}

if ($start >= 0) { # not first headword
    my $start_b64 = B64($start);
    my $length_b64 = B64($offset - $start);
    print "/$headword/ s/\\t.*/\\t$start_b64\\t$length_b64/\n";
}
