#!/usr/local/bin/perl

# Pulls the tests out of a python test file.
# Usage: make_tests test_xxx.py

die "Must specify a file name" if $ARGV[0] eq '';

if (-f 'ExtractTests.pm') {
    eval "use ExtractTests";
    die $@ if $@;
}

$ARGV[0] =~ /test_(.*)\.py/;
$outfile_base = "$1";
$counter = "00";
$suffix = ".dom";
$string = "";
while (<>) {
    next if 1 .. /generateTests/;
    next if /^\#/ && ! $in_string;
    if ($in_string) {
	if (/^\"\"\"(?: \% (.*?)\s*|\]?,\s*(?:\#.*)?)$/) {
	    my $vars = $VARS{"$counter$suffix"} || $1;
	    $vars =~ s/\]?,$//;
	    $vars =~ s/\b(\w+)\b/defined $DEFS{$1} ? "q($DEFS{$1})" : $1/ge;
	    my @args = eval($vars);
#	    string =~ s/\\\n//g;
	    printf FILE $string,@args;
	    close FILE;
	    $in_string = 0;
	    $string = "";
	    next;
	}
	s/\\n\\$//;# if $suffix eq ".rst";
	s/\\([\\\'\"])/$1/g unless $string_type =~ /r/;
	s/\"\"\"\s*\+\s*\"\"\"//g;
	$string .= $_;
    }
    elsif (/^\[?\(?([ru])?\"\"\"(.*)?$/) {
	$in_string = 1;
	$string_type = $1;
	$suffix = $suffix eq ".dom" ? ".rst" : ".dom";
	$counter++ if $suffix eq ".rst";
	$file = "$outfile_base$counter$suffix";
	open(FILE, ">$file") or die "Cannot write to $file";
	$string = "$2\n";
	$string =~ s/\\\n//g;
	next;
    }
}
