%% 2020-10-05
% This script will combine QUANT files into one big struct for plotting.
% This will make it easier to update the merged data set because it does
% not require opening each data struct (100's of Mb each), but instead
% opens the QUANT file (<100 Kb)
%
% User selects a directory that contains all individual QUANT.mat files to
% be combined, script does the rest
%
% Output: date-stamped .mat file saved in the same directory as that
% containing QUANT files. Contains a struct with all QUANT data.

clearvars

% Best directory to look for folder containing QUANT files
quantDir = "C:\";

% Prompt user to select directory containing quant files
quantDir = uigetdir(quantDir,'Select a directory containing analyzed summit data structs');
quantDir = strcat(quantDir,"\");

% List all data structs in folder
dirContents = dir(strcat(quantDir,"*QUANT*.mat"));
quantFiles = cell(1,length(dirContents));

for n=1:length(dirContents)
    quantFiles{n} = dirContents(n).name;
end

[ts, ds] = Stamps;

combinedSummit = struct;
combinedSummit.combinedStamp = strcat(ds,'_',ts);  % time and date stamp for when QUANT data were combined

expectedSubfields = ...
             {'geno',...             % line genotype
             'sumStart',...         % frame where summiting begins
             'sumEnd',...           % frame where summiting ends (speed returns to baseline)
             'sumDur',...           % summiting duration, in hours
             'meanSumInt',...       % mean distance traveled during summiting (integration under baseline corrected speed plot)
             'meanSumHt',...        % mean y position difference at start vs. end of summiting
             'meanPsWalkSpeed',...  % mean walk speed prior to summiting
             'meanPsDist',...       % mean distance walked prior to summiting
             'sumInt',...           % individual values, distance traveled during summitnig
             'sumHt',...            % individual values, y position difference at start vs. end of summiting
             'psWalkSpeed',...      % individual values, walking speed before summiting 
             'psDist',...           % individual values, distance traveled before summiting
             'numCad',...           % number of cadavers for genotype
             'sourceStruct',...     % data struct used to generate quantification
             'sourceStamp',...      % date source data struct was created (to account for updated data structs when new data are collected)
             'quantStamp'};          % date and time quantification occurred  

for a = 1:length(expectedSubfields)
    combinedSummit.(expectedSubfields{a}) = cell(1,length(quantFiles));
    
    % In order to check for duplicate genos in loop below, all genotypes
    % must be a string (not an empty cell). This will initialize them as
    % such
    if strcmp(expectedSubfields{a},'geno')
        [combinedSummit.geno{1:length(quantFiles)}] = deal("");
    end
end

combinedSummit.paramMismatch = cell(1,length(quantFiles));

for i=1:length(quantFiles)
    mismatch = 0;
    load(strcat(quantDir,quantFiles{i}))

    % Establish reference params from first QUANT file, to make sure all
    % genotypes were quantified using same parameters
    if i==1
        ref = struct;
        paramFields = fields(summit.params);
        for j=1:numel(paramFields)
            ref.(paramFields{j}) = summit.params.(paramFields{j});
        end
    end
    
    % Check that current QUANT file has same parameters as reference QUANT
    for j=1:numel(paramFields)
        if ~ref.(paramFields{j}) == summit.params.(paramFields{j})
            disp(strcat(paramFields{j}, "  don't match!!"));
            mismatch = 1;
        end
    end
    
    % Append data from all expected subfields into combinedSummit struct
    for a = 1:length(expectedSubfields)
        combinedSummit.(expectedSubfields{a}){i} = summit.(expectedSubfields{a});
        
        % if there is more than one instance of same geno, append a number
        % to differentiate it.
        if strcmp(expectedSubfields{a},'geno')
            checkGeno = findGeno(combinedSummit.geno,combinedSummit.geno{i});
            if length(checkGeno) > 1
                combinedSummit.geno{i} = strcat(combinedSummit.geno{i},'_',num2str(length(checkGeno)));
            end
        end       
    end
    
    % Record whether there is a parameter mismatch for QUANT struct
    combinedSummit.paramMismatch{i} = mismatch;
    
end

pQuantDir = getParentDir(quantDir);
outFile = strcat(quantDir,ds,"_combinedSummit.mat");
save(outFile,'combinedSummit','-mat','-v7.3');
writeGenosToFile(outFile);