function texhist(filename,y,x)
%TEXHIST
%	Make LaTeX histograms.
%	TEXHIST(Y) makes a histogram with 10 equally spaced bins between
%	the minimum and maximum values in Y, showing the distribution
%	of the elements in vector Y.
%	TEXHIST(Y,N), where N is a scalar, uses N bins.
%	TEXHIST(Y,X), where X is a vector, makes a histogram using the
%	bins specified in X.
%
%	See also HIST, BAR.

if nargin < 2
  error('Requires two or three input arguments.')
end
if nargin == 2
  x = 10;
end

[n,x]=hist(y,x);

divide=1;
while(max(n)>1000),
  n=n/10;
  divide=10*divide;
end
n=round(n);

fid=fopen(filename,'w');
fprintf(fid,'%\\textbf{}\\[5mm]\n');
fprintf(fid,'\\begin{barenv}\n');
fprintf(fid,'\\setnumberpos{empty}\n');
fprintf(fid,'\\setstretch{%d}\n',max(round(200/(max(n)-min(n))),1));
fprintf(fid,'\\setwidth{%d}\n',max(round(250/size(x,2)),1));
fprintf(fid,'%\\sethspace{0.1}\n');
fprintf(fid,'\\setxaxis{%d}{%d}{%.2f}\n',min(x),max(x),...
    ceil(size(x,2))/10));
fprintf(fid,'\\setyaxis{%d}{%d}{%.2f}\n',0,max(n),...
    ceil(max(n)/10));
fprintf(fid,'%\\setxname{}\n');
fprintf(fid,'\\setyname{Divided by %d}\n',divide);
fprintf(fid,'\\bar{%d}{1}\n',n);
fprintf(fid,'\\end{barenv}\n');
fclose(fid);


% Example
% texhist('hist.tex',[1 2 3 3 3 4 5 5 5 5 5 5 67 7 7 7 7 7 8 8 9 9 9 9 10],...
% [1 2 3 4 5 6 7 8 9 10])