%==========================================================================
% Data processing for the APS in-situ tension tests
% Current capabilities:
% plotting and saving
% force, stress, crosshead displacement, and time data for Nov 2017 tests
% force, stress, time data for Jun 2017 tests (crosshead displacement too,
%   but it is basically meaningless)
%
% USAGE:
% Data required: log files from load cell for Nov and/or Jun
% Data suggested: scan data (hdf, mat) from Nov and/or Jun, DIC data (.mat)
% for strains
% File dependancies, core: read_load_histories.m, specimenDatabase.m,
% File dependancies, scan data: getScanHDFdata.m, getInitDisp
% File dependancies, helper: padWithZeros.m, month2number.m
% Related files: saveScanData.m (converts load and time in HDF file to a
% .mat file for ease of distribution).
%
% Set the log and scan file paths for the Nov ("11") and Jun ("06") data
% Set the scan data type for Nov and Jun, depending on which data you have
% access to (mat is probably easiest).
% Set the path to save figures into (the seven figures this makes are
% automatically saved to png and .fig in this directory)
% Set the specimenRefData to plot using one of the four types of specifier
%
% There are several plotting options already set up here, selected with
% commenting and uncommenting block of the code. There is a section to plot
% each specimen on its own figure, seven different groups (discrete,
% continuous, horizontal, vertical, wall 1, wall 2, and wall 3) that can be
% plotted as either stress versus displacement (doesn't work well for the
% June data) or stress versus time (which is not has informative).
%
% The code should be entirely portable, but has only been fully tested on
% MATLAB R2016a under Linux and R2017b under Windows. It is a little slow
% right now; there might be improvements to make to get this faster
% (reading files is the slow part).
%
% -------------------------------------------------------------------------
% History - Orion L. Kafka
% 12-14-2017 - First complete(ish) version
% 02-09-2018 - Added components for reading/processing strain data from
%              .mat files
%
%==========================================================================

% =================================================================
% Set up
% =================================================================

clear all; close all; clc
format long

% =================================================================
% Set output data locations
% =================================================================

% path to save figures to
if ~exist(fullfile('plots'),'dir')
    mkdir(fullfile('plots'));
end
plotTLD = fullfile('plots');

% Save plots? "yes" or "no"
savePlots = 'yes';

% path to save .mat file with data for all the specimenRefData
if ~exist(fullfile('results'),'dir')
    mkdir(fullfile('results'));
end
saveLoc = fullfile('results');

% =================================================================
% Input data sources
% =================================================================
% TLDs for scan data and during-run data
% Log files for the June run have slightly different formatting than do the
% November, so we need to keep track of which is which.
logFilePath11 = fullfile('data','2017_11','all_loading_histories');
scanFilePath11 = fullfile('data','2017_11','scanFileData');

% either "hdf" (from raw data), "mat" (from previous processing), or "none"
% "hdf" processing requires "raw data" in HDF form, avaliable in the "raw
% data" part of the data, but is generally less useful for this part
% because it requires more i/o time and interpretation.
scanDataType11 = 'mat';

% If scan data is accessible, "scanFilePath" as an empty string - the code
% will skip looking for scan files.

% Crosshead displacement was measured incorrectly for the 06_2017 dataset
logFilePath06 = fullfile('data','2017_06','AllLoadHistories_2017_06');
scanFilePath06 = fullfile('data','2017_06','scanFileData');

scanDataType06 = 'none';

% Strain data comes from VIC DIC, and is stored in a different folder
strainTLD = fullfile('data','strains');

% Strain data could either be .mat files from VIC, or saved mat files from
% a previous run of this code. (They should still each be in their own
% folder though, just like the DIC results are).
% "vic" or "mat"
strainDataType = 'mat'; % mat format is faster


% =================================================================
% =================================================================
% Start data processing
% =================================================================
specimenRefData = specimenDatabase();

% =================================================================
% Set specimens to process
% =================================================================
% Comment and uncomment sections for different ways of choosing the
% specimen(s) to plot. The options are: range, pattern matching, list by
% name, and list by number. Leave only one option uncommented at a time.
% Use the block comment structure provided. Note that not all plotting 
% options/types are possible with all specimens.

% ==================
% Range style specifier, by specimen number (run specimenDatabase.m and
% type specimenRefData(specNum).name to see what number is which specimen, or
% just open specimenDatabase.m and look through the list).

%
%specList = 71:1:72;
%}

% ==================
% List style specifiers
%
% 1. Specify with pattern matching on the name
%
specList = [];
for ii = 1:length(specimenRefData)
    if ~isempty(specimenRefData(ii).name) &&...
            ~strcmp(specimenRefData(ii).name(1:2),'PH') && ...
            strcmp(specimenRefData(ii).name(2),'3')
            %str2double(specimenRefData(ii).name(end-1:end))<25

        %if strcmp(specimenRefData(ii).date,'11_2017') && ~strcmp(specimenRefData(ii).name,'V2-1')
        specList = [specList, ii];
        specName{ii} = specimenRefData(ii).name;
    end
end
%}

