﻿#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use open qw(:std :utf8);
use integer;


# Filter_2_02_sync_pb.pl
# 2010-04-18
# Wolfgang Schmidle

# what does it do? 
# input
# output

# note: the script assumes the images to be in JPG format


# text input

my @text;
while(<>) { push @text, $_; }


# go through the text

my @pageimg = ();

my $found = 0;

LINE: foreach (@text) {

	last LINE if m!<pb[ >]!;
	
	if (m!pageimg:!) {
		$found = 1;
		$_ = "";
		next;
	}
	if ($found) {
		if (m!^ *\n!) {
			$_ = "";
			last LINE;		
		}
		if (m!([^ \t]+)\.jpg!) {
			push @pageimg, $1;
			$_ = "";
			next LINE;
		}
		die "unrecognised image file name:\n$_\n";
	}

}

foreach (@pageimg) { s!\.jpg!!; }

my $i = 0;
my $pb = 0;
my $pbAlsText = "";
my $jpg = "";

foreach (@text) {

	$i++;
	if (m!<pb.+<pb!) { die "Line $i: more than one <pb> in one line:\n$_\n"; }
	next unless m!<pb!;
	
	if ($#pageimg == -1) {
		$pb++;
		$pbAlsText = "$pb";
		if ($pb < 1000) { $pbAlsText = "0$pbAlsText"; }
		if ($pb < 100) { $pbAlsText = "0$pbAlsText"; }
		if ($pb < 10) { $pbAlsText = "0$pbAlsText"; }		
		s!(<pb[^>]*>)!$1\[$pbAlsText\]!;
	} else {
		$jpg = $pageimg[$pb] || "\?\?\?\?";
		s!(<pb[^>]*>)!$1\[$jpg\]!;
		$pb++;
	}
}


# text output

print @text;

while (exists $pageimg[$pb]) {
	
	print "$pageimg[$pb]\n";
	$pb++;
}
