#!/usr/bin/perl -w 
use strict;
use Data::Dumper;
my $ref_matrius = &llegir_matrius;


my @keys = keys %{$ref_matrius};
while (my $m = shift (@keys)){
open (MAT_RAND, ">matrius_random/$m") or die $!;
my $j=0;
while ($j<20){
my $random_mat = &randomizar_mats ( ${$ref_matrius}{$m} );
$j = $j+1;

print MAT_RAND "I\$".$m."_r$j\n";
foreach my $fila (1..(scalar @{$random_mat})){
print MAT_RAND "$fila ";
foreach my $freq (@{${$random_mat}[$fila-1]}){
print MAT_RAND "$freq ";
}
print MAT_RAND "\n";
}
print MAT_RAND "//\n";
}

close (MAT_RAND);
}


sub esta_en_la_fila
{
my ($arref, $a) = @_;
foreach my $i (@{$arref}){
return 1 if ($i eq $a);
}
return 0;
}
sub randomizar_mats
{
my $rmat = shift @_;
my $n = 0;
my $rmat_random;


while ($n < scalar@{$rmat}){
my @fila = (@{${$rmat}[$n]});
my $cont_pos=0;
my @usades =();
my @fila_random;
while ( $cont_pos<4)
my $pos = int (rand(4));
while (&esta_en_la_fila (\@usades, $pos)){
$pos = int (rand(4));
}
push @usades,$pos;

$fila_random[$pos]=$fila[$cont_pos];
$cont_pos = $cont_pos + 1;
}
push @{$rmat_random}, [ @fila_random ];
$n = $n +1;
}
return $rmat_random;
}


sub llegir_matrius
{
my %hash_mat;
while (my $matrius = <STDIN>){
chomp ($matrius);
my $liniaID;
my $i=0;
my @mat;


while (!($matrius =~ m/\/\//)){
if($matrius =~ m/(^I.*$)/){
$liniaID = $1;
} else {
my ($pos, @valores) = split (/\s+/, $matrius);
$mat[$i] = [@valores];
$i = $i + 1;
$hash_mat {$liniaID}=[@mat];
}
$matrius = <STDIN>; }
}
return \%hash_mat;
}