function [h,p,stats] = chi2gof(x,varargin)
%CHI2GOF Chi-square goodness-of-fit test.
% CHI2GOF performs a chi-square goodness-of-fit test for discrete or
% continuous distributions. The test is performed by grouping the data into
% bins, calculating the observed and expected counts for those bins, and
% computing the chi-square test statistic SUM((O-E).^2./E), where O is the
% observed counts and E is the expected counts. This test statistic has an
% approximate chi-square distribution when the counts are sufficiently
% large.
%
% Bins in either tail with an expected count less than 5 are pooled with
% neighboring bins until the count in each extreme bin is at least 5. If
% bins remain in the interior with counts less than 5, CHI2GOF displays a
% warning. In that case, you should use fewer bins, or provide bin
% centers or edges, to increase the expected counts in all bins.
%
% H = CHI2GOF(X) performs a chi-square goodness-of-fit test that the data in
% the vector X are a random sample from a normal distribution with mean and
% variance estimated from X. The result is H=0 if the null hypothesis (that
% X is a random sample from a normal distribution) cannot be rejected at the
% 5% significance level, or H=1 if the null hypothesis can be rejected at
% the 5% level. CHI2GOF uses NBINS=10 bins, and compares the test statistic
% to a chi-square distribution with NBINS-3 degrees of freedom, to take into
% account that two parameters were estimated.
%
% [H,P] = CHI2GOF(...) also returns the p-value P. The P value is the
% probability of observing the given result, or one more extreme, by
% chance if the null hypothesis is true. If there are not enough degrees
% of freedom to carry out the test, P is NaN.
%
% [H,P,STATS] = CHI2GOF(...) also returns a STATS structure with the
% following fields:
% 'chi2stat' Chi-square statistic
% 'df' Degrees of freedom
% 'edges' Vector of bin edges after pooling
% 'O' Observed count in each bin
% 'E' Expected count in each bin
%
% [...] = CHI2GOF(X,'NAME1',VALUE1,'NAME2',VALUE2,...) specifies
% optional argument name/value pairs chosen from the following list.
% Argument names are case insensitive and partial matches are allowed.
%
% The following options control the initial binning of the data before
% pooling. You should not specify more than one of these options.
%
% Name