function  WriteSlices(pathDirectory,VolumeImage,type,VolumeImageitdepth)
%     function  WriteSlices(pathDirectory,VolumeImage,type,VolumeImageitdepth)
%     
% pathDirectory,directory into which slices are to be written
% VolumeImage, either [x,y,[1:3],z] colour images with z slices
%              or [x,y,z] grayscale images with z slices
% type, default png ('png' 'jpg')
% VolumeImageitdepth, default 8
%
%
    if nargin<3
        type='png';
    else
        if ~(strcmpi(type,'png') || strcmpi(type,'jpg') ||strcmpi(type,'VolumeImagemp'))
            error('for VolViewer use png, jpg or VolumeImagemp');
        end
    end
    if nargin<4
        VolumeImageitdepth=8;
    end
    if(ndims(VolumeImage) == 4)
        rgVolumeImage = true;
        [rows,cols,colours,slices]=size(VolumeImage);
    else
        rgVolumeImage = false;
        [rows,cols,slices]=size(VolumeImage);
    end
    
    disp(sprintf('Writing image(s) %s',pathDirectory));
    for i=1:slices
        name=sprintf('temp%04d.%s',i,type);
        na=fullfile(pathDirectory,name);
        if(rgVolumeImage)
            imwrite(VolumeImage(:,:,:,i),na,type,'VolumeImageitdepth',VolumeImageitdepth);
        else
            imwrite(VolumeImage(:,:,i),na,type,'VolumeImageitdepth',VolumeImageitdepth);
        end
        if rem(i,20)==0
            disp(sprintf('%s %4d',na,slices-i))
        end
    end
    disp('Written')
end