function AvgVolumes(volumes,out,center_measure)
%function AvgVolumes(volumes,out,center_measure)
%
% center_measure   : 'median' [default], 'mean', or 'mode'

% ---------------------------------
% Copyright (c) 2003 Serge Dumoulin
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License version 2
% as published by the Free Software Foundation.
% ---------------------------------

if nargin < 2,
   help(mfilename);
   return;
end;
if nargin < 3,
   center_measure=[];
end;
if isempty(center_measure), center_measure='median'; end;

if (center_measure(1,1:4)~='medi' | ...
    center_measure(1,1:4)~='mean' | ...
    center_measure(1,1:4)~='mode'),
   disp(sprintf('Unknown value of center_measure (%s)',center_measure));
   return;
end;
   
tic;

h = zeros(size(volumes,1),1);

for ix=1:size(volumes,1),
  h(ix) = openimage(deblank(volumes(ix,:)));
end;
sizes=getimageinfo(h(1),'ImageSize');
NumSlices=getimageinfo(h(1),'NumSlices');

nh_out = newimage(out,[0 NumSlices],deblank(volumes(1,:)));

for s=1:NumSlices,
   if s==1, fprintf('[%s]: Processing:',mfilename); end;
   fprintf('.');drawnow;
   
   for ix=1:size(volumes,1),
      sliceframes(ix,:)=getimages(h(ix),s)';
   end;
   
   if center_measure(1,1:4)=='medi',
      Output=median(sliceframes,1);
   elseif center_measure(1,1:4)=='mean',
      Output=mean(sliceframes,1);
   elseif center_measure(1,1:4)=='mode',
      Output=mode(sliceframes);
   else,
      disp(sprintf('Unknown value of center_measure (%f)',center_measure));
   end;
   putimages(nh_out,Output',s); 
end;

closeimage(nh_out);
for ix=1:size(volumes,1),
  closeimage(h(ix));
end;

fprintf('Done[%dsec].\n',round(toc));

