%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Title:    mat2hdf.m
%
%  Author:   Brons Larson
%            
%  Created:  May 5, 1998
%
%  Modified: October 6, 1999
%            August 15,2002 (Jean-Francois Remy)
%
%  Input:    An (m x n x nimgs) array of image data:
%            m = number of rows,
%            n = number of columns,
%            nimgs = number of images.
%            file_name = name of the output file (in single quotes).
%            precision = 'float64', 'float32','int8,16,32', 'uint8,16,32'
%
%  Output:   The same array stored as an hdf file, with
%            each image stored as a separate data set.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function mat2hdf(images,file_name,precision);

% Declare important variables.
[m,n,nimgs]=size(images);
NULL = '';
rank = 2;
dim = [n m];
start = [0 0];
stride = [];
edge = dim;

%Choose the right format
if (strcmp(precision,'float32')==1)
  images = single(images);
end
if (strcmp(precision,'float64')==1)
  images = double(images);
end
if (strcmp(precision,'int32')==1)
    images = int32(images);
end
if (strcmp(precision,'int16')==1)
    images = int16(images);
end
if (strcmp(precision,'int8')==1)
    images = int8(images);
end
if (strcmp(precision,'uint32')==1)
    images = uint32(images);
end
if (strcmp(precision,'uint16')==1)
    images = uint16(images);
end
if (strcmp(precision,'uint8')==1)
    images = uint8(images);
end

SD_id = hdfsd('start',file_name,'create');
if SD_id < 0
  error('Error with SDstart.');
end

% Loop through the input data and store each image as a separate data set.
for i = 1:nimgs
  sds_id = hdfsd('create',SD_id,NULL,precision,rank,dim);
  if sds_id < 0
    error('Error with SDcreate.');
  end

  status = hdfsd('writedata',sds_id,start,stride,edge,images(:,:,i));
  if status < 0
    error('Error with SDwritedata.');
  end

  status = hdfsd('endaccess',sds_id);
  if status < 0
    error('Error with SDendaccess.');
  end
end

status = hdfsd('end',SD_id);
if status < 0
  error('Error with SDend.');
end
