%% Collect Linux\Slurm metadata
disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
disp('Job is running on node:')
[~, node] = system('hostname');
disp(node)
disp('Job is run by user:')
[~, user] = system('whoami');
disp(user)
disp('Current slurm jobs of current user:')
[~, sq] = system(['squeue -u ', user]);
disp(sq)
tic
disp(['Start: ' datestr(now, 'yyyymmdd_HHMMSS')])
disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')

DataTransfer = 0;

if DataTransfer
    error('skipping image analysis because DataTransfer = 1')
end

%% Flags

delete(gcp('nocreate'))
myCluster = parcluster('local');
AvailableWorkers = myCluster.NumWorkers;
if AvailableWorkers >= 28
    pool = parpool(28)
else
    pool = parpool(1)
end

addpath(genpath('/work/projects/lcsb_hcs/Library/hcsforge'))

if ~exist('InPath') % if Inpath is provided  via command line, use that one
    %InPath = '/mnt/IrisHCS/Data/AxelChemla/CaNeuronsReinhard/AC_20220225_Fluo4Direct_Fluo4BaptaNeud32_plate96_in';
    InPath = '/mnt/IrisHCS/Data/AxelChemla/CaNeuronsReinhard/AC_20220812_Fluo4Direct_mat_iono_diff622_in';
    %InPath = '/mnt/IrisHCS/Data/AxelChemla/CaNeuronsReinhard/AC_20220225_Fluo4Direct_Fluo4BaptaNeud32_plate96_in';
end

MesPath = ls([InPath, '/*.mes']); MesPath = MesPath(1:end-1); % remove line break
MetaData = f_CV8000_getChannelInfo(InPath, MesPath);

if ~exist('OutPath') % if Outpath is provided  via command line, use that one
    OutPath = '/mnt/IrisHCS/Data/AxelChemla/CaNeuronsReinhard/AC_20220812_Fluo4Direct_mat_iono_diff622_out_tuning20220908';
    %OutPath = '/mnt/IrisHCS/Data/AxelChemla/CaNeuronsReinhard/AC_20220225_Fluo4Direct_Fluo4BaptaNeud32_plate96_out_tuning20220908';
end

%% Prepare folders
mkdir(OutPath)
PreviewPath = [OutPath, filesep, 'Previews'];
mkdir(PreviewPath)

%% Log
f_LogDependenciesLinux(mfilename, OutPath)



%% Load Metadata
ObjectsAll = {};
InfoTable = MetaData.InfoTable{:};
Wells = unique(InfoTable.Well);
fieldProgress = 0;
for w = 1:numel(Wells)
    WellThis = Wells{w};
    InfoTableThisWell = InfoTable(strcmp(InfoTable.Well, WellThis),:);
    FieldsThisWell = unique(InfoTableThisWell.Field);
    for f = 1:numel(FieldsThisWell)
        fieldProgress = fieldProgress + 1;
        FieldThis = FieldsThisWell{f};
        InfoTableThisField = InfoTableThisWell(strcmp(InfoTableThisWell.Field, FieldsThisWell{f}),:);
        ChannelsThisField =  unique(InfoTableThisField.Channel);
        ImPaths = cell(1, numel(ChannelsThisField));
        for c = 1:numel(ChannelsThisField)
            ChannelThis = ChannelsThisField{c};
            InfoTableThisChannel = InfoTableThisField(strcmp(InfoTableThisField.Channel,ChannelThis),:);
            InfoTableThisChannel = sortrows(InfoTableThisChannel, 'Plane', 'ascend');
            chThisPaths = cell(numel(ChannelsThisField),1);
            for p = 1:height(InfoTableThisChannel)
                chThisPaths{p} = InfoTableThisChannel{p, 'file'}{:};
            end
            ImPaths{c} = chThisPaths;
            MesFile = MetaData.MeasurementSettingFileName;
        end
       FieldMetaData{fieldProgress} = {ImPaths, MesFile, Wells{w}, FieldsThisWell{f}};
    end
end

listFields = cell2table(vertcat(FieldMetaData{:}))
disp('Debug point')
% ionomycine in D2 to D6
for i = 1:numel(FieldMetaData)% C02 --> i = 2
    try
        i
        FieldThis = FieldMetaData{i}{4};
        WellThis = FieldMetaData{i}{3};

        ch1files = sort(FieldMetaData{i}{1}{1});
        ch1Collector = cellfun(@(x) imread(x), ch1files, 'UniformOutput', false);
        ch1 = cat(3,ch1Collector{:}); % vol(ch1, 300, 1000) %Hoechst

        ch2files = FieldMetaData{i}{1}{2};
        ch2Collector = cellfun(@(x) imread(x), ch2files, 'UniformOutput', false);
        ch2 = cat(3,ch2Collector{:}); % vol(ch2, 0, 25000) %Fluo4
        %vi(ch2)

        MesFile = FieldMetaData{i}{2};
        WellThis = FieldMetaData{i}{3};
        f_imageAnalysis(ch1, ch2, WellThis, FieldThis, MesFile, PreviewPath);
    catch
       continue
    end
end
disp('Image analysis completed successfully')

f_plotAllKinetics(OutPath)
disp('Script completed successfully')
