#!/usr/bin/perl -w

use 5.034;

# Generador de programas DEA a resolver con lp_solve
#     Q: I did not read dea.c, I have no idea on using...
#     A: dea <your_data_file>
#          where the data file contents is
#
#                Ninputs Moutputs
#                col1in .. colNin col1out .. colMout
#                 ..     ..    ..    ..    ..    ..
#                etc    etc   etc   etc   etc   etc
#
#    Q: Ok, DEA... but what kind of DEA?
#    A: The simple one! (CCR) I don't agree using parametric DEA, since DEA is
#       a great model for non-parametric estimation on efficiency, forgiving
#       human assumptions on DMU operations.
#       Ps: DEA = Data Envelopment Analysis, DMU = Decision Making Units
#
#    Take x inputs, y outputs on n delegations, generate the set of programs
#                               Max  SUM wy'  for each delegation'(1..n)
#                               s.t. SUM vx - SUM wy >= 0  any n
#                                    SUM vx' = 1
#                                    all v,w >= 0
#     Q: Having perl, how to install?
#     A: chmod 755 dea AND run with ./dea file.txt 

if (scalar(@ARGV) < 1 ) {
    say "Usage: dea.pl inputfile";
    exit -2 ;
}

my ($ok, $numein, $numeout, $siz, $n, @line, @m, $nume, $number);

open (FIN, "<", $ARGV[0]) or die "Cannot open $ARGV[0]: $!";
$ok=0;
while (<FIN>){
    next if (/^#/);
    chomp;
    if ($ok==0){
	($numein, $numeout) = split /\s+/,$_; 
	$nume=$numein+$numeout;
	say "$numein $numeout";
	$ok=1;
    }else{
	$siz++;
	@line = split /\s+/,$_;
	print "@line\n";
	$n=0;
	for my $i (@line){
	    $n++;
	    $m[$siz][$n]=$i;
	}
	if ($n!=$nume) { die "Data does not match with header in line $siz+1"; }
    }	
}
close FIN;
    
open FSH, ">" , "lp.bat" or die "Cannot open lp.bat";
# unlink "results";
for my $n (1..$siz){
    $number=1000+$n;
    print FSH "lp_solve < $number >> results\n";
    open (FOUT, ">", "$number") or die "Cannot open $number";
    for my $y (1..$numein) { $m[$siz+1][$y]=$m[$n][$y]; }
    for my $y ($numein+1..$nume) { $m[0][$y]=$m[$n][$y]; }
       
    print FOUT "max: ";
    for (my $y=$numein+1; $y<=$nume; $y++){
	if ($m[0][$y]!=0) { print FOUT " +$m[0][$y] Y$y";} 
    }
    say FOUT ";";
	
    for my $x (1..$siz){
	for my $y (1..$numein){
	    if ($m[$x][$y]!=0){ print FOUT " +$m[$x][$y] X$y";}
	}
	for my $y ($numein+1..$nume){
	   if ($m[$x][$y]!=0){ print FOUT " -$m[$x][$y] Y$y";}
	}
	say FOUT " >= 0;";
    }
    for my $y (1..$numein){
	if ($m[$siz+1][$y]!=0) { print FOUT " +$m[$siz+1][$y] X$y"; }
    }
    say FOUT " = 1;";
    close FOUT;
}
# print FSH "find objective @results > RESULT\n";
close FSH;
system "sh lp.bat";
system "grep objective results > RESULT";

exit 2;

__END__
