#!/usr/bin/env perl

use strict;
use File::Spec;
use File::Path;
use Term::ReadLine;
use Config;

use FindBin;
use lib "$FindBin::Bin";
use File::Which;

sub findexecutable {
  my ($execname) = @_;
  my $retval = undef;
  my ($progvol, $progdirs, $progfile) = File::Spec->splitpath($0);
  my @progdirs = File::Spec->splitdir($progdirs);
  my $exeext = '';
  foreach my $appenddir (undef, File::Spec->catdir("..", "utils")) {
    if (defined($appenddir)) {
      $retval = File::Spec->catpath($progvol, File::Spec->catdir(@progdirs, $appenddir), "$execname");
    } else {
      $retval = File::Spec->catpath($progvol, $progdirs, "$execname");
    }
    if ($Config{'osname'} eq 'MSWin32') {
      return $retval if (-e $retval && -d $retval);
    } else {
      return $retval if (-x $retval);
    }
    if ($Config{'osname'} eq 'MSWin32') {
      if (defined($appenddir)) {
	$retval = File::Spec->catpath($progvol, File::Spec->catdir(@progdirs, $appenddir), "${execname}.exe");
      } else {
	$retval = File::Spec->catpath($progvol, $progdirs, "${execname}.exe");
      }
      return $retval if (-e $retval && -d $retval);
    }
  }
  return which($execname); # from File::Which
}

my @oldARGV = @ARGV;
@ARGV = ();
foreach my $arg (@oldARGV) {
  push @ARGV, $arg;
}

if (scalar(@ARGV) < 3) {
  print STDERR <<EOM;
Usage: fmriqa_biac <expName> <dataSubDir> <study>
Example: fmriqa_biac Study.01 Func 20010101_12345

  fmriqa_biac reads BXH files in the given study and creates an HTML
  page that displays QA data.
  In the example, it will look for the following BXH files:
    Study.01/Data/Func/20010101_12345/run*/run???_??.bxh
  and the output will go in the following experiment directory:
    Study.01/Data/Func/20010101_12345/QA
EOM
  exit -1;
}

my @expdbs = (
  "$ENV{HOME}/net/huxley/data/experiments.txt",
  "$ENV{HOME}/net/huxley/data/inactive.txt",
);
my %explist = ();
for my $expdb (@expdbs) {
  open(FH, "$expdb") || die "Error opening experiment database!";
  while (<FH>) {
    my ($exppath, $expname, @others) = split(/\s+/, $_);
    next if (!defined($expname) || @others);
    if ($Config{'osname'} ne 'MSWin32') {
      if ($exppath =~ m%^\\\\([^\\]*)\\([^\\]*)%) {
        my $server = "$ENV{HOME}/net/" . lc($1);
        my $share = lc($2);
        $exppath =~ s%^\\\\([^\\]*)\\([^\\]*)%$server/$share%;
      }
      $exppath =~ s%\\%/%g;
    }
    $explist{$expname} = $exppath;
  }
  close FH;
}

my $expname = shift;
my $datasubdir = shift;
my $study = shift;

my $exppath = $explist{$expname};
{
  my ($expvol, $expdirs, undef) = File::Spec->splitpath($exppath, 1);
  $exppath = File::Spec->catpath($expvol, File::Spec->catdir($expdirs, $expname), '');
}
die "Experiment directory $exppath doesn't exist?" if (! -d $exppath);
my ($expvol, $expdirs, undef) = File::Spec->splitpath($exppath, 1);
my $searchdirs = File::Spec->catdir($expdirs, "Data", $datasubdir, $study);
my $searchpath = File::Spec->catpath($expvol, $searchdirs, '');
opendir(DIRH, $searchpath) || die "Error opening directory $searchpath";
my @runpaths = map { File::Spec->catpath($expvol, File::Spec->catdir($searchpath, $_), '') } grep { /^run/ && -d File::Spec->catdir($searchpath, $_)} readdir(DIRH);
closedir(DIRH);
my @bxhpaths = ();
for my $runpath (@runpaths) {
  my ($runvol, $rundirs, undef) = File::Spec->splitpath($runpath, 1);
  opendir(DIRH, $runpath) || die "Error opening directory $runpath";
  push @bxhpaths,
    map { File::Spec->catpath($runvol, $rundirs, $_) }
      grep { /run..._..\.bxh$/ } readdir(DIRH);
}

if (scalar(@bxhpaths) == 0) {
  print STDERR "Didn't find any BXH files in the given directories!\n";
  exit -1;
}

my $outputpath = File::Spec->catpath($expvol, File::Spec->catdir($expdirs, "Data", $datasubdir, $study, "QA"), '');
if (-d $outputpath) {
  print STDERR "";
  print STDERR "Output directory $outputpath already exists!  Do you want to overwrite?\n";
  my $term = new Term::ReadLine 'fmriqa_biac';
  my $ans = $term->readline("(y/n)");
  if (!defined($ans) || $ans !~ /^(y|Y)/) {
    print STDERR "Exiting.\n";
    exit -1;
  }
} else {
  mkpath($outputpath);
}

my $progfmrigen = findexecutable("fmriqa_generate.pl");
if (!defined($progfmrigen)) {
  print STDERR "Can't find executable fmriqa_generate.pl!\n";
  exit -1;
}
my @cmd = ($progfmrigen, "--overwrite", "--verbose", @bxhpaths, $outputpath);
system(@cmd);
