#!/usr/bin/perl

use strict;
use warnings;

use Carp qw(confess);
use Data::Dumper;
#use Sys::RunAlone;

use List::Util qw(shuffle);
use Ernad::Learn;

use Proc::ProcessTable;

my $impna = $ARGV[0] = 'nep';

my $l=Ernad::Learn->new({'impna' => $impna,
                         'verbose' => 1});
my $e=$l->{'e'} or die "I need an erimp here";
my $r;

if(not $e->{'conf'}) {
  confess "I need this here.";
}

my @repcodes=$e->list_repcodes();

foreach my $repcode (@repcodes) {
  $r->{$repcode}=1;
}

my $being_trained;
my $count_trains=0;
my $t = new Proc::ProcessTable;
foreach my $p ( @{$t->table} ){
  my $cmd=$p->cmndline;
  if($cmd=~m|svm-train|) {
    $cmd=~m|(nep-...)|;
    my $report=$1;
    delete $r->{$report};
    if(not $being_trained->{$report}) {
      $count_trains++;
      print "report $report is being trained\n";
      $being_trained->{$report}=1;
    }
  }
}
if($count_trains > 3) {
  print "I reached the train limit\n";
  exit;
}

my $repcode;
my $repcode_to_do;
foreach $repcode (shuffle keys %{$r}) {
  my @files=glob("/home/ernad/ernad/var/nep/learn/mocla/$repcode/*.model");
  my $count=scalar @files;
  if($count > 0) {
    delete $r->{$repcode};
    next;
  }
  $repcode_to_do=$repcode;
}

if(not $repcode_to_do) {
  print "I have nothing to do.\n";
  exit;
}

## do the last one we have
$l->{'m'}->model_report($repcode_to_do);

my $count=scalar keys %{$r};

print "$count need doing\n";

exit;





__END__
