% Created by: Dima Al Damen
% November 8th 2007

% This file was created to test whether there is a cut in the direction of
% the frame within the frames by taking the calibrated camera location into
% account

function direction = getPersonWalkingDirection4 (newMedianFile, H, cameraX, cameraY, rescaleFactor, footLoc, params)
  
  if (params.Results.useFoot == true)
      origData = [footLoc(:,2)'; footLoc(:,3)'];
  else
      origData = [newMedianFile(:,4)'; newMedianFile(:,5)'];
  end;
  origData = origData ./ rescaleFactor;
  origData (3,:) = 1;
  transformedData = H * origData;
%   transformedData(1,:)
%   transformedData(2,:)
%   transformedData(3,:)
  changeInX = median(origData(1,7:10)) - median(origData(1,1:3));
  changeInY = median(origData(2,1:3)) - median(origData(2,7:10));
  transformedData(1,:) = transformedData(1,:)./transformedData(3,:);
  transformedData(2,:) = transformedData(2,:)./transformedData(3,:);
  transformedData(3,:) = transformedData(3,:)./transformedData(3,:);
  [m,n] = size (transformedData);
%   origData
  p = polyfit (transformedData (1,:), transformedData(2,:), 1);
  
  if (changeInX > 0 && changeInY > 0)
      personVector = [cos(p(1,1)); abs(sin(p(1,1)))];
  else if (changeInX > 0 && changeInY < 0)
          personVector = [cos(p(1,1)); -abs(sin(p(1,1)))];
      else if (changeInX < 0 && changeInY > 0)
              personVector = [-cos(p(1,1)); abs(sin(p(1,1)))];
          else
              personVector = [-cos(p(1,1)); -abs(sin(p(1,1)))];
          end;
      end;
  end;
  % used to decide the direction of motion (left or right) after knowing
  % the angle - this is equal to finding a vector rather than a line above.
  
%   direction = getPersonWalkingDirection (median2);
 
  angles = [];  
  for i = 1:n
      xPos = transformedData(1,i);
      yPos = -1*transformedData(2,i);
      thisFrameVector = [cameraX-xPos; cameraY-yPos];
      thisFrameVectorLength = sqrt (thisFrameVector (1,1) ^ 2 + thisFrameVector (2,1) ^ 2);
      thisFrameVector = thisFrameVector ./ thisFrameVectorLength;
      dotProd = sum (thisFrameVector .* personVector);
      thisFrameAngle = acos (dotProd)*180/pi;
      angles = [angles; thisFrameAngle];
   end;
   
   medianAngle = mean (angles);
   if (medianAngle >= 0 && medianAngle < 15)
       direction = 3;
   end;
   if (medianAngle >= 15 && medianAngle < 75)
       if (changeInX > 0)
          direction = 2;
       else
          direction = 4;
       end;
   end;
   if (medianAngle >= 75 && medianAngle < 105)
          if (changeInX > 0)
              direction = 1;
          else
              direction = 5;
          end;
   end;
   if (medianAngle >= 105 && medianAngle < 165)
          if (changeInX > 0)
              direction = 8;
          else
              direction = 6;
          end;
   end;
   if (medianAngle >= 165)
      direction = 7;
   end;
end