#!/usr/bin/perl -I../lib -w
use strict;
use Gift;
use Data::Dumper;


sub forall_correct_files {
  my ($type, $action) = @_;
  my $result;
  
  for my $file (glob("*_cor.$type")) {
    $file =~ m{(.*)\.$type$}; 
    my $file_ok = "$1.ok";
    eval {
      $result = $action->($file);
    };
    die "Unexpected error in $file: $@\n" if $@;
    open FILE, "> $file_ok";
    print FILE $result;
    close(FILE);
  }
}

sub dump_gift_object {
  my $file = shift;

  Dumper(Gift->GiftFromFile($file));
}

sub compute_gift_object {
  my $file = shift;

  Gift->GiftFromFile($file);
}

my $warnings = "";

sub warning_handler {
  $warnings .= $_[0];
}

# Capture stderr and dump its contents to a file
sub forall_error_files {
  my ($type, $action) = @_;
  
  for my $file (glob("*_err.$type")) {
    $file =~ m{(.*)\.$type$}; 
    my $file_ok = "$1.ok";
    eval {
      $warnings = ""; # reset warnings
      $SIG{__WARN__} = \&warning_handler;
      $action->($file);
      $warnings .= $@ if defined $@;
      delete($SIG{__WARN__});
    };
    warn "test on $file did not died\n" unless $@;
    open FILE, "> $file_ok";
    print FILE $warnings;
    close(FILE);
  }
}

#&forall_correct_files('gift', \&dump_gift_object);
&forall_error_files('gift', \&compute_gift_object);
