function T = Ttemp(e,Tref)
% Ttemp  Temperature of T-type thermocouple
%
% Synopsis:  T = Ttemp(e)
%            T = Ttemp(e,Tref)
%
% Input:  e    = emf of thermocouple junction, Volts:  -5.603e-3 <= e <= 20.872e-3
%         Tref = (optional) temperature of reference junction
%                Default:  Tref = 0 C (ice point)
%
% Output:  T = temperature, degrees C

if nargin<2
  T = TofTtype(e);  return;
elseif nargin==2
  eref = emfTtype(Tref);     %  emf of ice-point referenced T-couple at Tref
  T = TofTtype(e+eref);      %  correct for nonzero reference temperature
  return;
else
  error('only one or two inputs allowed');
end

% ==============================================================
function T = TofTtype(e)
% TofTtype  Temperature of T type thermocouple with ice-point compensation
%
% Synopsis:  T = TofTtype(e)
%
% Input:   e = (vector or scalar) emf of thermocouple junction in Volts
%              T-couple is assumed to have a reference junction at 0 C
%
% Output:  T = temperature, degrees C
em = e*1e3;             %  emf in mV, possibly a vector
T = zeros(size(em));    %  preallocate so T vector will be contiguous in memory
n = 1:length(em);       %  vector to monitor which em values have been converted
ihi = find(0<=em & em<=20.872);  %  vector of indices such that 0 <= e(i) <= 20.872
ilo = find(-5.603<=em & em<0);   %  vector of indices such that -5.603 <= e(i) <= 0
if ~isempty(ihi)
  c = [-7.293422e-7  6.048144e-5  -2.165394e-3  4.637791e-2 ...
       -0.7602961 25.92800  0];
  T(ihi) = polyval(c,em(ihi));
  n(ihi) = 0;   %  these i values are done, set elements in monitor vector to zero
end
if ~isempty(ilo)
  c = [1.2668171e-3   2.0241446e-2  0.13304473  0.42527777 ...
       0.79018692  -0.21316967  25.949192 0];
  T(ilo) = polyval(c,em(ilo));
  n(ilo) = 0;   %  these i values are done, set elements in monitor vector to zero
end
% --- Check to see if all elements of em vector have been converted
if any(n)
  nn = n(find(n~=0));   %  select only the nonzero indices
  warning(sprintf('e = %g value outside of range -5.603 <= e <= 20.872 mV\n',em(nn)));
end