function [theta] = fft_rot(x,y)

% [theta] = fft_rot(x,y);
% 
% This function was designed take vectors of x,y coordinates
% from accelerometer data (leaving z constant, since z is now in the vertical
% 'zenith' orientation to the earths center) and rotate iteratively
% 180 deg to determine the axis of maximum power in y and minimum in x for
% a target frequency. In this case we are looking at tailbeats in
% white shark. We assume that acceleration for tailbeat frequency (~0.4 Hz)
% occures primarily as sway, that would be most prominant perpendicular
% to the sharks body, along the y axis. Therefore we are looking to
% maximize y and minimize x. This inflection point is most clear 
% at it's max, since there is some decay near the min.
% Salvador Jorgensen (May 4, 2011) 





%% SET FFT PARAMETERS - THESE CORRESPOND TO 5Hz SAMPLING
Fs = 5;                       % Sampling frequency
T = 1/Fs;                     % Sample time
L = length(x);                % Length of signal
t = (0:L-1)*T;                % Time vector
NFFT = 2^nextpow2(L);         % Next power of 2 from length of y



%% LOOP THROUGH ROTATION
rot = 180;

%initiate variables
z=zeros(size(y));
xr=zeros(size(y));
yr=zeros(size(y));
zr=zeros(size(y));
freqy = zeros(1,rot);
freqx = zeros(1,rot);
maxy= zeros(1,rot);
maxx= zeros(1,rot);

for j = 1:rot
        for k = 1:length(x) % transform all x,y pairs - faster using non-matrix?
         [xr(k) yr(k) zr(k)] = rotz3(x(k),y(k),z(k),j);
        end

% perform FFT
Y = fft(yr,NFFT)/L;
X = fft(xr,NFFT)/L;

% Find peak frequency and power
powy = 2*abs(Y(1:NFFT/2+1)); % power vector Y
powx = 2*abs(X(1:NFFT/2+1)); % power vector X
f = Fs/2*linspace(0,1,NFFT/2+1);

peaky = find(powy==max(powy(f>0.25&f<0.6))); % find the peak Confined to equivalent of .45 hz +-
peakx = find(powx==max(powx(f>0.25&f<0.6)));
freqy(j) = f(peaky);
freqx(j) = f(peakx);
maxy(j)= powy(peaky);
maxx(j)= powx(peakx);

% find the rotation where tailbeat is minimal in x and max in y
 [~, theta] = max(maxy);%% find maximumm signal in y - best estimate of minimal x
end

theta 

%% EXAMPLE
% close all;
% plot(maxy,'.-');hold on;
% plot(maxx,'.-r');
% plot(freqx./100,'g.');plot(freqy./100,'k.')
% theta ;







