function [a,IC] = popfit(t,y,tmin,tmax)
%Take data and find best linear, quadratic, and cubic models
p = polyfit(t,y,1);
err(1) = (sum(((p(1)*t + p(2)) - y).^2)).^0.5;
a(1) = p(1); a(2) = p(2);
q = polyfit(t,y,2);
err(2) = (sum(((q(1)*t.^2 + q(2)*t + q(3)) - y).^2)).^0.5;
a(3) = q(1); a(4) = q(2); a(5) = q(3);
w = polyfit(t,y,3);
err(3) = (sum(((w(1)*t.^3 + w(2)*t.^2 + w(3)*t + w(4)) - y).^2)).^0.5;
a(6) = w(1); a(7) = w(2); a(8) = w(3); a(9) = w(4);
n = length(y);
k = [2 3 4];
BIC = n*log(err.^2/n) + k*log(n);
AIC = 2*k + n*(log(2*pi*err.^2/n)+1);
IC = [err.^2;BIC;AIC];

%Plot Data and Models
xx = linspace(tmin,tmax,250);
plot(t,y,'bo');
hold on
plot(xx,a(1)*xx+a(2),'b-','LineWidth',1.5);
plot(xx,a(3)*xx.^2+a(4)*xx+a(5),'r-','LineWidth',1.5);
plot(xx,a(6)*xx.^3+a(7)*xx.^2+a(8)*xx+a(9),'m-','LineWidth',1.5);
grid
h = legend('Data','Linear','Quadratic','Cubic','Location','northwest');
set(h,'Interpreter','latex')


% Set up fonts and labels for the Graph
fontlabs = 'Times New Roman';  
xlabel('$t$, years after 1790','FontSize',16,'FontName',fontlabs, ...
    'interpreter','latex');  
ylabel('Population (in Millions)','FontSize',16,'FontName',fontlabs, ...
    'interpreter','latex'); 
mytitle = 'U. S. Population';
title(mytitle,'FontSize',16,'FontName', ...
    'Times New Roman','interpreter','latex'); 
set(gca,'FontSize',16);

print -depsc us_poly.eps
end