% ==================
% 2. Provide a list of spec names
%{
%specName = {'V3-9','V3-5','V3-3','V3-10','V3-4'};
%specName = {'V3-9','V3-5','V3-3','V3-10','V3-4','H3-9','H3-5','H3-3','H3-10','H3-4'};
%specName = {'V2-3','V2-4','V2-5','H2-3','H2-4','H2-5'};
%specName = {'V2-4','V3-4','H2-4','H3-4'};%,'V3-9','V3-1','V3-7','V3-5','V3-3','V3-10'};
%specName = {'H1-6','V1-6','H1-11','V1-11'};
%specName = {'V1-2','V1-5','H1-2','H1-5'};
specName = {'H2-4'};
specList = [];
for ii = 1:length(specimenRefData)
    for jj = 1:length(specName)
        if strcmp(specimenRefData(ii).name,specName{jj})
            specList = [specList, ii];
        end
    end
end
%}

% ==================
% 3. Provide a simple list of spec numbers
%
%specList = [8];
%}
% end style options

jj = 0;
while jj < length(specList)
    jj = jj + 1;
    specNum = specList(jj);
    % ==================================
    if ~isempty(specimenRefData(specNum).mode)
        
        % =================================================================
        % Data collection phase
        % =================================================================
        
        % FIND DISPLACEMENTS AND LOADS
        
        % The following determines which case the specimen falls under,
        % discrete or continuous and June or November. It then runs
        % readLoadHistories with the right flags to extract all the data.
        % readLoadHistories will figure out which experiment numbers
        % correlate to the specimen number, and combines all the data for
        % that specimen to a single variable, points. points has fields for
        % load, disp, and time
        
        if strcmp(specimenRefData(specNum).mode,'discrete')
            if strcmp(specimenRefData(specNum).date,'11_2017')
                %{
                % For scans stored in multiple locations; this shouldn't happen any more
                if specNum <= 110
                    specPoints = readLoadHistories('discrete', logFilePath11, scanFilePath11_1,...
                                specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd, scanDataType11);
                elseif specNum > 110
                    specPoints = read_load_histories('discrete', logFilePath11, scanFilePath11_2,...
                                specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd, scanDataType11);
                end
                %}
                [specPoints, endTimes] = readLoadHistories('discrete', logFilePath11, scanFilePath11,...
                    specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd, scanDataType11);
                %}
            elseif strcmp(specimenRefData(specNum).date,'06_2017')
                [specPoints, endTimes] = readLoadHistories('discrete', logFilePath06, scanFilePath06,...
                    specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd, scanDataType06);
            end
            if isfield(specPoints,'nan')
                disp(['Missing specNum ',num2str(specNum)]);
                continue
            end
        elseif strcmp(specimenRefData(specNum).mode,'continuous')
            if strcmp(specimenRefData(specNum).date,'11_2017')
                %{
                if specNum <= 110
                    specPoints = readLoadHistories('continuous', logFilePath11, scanFilePath11_1,...
                        specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd);
                elseif specNum > 110
                    specPoints = readLoadHistories('continuous', logFilePath11, scanFilePath11_2,...
                        specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd);
                end
                %}
                [specPoints, endTimes] = readLoadHistories('continuous', logFilePath11, scanFilePath11,...
                    specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd, scanDataType11);
            elseif strcmp(specimenRefData(specNum).date,'06_2017')
                [specPoints, endTimes] = readLoadHistories('continuous', logFilePath06, scanFilePath06,...
                    specimenRefData(specNum).expStart, specimenRefData(specNum).expEnd, scanDataType06);
            end
            if isfield(specPoints,'nan')
                disp(['Missing specNum ',num2str(specNum)]);
                continue
            end
        end
        
        % re-organize
        for ii = 1:length(specPoints)
            displacement(specNum,ii) = specPoints(ii).disp;
            force(specNum,ii) = specPoints(ii).load;
            stress(specNum,ii) = specPoints(ii).load/specimenRefData(specNum).crosssection;
            loadTime(specNum,ii) = specPoints(ii).time;
        end
        % set starting displacement to zero; this way we are actually
        % working with displacement, not crosshead location
        displacement(specNum,1:length(specPoints)) =...
            displacement(specNum,1:length(specPoints)) - displacement(specNum,1);
        %time(specNum,1:length(specPoints)) = time(specNum,:) - time(specNum,1);
        % record the total number of points for each specimens
        totalPoints(specNum) = length(specPoints);
        
        % FIND STRAINS
        
        % Do we have strain data (.mat files from VIC or a .mat summary file)?
        % If we do, get that information and added it to the body of data
        % that we're collecting
        if exist(fullfile(strainTLD,specimenRefData(specNum).name,'matOut'),'dir')...
                || exist(fullfile(strainTLD,specimenRefData(specNum).name,'totalStrains.mat'),'file')
            disp(['Reading strain data for specimen ',specimenRefData(specNum).name])
            % All of the strain data is in once place, listed by name, not
            % number; this makes sense, since the DIC is processed and saved
            % for full specimens, not for each experiment (in cases where this
            % differs)
            if strcmp(strainDataType,'vic')
                % Read in the total gauge strain for the life of the specimen
                % from .mat files from VIC DIC
                [curSpecStrain,imgNums] = readMatFiles(fullfile(strainTLD,specimenRefData(specNum).name,'matOut'));
            elseif strcmp(strainDataType,'mat')
                strainData = load(fullfile(strainTLD,specimenRefData(specNum).name,'totalStrains'));
                curSpecStrain = strainData.totalStrain;
                imgNums = strainData.imgNums;
            end
            
            imageTime = zeros(1,length(imgNums));
            clear endImgNum endImgTime
            
            if strcmp(specimenRefData(specNum).mode,'discrete')
                % figure out the time the strain data was taken:
                % 1. find the time of each time image capture was stopped
                % (it matches with when load recording was stopped)
                for ii = 1:length(specimenRefData(specNum).imgEnd)
                    idx = strfind(imgNums{ii},'-');
                    endImgNum(ii) = specimenRefData(specNum).imgEnd(ii);
                    endImgTime(ii) = endTimes(str2double(imgNums{ii}(1:idx-1)));
                end
                
                % 2. Back count for each image, assuming the 1 Hz capture
                % frequency was faithfully abided (not super strong, but
                % it's the best we have).
                count = 1;
                for ii = 1:length(imgNums)
                    idx = strfind(imgNums{ii},'-');
                    imageTime(ii) = endTimes(str2double(imgNums{ii}(1:idx-1)))...
                        - (endImgNum(count) - str2double(imgNums{ii}(idx+1:end)));
                    try
                        if ~strcmp(imgNums{ii}(1:idx-1),imgNums{ii+1}(1:idx-1))
                            count = count + 1;
                        end
                    catch
                        count = count + 1;
                    end
                end
                
            elseif strcmp(specimenRefData(specNum).mode,'continuous')
                idx = strfind(imgNums{end},'-');
                endImgNum = specimenRefData(specNum).imgEnd;
                endImgTime = endTimes(2);
                
                for ii = 1:length(imgNums)
                    idx = strfind(imgNums{ii},'-');
                    imageTime(ii) = endImgTime...
                        - (endImgNum - str2double(imgNums{ii}(idx+1:end)));
                end
            end
            
            % 3. match up the stress and strain data by time
            
            for ii = 1:max(size(imageTime))
                % find the closes point in the "load times" to the current
                % "image time" by finding the minimum absolute difference
                % between the current image time and all the load times for
                % that specimen. timeDelta tracks the maximum difference in
                % times; this should be low.
                [timeDelta(specNum,ii), indLoadTime] = min(abs(loadTime(specNum,:) - imageTime(ii)));
                
                % add strain information into an array that matches the
                % format of the load data - points at which strain was
                % measured will have a value, and where it was not measured
                % will be blank (0)
                strain(specNum, indLoadTime) = curSpecStrain(ii);
                
            end
            
            % "densify" data, so that only the points
            % with both are included; this ought to be done with logical
            % indexing (e.g. force(specNum, strain(specNum,:)~=0)), but
            % we don't know the sizes before hand. So the easiest way is
            % to use a for loop and change the sizes dynamically
            
            nzCount = 1;
            for ii = 1:size(strain,2)
                if strain(specNum,ii) ~= 0
                    stressShort(specNum,nzCount) = stress(specNum, ii);
                    strainShort(specNum,nzCount) = strain(specNum, ii);
                    dispShort(specNum,nzCount)   = displacement(specNum, ii);
                    forceShort(specNum,nzCount)  = force(specNum, ii);
                    timeShort(specNum,nzCount)   = loadTime(specNum, ii);
                    nzCount = nzCount + 1;
                end
            end
            
            totalShortPoints(specNum) = nzCount-1;

            
            % STORE DATA
            % use a  couple differnt formations, which might be useful for
            % different things.
            
            % use a struct with specimens.<name>.<field>(value) to store
            % all the data
            
            specimens(1).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                'time (from load reading)';
            specimens(2).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                timeShort(specNum,:);
            specimens(3).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                'displacement';
            specimens(4).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                dispShort(specNum,:);
            specimens(5).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                'force';
            specimens(6).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                forceShort(specNum,:);
            specimens(7).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                'stress';
            specimens(8).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                stressShort(specNum,:);
            specimens(9).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                'strain';
            specimens(10).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                strainShort(specNum,:);
            specimens(11).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                'time mismatch between stress reading and strain reading';
            specimens(12).([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)]) =...
                timeDelta(specNum,:);
            
            
            % Use a cell array of structs with name and stress/strain data;
            % this isn't very intuitive
            allSpecimenPoints{specNum} =...
                struct([specimenRefData(specNum).name(1:2),'_',...
                specimenRefData(specNum).name(4:end)],{specPoints;strain(specNum,:)});
        else
            allSpecimenPoints{specNum} =...
                struct([specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)],specPoints);
        end
        disp(['Completed specimen: ',specimenRefData(specNum).name(1:2),'_',specimenRefData(specNum).name(4:end)])
        
    end % end isempty
    
