%% 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('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')


MitoTrackerWells = {'C02', 'B01'}
CellTrackerWells = {'C02', 'B01'}


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'))
addpath(genpath('/work/projects/lcsb_hcs/Library/hcsIris'))

if ~exist('InPath') % if Inpath is provided  via command line, use that one
    %InPath = '/work/projects/lcsb_hcs/Data/AxelChemla/TMRE_20xIPSderivedNeurons/templateTMRE20200925_in';
    %InPath = '/mnt/AtlasHCS/YokogawaCV8000Horst/CellPathfinder/Paul/AC_20201203_CellTrMitoTrCellRox_60x_ValinoAntimycin_20201203_161147/AssayPlate_PerkinElmer_CellCarrier-96'
    %'InPath = '/mnt/AtlasHCS/YokogawaCV8000Horst/BTSData/MeasurementData/Paul/JO_20201202_CellTracker_CellROX_v2_Mamasyn-run1_20201202_133814/AssayPlate_PerkinElmer_CellCarrier-96'
    %InPath = '/mnt/IrisHCS/Data/JochenOhnmacht/CellRoxCellTracker_iPSneurons/JO_20201202_CellTracker_CellROX_v2_Mamasyn-run1_20201202_133814'
    %InPath = '/mnt/AtlasHCS/YokogawaCV8000Standalone/CellPathfinder/Axel/AC_20210118_CellTrTrCellRox_60x_SA_20210118CroxNeuD28_20210118_181322/TemplateAssayCellCarrier96'
    InPath = '/mnt/IrisHCS/Data/AxelChemla/CellROXCellTracker/AC_20210118_CellTrTrCellRox_60x_SA_20210118CroxNeuD28_20210118_181322_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 = '/work/projects/lcsb_hcs/Data/AxelChemla/TMRE_20xIPSderivedNeurons/templateTMRE20200925_out';
    %OutPath = '/mnt/D/tmp/AxelCellRox20210106';
    %OutPath = '/mnt/AtlasHCS/HCS_Platform/Data/AxelChemla/CaNeuronsReinhard/AC_20201203_CellTrMitoTrCellRox_60x_ValinoAntimycin_20201203_161147_out';
    %OutPath = '/mnt/D/tmp/JochenCellRox20210114';
    OutPath = '/mnt/D/tmp/Axel20210201';
end

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

%% Log
f_LogDependenciesLinux(mfilename, OutPath)

%% get csv
%[~, csvpath] = system(['find ' InPath '/*.csv']);
Layout = Iris_GetLayout(InPath)

%% Load Metadata
ObjectsAll = {};
%MetaData = f_CV8000_getChannelInfo(InPath, MesPath);
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'}{:};
                %for t = 1:height()
            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')


%parfor i = 1:4 %1:numel(FieldMetaData)% C02 --> i = 55 
%parfor i = 1:numel(FieldMetaData)% C02 --> i = 55 
parfor i = 1:numel(FieldMetaData)% C02 --> i = 55 
%for i = 24%1:numel(FieldMetaData)% C02 --> i = 55 
%for i = 1
%parfor i = 1:numel(FieldMetaData)
%parfor i = 1: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, 0, 2000) Hoechst

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

        ch3files = FieldMetaData{i}{1}{3};
        ch3Collector = cellfun(@(x) imread(x), ch3files, 'UniformOutput', false);
        ch3 = cat(3,ch3Collector{:}); % vol(ch3, 0, 500) CellRox

        MesFile = FieldMetaData{i}{2};
        WellThis = FieldMetaData{i}{3};
        %FieldThis = FieldMetaData{i}{4};
        Objects = f_imageAnalysis(ch1, ch2, ch3, WellThis, FieldThis, PreviewPath, Layout);
        ObjectsAll{i} = Objects;
    catch
       continue
    end
end

data = vertcat(ObjectsAll{:});
writetable(data, [OutPath, filesep, 'data.csv']);
disp('Script completed successfully')
