#! /usr/bin/perl -w
#
#*** Copyright 2002-2004 The Acute Team
#
#  Allen-Williams, Mair
#  Bishop, Steven
#  Fairbairn, Matthew
#  Habouzit, Pierre [*]
#  Leifer, James [*]
#  Sewell, Peter
#  Sjberg, Vilhelm
#  Steinruecken, Christian
#  Vafeiadis, Viktor
#  Wansbrough, Keith
#  Zappa Nardelli, Francesco [*]
#  Institut National de Recherche en Informatique et en Automatique (INRIA)
#
#  Contributions of authors marked [*] are copyright INRIA.
#
#All rights reserved.
#
#This file is distributed under the terms of the GNU Lesser General
#Public License, with the special exception on linking described in
#file NEW-LICENSE.
#
#***

use strict;
use Getopt::Std;

my %opts;
$opts{'e'} = 'tex';
$opts{'P'} = '.';
$opts{'p'} = 'scripts/dumptests_prefix.tex';
$opts{'s'} = 'scripts/dumptests_suffix.tex';
$opts{'r'} = 'scripts/dumptests_separator.tex';


getopts('hf:d:p:s:r:e:P:', \%opts);

if($opts{'h'}) {
    print <<EOF
usage : runtest [options] -d dir -f fam
    -d dir      output in directory dir
    -f fam      search for tests in family fam
    -p path     where 'runtest' is (default '.')

    -p file     choose a prefix file    (default: \$path/scripts/dumptests_prefix.tex)
    -s file     choose a separator file (default: \$path/scripts/dumptests_suffix.tex)
    -r file     choose a separator file (default: \$path/scripts/dumptests_separator.tex)
    -e str      choose the extension of dumped files (default: tex)

    -h          this help
EOF
    ;
    exit 0;
}

die "no family selected" if(!$opts{'f'});
die "no output directory selected" if(!$opts{'d'});

mkdir $opts{'d'};
my $path = `pwd`;
chop($path);
chdir $opts{'P'}.'/';

die "runtest not found at position [${path}runtest]" if(!-f "runtest");

sub get_file($$) {
    my ($type,$flag) = @_;
    open FILE,$opts{$flag} || die "cannot open $type file ${opts{$flag}}";
    my @res = <FILE>;
    close FILE;
    @res;
}

sub get_test($) {
    my $name = shift;
    open TEST,"./runtest -GG1 -G $name |";
    my @res = <TEST>;
    close TEST;
    @res;
}

my @prefix = get_file("prefix",'p');
my @suffix = get_file("suffix",'s');
my @separator = get_file("separator",'r');

sub dump_subtest($@) {
    my ($name,@test) = @_;

    open FILE2,">$path/${opts{'d'}}/$name.${opts{'e'}}";
    print FILE2 @prefix;
    print FILE2 @test;
    print FILE2 @suffix;
    close FILE2;
}

sub dump_test(@) {
    my ($name,$first,@list) = @_;
    open FILE,">$path/${opts{'d'}}/$name.${opts{'e'}}";

    my @test = get_test($first);
    dump_subtest($first,@test) unless($first eq $name);

    print FILE @prefix;
    print FILE @test;
    foreach my $t_name (@list) {
        @test = get_test($t_name);

        print FILE @separator;
        print FILE @test;
        dump_subtest($t_name,@test);
    }
    print FILE @suffix;
}

open TESTS, "./runtest -F ${opts{'f'}} |";
while(<TESTS>) {
    chop;
    my @t_list = split / /;
    dump_test(@t_list);
}
close TESTS;

exit 0;
