%-----------------------------------------------------------|
% [ inspos ] = LoadInsposFile( filename )
%-----------------------------------------------------------|
%
% INPUT
% filname  [1x*]  [char]    Filename (including path)
%                           default: 'winastra.inspos'
%
% OUTPUT
% inspos   [1x1]  [struct]  Struct holding data from file
%  .h      [cx1]  [cell]    Column headers
%  .u      [cx1]  [cell]    Column units
%  .d      [nxc]  [dbl]     Data matrix
% 
% DESCRIPTION
% Load content of *.inspos file generated by WinAstra
% running in INS mode
% Expected format:
%
%   # comments
%   # more comments
%   col 1, col 2,  col 3
%   u 1,     u 2,    u 3 
%   11.1,     12,     13
%   21,       NA,   23.4
%   31,     32.0,     na
%   41,     42.0,     43
%
% REFERENCES
% None.
%
% COPYRIGHT © 2013, Trimble-Terrasat GmbH, Muenchen, Germany

function [ inspos ] = LoadInsposFile( varargin )

filename = HandleOptionalArguments( varargin );

fid = fopen( filename, 'r' );

[ inspos.h, inspos.u, n ] = ReadHeader( fid, GetFormat );
[ inspos.d ] = ReadData( fid, GetFormat, n );

fclose( fid );

end

%--------------------------------------------------------------------------
% Local functions
%--------------------------------------------------------------------------

%% Handle optional arguments
function [ filename ] = HandleOptionalArguments( optArgIn )

filename = 'winastra.inspos';

nArg = length( optArgIn );
if nArg > 1
  error( 'LoadInsposFile:invalidArguments', 'Encountered more than one argument.');
end

if nArg == 1
  filename = optArgIn{1};
end

end

%% Get input file formatting parameters
function [ format ] = GetFormat()

format.colDelimiter = ',';
format.comment = '#';
format.ignore = {'NA', 'na'};

end

%% Read header lines
function [ header, unit, colNum ] = ReadHeader( fid, format )

% Skip leading comments
line = fgetl( fid );
while ~isempty( regexp( line,  ['\s*' format.comment], 'once' ) )
  line = fgetl( fid );
end

% Read 1st line: column headers
header = textscan( line, '%s', 'Delimiter', format.colDelimiter, 'CommentStyle', format.comment );
header = header{1};

line = fgetl( fid );

% Read 2nd line:  units
unit = textscan( line, '%s', 'Delimiter', format.colDelimiter, 'CommentStyle', format.comment );
unit = unit{1};

% Get number of columns
colNum = length(header);

end

%% Read data
function [ data ] = ReadData( fid, format, n )

data = textscan( fid, repmat('%f', 1, n)',...
  'Delimiter', format.colDelimiter,...
  'CollectOutput', 1,...
  'TreatAsEmpty', format.ignore,...
  'CommentStyle', format.comment );
data = data{1};

end