#! /usr/bin/env perl
#
# generate a nonlinear xfm
#
# Andrew Janke - a.janke@gmail.com
#
# Copyright Andrew Janke, The Australian National University.
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies.  The
# author and the University make no representations about the
# suitability of this software for any purpose.  It is provided "as is"
# without express or implied warranty.

#use strict;
use warnings "all";
use Getopt::Tabular;
use File::Basename;
use File::Temp qw/ tempdir /;

# until I get organised and do this properly
my $PACKAGE = &basename($0);
my $VERSION = '1.0.0';
my $PACKAGE_BUGREPORT = '"Andrew Janke" <a.janke@gmail.com>';

my($Help, $Usage, $me);
my(@opt_table, %opt, $outfile, @args);

$me = &basename($0);
%opt = (
   'verbose' => 0,
   'clobber' => 0,
   'fake' => 0,
   'ident' => 0,
   'like' => undef,
   'step' => 1,
   );

$Help = <<HELP;
| $me makes various nonlinear xfms
| 
| Although currently only identity xfms are supported!
|
| Problems or comments should be sent to: a.janke\@gmail.com
HELP

$Usage = "Usage: $me [options] <out.xfm>\n".
         "       $me -help to list options\n\n";

@opt_table = (
   ["General Options", "section" ],
   ["-version", "call", 0, \&print_version_info,
      "print version and exit" ],
   ["-verbose", "boolean", 0, \$opt{verbose},
      "be verbose" ],
   ["-clobber", "boolean", 0, \$opt{clobber},
      "clobber existing check files" ],
   ["-fake", "boolean", 0, \$opt{fake},
      "do a dry run, (echo cmds only)" ],
      
   ["nlxfm Options", "section" ],
   ["-ident", "boolean", 0, \$opt{'ident'},
      "Generate an identity xfm" ],
   ["-step", "integer",  1, \$opt{'step'}, 
      "output ident xfm step" ],
   ["-like", "string",  1, \$opt{'like'}, 
      "Generate a nlxfm like this file" ],
   );
   
# get history string
chomp($history = `date`);
$history .= '>>>> ' . join(' ', $me, @ARGV);

# Check and get arguments
&Getopt::Tabular::SetHelp($Help, $Usage);
&GetOptions (\@opt_table, \@ARGV) || exit 1;
die $Usage if $#ARGV != 0;
$out_xfm = shift @ARGV;

# make tmpdir
$tmpdir = &tempdir( "$me-XXXXXXXX", TMPDIR => 1, CLEANUP => 1 );

# check for the output xfm
if(-e $out_xfm && !$opt{'clobber'}){ 
   die "$me: $out_xfm exists! use -clobber to overwrite\n\n"; 
   }


# write the output xfm
$outgrid = $out_xfm;
$outgrid =~ s/\.(nlxfm|xfm)$/\_grid\_0\.mnc/;
chomp($outgrid_base = `basename $outgrid`);

open(XFM, ">$out_xfm");
print XFM "MNI Transform File\n" .
          "%\n" .
          "% Created by $me\n" .
          "%\n" .
          "% $history \n" .
          "\n";

# add in linear identity matrix
print XFM "Transform_Type = Linear;\n" .
          "Linear_Transform =\n" .
          " 1 0 0 0\n" .
          " 0 1 0 0\n" .
          " 0 0 1 0;\n" if $opt{'ident'};

print XFM "Transform_Type = Grid_Transform;\n".
          "Displacement_Volume = $outgrid_base;\n";
close(XFM);

# create the output grid_transform
chomp($resampl = `volextents -step $opt{'step'} $opt{'like'}`);
&do_cmd('mincresample', '-clobber',
        split(/\ /, $resampl),
        $opt{'like'}, "$tmpdir/scalar-like.mnc");
&do_cmd('minclookup', '-clobber',
        '-lut_string', '0 0 0 0;1 0 0 0',
        "$tmpdir/scalar-like.mnc", $outgrid);



sub do_cmd { 
   print STDOUT "@_\n" if $opt{verbose};
   if(!$opt{fake}){
      system(@_) == 0 or die;
      }
   }


sub print_version_info {
   print STDOUT "\n$PACKAGE version $VERSION\n".
                "Comments to $PACKAGE_BUGREPORT\n\n";
   exit 0;
   }
