#!/bin/perl

$nom = shift;
$nb_train = shift;
open(F,$nom);
@fich = <F>;
close(F);
$lin = $fich[0];
chomp($lin);
@mots = split(' ',$lin);
$nb_ex = $mots[0];
$nb_att = $mots[1];
for ($j=0; $j < $nb_att - 1; $j++) {
  $MAX[$j] = -1e30;
  $MIN[$j] = 1e30;
}
print " Nb ex $nb_ex, att $nb_att \n";
$k = 0;
for ($i=1; $i <= $#fich; $i++) {
  $lin = $fich[$i];
  chomp($lin);
  @mots = split(",",$lin);
#  print " Ex $i, taille $#mots classe $mots[$#mots] \n";;
  for ($j = 0; $j < $nb_att; $j++) {
    $tout[$k++] = $mots[$j];
    if ($mots[$j] < $MIN[$j]) { $MIN[$j] = $mots[$j];}
    if ($mots[$j] > $MAX[$j]) { $MAX[$j] = $mots[$j];}
  }
}
for ($j = 0; $j < $nb_att; $j++) {
  print " $j --> $MIN[$j], $MAX[$j] ";
  if ($MAX[$j] > $MIN[$j]) {
    $RATIO[$j] = 1. / ($MAX[$j] - $MIN[$j]);}
  else { $RATIO[$j] = 0.;}
  print " \t\t $RATIO[$j] \n";
}

print " ex $nb_train att $nb_att\n";
$k = 0;
open (F, ">out.learn");
print F "$nb_train $nb_att \n";
for ($i = 0; $i < $nb_train; $i++) {
  for ($j = 0; $j < $nb_att - 1; $j++) {
#    print " ICI ex $i, att $j \n";
    $v = ($tout[$k] - $MIN[$j]) * $RATIO[$j];
    print F " $v";
    $k++;
  }
  print F " $tout[$k++] \n";
}
close(F);
open (F, ">out.test");
$nb_test = $nb_ex - $nb_train;
print F "$nb_test $nb_att \n";
for (; $i < $nb_ex; $i++) {
  for ($j = 0; $j < $nb_att - 1; $j++) {
#    print " ICI ex $i, att $j \n";
    $v = ($tout[$k] - $MIN[$j]) * $RATIO[$j];
    print F " $v";
    $k++;
  }
  print F " $tout[$k++] \n";
}
close(F);


