function [Kgg,Pg,kmax]=PenaltySystemMatrices(grids,loads,materials,kflag,pflag, sparsity,inputs,analysis_type,Kgg,Pg);
%PENALTYSYSTEMMATRICES - add penalties to the stiffness matrix and load vector
%
%   Usage:
%      [Kgg,Pg,kmax]=PenaltySystemMatrices(grids,loads,materials,kflag,pflag, sparsity,inputs,analysis_type,Kgg,Pg)

%Get stiffness matrix maximum magnitude
kmax=max(max(abs(Kgg)));

if kflag, 
	
	%Go through loads capable of generating stiffnesses (penalties)
	for l=1:length(loads),
		
		if ~isempty(loads(l).load),
			%call load system matrix generation.
			Kpenalty=PenaltyCreateKMatrix(loads(l).load,grids,materials,inputs,analysis_type,kmax);
			
			%plug element system matrix into global system matrix.
			Kgg=AddElemMatrix(Kpenalty,Kgg);
		end
	end

else
	Kgg={};
end

if pflag, 

	%Go through loads created by penlties
	for l=1:length(loads),
		if ~isempty(loads(l).load),
			%Call vector matrix generation
			Ppenalty=PenaltyCreatePVector(loads(l).load,grids,materials,inputs,analysis_type,kmax);
			
			%plug load contribution into load vector
			Pg=AddElemVector(Ppenalty,Pg);
		end
	end
else 
	Pg={};
end
