% Pasha SHADKAMI  PIMA  25/02/2008
% Extraire des coupes2D d'une image 3D - .IMA 
%*************************************************************


function imag = ima2mat3D(name)

% Ouvrire, lire et fermer les fichiers de dimension.

if nargin == 0
  error('You have to specify a filename (between quotes: ''name'') !');
end;

% Ouvrire, lire et fermer les fichiers de dimension.

nameLength = length(name);
baseName = name;
if (nameLength > 4)
  if sum(name(nameLength-3:nameLength) == '.dim') == 4 | ...
	sum(name(nameLength-3:nameLength) == '.ima') == 4
    baseName = name(1:nameLength-4);
  end;
end;
fileName = [baseName '.dim'];

dimfid = fopen(fileName, 'r');
if ~(dimfid > 2)
  error(['Failed to open the dimension file: ' fileName]);
end;

disp(['Read from file: ' fileName]);
[dim, nrRead] = fscanf(dimfid,'%d', 3);

if nrRead == 3 & dim(1)>0 & dim(2)>0 & dim(3)>0
  % Ancien type IMA
  dim = dim';
  disp(['     IMA file type ; values in [0, 255] ; size (' ...
	  int2str(dim(1)) ', ' int2str(dim(2)) '), ' int2str(dim(3)) ' Coupes']); 
  type = 'uchar';
else 
   error(['Invalid dimension file: ' fileName]);
end;
 
dimstat = fclose(dimfid);
if ~(dimstat == 0)
  error('Failed to close the dimension file')
end;

% Ouvrire, lire et fermer les fichiers d'image.

fileName = [baseName '.ima'];
imafid = fopen(fileName, 'r');
if ~(imafid > 2)
  error(['Failed to open the file: ' fileName]);
end;

disp(['Read from file: ' fileName]);
for i=1:dim(3)
[ima, nrRead] = fread(imafid,[dim(1), dim(2)],type);
if nrRead~=dim(1)*dim(2)
  error(['Image data file size does not match dimension '...
	  'specifications.']);
end;
ima=ima';
imag(:,:,i)=ima;
end;

imastat = fclose(imafid);
if ~(imastat == 0)
  error(['Failed to close the file:' fileName]);
end;
disp('Image read !');
ch=input('Do you want to watch images? y/n   ');
if ch=='y'
    counter = ceil(dim(3)/20);
    k=1;
    i=1;
    chk = dim(3);
    while(counter~=0)
             for j=1:20
                 if(chk>0)
                    figure(k);subplot(4,5,j);imagesc(imag(:,:,i));colormap(gray);
                    chk=chk-1;
                    i=i+1;
                 end
             end
    k=k+1;
    counter=counter-1;
    end
   

end;
end

%fin. 
