#!/usr/bin/perl

# fix_xml.pl

# Adds ids to all elements

# ONLY run this ONCE on each file

use utf8;
use strict;
binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");

my %ID;

#####################################
#
# Change the BOOKID to your book's ID
#
#####################################
my $BOOKID = "";


if ($BOOKID eq "") {
    print STDERR "Please set your book ID\n";
    exit();
}


my $CHAP = $ARGV[0];

if ($CHAP !~ /^[a-z]+\d+$/) {
    print STDERR "Please pass in a filetype and number (e.g. ch1)\n";
    exit();
}

my $line;
while ($line = <STDIN>) {
    chomp($line);
    $line =~ s/\r//g;

    $line =~ s`<manuscript [^>]+>``;
    $line =~ s`</manuscript>``;

    $line =~ s`<(chapter|image|section|box|p|list|table|figure|question)( [^>]+)?>`add_id($1, $2)`ge;

    if ($line ne "") {
	print $line, "\n";
    }
}

sub add_id {
    my $tag = shift;
    my $args = shift;

    if ($args =~ /id="[^"]+"/) {
	return "<${tag}${args}>";
    }

    if (!exists($ID{$tag})) {
	$ID{$tag} = 1;
    }
    else {
	$ID{$tag}++;
    }

    return "<${tag} id=\"${BOOKID}-${CHAP}-${tag}-$ID{$tag}\"${args}>";
}
