function grids=Dof(grids)
%DOF - assign the degrees of freedom to each grid
%
%   Establish the degrees of freedom that exist on each grid. For each grid, 
%   we default to 6 degrees of freedom, 3 in translation and 3 in rotation (Nastran convention)
%   When running serially, the dofs (degrees of freedom) are setup incrementaly,  6 for each grid. 
%   In parallel, things are a bit more complex. We want grids belonging to the same partition to 
%   be side by side in the global system matrices, to improve the sparsity pattern.  We also want 
%   the border grids, grids that belong to several partitions, to be lumped at the end of the dof list. 
%
%   Usage:
%      grids=Dof(grids)

global cluster

dofcount=length(grids)*6;

if ~cluster,
	dof=1;
	for i=1:length(grids),
		grids(i).grid.doflist=dof:1:(dof+5);
		dof=dof+6;
	end
else
	borderdof=1;
	dof=1;
	for i=1:length(grids),
		if ~isempty(grids(i).grid),
			if ~grids(i).grid.border,
				grids(i).grid.doflist=dof:1:(dof+5);
				dof=dof+6;
			else
				grids(i).grid.doflist=borderdof:1:(borderdof+5);
				borderdof=borderdof+6;
			end
		end
	end
	localdofcount=dof-1;
	localborderdofcount=borderdof-1;

	%Now, offset the border dofs so that they are lumped at the end of the dof list.
	for i=1:length(grids),
		if (~isempty(grids(i).grid) & grids(i).grid.border),
			grids(i).grid.doflist=grids(i).grid.doflist+dofcount-localborderdofcount;
		end
	end

	%Now, update the regular local grid dofs to account for other cpu grids.
	alldofcounts=gcat(localdofcount); %this array holds the dof count for all cpus.
	
	%Determine offset for all grid dofs
	dofoffset=sum(alldofcounts(1:labindex-1));
	
	%offset all grid dofs.
	for i=1:length(grids),
		if (~isempty(grids(i).grid) & ~grids(i).grid.border),
			grids(i).grid.doflist=grids(i).grid.doflist+dofoffset;
		end
	end
end
