function [ registration_struct ] = read_freesurfer_registration( registration_fqn )
%READ_FREESURFER_REGISTRATION read registration matrix into matlab
%   Detailed explanation goes here
% FREESURFER REGISTRATION CONVENTIONS
% 
% For the purposes of FreeSurfer, the registration matrix maps the XYZ
% of the anatomical reference (ie, the subjects brain as found in 
% $SUBJECTS_DIR) to the XYZ of the functional volume. The anatomical
% reference is the 'target' volume (argument of --targ) and the 
% functional volume is the 'movable' volume (argument of --mov).
% The XYZ of a given col, row, and slice is defined
% based on the field-of-view by the following matrix:
% 
%           (-dc 0   0  dc*Nc/2)
%      T =  ( 0  0  ds -ds*Ns/2) 
%           ( 0 -dr  0  dr*Nr/2)
%           ( 0  0   0     1   )
% 
% where dc, dr, and ds are the voxel resolutions in the column, row,
% and slice directions, respectively, and  Nc, Nr, and Ns are the
% number of columns, rows, and slices.  Under this convention, 
% 
%   XYZ = T*[r c s 1]
% 
% The FreeSurfer registration matrix is then defined by:
% 
%    XYZmov = R*XYZtarg
% 
% FREESURFER REGISTRATION FILE FORMAT
% 
% The FreeSurfer registration is stored in an ASCII file with the 
% following format:
% 
%       subjectname
%       in-plane-res-mm
%       between-plane-res-mm
%       intensity
%       m11 m12 m13 m14
%       m21 m22 m23 m24
%       m31 m32 m33 m34
%       0   0   0   1
% 
% The subject name is that as found in the SUBJECTS_DIR. The in-plane-res-mm
% is the in-plane pixels size in mm. The between-plane-res-mm is
% the distance between slices in mm. Intensity only affect the display
% of the movable in the GUI.


% example of freesurfer registration matrix
% subject-unknown
% 0.500000
% 0.500000
% 0.150000
% 9.999794e-01 3.618304e-03 5.413820e-03 -3.438210e-01 
% -3.503619e-03 9.997724e-01 -2.104418e-02 8.644047e+00 
% -5.488733e-03 2.102475e-02 9.997640e-01 8.490714e+00 
% 0 0 0 1
% round

debug = 1;

if (debug)
	registration_fqn = fullfile(pwd, '..', '..', 'mri', 'rotate_unconf_2_120227Rocco_raw_rawavg.dat');
end

% check existence
if isempty(dir(registration_fqn))
	disp(['Could not open ', registration_fqn, ' file does not exist']);
	return;
end

% open the file
reg_fd = fopen(registration_fqn,'r');
if reg_fd == -1
	disp(['Could not open ', registration_fqn, ' file might not be readable, please check the permissions']);
	return
end


% read in the contents
registration_struct.subjectname = fgetl(reg_fd);
registration_struct.in_plane_res_mm = str2num(fgetl(reg_fd));
registration_struct.between_plane_res_mm = str2num(fgetl(reg_fd));
registration_struct.intensity = str2num(fgetl(reg_fd));

% read the actual affine matrix:
reg_mat = zeros([4 4]);
for i_row = 1 : 4
	reg_mat(i_row, :) = str2num(fgetl(reg_fd));
end
registration_struct.reg_mat = reg_mat;

registration_struct.round = fgetl(reg_fd);

% clean up
fclose(reg_fd);


% TODO? check inputs for sanity???


return
end

