#!/usr/bin/perl -w

# (c) 2005 Emilia Oikarinen

# usage: prio_circ2dlp <file> <min_atoms:different:priorities:separated> [-v <varying> -f <fixed>] 

$file = $ARGV[0];
$output = "./prio_circ2dlp_output_file";
$tmp = "./prio_circ2dlp_tmp_file";

die "File $output exists" if (-e $output);
die "File $tmp exists" if (-e $tmp);

$read_vary = 0;
$read_fixed = 0;

# Parsing the input.
for ($i = 1; $i <= $#ARGV; $i++) {

    if ($ARGV[$i] eq "-v") {
        $read_vary = 1;
        $read_fixed = 0;
    }
    elsif($ARGV[$i] eq "-f") {
        $read_fixed = 1;
        $read_vary = 0;
    }
    elsif($read_vary == 1) {
        $varying_atoms .= $ARGV[$i]." ";
    }
    elsif($read_fixed == 1) {
        $fixed_atoms .= $ARGV[$i]." ";
    }
    else { 
        $min_atoms .= $ARGV[$i]." ";
    }
}

# Parsing the atoms to be minimized with different priorities.
@min_atoms = split(/:/, $min_atoms);

# Translation to DLP using Litschitz's scheme and translation circ2dlp,
# lpcat is used to concatenate programs.
for ($i = 0; $i <= $#min_atoms; $i++) {

    $v_atoms = "\"";
    $f_atoms = "\"";

    for ($j = $i+1; $j <= $#min_atoms; $j++) {
        $v_atoms .= $min_atoms[$j]." ";
    }
    $v_atoms .= $varying_atoms if ($varying_atoms);
 
    for ($j = 0; $j < $i; $j++) {
        $f_atoms .= $min_atoms[$j]." ";
    }
    $f_atoms .= $fixed_atoms if ($fixed_atoms); 

    $v_atoms .= "\"";
    $f_atoms .= "\"";

    if ($i == 0) {
        `./circ2dlp $file -v $v_atoms -f $f_atoms > $output`;

    }
    else {
        `mv $output $tmp`;
        `./circ2dlp $file -v $v_atoms -f $f_atoms | ./lpcat $tmp - > $output`;
    }
}

unlink($tmp) || die "Could not delete temporary file: $!" if (-e $tmp);

open(OUT, $output) || die "Could not open file: $!";
while(<OUT>) {
    print $_;
}

unlink($output) || die "Could not delete temporary file: $!" if (-e $output);