end

% Load "baseline" wrought material data
refCurve = load(fullfile('data','refData_wrought_WJ3.mat'));

refStrain = refCurve.vicStrain2;
refStress = refCurve.stressMatch2/1e6; %convert to MPa

% Finally, save the struct that contains all the processed data
save(fullfile(saveLoc,'allSpecimenPoints'),'allSpecimenPoints');

%%
% start a new section, so we can do plotting and data collection seperately
% =================================================================
% Data analysis and plotting phase
% =================================================================
% Comment/uncomment sections to change plotting behavior. There are a lot
% of prototype options here, not all of which are useful for all specimens.
% But, these have all been used over time, and might be helpful to
% understand the data.

close all
% Set up cell arrays to build legends into
disLegStr = {};
conLegStr = {};

vLegStr = {};
hLegStr = {};

oneLegStr = {};
twoLegStr = {};
threeLegStr = {};

%close all
%clear h1 h2 h3 h4 h5 h6 h7
%specList =  71:72;%[1, 2, 3];
%{
jj = 0;
kk = 0;
while jj < length(specList)
    jj = jj + 1;
    specNum = specList(jj);
    for mm = 1:length(specName)
        if strcmp(specimenRefData(specNum).name,specName{mm})
            kk = kk + 1;
            break
        end
    end
    
    % UTS
    stressMaxes(kk) = max(stress(specNum,:));
    specNameSorted{kk} = specimenRefData(specNum).name;
end

% plot uts's
figure(1)
bar(stressMaxes)
set(gca,'XTick',1:length(specNameSorted),'xticklabel',specNameSorted);
%xlabel(specName1)
ylabel('UTS (MPa)')
title('Max stresses')
%}

