function [data] = readinTestbedData(filename)
% Read in data files generated by LRAUV testbed LabView DAQ
%
% INPUT:
% filename = path to file
%
% OUTPUT:
% data = data struct
%
%  data
%   | \        /time
%   |  channel1
%   |          \val
%   channel2...
%
% Last modified Feb. 23, 2017
% Ben Raanan, MBARI

% read config file
foldername = fileparts(filename);
[cfg] = readinTestbedConfig(foldername);

% determine if file contains intrinsic data
intrinsic = ~isempty(regexp(filename, 'intrinsic', 'once'));

% import raw data from file
raw_data = readtable(filename,'ReadVariableNames',false);

if intrinsic
    [data] = parse_tb_intrinsic_data(raw_data);
else
    [data] = parse_tb_data(raw_data, cfg);
end

end


function [data] = parse_tb_intrinsic_data(raw_data)


raw_data.Properties.VariableNames =  {'channel', 'time_lv', 'time_intr', 'val'};

% extract channel names
channels = unique(raw_data.channel);

for chnl=channels(:)'
    
    % index channel
    id = find(strcmp(chnl, raw_data.channel));
    
    % remove duplicate entries from index
    [~,ui] = unique(raw_data.time_intr(id));
    id = id(ui);
    
    % extract intrinsic data
    data.(chnl{:}).time_lv = raw_data.time_lv(id)';
    data.(chnl{:}).time_inter = raw_data.time_intr(id)';
    
    switch chnl{:}
        case 'state'
            data.(chnl{:}).val = raw_data.val(id,:)';
       
        otherwise
            data.(chnl{:}).val = cellfun(@str2double,raw_data.val(id,:)');
    end
end
end


function [data] = parse_tb_data(raw_data, cfg)



% rename table variables
raw_data.Properties.VariableNames([1 2]) =  {'channel', 'time_lv'};

% extract channel names
channels = unique(raw_data.channel);

% extract labview timestamp
time_lv = raw_data.time_lv;

[~, n] = size(raw_data(:, 3:end));
for chnl=channels(:)'
    
    % index channel
    id = strcmp(chnl, raw_data.channel);
    cols = n*sum(id);
    
    
    % extract data
    chnl_val = table2array(raw_data(id, 3:end));
    chnl_time = repmat(time_lv(id),1,n);
    
    % reshape to vector
    data.(chnl{:}).time_lv = reshape(chnl_time',1,cols);
    
    switch chnl{:}
        case 'current'
            volt_to_current = 50;  % amp/volt
            data.(chnl{:}).val = reshape(chnl_val', 1, cols) * volt_to_current;
            
        case 'voltage'
            volt_to_voltage = 5; % v/volt
            data.(chnl{:}).val = reshape(chnl_val', 1, cols) * volt_to_voltage;
            
        case 'position'
            idx = strcmp(cfg.Name,'String-pot');            
            v_source = str2double(cfg(idx, :).Value);
            volt_to_meter = (1/(0.94*v_source)) * 12.5 * 25.4;  % V_reading/(0.94*V_source) * (12.5in *25.4mm/in) = (169 +/-7) V_reading (when V_source = 2V)
            data.(chnl{:}).val = reshape(chnl_val', 1, cols) * volt_to_meter;
            
        otherwise
            data.(chnl{:}).val = reshape(chnl_val', 1, cols);
    end
end
end
