%% Instructions: For each sample, create one folder containing HEX tif images and one folder containing GFP tif images. Run the script. When prompted to choose a folder, select the parent folder containing all the subfolders with the images.
%% Choose parent folder containing image data

clc
datafolder = uigetdir('Choose the folder containing your data');
datafolderinfo = dir(datafolder);
datafolderinfo(~[datafolderinfo.isdir]) = [];
tf = ismember( {datafolderinfo.name}, {'.', '..'});
datafolderinfo(tf) = [];

p = 1;
q = length(datafolderinfo);

%% Analyze each sample

for p = 1:q;
    fluor = fullfile(datafolder,datafolderinfo(p).name);
    cd(fluor);
    fluorList = dir(fluor);
    fluorList(~[fluorList.isdir]) = [];
    fN = ismember( {fluorList.name}, {'.', '..'});
    fluorList(fN) = [];
    l = 1;
    m = length(fluorList);
 
    %% Analyze images in each subfolder

    for l = 1:m;
        sample = fullfile(datafolder,datafolderinfo(p).name,fluorList(l).name);
        cd(sample);
        sampleNames = dir('*.jpg');
        excelI = [];
        excelT = [];
        i = 1;
        k = length(sampleNames);
    
        %% Calculate Average Green Intensity of Each Image
              for i = 1:k;
                  myimage = imread(sampleNames(i).name);
                  myimagegreen = myimage(:,:,2);
                  meanI = mean2(myimagegreen);
                  excelI = [excelI; meanI];
                  i = i + 1;
              end

        %% Process Data and Write to Excel

        [a, b, c] = fileparts(sample);
        header = {b};
        excelfilename = strcat(datafolder,'_analysis.xlsx');
        alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        z = l + 2;
        column = alphabet(z);
        cellH = strcat(column,'1');
        cellD = strcat(column,'2');
        x = datafolderinfo(p).name;
        xlswrite(excelfilename,header,x,cellH);
        xlswrite(excelfilename,excelI,x,cellD);

    end
    
    p = p + 1;
end

header = {'Cycle'};
cycle = [1:60]';
excelfilename = strcat(datafolder,'_analysis.xlsx');
cellH = strcat('B','1');
cellD = strcat('B','2');
sheetF = datafolderinfo(1).name;
sheetH = datafolderinfo(2).name;
xlswrite(excelfilename,header,sheetF,cellH);
xlswrite(excelfilename,cycle,sheetF,cellD);
xlswrite(excelfilename,header,sheetH,cellH);
xlswrite(excelfilename,cycle,sheetH,cellD);