function [Indices, dim] = lyngby_spm_xyz2ind(XYZ, dim, origin)

% lyngby_spm_xyz2ind   - Convert SPM XYZ structure to voxel indices
%
%	function [Indices, dim] = lyngby_spm_xyz2ind(XYZ, ...
%           dim, origin)
%
%	Input:	Vmask	a voxel mask (a sparse matrix)
%               origin  (Optional)
%		dim	(Optional) 
%
%	Output:	Indices	Indices for all voxels that will be in the
%	                masked voloume 
%               dim
%
%	See also: lyngby_index2vmask, lyngby_vmask2index

% cvs : $Id: lyngby_spm_xyz2ind.m,v 1.1 1999/03/24 15:26:32 fnielsen Exp $


    [rXYZ,cXYZ] = size(XYZ);

    if all(size(origin) == [1 3])
      origin = origin';
    elseif ~all(size(origin) == [3 1])
      error('Wrong size of origin')
    end
    
    stepX = min(diff(unique(XYZ(1,:))));
    stepY = min(diff(unique(XYZ(2,:))));
    stepZ = min(diff(unique(XYZ(3,:))));
    step = [ stepX stepY stepZ ]';
      
    if nargin == 1
      maxXYZ = max(XYZ')';
      minXYZ = min(XYZ')';
 
      dim = (maxXYZ - minXYZ) ./ step + 1;
 
    elseif nargin == 3
    
      minXYZ = - (origin-1) .* step;
       
    else
      error('Wrong number of arguments');
    end

    Coord = (XYZ - minXYZ(:,ones(1,cXYZ))) ./ step(:,ones(1,cXYZ));
    Indices = Coord(1,:)+1 + Coord(2,:)*dim(1) + ...
	Coord(3,:)*(dim(1)*dim(2));






