%% Find all folders
% you may have to remove any folder that do not contain data or that does not interest you. Just have a look at the variable 'folders' after running the section.

path = '/Volumes/apt-data';

% extract all subfolders of the path
contents = dir(path);
folders = contents([contents(:).isdir]);
folders = folders(~ismember({folders(:).name},{'.','..'})); % remove hidden folders


%
% analyse H content in all datasets with range figure

numDatasets = length(folders)

for ds = 1:numDatasets

    %RANGES
    disp(['file ' num2str(ds) ': ' folders(ds).name]);
    dirName = [folders(ds).folder '/' folders(ds).name];
    fileList = dir(dirName);
    fileList = struct2cell(fileList);
    fileList = string(fileList(1,:));
    isFileName = contains(fileList,"fig");
    if not(any(isFileName))
        disp([folders(ds).name ' has no range file']);
    else

        % find metadata file in directory
        rangeFileName = string(dirName) + "/" + fileList(isFileName);

        % loading of ranges from figure
        rangeFigureVisibility = 'invisible'; % or 'visible'
        rngFig = openfig(rangeFileName,rangeFigureVisibility);
        spec = findobj( get(rngFig,'Children'), '-depth', 2, 'DisplayName', 'mass spectrum');
        rangeTable{ds,1} = rangesExtractFromMassSpec(spec);
        close(rngFig);


        %DATASET
        isFileName = contains(fileList,[".epos",".EPOS"]);
        posFileNames(ds,1) = string(dirName) + "/" + fileList(isFileName);
        pos = posToTable(posFileNames(ds,1));

        %CONCENTRATION CALCULATION
        pos = posAllocateRange(pos,rangeTable{ds,1},'decompose');
        conc{ds,1} = posCalculateConcentrationSimple(pos,.37,{'unranged'},char(fileList(isFileName)));
    end



end


%
% extract H concentrations and main elements

conc2 = conc{1}(conc{1}.format == 'concentration',:);
for ds = 2:length(conc)
    if not(isempty(conc{ds}))
        conc2 = outerjoin(conc2,conc{ds}(conc{ds}.format == 'concentration',:),'MergeKeys',true);
    end
end

%
% sort and find base element

conc2 = sortrows(conc2,'H','descend');
baseConc = max((table2array(conc2(:,5:end)))')';

ionCats = string(conc2.Properties.VariableNames);
for i=1:height(conc2)
    isBase(i) = find(table2array(conc2(i,5:end)) == baseConc(i)) + 4;
    base(i) = ionCats(isBase(i));
end

%
% match property variable to concentration analysis variable (Voltage/Laser, base temp, laser energy / pulse fraction)

% find matching dataset name
runNamesFolder = struct2table(folders); runNamesFolder = string(runNamesFolder.name);
runNamesConc = extractBefore(string(conc2.volume),10); %takes only the first 9 digits of the run name (LEAP)
match = arrayfun(@(x) find(contains(runNamesFolder,x)), runNamesConc);

%
% match property from csv file (if applicable)

%csv file loaded as 'meta'
runNamesConc = extractBefore(string(conc2.volume),10); %takes only the first 9 digits of the run name (LEAP)
match = arrayfun(@(x) find(contains(meta.RunID,x)), runNamesConc);

isVoltage = isnan(meta.LaserPulseEnergynJ(match));
endVoltage = meta.VoltageV(match);
specimenTemperature = meta.TemperatureK(match);

%


% add property
%conc2 = addvars(conc2,pulseType(match),'NewVariableNames','pulseType');

%
% plot

concPlot = conc2(isVoltage,:);
basePlot = base(isVoltage);

figure
yyaxis left
p(1) = scatter(1:height(concPlot),concPlot.H*1e6,'x');%,'MarkerEdgeColor',[0 1 1],'DisplayName','H');
hold on
%p(2) = scatter(1:height(conc2),conc2.H2*1e6,'x','MarkerEdgeColor',[1 0 1],'DisplayName','H_2');
ax = gca;
ax.YScale = 'log';
%p(1).Marker = 'x'
%p(2).Marker = 'o'

for i = 1:height(concPlot)
    %if isVoltage(i)
    %    pt = "V";
    %    textColor = 'b';
    %else
    %    pt = "L";
    %    textColor = 'r';
    %end
    textColor = 'k';
    elementTxt(i) = text(i,1.1e5,0,basePlot(i),"FontAngle","normal","Rotation",90,"Color",textColor);

    %pulseTypeTxt(i) = text(i,3e5,pt,"Rotation",0);

end

xlabel 'ordered dataset number'
ylabel 'ionic H content [ppm]'
box on
legend

yyaxis right
scatter(1:height(concPlot),specimenTemperature(isVoltage),'.','DisplayName','T');
ylabel 'specimen temperature [K]'