"""This is a matlab script that was used by John Chandler to analyze fast (Sparse) pws data. This functionality should be added into the main code."

% Reduced Wavelength (Whole Slide PWS) Analysis Code

% John Chandler

% 3-13-15



%% Get all measurements in the experiment directory

clear; clc; close all;



% Experiment directories

fldrs = {'E:\IRIS computer\Greta\2015\4-15-15\ss1',...

    'E:\IRIS computer\Greta\2015\4-15-15\ss1\overnight',...

    'E:\IRIS computer\Greta\2015\4-16-15\CVuntreated',...

    'E:\IRIS computer\Greta\2015\4-16-15\CVuntreated\overnight'...

    'E:\IRIS computer\Greta\2015\4-17-14\AoAF\SIRT1TNF'...

    'E:\IRIS computer\Greta\2015\4-17-14\AoAF\SIRT1TNF\overnightTNF'...

    'E:\IRIS computer\Greta\2015\4-20-15\AoAF\CVTNF'...

    'E:\IRIS computer\Greta\2015\4-20-15\AoAF\CVTNF\overnight'...    

        };



% Specify normalization measurement number

normalization_number = 997;



% Set the dark count, for live cell PWS system

darkCount = 50; 



% Wavelengths used for reduced wavelength acquisition/analysis

wv_range = [500 525 540:3:559 575 600 625 650 675 700];

numWVs = length(wv_range);



% Get the number of experiments

num_experiments = length(fldrs);



% get the current directory

currdir = cd;



% notify user that program is working

display('Analyzing reduced wavelength data...');



% True if measurement is a full spectrum PWS data cube

isFullSpectrumMirror = false;

isFullSpectrumCell = false;



%%%% Must manually set exposure times if isFullSpectrum = true



% Analyze all the experiments

for i = 1:num_experiments



    % Get a list of cells in the experiment folder

    listCells = dir([fldrs{i}, '/Cell*']);

    

    % Determine the quanity of cells in the experiment folder

    quantityCells = length(listCells);

    

    % Check if normalization measurement exists, if it does not skip the

    % current experiment

    if ~exist([fldrs{i},'/Cell', num2str(normalization_number)],'dir')

        display(['No normalization measurement found for experiment',num2str(i)]);

        return

    else

        % Go to normalization measurement directory

        cd([fldrs{i},'/Cell', num2str(normalization_number)]);

        if isFullSpectrumMirror

            exposureMirror = 60;

            

            load('WV.mat')

            load('image_cube.mat')

            [sizeCubeX, sizeCubeY, ~] = size(image_cube);

            cubeMirror = zeros(sizeCubeX,sizeCubeY,numWVs);

            wv_indx = zeros(1,numWVs);

            for j = 1:numWVs

                wv_indx(j) = find(WV == wv_range(j));

                cubeMirror(:,:,j) = image_cube(:,:,wv_indx(j));

            end

                        

        else

        

        % Load the info file for the normalization measurement

        load('info3.mat')

        sizeCubeX = info3(3);

        sizeCubeY = info3(4);

        exposureMirror = info3(2);

        clear info3

            

        % Use multibandread to load the image_cube from a binary file

        cubeMirror = multibandread('image_cube',[sizeCubeX,sizeCubeY,...

            numWVs],'int16',0,'bsq','ieee-le');

        end

        % Convert the cubeMirror to single

        cubeMirror = single(cubeMirror);

        

        % Exposure normalize normalization measurement

        cubeMirror = (cubeMirror - darkCount)./exposureMirror;

                 

    end

            

    % for each cell in the experiment folder

    count = 0;

    for ii = 1:quantityCells

        

        count = count+1;

        clc

        display(['Completed Experiment' num2str(i), ', Cell' num2str(count)]);

        

        % go to the first cell in the list

        cd([fldrs{i}, '/', listCells(ii).name]);

        

        if exist('p0_sd_lambda_997.mat','file')

            continue % skip this cell if it has already been analyzed

        end

        

        if isFullSpectrumCell

            exposureCell = 100;

            

            load('WV.mat')

            load('image_cube.mat')

            cubeCell = zeros(sizeCubeX,sizeCubeY,numWVs);

            for j = 1:numWVs

                cubeCell(:,:,j) = image_cube(:,:,wv_indx(j));

            end

            

            

        else

        

        % Load the info file

        load('info3.mat')

        sizeCubeX = info3(3);

        sizeCubeY = info3(4);

        exposureCell = info3(2);

        

        % Use multibandread to load the image_cube from a binary file

        cubeCell = multibandread('image_cube',[sizeCubeX,sizeCubeY,...

            numWVs],'int16',0,'bsq','ieee-le');

        end

        % Convert the cubeMirror to single

        cubeCell = single(cubeCell);

        

        % Exposure normalize normalization measurement

        cubeCell = (cubeCell - darkCount)./exposureCell;

        

        % Normalize the cell by the normalization measurement

        cubeCell = cubeCell./cubeMirror;

         

        %% Filter and polyfit the reduced wavelength range normalized signal

        

        % Reshape the cube cell from a 3D matrix to a 2D array.  This is

            % required as some functions may operate only on 1D vectors and 2D

            % arrays.

            cubeCell = permute(cubeCell, [3 1 2]);

            cubeCell = reshape(cubeCell, numWVs, []);

            % Set the filter parameters

            [b, a] = butter(4,0.15);

            % Filter the cell cube

            cubeCell = filtfilt(b, a, double(cubeCell));

           

            if size(wv_range,1) == 1;

                wv_range = shiftdim(wv_range);

            end

            

            % Perform a low-order polynomial fit for each signal.

            % Create Vandermonde matrix, V.

            V = bsxfun(@power,wv_range,0:0);

            % Calculate the multiplier-matrix, M, by matrix-multiplying V with the

            % pseudo-inverse of V.

            M = V*pinv(V);

            % Obtain the polynomial fit by multiplying the reshaped cubeCell by M.

            cubePoly = M*cubeCell;

            % Explanation:

            % V*c = Y;

            % c = pinv(V)*Y where pinv(v) = [((v'*v)^-1)*v'];

            % Yp = V*c = V*pinv(V)*Y;

            % Yp = M*Y where M = V*pinv(V);

            

            % Remove the polynomial fit from filtered cubeCell.

            cubeCell = cubeCell - cubePoly;

            

            % Clear cubePoly, as it is no longer needed.

            clear cubePoly;

            

            % Return the cell cube to the original dimensions

            cubeCell = reshape(cubeCell, numWVs, sizeCubeX, sizeCubeY);

            cubeCell = permute(cubeCell, [2 3 1]);

            

            %% SD_lambda analysis

            

            % Take the standard deviation over the wavelength dimension

            sd_lambda = std(cubeCell, 0, 3);

            % Create averaging filter

            h = fspecial('average', [4 4]);

            % Filter the sd_lambda image with the averaging filter

            sd_lambda = imfilter(sd_lambda,h);

%             figure; imagesc(sd_lambda,[0.003, 0.04]); colormap('jet')

            

            % Save the sd_lambda result

            save ('p0_sd_lambda_997.mat','sd_lambda')

            

   

    end

    % Update progress

    display(['Analysis complete for experiment ' num2str(i), ' of ' num2str(num_experiments)]);

    

end

