#include "exec.hpp"



//------------ EXECUTER & Base Poliz Elem Module  ---------------//
//						  v 15 . 04 .  2007						 //
//																 //
//								MT								 //
//---------------------------------------------------------------//

void PolizElem :: Push(PolizElem *e) 
	{ exe->Push(e); };
PolizElem* PolizElem :: Pop() 
	{ return exe->Pop(); };


//------------------------------ HELPER ------------------------------+


//--- Show Error
void CExecuter :: ShowError(const char *str, char *str2)
{
	Error.Gum("Runtime error. ");
	Error.Gum(str);
	if (str2!=NULL){
		Error.Gum(" '"); Error.Gum(str2); Error.Gum("'");
	}
	Error.Gum("\n");
	Error.OnErrorSpit(-750);
};


//============================== HELPER ===============================

//--- Set Current by number
unsigned int CExecuter :: SetCur(unsigned int i, bool next)
{
	if (next) {
		cur = cur->next;
		cur_num++;
		return cur_num;
	} 
	if (i==0) throw "Wrong operation address.";

	cur = begin;
	unsigned int j=1;
	for (j=1; j<i; j++)
		cur = cur->next;
	cur_num = i;

	return cur_num;
};


//------------------------- Variables ---------------------------------

//--- Get Variable from VarTable
int CExecuter :: GetVar(char *str, int n)
{
	try { return VarTable.GetVar(str, n); }
	catch (const char *s) {
		if (strcmp(VT_VAR_NOT_FOUND, s) == 0)
		{
			Debug("|GetVar for undefined var|");
			SetVar(str, 0, n);
		}
		else 
			ShowError(s, str);
		return 0;
	}
};

void CExecuter :: SetVar(char *name, int val, int n)
{
	try { VarTable.SetVar(name, val, n); }
	catch (const char *s) {
		ShowError(s, name);
	}
	catch (...) {
		ShowError("Undefined error in VarTable");
	}
};

//--------------------------- Stack -----------------------------------

//--- Push 
void CExecuter :: Push(PolizElem *e)
{
	PolizItem *tmp = new PolizItem(e);
	stack.Push(tmp);
};


//--- Pop
PolizElem* CExecuter :: Pop()
{
	try {
		 PolizItem *tmp = stack.Pop();
		 PolizElem *val = tmp -> p;
		 delete tmp;
		 return val;
	}
	catch (CStackEmptyEx) {
		ShowError("Stack access: stack is empty.");
	}
	catch (...) {ShowError("Strange error about stack.");}
	return NULL;
};

//---------------------------------------------------------------------

//--- Destructor
CExecuter  :: ~CExecuter()
{ 
	delete begin;
};

