StateMachine =
{
---	m_iPrevState = 0,
	--m_iNextState = 0,
--	m_oBase = 0
}

-- Create, set the initial state
function StateMachine:Create( i_InitState, i_obj )

	-- Set the base object to call the state changes
	if ( i_obj == nil ) then
		ret = {}
	else
		ret = i_obj
	end
	
	-- The initial state
	ret.m_iState = 0
	
	-- Prev state
	ret.m_iPrevState = 0	
	
	-- Next State
	ret.m_iNextState = i_InitState

	ret.m_fTimeInState = 0
	
	StateMachine:Bind( ret )
	
	return ret;
end

function StateMachine:GetTimeInState()
	return self.m_fTimeInState
end

-- Set the state
function StateMachine:SetState( i_NextState )
	-- First make sure this isnt the current state
	if( i_NextState ~= self.m_iState ) then
		self.m_iNextState = i_NextState
	end
end

-- Main loop for driving the statemachine
function StateMachine:RunStateMachine( )
	self.m_fTimeInState = self.m_fTimeInState + 1 / 60

	-- If the next state is different from the current state
	if( self.m_iNextState ~= self.m_iState ) then
		--log( "next "..self.m_iNextState )
		-- Now set the prev state
		self.m_iPrevState = self.m_iState
		--log( "prev "..self.m_iPrevState )
		-- Set the current state
		self.m_iState = self.m_iNextState
		--log( "state "..self.m_iState )
		
		-- Now Call the leavestate function		
		if( self.OnLeaveState ~= nil ) then
			self:OnLeaveState( self.m_iPrevState )
		end
			
		-- Now call the enter state
		if( self.OnEnterState ~= nil ) then
			self.m_fTimeInState = 0
			self:OnEnterState( self.m_iState )
		end
	end
	
	-- Now call the run state function
	if( self.OnRunState ~= nil ) then
		self:OnRunState( self.m_iState )
	end
end

-- Return the current state
function StateMachine:GetState( )
	return self.m_iState
end

-- call this in C++ after a reload to rebind functions
function StateMachine:Bind( i_obj )
	-- $$ make bind obj recurse
	BindObj( self, i_obj )
end

-- bind one object to its base (refreshes any default functions, doesn't remove new)
function BindObj( i_base, i_obj )
	if ( i_obj ~= nil ) then
		for i in pairs( i_base ) do
			if ( type( i_base[ i ] ) == "function" ) then
				i_obj[ i ] = i_base[ i ]
			end
		end
	end
end
