function [u_bb,f_bb]=cts_from_real(u,fs,f0)
%
% Call [u_bb,f_bb]=cts_from_real(u,fs,f0);
%
% INPUTS:
% u         = Input real time series;
% fs        = Sample rate of u;
% f0        = Basebanding frequency;
%
% OUTPUTS:
% u_bb      = Basebanded time series;
% f_bb      = Basebanding frequency (may be different from f0 since must be a multiple of df);
%
% See:  cts_details, cts_open, cts_read, cts_write, cts_write_open, cts_combine, cts2fft, cts2spec, 
%       cts_from_real, cts_shot, cts_wf_make, fft2cts, mcs_gui.
%
%
% COPYRIGHT (c) 2008
% 
% Applied Research Laboratories, The University of Texas at Austin
% (ARL:UT)
% All rights reserved.
% 
% This material may be reproduced by or for the U.S. Government
% only. This notice must appear in all copies of this file and its
% derivatives. Further distribution outside the U.S. Government is
% prohibited without the explicit written authorization from the
% Director of the Environmental Sciences Laboratory, ARL:UT.
% 
% THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
% EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE
% IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
% PURPOSE, OR NONINFRINGEMENT.
% 
% IN NO EVENT WILL ARL:UT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING
% OUT OF THE USE OR INABILITY TO USE THIS SOFTWARE, EVEN IF ARL:UT HAS
% BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

% Take forward FFT:
U=fft(u); npt=length(u); df=fs/npt;
% Compute basebanding frequency as closest f bin to f0:
if f0==0,
    U_abs=abs(U(1:npt/2));
    [U_max,jf_max]=max(U_abs);
    dB_down=40;
    U_thresh=U_max*10^(-dB_down/20);
    ii=find(U_abs>U_thresh);
    f_lo=(ii(1)-1)*df; f_hi=(ii(end)-1)*df;
    f0=.5*(f_lo + f_hi); disp(['Auto Calc of f0: ',num2str(f0)]);
end
jf_bb=round(f0/df) + 1; f_bb=(jf_bb-1)*df;
npt2=round(npt/2);
% Indices into pos half of spectrum U such that f_bb maps to zero frequency:
iiposf=[jf_bb:npt2]; iinegf=[1:jf_bb-1];
% Indices into basebanded spectrum U_bb such that iiposj starts at index 1 
% (0 frequency):
% Make lengths of iiposf, iiposj same, and make iiposj start at one
% and iinegj end at nfft_bb:
iiposj=1:npt2-jf_bb+1; iinegj=npt-jf_bb+2:npt;
U_bb=zeros(size(U)); 
U_bb(iiposj)=U(iiposf); 
U_bb(iinegj)=U(iinegf);
% Take inverse FFT:
u_bb=ifft(U_bb);
