function A=permutegroups(A,doms,perm)
% permutegroups -  Reorder dimensions of array in groups
% 
% Like PERMUTE, PERMUTEGROUPS rearranges the dimensions of a 
% multidimensional array in the same way that transpose swaps
% the 2 dimensions of a matrix. However, rather than specifying
% the permutation in terms of individual dimensions, the
% dimensions are matched to a groups template and the then
% the groups are permuted. Eg, suppose A is an array such that
% the index domain size(A)=[6 3 4 7]. Now suppose the these
% are grouped as [ [6 3] [4 7] ] and we wish to swap the groups.
% Rather than saying
%
% 		permute(A,[3 4 1 2])
%
% we can say
%
%		permutegroups(A,{[6 3] [4 7]},[2 1])
%
% where the 2nd parameter specifies the two groups, and the third
% indicates that we want to swap them. Actually, the numbers in the
% group specification are not important - only the lengths of the
% groups matters.
%
% Usage:	B=permutegroups(A,groups,perm)
%
%		A:		orginal array
%		groups: list of array subdomains (ie sub-sequences of size(A))
%				One of these may be nan, in which case, all remaining dims
%				are assigned to that group.
%		perm:  desired permutation of groups

a=0;
dims=cell(size(doms));
nanat=0;
for i=1:length(doms)
	if isempty(doms{i}), dims{i}=[];
	else
		if ~isnan(doms{i})
			l=length(doms{i});
			dims{i}=a+(1:l);
			a=a+l;
		else
			nanat=i;
			dims{i}=a;
		end
	end
end

if nanat>0
	gap=length(size1(A))-a;
	if gap>0, 
		dims{nanat}=dims{nanat}+(1:gap);
		for j=nanat+1:length(doms)
			if ~isempty(dims{j}), dims{j}=dims{j}+gap; end
		end
	else
		dims{nanat}=[]; 
	end
else 
	gap=0;
end

perm=cell2mat(dims(perm));
maxdim=a+gap;
if maxdim<1, perm(end+1)=1; end
if maxdim<2, perm(end+1)=2; end

A=permute(A,perm);
