%% 2020-10-05
% Now generates 1 QUANT mat file for every input data file (instead of a
% combined output file). I think that this will make it easier to combine files into
% structs and pull out specific data for plotting.

% Purpose: quantify summiting in chosen data structs and spit out
% quantification information into separate quant structs
%
% Description: Expects directory expected to contain data structs (output from triggerOnDeath2019fun.m)
% then goes through each data struct to calculate integral under smoothed
% speed curve for each individual cadaver from summitStart to summitEnd.
% The integral values are saved in a struct called "summit", which is saved
% for future use.
%
% Input: directory containing saved data structs
% Output: summit struct, containing speed integral for each individual
% cadaver observed

%% Make sure lastDir has some value
try
    clearvars -except lastDir;
    % To avoid getting stuck in a loop where lastDir = 0
    if lastDir == 0
        lastDir = "C:\";
    end
catch
    lastDir = "C:\";
end

tic;

%% Load folder containing data structs

try
    infoDlg = ["The following directory is already loaded: ", newline, lastDir];  
    infoDlg = [infoDlg,"Would you like to select new directory?'"];
        
    newChoice = questdlg(infoDlg,...
            'Choose new directory?',...
            'Yes','No','No');    
catch
    newChoice = 'Yes'; 
end

if strcmp(newChoice,'Yes')    
    lastDir = uigetdir(lastDir,'Select a directory containing analyzed summit data structs');
    lastDir = strcat(lastDir,"\");
end

% List all data structs in folder
dirContents = dir(strcat(lastDir,"*hours.mat"));
structFiles = cell(1,length(dirContents));

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

%%
% Initialize struct to hold data
params = struct;
[ts, ds] = Stamps;

params.cutoffTime = 50000;       % Set earliest time at which summiting can be expected to occur (in frames before death)
params.endPad = 1*3600*3;        % Decide how many hours after time of death you can look for end of summiting
params.smoothWin = 10000;        %Determine window for smoothing
params.summitStart = (12 - 2.5) * 3600 * 3;  % Manually determine onset time of summiting to equalize across experiments
params.minSumDur = 90;           % in minutes, minimum length of time that summiting can occur
params.moveThresh = 0.8065;      % min speed to consider a fly walking vs. still        

outBase = uigetdir("Select out dir");
outDir = strcat(outBase,ds,'\');
try
    mkdir(outDir);
catch
end         
         
% Go through cohorts and correlate ht and speed of summit bump
for a=1:numel(structFiles)
    disp(strcat("File number ",num2str(a)," of ",num2str(numel(structFiles))));
    
    summit = struct;
    summit.sourceStruct = strcat(lastDir,structFiles{a}); % data struct used to generate quantification
    
    load(summit.sourceStruct, 'data');  
    
    summit.sourceStamp = strcat(data.dateStamp,'_',data.timeStamp); % date source data struct was created (to account for updated data structs when new data are collected)
    summit.quantStamp = strcat(ds,'_',ts); % date and time quantification occurred   
    
    outName = split(structFiles{a},'.mat');
    outName = strcat(outName{1},'_QUANT.mat');

    if strfind(structFiles{a},'_Female')
        genoName = strcat(data.geno,'-F');
    elseif strfind(structFiles{a},'_Male')
        genoName = strcat(data.geno,'-M');
    else
        genoName = data.geno;
    end
    
    summit.geno = genoName;   % line genotype
    
    summit.params = params;

    %% Determine sumStart and sumEnd and resultant calculated integrals and height differences
    % manually via user input
    [summit.sumStart, ...       % frame where summiting begins
     summit.sumEnd, ...         % frame where summiting ends (speed returns to baseline)
     summit.sumDur, ...         % summiting duration, in hours
     summit.meanSumInt, ...     % mean distance traveled during summiting (integration under baseline corrected speed plot)
     summit.meanSumHt, ...      % mean y position difference at start vs. end of summiting
     summit.meanPsWalkSpeed, ...% mean walk speed prior to summiting
     summit.meanPsDist,...      % mean distance walked prior to summiting
     summit.sumInt, ...         % individual values, distance traveled during summiting
     summit.sumHt, ...          % individual values, y position difference at start vs. end of summiting
     summit.psWalkSpeed, ...    % individual values, walking speed before summiting 
     summit.psDist,...          % individual values, distance traveled before summiting
     summit.numCad] = ...       % number of cadavers for genotype
            integrateSummitBump(data, ...
                                genoName, ...
                                outDir, ...
                                summit.params.endPad, ...
                                summit.params.smoothWin,...
                                summit.params.summitStart,...
                                summit.params.moveThresh,...
                                summit.params.minSumDur);
                            
      outFile = strcat(outDir,outName);
      save(outFile,'summit','-mat','-v7.3');
end