%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The Transformation Code
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clearvars

% Read the bottle sheet and store it in 'tab2':
tab2 = table2struct(readtable('The bottles sheet.xlsx'));

% Loop through all the Go Pro videos listed in tab2:
for i = 1:numel(tab2)
    
    % Read the name of the first Go Pro video in the column 'Video' in
    % the tab2 structure:
    Name = tab2(i).Video;
    
    % L will loop through the two plastic items: A and B
    for L = 'AB'
        
        % In the current folder read the Excel file (which is the output from Kinovea)
        % with the following name and write it to 'Data':
        Data = readtable([Name, '-', L, '.xlsx']);
        
        % Put the first two columns of the Data table in a table called
        % Video_xy (and convert to an array):
        Video_xy = table2array(Data(:,1:2));
        % Put the last column of the Data table in a table called
        % Video_t (and convert to an array):
        Video_t = table2array(Data(:,3));
        
        % Remove the headers in the upper 3 rows from both Video arrays:
        Video_xy([1,2,3],:) = [];
        Video_t([1,2,3],:) = [];
        
        % Find empty time slots in the Video_xy and Video_t tables and, 
        % if present,remove them:
        fempty = cellfun(@isempty,Video_t);
        Video_xy(fempty,:) = [];
        Video_t(fempty,:) = [];
        
        % Convert the times from the time Video_t array:
        time = datetime(datevec(Video_t,'HH:MM:SS:FFF'));
        Time = seconds(time-time(1));
        
        % Find the total number of time steps:
        time_steps = size(time,1);
               
        % Path of the plastic item in RELATIVE pixel coordinates (w.r.t. 
        % the start pixel coordinates):
        path_rel_pix = zeros(time_steps,3);
        for k = 1:time_steps
            path_rel_pix(k,1) = Time(k);
            path_rel_pix(k,2) = str2double(Video_xy(k,1));
            path_rel_pix(k,3) = str2double(Video_xy(k,2))*(-1);
        end
        
        % Extract the pixel coordinates of the reference points from tab2
        % (i is the row number and corresponds to the Go Pro video
        % that is being processed now):
        UL_x = tab2(i).UL_x;
        UL_y = tab2(i).UL_y;
        UR_x = tab2(i).UR_x;
        UR_y = tab2(i).UR_y;
        LL_x = tab2(i).LL_x;
        LL_y = tab2(i).LL_y;
        LR_x = tab2(i).LR_x;
        LR_y = tab2(i).LR_y;
        
        % Extract the start pixel coorinates of the plastic item from tab2:
        if L == 'A'
            x0 = tab2(i).A_x0;
            y0 = tab2(i).A_y0;   
        else
            x0 = tab2(i).B_x0;
            y0 = tab2(i).B_y0;
        end
     
        % Use the start pixel coordinates of the plastic item to obtain
        % the path of the plastic item in ABSOLUTE pixel coordinates:
        path_abs_pix = zeros(time_steps,3);
        for k = 1:time_steps
            path_abs_pix(k,1) = Time(k);
            path_abs_pix(k,2) = path_rel_pix(k,2) + x0;
            path_abs_pix(k,3) = path_rel_pix(k,3) + y0;
        end
        
        % Make the transformation matrix:
        movingPoints   = [UL_x UL_y; UR_x UR_y; LL_x LL_y; LR_x LR_y];
        fixedPoints    = [600 600; 0 600; 600 0; 0 0];
        transformatrix = fitgeotrans(movingPoints,fixedPoints,'projective');
        
        % Transform all absolute pixel coordinates to real coordinates 
        % using the transformation matrix:
        [x_transformed, y_transformed] = transformatrix.transformPointsForward(path_abs_pix(:,2), path_abs_pix(:,3));
        
        % Path of the plastic item in ABSOLUTE millimeter coordinates
        % (Note that the coordinate system of these coordinates are 
        % defined by the values that are in the fixedPoints matrix):
        path_abs_mm = zeros(time_steps,3);
        for k = 1:time_steps
            path_abs_mm(k,1) = Time(k);
            path_abs_mm(k,2) = x_transformed(k);
            path_abs_mm(k,3) = y_transformed(k);
        end
        
        % Path of the plastic item in RELATIVE millimeter coordinates
        % (w.r.t. the start coordinates):
        path_rel_mm = zeros(time_steps,3);
        for k = 1:time_steps
            path_rel_mm(k,1) = Time(k);
            path_rel_mm(k,2) = path_abs_mm(k,2) - x_transformed(1);
            path_rel_mm(k,3) = path_abs_mm(k,3) - y_transformed(1);
        end
        
        % Add new columns to the tab2 array to store the computed 
        % output data, which consists of 
        
        % ...the time data:
        tab2(i).([L, '_t']) = path_rel_mm(:,1);
        
        % ... the transformed x coordinates:
        tab2(i).([L, '_x_displ_rel_mm']) = path_rel_mm(:,2);
        
        % ... and the transformed y coordinates:
        tab2(i).([L, '_y_displ_rel_mm']) = path_rel_mm(:,3);
        
        % Gradient in x direction, i.e. velocity in x direction:
        v_x = gradient(path_rel_mm(:,2), path_rel_mm(:,1));
        V_x = zeros(time_steps,2);
        for k = 1:time_steps
            V_x(k,1) = Time(k);
            V_x(k,2) = v_x(k);
        end
              
        % Gradient in y direction, i.e. velocity in y direction:
        v_y = gradient(path_rel_mm(:,3), path_rel_mm(:,1));
        V_y = zeros(time_steps,2);
        for k = 1:time_steps
            V_y(k,1) = Time(k);
            V_y(k,2) = v_y(k);
        end
        
        % Add new columns to the tab2 array to store the computed 
        % output data, which consists of 
        
        % ... the x velocity:
        tab2(i).([L, '_x_velocity_mm_per_s']) = V_x(:,2);
        
        % ... the x velocity:
        tab2(i).([L, '_y_velocity_mm_per_s']) = V_y(:,2);
        
    end
        
end

save('Bottles_output.mat', 'tab2');



% The last step is to extract the last values from the time and displace-
% met related tables, so that we obtain the total duration and the total
% travelled distance of the plastic item:

load('Bottles_output.mat');

number_videos = size(tab2,1);

for j = 1:number_videos
    
    duration_A(j,:)        = tab2(j).A_t(end);
    travelled_dist_A(j,:)  = tab2(j).A_x_displ_rel_mm(end);
        
    duration_B(j,:)        = tab2(j).B_t(end);
    travelled_dist_B(j,:)  = tab2(j).B_x_displ_rel_mm(end);
        
end

% In the Excel sheet named 'Wind- & rain-driven macroplastic mobilization 
% and transport - DATA.xlsx', the duration values in column K are the
% values in the 'Duration_A' and 'Duration_B' table that we created here.
% The travelled distance (mm) values in column L in the Excel sheet are 
% copied from the values in the 'travelled_dist_A'and 'travelled_dist_B'
% tables that we created here.
