% 2021-02-09
% Takes in cell array of file paths pointing to scrambled .mat files
% (randCadFiles) comprised entirrely of cadaver ROIs
function manuallyCallTod(randCadFiles, localTime, totalCads, callEveryROI)
 
    [plotcolor, lightcolor] = colorROIs('Cadaver',0.5); % establish plot color for all ROIs

    cadCt = 1;
    
    for i = 1:numel(randCadFiles)
    %for i = 9
        % Load randData struct
        load(randCadFiles{i});
        
        % Plotting options, pulled from summitParams
        % xInc choice depends on length of experiment in hours
        [noMvmtXMax, xInc, smoothWin] = summitParams(length(randData.ypos)/(3600*3));
        
        % Determine number of ROIs in file
        numROIs = length(randData.survival);
        
        % Pull out all survival data so we can add column header for column
        % N, Blind_TOD
        timeArrays = localTime(1,:);
        sFiles = localTime(2,:);
        
        % This will execute once for every random mat file generated (so
        % not optimal), but shouldn't noticeably slow program
        for j=1:length(sFiles)
            xlswrite(sFiles{j},{'Blind_TOD'},1,'N1')
        end
        
        % Plot individual ROI data
        for roi = 1:numROIs   
        %for roi = [71]
            if mod(cadCt,ceil(totalCads/10))==0
                disp(strcat("ROI ",num2str(cadCt)," of ",num2str(totalCads),": ", num2str(round((100*cadCt)/totalCads)),"% done."));
            end
            smoothedSpeed = smoothdata(randData.speed(:,roi),'movmean',smoothWin);
            scaledHt = scaleHt(randData.ypos(:,roi));
            
            % Pull out local time array (localT) and original survival file
            % path for given ROI (ogSurvival) from localTime
            fileNum = strcmp(randData.survival{roi},string(localTime(2,:)));
            ogSurvival = sFiles{fileNum};
            
            surTable = readtable(ogSurvival);
            
            ogROI = randData.ogROI(roi);
            
            %if strcmp(surTable{ogROI,'Auto_notes'},'Bad trace')
            if isnan(surTable{ogROI,'Blind_TOD'}) || callEveryROI
            
                localT = cell2mat(timeArrays(fileNum));            

                todYVals = [1,max(smoothedSpeed),noMvmtXMax];

                fig = figure();
                set(fig,'defaultAxesColorOrder',[0 0 0;0 0 0]);

                % Set window size to be essentially max screen size
                set(gcf, 'Position',  [0, 50, 1900, 950])

                p1 = subplot(3,1,1);
                hold on;            
                
                % Display no info for ROI (no box, no ROI #, no genotype, no
                % sex, no date!)
                title(strcat('Select time of death for ROI: File ',num2str(i),'/',num2str(numel(randCadFiles)),' , ROI #',num2str(roi),'/',num2str(numROIs)));

                % Plot raw y position data
                plot(p1,scaledHt,'Color',lightcolor);
                ylabel(p1,'Y position');
                ylim(p1,[0 1]);
                adjustROIPlot(p1, 0, 0, todYVals(1), xInc, localT);

                % Plot speed data
                p2 = subplot(3,1,2);
                hold on;

                plot(randData.speed(:,roi),'Color',lightcolor);
                plot(smoothedSpeed,'Color',plotcolor)
                ylabel('Speed');
                ylim([0 50]);
                yyaxis right
                plot(cumsum(randData.speed(:,roi)));
                ylabel('Cumulative frames moved');
                try
                    ylim([0 nansum(randData.speed(:,roi))])
                catch
                    xlswrite(ogSurvival,{'Bad trace'},1,strcat('Q',num2str(ogROI+1)))
                    break;
                end
                yyaxis left;
                adjustROIPlot(p2, 0, 0, todYVals(2), xInc, localT);

                % Plot time since last mvmt
                p3 = subplot(3,1,3);
                hold on;
                framesNoMvmt = zeros(size(scaledHt));
                count = 0;
                for idx = 1:numel(scaledHt)
                  if isnan(scaledHt(idx))
                    count = count + 1;
                  else
                    count = 0;
                  end
                  framesNoMvmt(idx) = count;
                end
                plot(p3,framesNoMvmt);
                ylabel(p3,'Last mvmt (minutes ago)');
                ylim(p3,[0 3*3600+1]);
                set(gca,'ytick',1:10*3*60:length(scaledHt));
                set(gca,'yticklabel',0:10:length(scaledHt)/(60*3));
                adjustROIPlot(p3, 0, 0, todYVals(3), xInc, localT);

                subplots = [p1,p2,p3];
                linkaxes(subplots,'x')                         

    %             % For debugging - checking if writing correct values to correct
    %             % ROI
    %             expName = split(ogSurvival,'\');
    %             expName = expName(length(expName));
    %             %expDir = getParentDir(ogSurvival);
    %             %boxID = getboxID(expDir);
    %             boxID = "TEST";
    %             suptitle(strcat(boxID,' - ROI #',num2str(randData.ogROI(roi)),' - ',expName));

            todAnswer = 0;
            timeOfDeath = 0;
                while ~todAnswer 
                    % Skip asking if time of death is accepted if I
                    % haven't selected it yet (indicated by value still
                    % set at 1)
                    if timeOfDeath == 0
                        todAnswer = 'No';
                    else
                        % If experiment is longer than 24 hours, refigure
                        % plot to display only ~24 hours (to scale
                        % graph for my manually calling TOD as they appeare
                        % before pandemic forced me to run longer
                        % experiments)
                        if length(scaledHt)/(3*3600) > 24
                            for sp = 1:3
                                xlim(subplots(sp),[timeOfDeath-(3600*3*20) timeOfDeath+(3600*3*4)]);
                            end
                        end
                        % Double-check before confirming save of of death
                        todAnswer = questdlg(['Accept ',num2str(timeOfDeath),' as time of last mvmt (proxy for time of death)?'],...
                        'Determine time of death',...
                        'Yes','No','Bad Trace','Yes');
                    end
                     switch todAnswer
                        case 'Yes'
                            % Save to survival spreadsheet (column N)
                            ogROI = randData.ogROI(roi);
                            xlswrite(ogSurvival,timeOfDeath,1,strcat('N',num2str(ogROI+1)));
                        case 'No'
                            % Wait for user to input time of death via
                            % graph
                            todAnswer=0;
                            pause;
                            timeOfDeath = ginput(1);
                            timeOfDeath = round(timeOfDeath(1));
                            for sp = 1:3
                                scatter(subplots(sp),timeOfDeath,todYVals(sp),'g*');
                            end
                        case 'Bad Trace'
                            xlswrite(ogSurvival,{'Bad trace'},1,strcat('Q',num2str(ogROI+1)));
                        case 'Cancel'
                            break;
                    end
                end

                % Plot accepted time of death 
                if timeOfDeath >0
                    for sp = 1:3
                        scatter(subplots(sp),timeOfDeath,todYVals(sp),'c*');
                    end
                    text(p1, double(timeOfDeath),1,num2str(timeOfDeath));
                end        
                close;

            end
            cadCt = cadCt+1;
        end
    end
end