function [t,p,dfout,xbout,varout] = ttest_unequalvar(x1,x2)
% ttest  Student-t test for significance of different means when variances
%        are not equal and when length of data sets are not equal.
%
%        See Douglas Montgomery, Design and Analysis of Experiments, 5th ed.
%            Wiley, 2001, p. 44 (Section 2-4.4)
%        See G.D. Ruxton, Behavioral Ecology, 17 May 2006, doi:10.1093/beheco/ark016
%
% Synopsis:  [t,p]             = ttest_unequalvar(x1,x2)
%            [t,p,df]          = ttest_unequalvar(x1,x2)
%            [t,p,df,xbar]     = ttest_unequalvar(x1,x2)
%            [t,p,df,xbar,var] = ttest_unequalvar(x1,x2)
%
% Input:   x1, x2 = vectors of data to be compared
%
% Output:  t = student t value for difference of means of the data sets
%          p = significance, i.e., probability that the true t value could be
%              larger (in absolute value) than the computed t, just by chance.
%          df = (optional) degrees of freedom used to compute p
%          xbar = (optional) two-element vector of means of x1 and x2
%          var  = (optional) two-element vector of variances of x1 and x2

n1    = length(x1);   n2    = length(x2);
xbar1 = mean(x1);     xbar2 = mean(x2);    
var1  = var(x1);      var2  = var(x2);
svar = sqrt(var1/n1 + var2/n2);
df = ( (var1/n1 + var2/n2)^2) / ( ((var1/n1)^2)/(n1-1) + ((var2/n2)^2)/(n2-1) );

if svar==0 || isnan(svar)
  warning('TTEST:varianceError','svar = %f',svar);
  t = 0;  p = 0;
  if nargout>2, xbout = [xbar1 xbar2];  end
  if nargout>3, varout = [0 0];   end
  return
end

t = (xbar2-xbar1)/svar;
p = betainc(df/(df+t^2),0.5*df,0.5);
if t<0, p = 1 - p;  end

if nargout>2, dfout = df;  end
if nargout>3, xbout = [xbar1 xbar2];  end
if nargout>4, varout = [var1 var2];   end