function img = read_img(filename, imsize)
%READ_IMG Read a raw file in 8-bit grayscale into a variable.
%	IM = READ_IMG(FILENAME, IMSIZE) reads a raw file of name FILENAME
%	into variable IM.  IMSIZE should be a two-element vector containing
%	the number of rows and columns of the image.  If IMSIZE is omitted,
%	it defaults to 512x512.  If IMSIZE is a scalar, the image is
%	assumed to be of size IMSIZExIMSIZE.
%
%	A warning is given if the file is not of the specified size.
%
%	See also WRITE_IMG, SHOW_IMG.

%	Modified T Kite Oct 1996, Jan 1998

if nargin == 1					% default size
  imsize = 512;
end

if length(imsize) == 1				% deal with image size
  img_size = [imsize imsize];
else
  img_size = imsize(2:-1:1);			% flip for column order
end

fileid = fopen(filename, 'r');
if fileid < 0
  error(['Unable to open file ' filename ' for reading'])
end

status = fseek(fileid, 0, -1);
if status >= 0
  [img, count] = fread(fileid, img_size, 'unsigned char');
  img=img';
  if count ~= prod(img_size)
    disp('Warning: Filesize not as specified')
  end
else
  error(['Unable to read file ' filename])
end
