function [Kgg,pg]=SystemMatrices(elements,grids,loads,materials,kflag,pflag, sparsity,inputs,analysis_type);
%SYSTEMMATRICES - create the stiffness matrix and load vector
%
%   Create system matrices (stiffness matrix and load vector), from element
%   formulations
%
%   Usage:
%      [Kgg,pg]=SystemMatrices(elements,grids,loads,materials,kflag,pflag, sparsity,inputs,analysis_type)

%initialize system matrices
dofcount=getdofcount(grids);
Kgg={};
pg={};

%figure out active elements that will take part in the stiffness and load generation
[n1,n2]=GetNumberOfActiveElements(elements);

if kflag, 
	
	%allocate 
	Kgg=spalloc(dofcount,dofcount,floor(dofcount*dofcount*sparsity)); 

	%Go through elements and build stiffness matrix 
	for n=n1:n2,

		if ~isempty(elements(n).element),
			%call element system matrix generation.
			Ke=CreateKMatrix(elements(n).element,grids,materials,inputs,analysis_type);
			
			%plug element system matrix into global system matrix.
			Kgg=AddElemMatrix(Ke,Kgg);
		end

	end
	
else
	Kgg={};
end

if pflag, 
	pg=spalloc(dofcount,1,floor(dofcount*sparsity));

	%Go through elements and build loads
	for n=n1:n2,
		
		if ~isempty(elements(n).element),
			%call element load generation
			pe=CreatePVector(elements(n).element,grids,materials,inputs,analysis_type);
		
			%plug element load vector into global vector
			pg=AddElemVector(pe,pg);

		end
	end

	%Go through loads created by presence of boundary conditions.
	for l=1:length(loads),
		if ~isempty(loads(l).load),
			%Call vector matrix generation
			pe=CreatePVector(loads(l).load,elements,grids,materials,inputs,analysis_type);
			
			%plug load contribution into load vector
			pg=AddElemVector(pe,pg);
		end
	end
else 
	pg={};
end
