function [rotated_stack] = RotateStackByTransformMatrix(input_transform,filename,read_suffix,write_suffix,on_head,show_result,write_result,optreg,is_moving_dataset)

% For this function to work properly, input conjugate should contain
% whatever is necessary to bring the embryo to the center position.  To
% just put an already aligned image on head, use input_transform
% = eye(4) (with on-head flag = true);

% Call from a loop to do more than one stack.

if is_moving_dataset
    strain_name =optreg.moving_strain_name;
else
    strain_name = optreg.target_strain_name;
end


if exist('optreg','var')
    z_multiplier = optreg.z_multiplier;
    center_position = optreg.center_position;
    new_frame = optreg.new_frame;
    num_slices = optreg.num_slices;
else
    z_multiplier = 3.077;
    center_position = [250.5 250.5 144];
    new_frame = [500 500 287];
    num_slices = 93;
end

if is_moving_dataset
    dataset_directory = optreg.moving_dataset_directory;
    run_number = optreg.moving_run_number;
else
    dataset_directory = optreg.target_dataset_directory;
    run_number = optreg.target_run_number;
end

if on_head
    write_suffix = [write_suffix ' on head'];
    on_head_matrix = [0 0 1 0; 0 1 0 0; -1 0 0 0; 0 0 0 1];
    first_translation = [-center_position 1].';
    first_translation = [[eye(3);[0 0 0]] first_translation];
    second_translation = [center_position 1].';
    second_translation = [[eye(3);[0 0 0]] second_translation];
    full_transform_conjugate = input_transform.'*first_translation.'*on_head_matrix*second_translation.';
else
    full_transform_conjugate = input_transform.';
end

cd(dataset_directory)

input_filename = [filename read_suffix];
input_stack = TiffStackImport(input_filename);

if size(input_stack,3) == num_slices;
stretch_matrix = [1 0 0; 0 1 0; 0 0 z_multiplier];
stretch_matrix = [stretch_matrix [0; 0; 0];[0 0 0 1]];
rotated_stack = imwarp(input_stack,affine3d(stretch_matrix*full_transform_conjugate),'OutputView',imref3d(new_frame));
else
rotated_stack = imwarp(input_stack,affine3d(full_transform_conjugate),'OutputView',imref3d(new_frame));
end

if show_result
figure; imshow3d(rotated_stack)
end

if write_result
cd(['Run ' num2str(run_number)])
mkdir('AlignedImages')
cd AlignedImages
TiffStackWrite(rotated_stack,[filename write_suffix],16);
cd ..
end

end