% requires a reference img ".jpg" and it should be the only .jpg in your working directory
% hard codes 250 frames per each movie file
% note the parsing of the videos requires some hardcoded format from the videos
% creates a data_info file that can be save to track how the treatments correspond to the frame # 
% ex: the video named "doma_water_2dpf_1_basln_1" -> goes under the column "doma_water_2dpf" and the string "dpf" is the parser

disp('Select folder that  contains reference video')
path = uigetdir(); % select folder that contains the movies
cd(path)
[reference_img pathname]=uigetfile('*.jpg','Select Reference Img');

background= imread(reference_img);
background= rgb2gray(background);
            
%% get treatment vids to convert
%  required naming format -> treatment followed by dpf then plate 

disp('Select folder that contains movies to analyze')
path = uigetdir(); % select folder that contains the movies
cd(path)

disp('Num frames set to 250')
numframes = 250; % does not need to be hardcoded, but processing is easier that pulling it out

list= dir('*.mov'); % grabs a list of the newly renamed movies

%% subtract background from frames using reference video
data_info =cell(300, 25); %initiates a cell to populate treatment data

classifier = 'placeholder'

for idx = 1:length(list)   % go through every movie file
    filename =strsplit(list(idx).name, '_');
    vid_name = strrep(list(idx).name, '.mov', '');
    filename{end} = strrep(filename{end}, '.mov' , ''); %removes .mov extension

    %read the video file 
    vidObj= VideoReader(list(idx).name);

    %numframes = vidObj.NumberOfFrames;
    vidHeight = vidObj.Height;
    vidWidth = vidObj.Width;
   
    if numel(find(strcmp(filename(:), 'label'))) % do not convert label movies into jpeg stack
        continue
    else  
        %disp('edits video')
        %reads video frame by frame, converts in gray scale tiffs (grayscale is done using
        %rgb2gray)
        frame = 0 ; % starts frame off at 0
        
        while hasFrame(vidObj)
            img = rgb2gray(readFrame(vidObj)); 
            subtracted = imcomplement(imsubtract(background, img));
            contrast_img = imadjust(subtracted ,[0.6 1], [0.2 0.95], []);
            
            smoothed = wiener2(contrast_img,[2 2]);
                         
            %for the first frame, find associated file name, in some
            %instances grab this file name of image, and store in data_info
            %cell array
            if frame == 0 %if going through movie for the first time
                clear classifier
                convert = 'yes';
                
                %grab treatment 
                %assumes dpf index is the cut-off
                dpf_idx = find(~cellfun(@isempty,strfind(filename(:),'dpf'))) %get index with 'dpf' in it
                
                if isempty(dpf_idx) %if there is no dpf in the label... 
                    %the classifier is just the first label
                    if exist('classifier') % if the folder has already been created  
                        classifier = [classifier,'_',filename{1}];
                    else
                        classifier = [filename{1}];
                    end
                end
                
                for idx2 = 1: (dpf_idx-1) 
                    if exist('classifier') % if the folder has already been created  
                        classifier = [classifier,'_',filename{idx2}];
                    else
                        classifier = [filename{idx2}];
                    end
                    
                end
                        
                %grab day injected
                if ~isempty(dpf_idx)
                    dpf= filename{dpf_idx};
                    classifier = [classifier, '_', dpf];
                end
               
                col_names = {};
                
                %classifier = 'test'
                
                for c = 1: size(data_info, 2) %goes through the columns in fdata info file
                    if ~isempty(data_info{1,c}) 
                        treatmentName = [data_info{1,c}];% grabs string in the cell array
                        col_names = [col_names {treatmentName}];
                    end
                end   

                if ~any(strcmp(col_names, classifier)) % no column with this name in the case that doesn't folder doesn't exist
                    index = find(cellfun('isempty', data_info(1,:)), 1); % finds the first empty column
                    data_info{1, index} = classifier ; % first element in the column is name of the parent folder
                    data_info{2, index} = vid_name; % second column (second element is first file in folder (treatment)
                    frame_add = 0;

                else
                    col_index = find(strcmp(data_info(1,:), classifier)); % get column index for corresponding folder
                    row_index = find(cellfun('isempty', {data_info{:,col_index}}), 1); % get first empty row in column
                    data_info{row_index, col_index} = vid_name;
                    frame_add = (row_index- 2) * numframes;
                end
                clear col_names
            end

            if strcmp(convert,'yes')
                if ~exist([path '/' classifier], 'dir')
                    mkdir([path '/' classifier]);
                end
                index =  frame + frame_add;
                i = sprintf('%04d',index);
                imwrite(smoothed ,[classifier '/' classifier '_' num2str(i) '.jpg'],'Quality', 75);

                %imwrite(contrast_img ,[classifier '/' classifier '_' num2str(i) '.jpg'],'Quality', 75);
            end

         frame = frame + 1;   
        end
    end
end

disp('finished processing vidoes')

%% write the data 
data_info_copy = data_info;

temp_col = data_info_copy(1,:)
colIdx = find(cellfun(@isempty,temp_col),1) %finds first col that is empty

emptyCells = cellfun(@isempty,data_info_copy); %logical for empty cells

%finds the last row with any data in it
rowIdx = 0
for col = 1: colIdx
    temp_row = data_info_copy(:,col); %grabs data from rows within the column
    tempIdx = find(cellfun(@isempty,temp_row),1) ; %first row with empty data
    if tempIdx > rowIdx
        rowIdx = tempIdx - 1 %stores last row with data
    end
end

%calculates the frame number corresponding to each video
for c = 1: rowIdx %goes through the rows with data in it
        if c == 1
            data_info_copy{c, colIdx + 1} = 'frame_number_start'; %header
            data_info_copy{c, colIdx + 2} = 'frame_number_end'; %header
            data_info_copy{c, colIdx + 3} = 'movie_num'; %header

        else
            newCol = (c - 2) * numframes; %calculates the numframes
            data_info_copy{c, colIdx + 1} = newCol;
            data_info_copy{c, colIdx + 2} = newCol + 249;
            frameCol = c -2; %lists the track number associated with video (starting at 0)
            data_info_copy{c, colIdx + 3 } = frameCol;

        end
    
end




filename = strsplit(path, '/');
export_data = cell2table(data_info_copy);
writetable(export_data, [path '/' filename{end} '_data_order_info.csv']);

