#!/usr/local/perl/bin/perl
#
# $Id: dmi.pl,v 1.2 2008/06/03 15:27:19 builds Exp $
#
# DMI executable for the four DMIs (with their types):
#
#     out			Output
#     in			Input
#     dates			Input
#     datesMulti    Input
#
# for all DMIs it prints the parameters.
#
# for the Output DMI it reads the exported data files in the 'out'
# directory, removes the 'keyword: value' lines, and writes the
# imported data files in the 'in' directory.
#

use strict;
use warnings;

use File::Path;
use File::Basename;

# print the parameters.
my $i = 0;
map { print '$ARGV[', $i++, '] = ', $_, "\n" } @ARGV;

# seven fixed parameters plus one user parameter.
die "$0: Unexpected number of parameters\n" unless @ARGV == 8;

$ARGV[7] =~ /-UDMI_Type=(.*)/;
my $type = $1;

if ($type eq 'Output') {
    # get the output and input directories.
    my $outdir = $ARGV[1];
    my $indir = dirname($outdir) . '/in';

    # get the output files (the .dat files in the output directory).
    opendir(DIR, $outdir) ||
        die "Cannot read output directory \"$outdir\": $!\n";
    my @files = grep { /\.dat$/ && $_ } readdir DIR;
    closedir DIR;

    # remove then create the input directory.
    rmtree($indir, 0, 1);
    mkpath($indir, 0, 0755);

    # for each output file...
    foreach (@files) {
        # get the output and input file paths.
        my $outfile = $outdir . '/' . $_;
        my $infile = $indir . '/' . $_;

        # open the output file for reading and the input file for
        # writing.
        open(OUT, '<' . $outfile) ||
            die "Cannot read output file \"$outfile\": $!\n";
        open(IN, '>' . $infile) ||
            die "Cannot open input file \"$infile\": $!\n";

        # strip the output file's 'keyword: value' lines when writing
        # the input file.
        map { print IN unless /^[a-z_]+:/ } <OUT>;

        close IN;
        close OUT;

        # remove the output file.
        unlink $outfile;
    }

    print 'Processed ', scalar(@files), ' data files', "\n";
}

print "(Done)\n";
exit 0;
