#!/usr/bin/perl

use strict;
use IO::File;

my $usage = "Usage: $0 types schema [top_element_name]\n";

my $type_fn = shift || die $usage;
my $topdl_fn = shift || die $usage;
my $ename = shift || 'experiment';

my $id_type = "<!-- imported from $type_fn -->\n";
my $first;
my $v;

my $f = new IO::File($type_fn) || die "Can't open $type_fn: $!\n";


while (<$f>) {
    (/<xsd:complexType name="IDType">/ .. m#</xsd:complexType>#) && do {
	$id_type .= $_;
    };
}
$id_type .= "<!-- end import -->\n\n";
$f->close();
$f = new IO::File($topdl_fn) || die "Can't open $topdl_fn: $!\n";

while (<$f>) {
    ($v = /<xsd:schema/ .. />/) && do { 
	chomp;
	if ($v == 1 ) {
	    print "<!-- old schema declaration $_ ";
	}
	elsif ($v =~ /E0/) {
	    print "$_ -->\n";
	    print "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/" .
		"XMLSchema\">\n";
	}
	else { print "$_ "; }
	next;
    };
	
    m#xmlns:fns="http://www.isi.edu/fedd_types"# && next;
    !$first && /<xsd:complexType/ && do {
	print $id_type;
	$first++;
    };
    m#</xsd:schema># && do { 
	print "<xsd:element name=\"$ename\" type=\"topologyType\"/>\n";
    };
    s/[tf]ns://g;
    print;
}
$f->close();