fig_width = 600;
fig_height = 500;
fig_bot = 50;
fig_left= 20;
fig_row = 0;
jj = 0;
syV_idx = 1;
syH_idx = 1;
sigma_y_V = nan(length(specList),1);
sigma_y_H = nan(length(specList),1);
while jj < length(specList)
    jj = jj + 1;
    specNum = specList(jj);
    if ~isempty(specimenRefData(specNum).mode) &&...
            exist('strainShort', 'var') &&...
            specNum <= size(strainShort,1) &&...
            strainShort(specNum,1) ~= 0
        
        disp(['Plotting specimen ',specimenRefData(specNum).name])
        
        % Young's Modulus
        startFit = find(stressShort(specNum,:) > 50, 1, 'first');
        endFit = find(stressShort(specNum,:) > 300, 1, 'first');
        
        fo1 = fit(strainShort(specNum,startFit:endFit)',stressShort(specNum,startFit:endFit)','poly1');
        % store E
        youngsModulus(specNum) = fo1.p1;
        
        % Yeild Stress
        offset = fo1.p1 * (strainShort(specNum,:)-0.002) + fo1.p2;
        lineDiff = stressShort(specNum,:) - offset;
        [a,ysInd(specNum)] = min(abs(lineDiff));
        sigma_y(specNum) = stressShort(specNum,ysInd(specNum));
        
        if specimenRefData(specNum).name(1) == 'V'
            sigma_y_V(syV_idx) = sigma_y(specNum);
            syV_idx = syV_idx + 1;
        elseif specimenRefData(specNum).name(1) == 'H'
            disp(specimenRefData(specNum).name(1))
            sigma_y_H(syH_idx) = sigma_y(specNum);
            syH_idx = syH_idx + 1;
        end
                
        % make the empty parts of the re-organized matrices NaN, instead of
        % zero - this makes for better looking plots (no big tails)
        displacement(specNum,totalPoints(specNum)+1:end) = NaN;
        force(specNum,totalPoints(specNum)+1:end) = NaN;
        stress(specNum,totalPoints(specNum)+1:end) = NaN;
        loadTime(specNum,totalPoints(specNum)+1:end) = NaN;
        %strain(specNum,totalStrainPoints(specNum)+5:end) = NaN;
        
        timeShort(specNum,totalShortPoints(specNum)-2:end) = NaN;
        dispShort(specNum,totalShortPoints(specNum)-2:end) = NaN;
        forceShort(specNum,totalShortPoints(specNum)-2:end) = NaN;
        stressShort(specNum,totalShortPoints(specNum)-2:end) = NaN;
        strainShort(specNum,totalShortPoints(specNum)-2:end) = NaN;
        
        % -- Plot one experiment per figure --
        %
        %floor(totalShortPoints(specNum)*0.05):ceil(totalShortPoints(specNum)*0.08)
        %
            % figure out where to put the figure
            fig_bot=fig_row*(fig_height+2)+50;
            if fig_left+fig_width > 2000
                fig_row = fig_row+1;
                fig_left = 20;
            else
                fig_left = fig_left + fig_width + 2;
            end
            % start overlapping along the bottom row if there's too many
            if fig_bot + fig_height > 1400
                fig_row = 0;
            end
            
            f = figure(specNum);
            set(f,'OuterPosition',[fig_left,fig_bot,fig_width,fig_height]);
            plot(strainShort(specNum,:),stressShort(specNum,:),'-','linewidth',2)
            %plot(time(specNum,:)-time(specNum,1),force(specNum,:),'-','linewidth',2,'Markersize',2)
            %ylabel('Crosshead displacement ($\mu m$)','interpreter','latex','fontsize',24)
            hold on
            
            % Show 0.2% offset line:
            plot(strainShort(specNum,ysInd(specNum)),sigma_y(specNum),'.','markersize',14)
            line([strainShort(specNum,1)+0.002,strainShort(specNum,ysInd(specNum))],...
                [stressShort(specNum,1),sigma_y(specNum)],'color','k','linestyle','--');
            text(.01,120,['$\sigma_y$ (0.2\% offset) = ',num2str(stressShort(specNum,ysInd(specNum)))],'interpreter','latex')
            
            % Show Young's Modulus
            text(0.0075,65,['E = ',num2str(youngsModulus(specNum)/1e3),' GPa'])
            
            ylabel('Stress, $\sigma$ (MPa)','interpreter','latex')
            xlabel('Strain, $\varepsilon$','interpreter','latex')
            set(gca,'fontsize',14)
            title(specimenRefData(specNum).name)
            axis([0,0.62,0,850])
            grid on
            hold off
        %}
        
        % If there's strain data, plot stress vs strain
        %
        if strcmp(specimenRefData(specNum).mode,'continuous')
            h1 = figure(length(specimenRefData)+1);
            hold on
            plot(strainShort(specNum,:),stressShort(specNum,:),'-','linewidth',2)
            hold off
            conLegStr = [conLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).mode,'discrete')
            h2 = figure(length(specimenRefData)+2);
            hold on
            plot(strainShort(specNum,:),stressShort(specNum,:),'-','linewidth',2)
            hold off
            disLegStr = [disLegStr,specimenRefData(specNum).name];
        end
        %
        % Plot vertical on one figure and horizontal on another
        if strcmp(specimenRefData(specNum).name(1),'V')
            h3 = figure(length(specimenRefData)+3);
            hold on
            plot(strainShort(specNum,:),stressShort(specNum,:),'-','linewidth',2)
            hold off
            vLegStr = [vLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).name(1),'H')
            h4 = figure(length(specimenRefData)+4);
            hold on
            plot(strainShort(specNum,1:end-5),stressShort(specNum,1:end-5),'-','linewidth',2)
            hold off
            hLegStr = [hLegStr,specimenRefData(specNum).name];
        end
        %
        % Plot walls 1, 2, and 3 (processing conditions) seperately
        if strcmp(specimenRefData(specNum).name(2),'1')
            h5 = figure(length(specimenRefData)+5);
            hold on
            plot(strainShort(specNum,1:end-5),stressShort(specNum,1:end-5),'-','linewidth',2)
            hold off
            oneLegStr = [oneLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).name(2),'2')
            h6 = figure(length(specimenRefData)+6);
            hold on
            plot(strainShort(specNum,:),stressShort(specNum,:),'-','linewidth',2)
            hold off
            twoLegStr = [twoLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).name(2),'3')
            h7 = figure(length(specimenRefData)+7);
            hold on
            plot(strainShort(specNum,:),stressShort(specNum,:),'-','linewidth',2)
            hold off
            threeLegStr = [threeLegStr,specimenRefData(specNum).name];
        end
    else
        % Otherwise, plot stress versus time, because that's all we have
        % Plot continuous on one figure and discrete on another
        %{
        if strcmp(specimenRefData(specNum).mode,'continuous')
            h8 = figure(length(specimenRefData)+8);
            hold on
            plot(loadTime(specNum,1:totalPoints(specNum))-loadTime(specNum,1),stress(specNum,1:totalPoints(specNum)),'-')
            hold off
            conLegStr = [conLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).mode,'discrete')
            h9 =figure(length(specimenRefData)+9);
            hold on
            plot(loadTime(specNum,1:totalPoints(specNum))-loadTime(specNum,1),stress(specNum,1:totalPoints(specNum)),'-')
            hold off
            disLegStr = [disLegStr,specimenRefData(specNum).name];
        end
        
        % Plot vertical on one figure and horizontal on another
        if strcmp(specimenRefData(specNum).name(1),'V')
            h10 = figure(length(specimenRefData)+10);
            hold on
            plot(loadTime(specNum,1:totalPoints(specNum))-loadTime(specNum,1),stress(specNum,1:totalPoints(specNum)),'-')
            hold off
            vLegStr = [vLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).name(1),'H')
            h11 = figure(length(specimenRefData)+11);
            hold on
            plot(loadTime(specNum,1:totalPoints(specNum))-loadTime(specNum,1),stress(specNum,1:totalPoints(specNum)),'-')
            hold off
            hLegStr = [hLegStr,specimenRefData(specNum).name];
        end
        % Plot walls 1, 2, and 3 (processing conditions) seperately
        if strcmp(specimenRefData(specNum).name(2),'1')
            h12 = figure(length(specimenRefData)+12);
            hold on
            plot(loadTime(specNum,1:totalPoints(specNum))-loadTime(specNum,1),stress(specNum,1:totalPoints(specNum)),'-')
            hold off
            oneLegStr = [oneLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).name(2),'2')
            h13 = figure(length(specimenRefData)+13);
            hold on
            plot(loadTime(specNum,1:totalPoints(specNum))-loadTime(specNum,1),stress(specNum,1:totalPoints(specNum)),'-')
            hold off
            twoLegStr = [twoLegStr,specimenRefData(specNum).name];
        elseif strcmp(specimenRefData(specNum).name(2),'3')
            h14 = figure(length(specimenRefData)+14);
            hold on
            %plot(strain(specNum,:),'o')
            plot(loadTime(specNum,1:totalPoints(specNum))-loadTime(specNum,1),stress(specNum,1:totalPoints(specNum)),'-')
            hold off
            threeLegStr = [threeLegStr,specimenRefData(specNum).name];
        end
        %}
    end
