args = parser.parse_args()

tmp_dir = imagej2_base_utils.get_temp_dir()
source_image_path = imagej2_base_utils.get_input_image_path( tmp_dir, args.source_image, args.source_image_format )
target_image_path = imagej2_base_utils.get_input_image_path( tmp_dir, args.target_image, args.target_image_format )
source_elastic_transformation_path = imagej2_base_utils.get_input_image_path( tmp_dir, args.source_elastic_transformation, 'txt' )
target_raw_transformation_path = imagej2_base_utils.get_input_image_path( tmp_dir, args.target_raw_transformation, 'txt' )

# Define command response buffers.
tmp_out = tempfile.NamedTemporaryFile().name
tmp_stdout = open( tmp_out, 'wb' )
tmp_err = tempfile.NamedTemporaryFile().name
tmp_stderr = open( tmp_err, 'wb' )

# Build the command line to compose the raw and elastic transformations.
cmd = imagej2_base_utils.get_base_cmd_bunwarpj( None )
if cmd is None:
    imagej2_base_utils.stop_err( "bUnwarpJ not found!" )
cmd += ' -compose_raw_elastic'
# Target is sent before source.
cmd += ' %s' % target_image_path
cmd += ' %s' % source_image_path
cmd += ' %s' % target_raw_transformation_path
cmd += ' %s' % source_elastic_transformation_path
cmd += ' %s' % args.output

# Compose the raw and elastic transformations into another raw transformation using bUnwarpJ.
proc = subprocess.Popen( args=cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True )
rc = proc.wait()
if rc != 0:
    error_message = imagej2_base_utils.get_stderr_exception( tmp_err, tmp_stderr, tmp_out, tmp_stdout )
    source_file_name = imagej2_base_utils.get_file_name_without_extension( tmp_source_out_tiff_path )
    tmp_source_out_transf_path = os.path.join( tmp_dir, '%s_transf.txt' % source_file_name )
    target_file_name = imagej2_base_utils.get_file_name_without_extension( tmp_target_out_tiff_path )
    tmp_target_out_transf_path = os.path.join( tmp_dir, '%s_transf.txt' % target_file_name )

# Set the size of the memory allocation pool used by the JVM.
memory_size = imagej2_base_utils.get_max_heap_size_value( args.max_heap_size_type, args.max_heap_size )

# Define command response buffers.
tmp_out = tempfile.NamedTemporaryFile().name
tmp_stdout = open( tmp_out, 'wb' )
tmp_err = tempfile.NamedTemporaryFile().name
tmp_stderr = open( tmp_err, 'wb' )

# Build the command line to align the two images.
cmd = imagej2_base_utils.get_base_cmd_bunwarpj( memory_size )
if cmd is None:
    imagej2_base_utils.stop_err( "bUnwarpJ not found!" )
cmd += ' -align'
# Target is sent before source.
cmd += ' %s' % target_image_path
if args.target_mask is None:
    target_mask_str = ' NULL'
else:
    target_mask_str = ' %s' % tmp_target_mask_path
cmd += target_mask_str
cmd += ' %s' % source_image_path
if args.source_mask is None:
    source_mask_str = ' NULL'
else:
    source_mask_str = ' %s' % tmp_source_mask_path