function D = KolmogorovSmirnov(data,model)
% KolmogorovSmirnov(data,model)
% Returns KS statistic: maximum vertical distance between CDFs of model distribution and data
% Based on NumRec

% sort data
data = sort(data);
ndata=length(data);

fo=0;
D=0;

dataCDF = [1:ndata] ./ ndata;
modlCDF = BinomCDF(model,data);
absdiff = abs(dataCDF-modlCDF);

for j=1:ndata
   dt = max( abs(fo-modlCDF(j)), absdiff(j) );
   if dt>D
      D=dt;
   end
   fo=dataCDF(j);
end