#!/bin/sh

###
### WARNING: DO NOT RUN THIS SCRIPT ON DOCUMENTS ALREADY PUBLISHED!
###
### This script shall be run right before the publication of a new chapter.
###


fn=$1
if test ! -f "$fn"
then
	echo file not found
	exit 1
fi

awk '
BEGIN {
	next_id=0
}

function gen_next_id()
{
	return "{" doc ":" next_id++ "}"
}

{
	rest = $0
	out = ""
	while(match(rest, "[{][a-z]*[0-9]*:[^}]*[}]")) {
		if (doc == "") {
			doc = substr(rest, RSTART+1, RLENGTH-2)
			sub(":.*", "", doc)
		}
		out = out substr(rest, 1, RSTART-1) gen_next_id()
		rest = substr(rest, RSTART+RLENGTH, length(rest))
	}
	print out rest
}
' < $fn > $fn.tmp

mv $fn.tmp $fn
