function [tmin_predicted] = modelfun(b, X)
% MODELFUN a function to compute the predicted minimum temperature.
% b is [C0 C1 C2 S0 S1 S2].  ( the coefficients of the model )
% X is [C H Tmax N]        ( the data values to evaluate for )
% N is the number of seconds in the night (hod * 3600)
    
    C1 = b(1); C2 = b(2); S0 = b(3); S1 = b(4); S2 = b(5);
    C = X(:,1); 
    H = X(:,2); 
    Tmax = X(:,3) + 273; % convert Celcius to Kelvin
    N = X(:,4);
    Ch = 8E5 * (0.8 + C1 * H + C2 * C); %heat capacity
    Sp = 2.8E-8 * (S0 + S1 * H + S2 * C); % Sigma prime: emissivity for earth * stefan's constant 
    tmin_predicted = Tmax - (Sp .* N .* (Tmax.^4))./(Ch+2*Sp.*N.*(Tmax.^3));
    tmin_predicted = tmin_predicted - 273; % Convert Kelvin to Celcius
    % clean up any dodgy values
    bad_indices = isnan(tmin_predicted) | isinf(tmin_predicted);
    tmin_predicted(bad_indices) = zeros(1, sum(bad_indices));
end