function cf = funitconv(OldUnit,NewUnit,TimeUnit)
%FUNITCONV  Computes conversion factor between frequency units.
%
%   CF = FUNITCONV(OLDUNITS,NEWUNITS,TIMEUNITS)
%
%   Supported frequency units include:
%     1) 'rad/s', 'Hz', 'kHz', 'MHz', 'GHz', and 'rpm'
%     2) 'rad/TimeUnit' and 'cycles/TimeUnit' (time-relative units)
%     3) Units obtained by replacing "TimeUnit" above by one of the following
%        time units: nanoseconds, microseconds, milliseconds, seconds, minutes, 
%        hours, days, weeks, months, years.
%
%   The third input TIMEUNITS is required when the old or new units are 
%   'rad/TimeUnit' or 'cycles/TimeUnit'.

%   Copyright 1986-2010 The MathWorks, Inc.
if strcmp(OldUnit,NewUnit)
   cf = 1;  return
end

% Conversion factor for time units
if nargin>2
   f_time = tunitconv('seconds',TimeUnit);
else
   f_time = 1;
end

% Compute factor OldUnit -> rad/s
switch OldUnit
   case 'rad/TimeUnit'
      f_old = f_time;
   case 'rad/s'
      f_old = 1;
   case 'cycles/TimeUnit'
      f_old = 2*pi*f_time;
   case 'Hz'
      f_old = 2*pi;
   case 'kHz'
      f_old = 2e3*pi;
   case 'MHz'
      f_old = 2e6*pi;
   case 'GHz'
      f_old = 2e9*pi;
   case 'rpm'
      f_old = pi/30;
   otherwise
      if strncmp(OldUnit,'rad/',4)
         f_old = tunitconv('seconds',[OldUnit(5:end),'s']);
      elseif strncmp(OldUnit,'cycles/',7)
         f_old = (2*pi)*tunitconv('seconds',[OldUnit(8:end),'s']);
      end
end

% Compute factor NewUnit -> rad/s 
switch NewUnit
   case 'rad/TimeUnit'
      f_new = f_time;
   case 'rad/s'
      f_new = 1;
   case 'cycles/TimeUnit'
      f_new = 2*pi*f_time;
   case 'Hz'
      f_new = 2*pi;
   case 'kHz'
      f_new = 2e3*pi;
   case 'MHz'
      f_new = 2e6*pi;
   case 'GHz'
      f_new = 2e9*pi;
   case 'rpm'
      f_new = pi/30;
   otherwise
      if strncmp(NewUnit,'rad/',4)
         f_new = tunitconv('seconds',[NewUnit(5:end),'s']);
      elseif strncmp(NewUnit,'cycles/',7)
         f_new = (2*pi)*tunitconv('seconds',[NewUnit(8:end),'s']);
      end
end

cf = f_old/f_new;