#! /usr/bin/env perl

use warnings;

while (<>) {
    chomp;
    $define_cmd = $_;
    
    $projection_cell = $define_cmd;
    $projection_cell =~ s/.*?-projection_cell (.+?) .*/$1/;
    $seq_id = $define_cmd;
    $seq_id =~ s/.*-seq_id (.+?).*/$1/;
    $filter = $define_cmd;
    $filter =~ s/.*-filter (.*?).*?/$1/;
    
    $state = get_run_state($seq_id,$projection_cell,$filter);

    if (defined($state)) {
	print "$projection_cell $seq_id $filter $state\n";
    }
    else {
	print "$projection_cell $seq_id $filter NoStateYet\n";
    }

    unless (defined($state)) {

	print "$define_cmd\n";
	system($define_cmd);

	$i = 0;
	do {
	    sleep(5);
	    $state = get_run_state($seq_id,$projection_cell,$filter);
	    print "\t$i $seq_id $projection_cell $filter $state\n";
	    $i++;
	    
	    unless(defined($state)) {
		die "state not found, definerun command failed! $seq_id $projection_cell $filter\n";
	    }

	} while ($state ne 'run');
	
    }
    
   

}

    
sub get_run_state {
    my ($seq_id, $projection_cell, $filter) = @_;
    my $response;
    chomp($response = `laptool -listrun -projection_cell $projection_cell -seq_id $seq_id -filter $filter -simple`);
    my $state = (split /\s+/, $response)[5];
    return($state);
}
    