end

%{
%This currently only works for some specified specimens
figure(10)
plot(strainShort(3,:),stressShort(3,:),'-','linewidth',2,'color',[0 149/255 0])
hold on
plot(strainShort(46,:),stressShort(46,:),'-','linewidth',2,'color',[1 0 1])
plot(strainShort(47,:),stressShort(47,:),'-','linewidth',2,'color',[0.6 0 0.6])
plot(strainShort(48,:),stressShort(48,:),'-','linewidth',2,'color',[0 239/255 0])
plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
legend({'V3-4','H2-4','H3-4','V2-4','Wrought'})
%xlabel('Crosshead displacement ($\mu m$)','interpreter','latex')
xlabel('Strain ($\varepsilon$)','interpreter','latex')
ylabel('Stress (MPa)','interpreter','latex')
%axis([0,2600,0,950])
set(h5,'position',[50,50,800,500]);
set(gca,'fontsize',14)
axis auto
xlim([0,0.6])
ylim([0,850])
grid on
%}


%===================
% Plot overall data

figure(9)
boxplot([sigma_y_V,sigma_y_H],{'Vertical','Horizontal'})
hold on
figMaxStrain = notBoxPlot([sigma_y_V,sigma_y_H]);
d = [figMaxStrain.data];
set(d(2:2:end),'markerfacecolor',[0.9,0,0.9],'color',[0.4,0,0.4]);
set(d(1:2:end),'markerfacecolor',[0,0.9,0],'color',[0,0.4,0]);
set(d, 'markersize', 6);
set(gca,'fontsize',14);
ylabel('\sigma_y (MPa)')
grid on
hold off

