%-----------------------------------------------------------------------
%	CreateFEMModel.m: from a matlab ISSM @model class object, create a finite element 
%                  compatible with Cielo.
%
%-----------------------------------------------------------------------
function  m=CreateFEMModel(md,analysis_type )

	global ParameterDefaults

%	read input data:

	disp(sprintf('\n   reading data from model %s...',md.name));
	[m.ncase, m.dynamic, m.ept, m.geom1, m.geom1b, m.geom2, m.part, m.tpart, m.geom3, ...
		m.geom4, m.mpt, m.pvt, m.sets, m.dit] = newImp( md ,analysis_type);

		error;
		
%	generate list of states from case control (ncase), if any:

	disp('   generating states...');
	[m.states] = GenerateStates( m.ncase, m.dynamic);
	
	%ncase not needed anymore
	m=rmfield(m,'ncase');

%	generate grid point definition table
%	(internal grid records, contain sil and uset data)
	
	disp('   generating gpdt...');
	[m.gpdt,m.gpdtb] = Gp1( m.geom1, m.geom1b);

	
%	generate coordinate system transformation matrices, transform
%	grids to basic coordinate system

	disp('   generating updated gpdt...');
	[m.cstm, m.bgpdt, m.bgpdtb] = Gp1b( m.geom1, m.geom1b, m.gpdt, m.gpdtb);

	m=rmfield(m,'gpdt');
	if ~isempty(m.gpdtb), m=rmfield(md,'gpdtb');end;

	%geom1 and geom1b not needed anymore
	m=rmfield(m,'geom1');
	if ~isempty(m.geom1b), m=rmfield(m,'geom1b'); end;

	%disp('   generating element objects...');
	[m.est,m.lst] = Gp2( m.bgpdt, m.bgpdtb, m.ept, m.geom2, m.mpt, m.geom3);

	%geom2 not needed anymore
	m=rmfield(m,'geom2');

%	phase 1:
%
	
%	set parameters using bulk data, nastran case control above subcase level:
	current_state = {};
	[next_state] = NextState( m.states, current_state);
	m.current_state = next_state;
	clear next_state current_state;

	[m.params] = Pvt( m.current_state, m.pvt);
	

%	generate usets and constraint matrices:

	disp('   generating uset data and constraints...');

	[m.updated_bgpdt, m.updated_bgpdtb, m.y_g, m.R_mg] = Gp4( m.states, m.geom4, m.bgpdt, m.bgpdtb,analysis_type);
	
	
	%geom4 not needed anymore
	if ~isempty(m.geom4), m=rmfield(m,'geom4');end;

%	replace old bgpdt with new (bgpdt unchanged if nonexistent updated_bgpdt):
	m.bgpdt = m.updated_bgpdt;m=rmfield(m,'updated_bgpdt');
	if ~isempty(m.updated_bgpdtb),
		m.bgpdtb = m.updated_bgpdtb;
		m=rmfield(m,'updated_bgpdtb');
	end;

%   create uset table 
	m.uset=Builduset(m.bgpdt,m.bgpdtb,analysis_type); 

	
%
%	phase 1:
%
%	autospc operations:
%	autospc is done on the g_set, it should be done on the n_set later

%	Partition R_mg into R_mm and R_mn, and
%	calculate G_mn = - R_mm^-1 * R_mn  (MCE1 type operations)

	[m.G_mn] = Normalizeconstraints( m.R_mg, m.uset);

%	Reduce enforced displacements / temperatures 
	[m.y_s] = Reducevectorg( m.y_g ,m.uset);
	

	if isempty(m.y_s),
		flag_y_s= 0;
	else
		flag_y_s= 1;
	end
end
