function varargout = xdevdemo302(WformIn1)
%XDEVDEMO302 Recovers the primary sinewave of the waveform and removes it.
%
%  WFORMOUT = XDEVDEMO302(WFORMIN1) calculates the primary tone in the 
%  signal WFORMIN1 and returns the original waveform minus the primary 
%  sinewave.
%
%
% Example:
%   WformOut = xdevdemo302(WformIn1);
%
% See also DEMOS, XDEVDEMO, XDEVDEMO300.
%

%   $Author: Ldean $Revision: 1.0 $  $Date: 9/24/02 5:32p $

%   Testing:
%   This function was tested on the WAVEMASTER series scope.
%

% $Notes: 
% $EndNotes 

% $Description:
% $
if nargin==0
    help(mfilename)
    return;
end;

% Take the FFT of the data and find the largest signal above DC
% then generate a sin wave with this frequency.

% Get the length of the signal
N=length(WformIn1);

% Take the FFT of the data removing DC
fftdata = fft(WformIn1-mean(WformIn1));

% Find the maximum peak in the FFT
[y,idxTone] = max(fftdata);
idxTone=idxTone;
% Calculate the frequency that this peak represents.
freq=(idxTone-1)/N;

% Generate the sin wave that represents this frequency using the angle from
% the FFT data.
a1=angle(fftdata(idxTone));
a2=angle(fftdata(N-idxTone+2));
if a1>=0
    if a2>0
        disp('Imaginary Results in FFT.  We have a problem.');
        ang = 0;        
    else
        ang = a1+pi/2; % cos(ang)
    end;
else
    if a2>=0
        ang = a1+pi/2; %sin(ang)
    else
        disp('Imaginary Results in FFT.  We have a problem.');
        ang = 0;        
    end;
end;
varargout{1}=WformIn1-((2*abs(y)/N)*sin(2*pi*[0:N-1]'*freq+ang));