%{
% use for plotting all of V1 and H1
%
% v and h vect's must be manually set currently
%vVect = [29,30,48]; % wall 2
%hVect = [26,27,46]; % wall 2

%vVect = [1,3,4,6]; % wall 3
%hVect = [25,28,47,49]; % wall 3

%vVect = [3,48];
%hVect = [46,47];

stressMeanV = mean(stressShort(vVect,:),1);
stressMaxV = max(stressShort(vVect,:));
stressMinV = min(stressShort(vVect,:));
strainMeanV = mean(strainShort(vVect,:),1);

% figure(4)
% shadedErrorBar(strainMeanV,stressShort(vVect,:),{@mean,@std},'lineprops','g')
% hold on
% plot(strainMeanV,stressMaxV,'b:')
% plot(strainMeanV,stressMinV,'b--')
% hold off
% xlabel('Strain (\epsilon)')
% ylabel('Stress (MPa)')
% xlim([0,0.45])
% legend('Range','Upper STDEV','Lower STDEV','Mean stress','Max stress','Min Stress')
% grid on

stressMeanH = mean(stressShort(hVect,:),1);
stressMaxH = max(stressShort(hVect,:));
stressMinH = min(stressShort(hVect,:));
strainMeanH = mean(strainShort(hVect,:),1);

% figure(5)
% shadedErrorBar(strainMeanH,stressShort(hVect,:),{@mean,@std},'lineprops','m')
% hold on
% plot(strainMeanH,stressMaxH,'r:')
% plot(strainMeanH,stressMinH,'r--')
% hold off
% xlabel('Strain (\epsilon)')
% ylabel('Stress (MPa)')
% legend('Range','Upper STDEV','Lower STDEV','Mean stress','Max stress','Min Stress')
% grid on
% 
% figure(6)
% vShadedFig = shadedErrorBar(strainMeanV,stressShort(vVect,:),{@mean,@std},'lineprops','g');
% hold on
% hShadedFig = shadedErrorBar(strainMeanH,stressShort(hVect,:),{@mean,@std},'lineprops','m');
% hold off
% set(gca,'fontsize',16)
% xlabel('Strain (\epsilon)')
% ylabel('Stress (MPa)')
% %legend([vShadedFig.patch],{'Vertical, +/- 1 standard deviation'})
% legend([vShadedFig.patch,hShadedFig.patch],...
%    {'Vertical, +/- 1 standard deviation','Horizontal, +/- 1 standard deviation'})
% xlim([0.0,0.45])
% ylim([0,800])
% grid on


%elongation at failure
% maxStrainV = max(strainShort(vVect,:),[],2);
% 
% maxStrainH = max(strainShort(hVect,:),[],2);
% 
% figure(7)
% boxplot([maxStrainV*100,maxStrainH*100],{'Vertical','Horizontal'})
% hold on
% figMaxStrain = notBoxPlot([maxStrainV*100,maxStrainH*100]);
% d = [figMaxStrain.data];
% set(d(2:2:end),'markerfacecolor',[0.9,0,0.9],'color',[0.4,0,0.4]);
% set(d(1:2:end),'markerfacecolor',[0,0.9,0],'color',[0,0.4,0]);
% set(d, 'markersize', 6);
% set(gca,'fontsize',14);
% ylabel('Max elongation, % strain')
% ylim([39,90])
% grid on
% hold off

%boxplot([maxStrainV*100,maxStrainH*100],{'Vertical','Horizontal'})
%ylabel('Max elongation, % strain')
%meanMaxStrain = mean([maxStrainV;maxStrainH]);
%stdDevMaxStrain = std([maxStrainV;maxStrainH]);

% figure(8)
% boxplot([youngsModulus(vVect)'/1000,youngsModulus(hVect)'/1000],{'Vertical','Horizontal'})
% hold on
% figMaxStrain = notBoxPlot([youngsModulus(vVect)'/1000,youngsModulus(hVect)'/1000]);
% d = [figMaxStrain.data];
% set(d(2:2:end),'markerfacecolor',[0.9,0,0.9],'color',[0.4,0,0.4]);
% set(d(1:2:end),'markerfacecolor',[0,0.9,0],'color',[0,0.4,0]);
% set(d, 'markersize', 6);
% set(gca,'fontsize',14);
% ylabel('E (MPa)')
% ylim([15,210])
% grid on
% hold off

%}
%{
jj = 0;
kk = 0;
while jj < length(specList)
    jj = jj + 1;
    specNum = specList(jj);
    for mm = 1:length(specName)
        if strcmp(specimenRefData(specNum).name,specName{mm})
            kk = kk + 1;
            break
        end
    end
    
    % UTS
    stressMaxes(kk) = max(stress(specNum,:));
    
    if specNum <= size(strainShort,1)
        youngsSorted(kk) = youngsModulus(specNum)/1000; % in GPa
        ysSorted(kk) = sigma_y(specNum);
    end
    
    specNameSorted{kk} = specimenRefData(specNum).name;
end

% plot uts's
% uts_bar = figure(1);
% bar(stressMaxes(1:length(specNameSorted)))
% set(gca,'XTick',1:length(specNameSorted),'xticklabel',specNameSorted);
% %xlabel(specName1)
% ylabel('UTS (MPa)')
% title('Max stresses')
% ylim([600,850])
% hold on
% line([1,length(specNameSorted)],[mean(stressMaxes(1:length(specNameSorted))),...
%     mean(stressMaxes(1:length(specNameSorted)))],'linewidth',2,'color','r');
% legend('UTS',['Mean = ',num2str(round(mean(stressMaxes(1:length(specNameSorted))))),' MPa'])
% hold off
% if strcmpi(savePlots,'yes')
%     saveas(uts_bar,fullfile(plotTLD,'UTS_Bar'),'fig');
%     saveas(uts_bar,fullfile(plotTLD,'UTS_Bar'),'png');
% end

% plot E's
% E_bar = figure(2);
% bar(youngsSorted)
% set(gca,'XTick',1:length(specNameSorted),'xticklabel',specNameSorted);
% %xlabel(specName1)
% ylabel('E (GPa)')
% title('Elastic Modulus')
% ylim([0,250])
% hold on
% line([1,length(specNameSorted)],[mean(youngsSorted),mean(youngsSorted)],'linewidth',2,'color','r');
% legend('E',['Mean = ',num2str(round(mean(youngsSorted))),' GPa'])
% hold off
% if strcmpi(savePlots,'yes')
%     saveas(E_bar,fullfile(plotTLD,'E_bar'),'fig');
%     saveas(E_bar,fullfile(plotTLD,'E_bar'),'png');
% end

% plot YS's
% YS_bar = figure(3);
% bar(ysSorted)
% set(gca,'XTick',1:length(specNameSorted),'xticklabel',specNameSorted);
% %xlabel(specName1)
% ylabel('Yield Stress (0.2% offset) (MPa)')
% title('Yield Stresses')
% ylim([200,450])
% hold on
% line([1,length(specNameSorted)],[mean(ysSorted),mean(ysSorted)],'linewidth',2,'color','r');
% legend('\sigma_y',['Mean = ',num2str(round(mean(ysSorted))),' MPa'])
% hold off
% if strcmpi(savePlots,'yes')
%     saveas(YS_bar,fullfile(plotTLD,'YS_bar'),'fig');
%     saveas(YS_bar,fullfile(plotTLD,'YS_bar'),'png');
% end

figure(9)
boxplot([sigma_y_V,sigma_y_H],{'Vertical','Horizontal'})
hold on
figMaxStrain = notBoxPlot([sigma_y_V,sigma_y_H]);
d = [figMaxStrain.data];
set(d(2:2:end),'markerfacecolor',[0.9,0,0.9],'color',[0.4,0,0.4]);
set(d(1:2:end),'markerfacecolor',[0,0.9,0],'color',[0,0.4,0]);
set(d, 'markersize', 6);
set(gca,'fontsize',14);
ylabel('\sigma_y (MPa)')
grid on
hold off
%}

