#!/usr/bin/perl -w
#
#  $Id: convert_xsd_comments,v 1.1 2005/07/08 14:51:37 dgregor Exp $
#
# Convert comments in XML schema files into <documentation> elements within
# the element that follows the comment.
#

while (<>) {
    chomp();

    # Opening comment
    if (s/^\s*<!---*\s*//) {
	if (defined($comment)) {
	    die("we were about to throw away the following comment at line $.:",
		$comment);
	}
	
	$in_comment = 1;
	$comment = $_;

	# Check for closing comment on the same line.
	if ($comment =~ s/\s*-*-->\s*$//) {
	    $in_comment = 0;
	}

	next;
    }

    # Closing of a multi-line comment
    if (s/\s*-*-->\s*$//) {
	$in_comment = 0;
	if ($_ ne "") {
	    $comment .= "\n$_";
	}
	next;
    }

    # We're in the body of a multi-line comment
    if ($in_comment) {
	s/^\s*//;
	$comment .= "\n$_";
	next;
    }

    if (m/<(element|attribute|complexType|sequence|simpleType|restriction|pattern)[ \t\/>]/ && defined($comment)) {
	$tag = $1;
	if (s/\/>/>/) {
	    print "$_\n";
	    print annotation($comment);
	    print "</$tag>\n";
	} else {
	    print "$_\n";
	    print annotation($comment);
	}

	undef($comment);
	next;
    }

    print "$_\n";
}

sub annotation {
    my $comment = shift(@_);

    return "      <annotation><documentation>" . format_annotation($comment) .
	"</documentation></annotation>\n";
}

sub format_annotation {
    my $annotation = shift(@_);

    $annotation =~ s/&/&amp;/g;
    $annotation =~ s/</&lt;/g;
    $annotation =~ s/>/&gt;/g;
    $annotation =~ s/[\r\n]+/<ns2:br\/>/g;

    return $annotation;
}
