#!/usr/bin/perl

# creates a copy of a stylesheet with namespace support
# the stylesheet is read from stdin, the output is sent to stdout
# arguments: -d create DocBook stylesheets using "d:"
#            -t create TEI stylesheets using "tei:"

# note: this script is not a one-size-fits-all universal stylesheet conversion
#       tool. It does just the minimum to successfully convert the stylesheets
#       shipped with RefDB. There is no guarantee whatsoever that it will work
#       with other stylesheets

foreach $arg (@ARGV) {
    if ($arg eq "-d") {
	$ns = "d:";
    }
    elsif ($arg eq "-t") {
	$ns = "tei:";
    }
}

while (<STDIN>) {
    if ($ns eq "d:") {
	if (/xsl:stylesheet/) {
	    # add the appropriate namespace to the stylesheet declaration
	    s!xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"!xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:d=\"http://docbook.org/ns/docbook\" xmlns:xl=\"http://www.w3.org/1999/xlink\"!;
	}
	elsif (/xsl:import/) {
	    # import the appropriate namespaced stylesheets
	    s!docbook.sourceforge.net/release/xsl!docbook.sourceforge.net/release/xsl-ns!;
	    s!docbk-refdblib!docbk-refdblib-ns!;
	}
	elsif (/ulink/) {
	    s!ulink!link!;
	}
	elsif (/name=\"target\" select=\".url\"/) {
	    s!name=\"target\" select=\".url\"!name=\"target\" select=\"\@href\"!;
	}
    }
    elsif ($ns eq "tei:") {
	if (/xsl:stylesheet/) {
	    # add the appropriate namespace to the stylesheet declaration
	    s!xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"!xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:tei=\"http://www.tei-c.org/ns/1.0\"!;
	}
	elsif (/xsl:import/) {
	    # import the appropriate namespaced stylesheets
	    s!tei/p4!tei/p5!;
	    s!tei-refdblib!tei-refdblib-ns!;
	}
    }

    if (/xsl:(template|for-each|apply-templates|value-of|variable|when).*(match|select|test)/) {
	# extract the match string proper for further manipulations
	my $matchstring = $_;
	chomp($matchstring);

	$matchstring =~ s!^(.*)(match|select|test)=\"([^\"]*)\".*$!$3!;
	$matchstring =~ s!(\w[\w-]+)!$ns$1!g;

	# insert the manipulated match string back into the original string
	$_ =~ s!^(.*)(match|select|test)=\"([^\"]*)\"(.*)$!$1$2=\"$matchstring\"$4!;
	# remove erroneously introduced namespaces from xsl reserved words
	s!$ns(or|not|id|substring|parent|ancestor|following-sibling|\d|string-length)!$1!g;
	s!(\$|\@|\'|\()$ns!$1!g;
	s!href!xl:href!g;
    }

    s!\@id!\@xml:id!g;

#    if (/(parent|ancestor|following-sibling)/) {
#	s!(parent||ancestor|following-sibling)::([^\*), ]+)!$1::$ns$2!g;
#    }

    print $_;
}

exit 0;
