function [dataRows, rowTitles, colTitles] = ...
                 readDelimitedWithColAndRowCaptions(fname, desimPoint)
% Reads a data file where first row is a text caption of columns 
% (double-quoted strings with whitespace in between with no escape 
% mechanism for the double quote character!), first column is text 
% caption of rows (double-quoted string like the col caption), data values 
% are all numerical and separated by whitespace, and decimal points are '.' 
% (English locale) or ',' (Finnish locale).
%
% This is something that I would expect Matlab to be able to do
% out-of-the-box, but despite some effort I could not find a way to make
% it happen, so I wrote this script.
%
% Output:
% 
%   dataRows  = numerical data as row vectors
%   rowTitles = the title strings of rows as a cell array
%   colTitles = the title strings of data columns
%


if nargin==2
  usingComma = strcmp(desimPoint, ',');
else
  usingComma = false;
end

fid = fopen(fname);

S = fgetl(fid);
colTitles = splitDoubleQuotedLine(S);
colTitles = colTitles(2:end);       % exclude first column's title

expectedVecLen = length(colTitles);

iR = 0;
while feof(fid) == 0
    iR = iR + 1;
    S = fgetl(fid);
    [rowTitles{iR}, dS] = splitRowCapAndRest(S);
    
    if usingComma, dS = strrep(dS, ',', '.'); end;
    dR = textscan(dS, '%f');
    
    if numel(dR{1}) ~= expectedVecLen
        error('Row length mismatch, line %d length %d ~= %d', iR, numel(dR{1}), expectedVecLen);
    end;
    
    dataRows(iR,:)  = dR{1};
end

fclose(fid);


% Helper functions
function split = splitDoubleQuotedLine(S)
split = {};
remain = S;
iOut = 0;

while(length(remain)>1)
    iOut = iOut+1;
    [token, remain] = strtok(remain, '"');         % Skip to next '"'
    [split{iOut}, remain] = strtok(remain, '"');   % Take inside
end

function [rowTitle, remain] = splitRowCapAndRest(S)
remain = S;
[token, remain] = strtok(remain, '"');         % Skip to first '"'
[rowTitle, remain] = strtok(remain, '"');      % Take inside
remain = remain(2:end);                        % Skip the remnant '"'
