% [ RAS, COLORS ] = otl2ras(Xc, Hc)
%
% Convert points from an otl file into absolute RAS coordinates.
%
% Xc {1xNFILES} - a cell array of data matrices, as returned by otlread
% Hc {1xNFILES} - a cell array of otl headers, as returned by otlread
%
% RAS {1xNFILES} - cell array of all of the otl points, in RAS coordinates,
%   each element of RAS is a [3xNPTS] matrix.
% COLORS {1xNFILES} - cell array listing colors of each otl point,
%   each element of COLORS is a [1xNPTS] character vector.
%
function [RAS, COLORS] = otl2ras(Xc, Hc)

% If Xc is a single data matrix, convert it to a cell array
if ~iscell(Xc),  Xc = { Xc }; end
% If Hc is a single structure, convert it to a cell array
if ~iscell(Hc), Hc = { Hc }; end

% Initialize RAS and COLORS
RAS = cell(1,length(Hc));
COLORS = cell(1,length(Hc));

for ifile=1:length(Hc),
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % First, print a warning if one of the file headers is incomplete
  if ~isfield(Hc{ifile},'channel_count') | ...
	~isfield(Hc{ifile},'top_left_hand_corner') | ~isfield(Hc{ifile},'top_right_hand_corner') | ...
	~isfield(Hc{ifile},'bottom_right_hand_corner') | ~isfield(Hc{ifile},'offset') | ...
	~isfield(Hc{ifile},'npixels'),
    if isfield(Hc{ifile}, 'image_id'),
      disp(sprintf('Header of %s does not include all of the necessary fields', Hc{ifile}.image_id));
    else
      disp(sprintf('Header %d does not include all of the necessary fields', ifile));
    end
    disp('Necessary fields are offset, npixels, and all three corners -- see otlwrite');
  
  else
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % If the file header is complete, and there are more than zero outline points, add them to RAS
     
    if size(Xc{ifile}, 1) >= 2 & size(Xc{ifile}, 2) > 0,
  
      % Convert the X coordinate into offsets from top_left_hand_corner, measured in R, A, S
      xcoord = (Xc{ifile}(1,:) - Hc{ifile}.offset(1)) / Hc{ifile}.npixels(1);
      xoffset = (Hc{ifile}.top_right_hand_corner' - Hc{ifile}.top_left_hand_corner') * xcoord;
      
      % Convert the Y coordinate into offsets from top_left_hand_corner, measured in R, A, S
      ycoord = (Xc{ifile}(2,:) - Hc{ifile}.offset(2)) / Hc{ifile}.npixels(2);
      yoffset = (Hc{ifile}.bottom_right_hand_corner' - Hc{ifile}.top_right_hand_corner') * ycoord;
      
      % Add the two offsets, plus top_left_hand_corner, to get absolute RAS coordinates
      RAS{ifile} = xoffset + yoffset + repmat(Hc{ifile}.top_left_hand_corner', [1 length(xoffset)]);
      
      % Find the color of each new point
      if size(Xc{ifile}, 1) > 2,
	COLORS{ifile} = char(min(127, max(32, round(Xc{ifile}(3,:)))));
      else,
	COLORS{ifile} = repmat('g', [1 length(xcoord)]);
      end
    end
  end
end