%
% Only format once, not for every specimen
% =================================================================
% Figure formatting and saving
% =================================================================
% Update names/axes depending on the choices used for plotting
%
if exist('h1','var')
    h1 = figure(length(specimenRefData)+1);
    title('Continuous')
    % add the reference data
    hold on
    plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
    hold off
    legend([disLegStr,'Wrought'])
    xlabel('Strain ($\varepsilon$)','interpreter','latex')
    ylabel('Stress (MPa)','interpreter','latex')
    %axis([0,2600,0,950])
    set(h1,'position',[50,50,800,500])
    set(gca,'fontsize',14)
    axis auto
    grid on
    if strcmpi(savePlots,'yes')
        saveas(h1,fullfile(plotTLD,'Continuous_SS'),'fig');
        saveas(h1,fullfile(plotTLD,'Continuous_SS'),'png');
    end
end

if exist('h2','var')
    h2 = figure(length(specimenRefData)+2);
    title('Discrete')
    % add the ref data
    hold on
    plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
    hold off
    legend([disLegStr,'Wrought'])
    xlabel('Strain ($\varepsilon$)','interpreter','latex')
    ylabel('Stress (MPa)','interpreter','latex')
    %axis([0,2600,0,950])
    set(h2,'position',[50,50,800,500])
    set(gca,'fontsize',14)
    axis auto
    xlim([0,0.6])
    grid on
    if strcmpi(savePlots,'yes')
        saveas(h2,fullfile(plotTLD,'Discrete_SS'),'fig');
        saveas(h2,fullfile(plotTLD,'Discrete_SS'),'png');
    end
