function [first, second, third]=hdfpeek( filename, tagref )
%HDFREAD Read data from HDF file.
%	I=HDFREAD('filename', [GROUPTAG GROUPREF]) reads a binary
%	or intensity image from an HDF file.  
%
%	[X,MAP]=HDFREAD('filename', [GROUPTAG GROUPREF]) reads an
%	indexed image and its colormap (if available) from an HDF file.
%
%	[R,G,B]=HDFREAD('filename', [GROUPTAG GROUPREF]) reads an
%	RGB image from an HDF file.
%
%	Use the HDFPEEK function to inspect the file for group tags,
%	reference numbers, and image types.  Example:
%	  [tagref,name,info] = hdfpeek('brain.hdf');
%	  for i=1:size(tagref,1), 
%	    if info(i)==8,
%	      [X,map] = hdfread('brain.hdf',tagref(i,:)); imshow(X,map)
%	    end
%	  end
%
%	See also: HDFPEEK, HDFWRITE, BMPREAD, GIFREAD, PCXREAD,
%	          TIFFREAD, XDWREAD.

%	Author: J.M. Winograd	7-93
%	Copyright (c) 1993 The Mathworks, Inc.

error( nargchk( 2, 2, nargin ) );

if (~isstr(filename))
    error( 'FILENAME must be a string.' );
end

% Find full filename
fid = fopen(filename);
if fid == -1, error(['File ',filename' not found.']); end
fname = fopen(fid); fclose(fid);

[first, second, third] = hdfreadc( fname, tagref );

if nargout==3 & isempty(third),
  if isempty(second),
    disp('Warning: File contains an intensity image. ')
    disp('  Use I = hdfread(''filename'',tagref) instead.')
    second = first; third = first;
  else
    disp('Warning: File contains an indexed image. ')
    disp('  Use [X,map] = hdfread(''filename'',tagref) instead.')
    [first,second,third] = ind2rgb(first,second);
  end

elseif (nargout==2)
  if isempty(second),
    disp('Warning: File contains intensity image. ')
    disp('  Use I = hdfread(''filename'',tagref) instead.')
    [first,second] = gray2ind(first,256);
  elseif ~isempty(third),
    disp('Warning: File contains an RGB image. ')
    disp('  Use [r,g,b] = hdfread(''filename'',tagref) instead.')
    [mp1 mp2 mp3] = meshgrid(0:.2:1,0:.2:1,0:.2:1);
    map = [mp1(:) mp2(:) mp3(:)];
    first=dither(first,second,third,map); %Uniform quantization, max. 216 colors
    second = map;
  end

elseif (nargout==1),
  if ~isempty(third),
    disp('Warning: File contains an RGB image. ')
    disp('  Use [r,g,b] = hdfread(''filename'',tagref) instead.')
    first = rgb2gray(first,second,third);
  elseif ~isempty(second),
    disp('Warning: File contains an indexed image. ')
    disp('  Use [X,map] = hdfread(''filename'',tagref) instead.')
    first = ind2gray(first,second);
  end   
end

% Return only the valid parts of the colormap
n = max(max(first));
if (nargout ==2) & (n > 1),
  second = second(1:n,:);
end

