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

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

% ==============================================================
function T = TofJtype(e)
% TofJtype  Temperature of J type thermocouple with ice-point compensation
%
% Synopsis:  T = TofJtype(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*1e6;             %  emf in microvolts, 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
ilo = find(em>=-8095 & em<=0);  %  vector of indices such that -8.095 <= e(i) <= 0
ihi = find(em>=0 & em<=42919);  %  vector of indices such that 0 <= e(i) <= 42.919
if ~isempty(ilo)
  c = [-8.3823321e-29  -2.3963370e-24  -2.8131513e-20  -1.7256713e-16 ...
       -5.9086933e-13  -1.0752178e-9  -1.2286185e-6  1.9528268e-2  0];
  T(ilo) = polyval(c,em(ilo));
  n(ilo) = 0;   %  these i values are done, set elements in monitor vector to zero
end
if ~isempty(ihi)
  c = [5.099890e-31  -5.344285e-26  3.585153e-21  -2.549687e-16  1.036969e-11 ...
       -2.001204e-7  1.978425e-2  0];
  T(ihi) = polyval(c,em(ihi));
  n(ihi) = 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 -5603 <= e <= 20872 microV\n',em(nn)));
end