end

if exist('h3','var')
    h3 = figure(length(specimenRefData)+3);
    title('Vertical')
    % add the reference data
    hold on
    plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
    hold off
    legend([vLegStr,'Wrought'])
    xlabel('Strain ($\varepsilon$)','interpreter','latex')
    ylabel('Stress (MPa)','interpreter','latex')
    %axis([0,2600,0,950])
    set(h3,'position',[50,50,800,500])
    set(gca,'fontsize',14)
    axis auto
    grid on
    if strcmpi(savePlots,'yes')
        saveas(h3,fullfile(plotTLD,'Vertical_SS'),'fig');
        saveas(h3,fullfile(plotTLD,'Vertical_SS'),'png');
    end
end

if exist('h4','var')
    h4 = figure(length(specimenRefData)+4);
    title('Horizontal')
    % add the reference data
    hold on
    plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
    hold off
    legend([hLegStr,'Wrought'])
    xlabel('Strain ($\varepsilon$)','interpreter','latex')
    ylabel('Stress (MPa)','interpreter','latex')
    %axis([0,2600,0,950])
    set(h4,'position',[50,50,800,500])
    set(gca,'fontsize',14)
    axis auto
    grid on
    if strcmpi(savePlots,'yes')
        saveas(h4,fullfile(plotTLD,'Horizontal_SS'),'fig');
        saveas(h4,fullfile(plotTLD,'Horizontal_SS'),'png');
    end
end

if exist('h5','var')
    h5 = figure(length(specimenRefData)+5);
    title('Wall 1')
    % add the reference data
    hold on
    plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
    hold off
    legend([oneLegStr,'Wrought'])
    xlabel('Strain ($\varepsilon$)','interpreter','latex')
    ylabel('Stress (MPa)','interpreter','latex')
    %axis([0,2600,0,950])
    set(h5,'position',[50,50,800,500]);
    set(gca,'fontsize',14)
    axis auto
    grid on
    if strcmpi(savePlots,'yes')
        saveas(h5,fullfile(plotTLD,'Wall_1_SS'),'fig');
        saveas(h5,fullfile(plotTLD,'Wall_1_SS'),'png');
    end
end

if exist('h6','var')
    h6 = figure(length(specimenRefData)+6);
    title('Wall 2')
    % add the reference data
    hold on
    plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
    hold off
    legend([twoLegStr,'Wrought'])
    xlabel('Strain ($\varepsilon$)','interpreter','latex')
    ylabel('Stress (MPa)','interpreter','latex')
    %axis([0,2600,0,950])
    set(h6,'position',[50,50,800,500])
    set(gca,'fontsize',14)
    axis auto
    grid on
    if strcmpi(savePlots,'yes')
        saveas(h6,fullfile(plotTLD,'Wall_2_SS'),'fig');
        saveas(h6,fullfile(plotTLD,'Wall_2_SS'),'png');
    end
end

if exist('h7','var')
    h7 = figure(length(specimenRefData)+7);
    title('Wall 3')
    % add the reference data
    hold on
    plot(refStrain(1:end-12),refStress(1:end-12),'color','k','linewidth',2)
    hold off
    legend([threeLegStr,'Wrought'])
    xlabel('Strain ($\varepsilon$)','interpreter','latex')
    ylabel('Stress (MPa)','interpreter','latex')
    %axis([0,2600,0,950])
    set(h7,'position',[50,50,800,500])
    set(gca,'fontsize',14)
    axis auto
    grid on
    if strcmpi(savePlots,'yes')
        saveas(h7,fullfile(plotTLD,'Wall_3_SS'),'fig');
        saveas(h7,fullfile(plotTLD,'Wall_3_SS'),'png');
    end
end
%}