% Analysis test to track mast angle:
% Alex Rattner, 2016-08-22

function [t, theta] = TrackMast(VideoFileName)
    %Load video
    V = VideoReader(VideoFileName);
    
    %setup t, theta
    t     = [];
    theta = [];
    
    while hasFrame(V)
       t = [t V.currentTime];
       F = readFrame(V);
       
       %Isolate mast
       MastMask = (F(:,:,1) < 20) & (F(:,:,3) > 80);

       figure(1);
       subplot(1,2,1);
       imagesc(F);
       axis off;
       subplot(1,2,2);
       imagesc(MastMask);
       axis off;
       pause(0.15);
       
       %Rotate 90 degrees
       MastMask = MastMask';
       
       
       %Find angle
       [ys, xs] = find(MastMask == 1);
       
       %End early if mast leaves the frame
       if (size(xs) < 2)
           t = t(1:end-1);
           break;
       end
       
       P = polyfit(xs, -ys, 1);
       theta = [theta (180/pi)*atan(P(1))];
    end
   
    theta = theta - 180*(theta > 90);
    
end