#!/usr/bin/perl
# -*- perl -*-
# Copyright 2007 DJ Delorie
# Released under the terms of the GNU General Public License, version
# 2 or higher.

# Given a file $prefix.texi and its inline images $prefix-N.png, where
# N is any floating point or integer number, renumber all the images
# to be sequentially numbered, in the same numeric order, and update
# the texi file to match.

# The net result is that if you have images $prefix-4.png and
# $prefix-5.png, for example, you can create $prefix-4.5.png and
# renumber to insert one into the sequence.

while (@ARGV[0] =~ /^-/) {
    $opt = shift;
    $noexec = 1 if $opt eq "-n";
}

$prefix = shift;
if (! $prefix) {
    print "Usage: $0 <prefix>\n";
    exit (1);
}

if (! -f "$prefix.texi") {
    print "No file $prefix.texi\n";
    exit (1);
}

opendir (D, ".");
while ($r = readdir D) {
    next unless $r =~ /^$prefix-([\d\.]+).(png|pcb)/;
    $found_ids{$1} = 1;
    $id{$r} = $1;
    $ext{$r} = $2;
    push (@found_files, $r);
}
closedir D;

$seq = 1;
for $id (sort { $a <=> $b } keys %found_ids) {
    $seq{$id} = $seq;
    $seq ++;
}

for $f (sort @found_files) {
    $id = $id{$f};
    $nid = $seq{$id};
    if ($id ne $nid) {
	$e = $ext{$f};
	&sys("mv $f $prefix-$id.$e.tmp");
    }
}

sub newimage {
    my ($tag, $file) = @_;
    #print "tag <$tag> file <$file>\n";
    if ($id{"$file.png"}) {
	$nid = $seq{$id{"$file.png"}};
	return "@" . $tag . "{$prefix-$nid}";
    } elsif ($id{"$file.pcb"}) {
	$nid = $seq{$id{"$file.pcb"}};
	return "@" . $tag . "{$prefix-$nid}";
    } else {
	return "@" . $tag . "{$file}";
    }
}

open (IN, "$prefix.texi");
open (OUT, "> $prefix.texi.tmp");

while(<IN>) {
    s/@(image|img){([^\{]+)}/&newimage($1,$2)/ge;
    print OUT;
}
close IN;
close OUT;

if (! $noexec) {
    rename "$prefix.texi", "$prefix.texi.bak";
    rename "$prefix.texi.tmp", "$prefix.texi";
}

for $f (sort @found_files) {
    $id = $id{$f};
    $nid = $seq{$id};
    $e = $ext{$f};
    if ($id ne $nid) {
	&sys("mv $prefix-$id.$e.tmp $prefix-$nid.$e");
    }
}

sub sys {
    my ($cmd) = @_;
    print "+ $cmd\n";
    if (! $noexec) {
	system $cmd;
    }
}
