function [grids,y_g]=SpcGrids(grids,constraints)
%SPCGRIDS - spc the grids
%
%   Go through the grids and figure out which are spcd
%
%   Usage:
%      [grids,y_g]=SpcGrids(grids,constraints)

global cluster

%initialize y_g, vector of constraint values in the g-set:
y_g=sparse(getdofcount(grids),1);

if cluster,
	y_g_border=sparse(getdofcount(grids),1);
end

%Go through constraints and add constraint on gridset list of corresponding grid
for i=1:length(constraints),

	constraint=constraints(i).constraint;
	if strcmpi(constraint.type,'spc'),
		constraint_grid=grids(constraint.grid).grid;
		
		%On the cluster, grids are partitioned across cpus, but constraints are replicated across cpus.  So 
		%grids pointed to by certain constraints might not exist on the local cpu. In this case, skip the 
		%constraint operations.
		if cluster & isempty(constraint_grid),
			continue;
		end

		%for the constrained grid, add the correct degree of freedom in the gridset list 
		constraint_grid.gridset=[constraint_grid.gridset num2str(constraint.dof)]; %concatenate two strings

		%plug modified grid back into grids dataset.
		grids(constraint.grid).grid=constraint_grid;

		%plug value of constraint in corresponding constraint vector y_g
		dof=constraint_grid.doflist(constraint.dof);
		if ~cluster,
			y_g(dof)=constraint.value;
		else
			%for cluster, we add to y_g only if grid does not belong to border (we don't want to add constraint.value several times for each cpu).
			if constraint_grid.border~=1,
				y_g(dof)=constraint.value;
			else
				y_g_border(dof)=constraint.value;
			end
		end
	end
end 

if cluster,
	%Add all the y_g from all the cpus
	y_g=gplus(y_g);
	%y_g_border is the same on all cpus, plug it into y_g
	y_g=y_g+y_g_border;
end
