/*
 *  EpeeEngine.cpp
 * 
 *
 *  EpeeEngine
 *	Created by Alan Uthoff on 3/12/06.
	Copyright (C) 2006

	This Code is free software; you can redistribute it and/or
    modify it under the terms of the zlib/libpng License as published 
	by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
	This software is provided 'as-is', without any express or implied warranty. 

	In no event will the authors be held liable for any damages arising from the use of this software.

	Permission is granted to anyone to use this software for any purpose, 
	including commercial applications, and to alter it and redistribute 
	it freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; 
	   you must not claim that you wrote the original software. 
	   If you use this software in a product, an acknowledgment 
	   in the product documentation would be appreciated but is not required.

    2. Altered source versions must be plainly marked as such, 
		and must not be misrepresented as being the original software.

    3. This notice may not be removed or altered from any source distribution.


*/

#define Version_Number_cpp .272
//#include <iostream>

#include <cstdio>
#include <vector>
#include "tinyxml.h"
#include "tinystr.h"
#if defined(_MSC_VER)
#include "SDL.h"

#else
#include "SDL/SDL.h"

#endif
//#include <SDL_main.h>
#include "EpeeEngine.h"	
#include "SDL_ttf.h"
#include "SDL_framerate.h"
#include "SDL_mixer.h"
//#include "SDL_imageFilter.h"
#include "SDL_rotozoom.h"

#define Graphics_Engine_Credits  " Made with the Epee Engine"
#define DEBUG_ME


//*************Sound Class Funtions*******************************
Sound::Sound(std::string _Name ,std::string _FileName,int _Channel,int _NumberOfTimesToLoop, int _Volume)
	{
		m_sName=_Name;
		m_sFileName=_FileName;
		m_iChannel=_Channel;
		m_pSound=NULL;
		m_iNumberOfTimesToLoop=_NumberOfTimesToLoop;
		if (_Volume>=0)
		{
			m_iVolume=_Volume;
		}
		else
		{
			m_iVolume=MIX_MAX_VOLUME;
		}
		
	}

Sound::~Sound()
	{
		if (m_pSound) {
			Mix_FreeChunk(m_pSound);

		}
	}

	int Sound::GetVolume()
	{
		
		return m_iVolume;
	}
	bool Sound::SetVolume(int _Volume)
	{
		
		if (m_pSound)
		{
			m_iVolume=_Volume;
			Mix_VolumeChunk(m_pSound,m_iVolume);
			return true;
		}
		else
		{
			return false;
		}
	}
	bool Sound::LoadSound()
	{
		
		if (m_pSound)
		{
			Mix_FreeChunk(m_pSound);
		}

		m_pSound=Mix_LoadWAV(m_sFileName.c_str());
	
		if (m_pSound)
		{
			Mix_VolumeChunk(m_pSound,m_iVolume);
		return true;
		}
		else
		{
			return false;
		}
	
	
	}

	Mix_Chunk * Sound::GetMixChunkPointer()
	{
		return m_pSound;
	}

	bool Sound::SetChannel(int _ChannelToSetTo)
	{
		m_iChannel=_ChannelToSetTo;
		if (m_iChannel==_ChannelToSetTo)
		{
			return true;
		}
		else
			return false;
	}

	int Sound::GetChannel()
	{
		return m_iChannel;
	}
	
	bool Sound::SetNumberOfTimesToLoop(int _NumberOfTimesToLoop)
	{
		m_iNumberOfTimesToLoop=_NumberOfTimesToLoop;
		if (m_iNumberOfTimesToLoop==_NumberOfTimesToLoop)
		{
			return true;
		}
		else
			return false;
	}

	int Sound::GetNumberOfTimesToLoop()
	{
		return m_iNumberOfTimesToLoop;
	}
	std::string Sound::GetName()
	{
		return m_sName;
	}
//************************End Of Sound Class Funtions*****************************


//***********************Sprocket Class Funtions**********************************

	Sprockets::Sprockets(std::string _NameMain,int _TypeMain)
	{
		m_sName	= _NameMain;
		m_iSprocketType=_TypeMain;
		m_bDraw=true;
		m_iz=0;
		m_bDraw=true;
		m_iCurrentPostion=0;
		 m_iRotation=0;
			 m_iScaleX=1;
			 m_iScaleY=1;
			 m_iAntiAliased=0;
			 m_porignalSurface=NULL;
			 m_bblit=true;
			 m_bactive=true;
			 m_bDontMoveButton=true;
			 	m_cCurrentError.m_iErrorCode=EPEE_NO_ERROR;
		m_cCurrentError.m_sError_Message=" ";
		m_cCurrentError.ObjectWhereErrorOccured=NULL;
	}

	Sprockets::Sprockets(std::string _NameMain,int _TypeMain, int _x, int _y,int _z)
	{
		m_sName	= _NameMain;
		m_iSprocketType=_TypeMain;
		m_cBox.x=_x;
		m_cBox.y=_y;
		m_iz=_z;
		m_bDraw=true;
		m_iCurrentPostion=0;
		 m_iRotation=0;
			 m_iScaleX=1;
			 m_iScaleY=1;
			 m_iAntiAliased=0;
			 m_porignalSurface=NULL;
			 m_bblit=true;
			  m_bactive=true;
			  m_bDontMoveButton=true;
			  	m_cCurrentError.m_iErrorCode=EPEE_NO_ERROR;
		m_cCurrentError.m_sError_Message=" ";
		m_cCurrentError.ObjectWhereErrorOccured=NULL;
	}
	
	Sprockets::Sprockets()
	{
		m_sName=" ";
		m_iSprocketType=Type_Image;
		m_cCurrentError.m_iErrorCode=EPEE_NO_ERROR;
		m_cCurrentError.m_sError_Message=" ";
		m_cCurrentError.ObjectWhereErrorOccured=NULL;
	}
	 Sprockets::~Sprockets()
	{
            if(m_porignalSurface)
	SDL_FreeSurface(m_porignalSurface);
	}


	void Sprockets::SetLocation(int _x,int _y)
	{
		m_cBox.x=_x;
		m_cBox.y=_y;
	}

   
	 int Sprockets::GetLocationX()
	{
		return m_cBox.x;
	}

	 int Sprockets::GetLocationY()
	{
		return m_cBox.y;
	}
	std::string Sprockets::GetName()
	{
		return m_sName;
	}
	int Sprockets::GetLocationZ ()
	{
		return m_iz; 
	}
	EpeeEngineError Sprockets::GetLastError()
	{
		return m_cCurrentError; 
	}
	
	void Sprockets::SetLastError(EpeeEngineError _error)
	{
		m_cCurrentError.m_iErrorCode=_error.m_iErrorCode;
		m_cCurrentError.m_sError_Message=_error.m_sError_Message;
		m_cCurrentError.ObjectWhereErrorOccured=_error.ObjectWhereErrorOccured;
		cerr<<"Error Has Occured In "<<this->GetName()<<"Error: "<<m_cCurrentError.m_sError_Message<<endl;

	}
	void Sprockets::ClearError()
	{
			m_cCurrentError.m_iErrorCode=EPEE_NO_ERROR;
		m_cCurrentError.m_sError_Message=" ";
		m_cCurrentError.ObjectWhereErrorOccured=NULL;
	}

	 void Sprockets::SetHeightWidth(unsigned int _Height,unsigned int _Width)
	{
		m_cBox.h=_Height;
		m_cBox.w=_Width;
		
	 }

	unsigned int Sprockets::GetHeight()
	{
		return m_cBox.h;
	}
	unsigned int Sprockets::GetWidth ()
	{
		return m_cBox.w;
	}
   
	bool Sprockets::SetDraw(bool _Draw)
	{
		m_bDraw=_Draw;
			if(m_bDraw==_Draw)
				return true;
			else
				return false;
	}

	bool Sprockets::GetDraw()
	{
		return m_bDraw;
	}

	int Sprockets::GetType()
	{
		return m_iSprocketType; 
	}
  
   
   
   bool Sprockets::SetScalingFactor(double _ScalingX,double _ScalingY)
	{
		m_iScaleX=_ScalingX;
		m_iScaleY=_ScalingY;
		if (m_iScaleX==_ScalingX && m_iScaleY==_ScalingY )
		return true;
		else
		return false;
		
	}
	
	
	 bool Sprockets::SetScalingFactorY(double _ScalingY)
	{
		m_iScaleY=_ScalingY;
		if (m_iScaleY==_ScalingY )
		return true;
		else
		return false;
		
	}
	 bool Sprockets::SetScalingFactorX(double _ScalingX)
	{
		m_iScaleX=_ScalingX;
		if (m_iScaleX==_ScalingX )
		return true;
		else
		return false;
		
	}
	
	double  Sprockets::GetScalingFactorX()
	{
		return m_iScaleX;
	
	}
	double  Sprockets::GetScalingFactorY()
	{
		return m_iScaleY;
	
	}
	bool Sprockets::SetRotation(double _Degrees )
	{
		m_iRotation=_Degrees;
		if (m_iRotation==_Degrees)
		return true;
		else
		return false;
		
	}
   double Sprockets::GetRotation()
	{
		return m_iRotation;
	}
	
	bool Sprockets::SetAntiAliased(bool _AntiAliased )
	{
		m_iAntiAliased=_AntiAliased;
		if (m_iAntiAliased==_AntiAliased)
		return true;
		else
		return false;
		
	}
	bool Sprockets::GetAntiAliased()
	{
		return m_iAntiAliased;
	}
   
   int Sprockets::GetCurrentVectorPostion()
   {
       return m_iCurrentPostion;
   }

     Sprockets * Sprockets::WasClicked(int _mouselocationX, int _mouselocationY)
	{
	
		if(m_bactive )
		{
		
		
			if( ( _mouselocationX >  m_cBox.x ) && ( _mouselocationX <  m_cBox.x +  m_cBox.w ) && (_mouselocationY >  m_cBox.y ) && (_mouselocationY < m_cBox.y + m_cBox.h ) )
			{
				return this;
			}
		
		
	
		
		}
	
	
		return NULL;
	
	}
   
	void Sprockets::DisableClick()
	{	
		m_bactive=false;
	}

	void Sprockets::EnableClick()
	{
		m_bactive=true;
	}
	bool Sprockets::GetIsClickEnabled()
	{
		return m_bactive;
	}	

	void Sprockets::DisableAndTurnOffDraw()
	{
		m_bactive=false;
		SetDraw(false);
	}

	void Sprockets::EnableAndTurnOnDraw()
	{
	m_bactive=true;
	SetDraw(true);
	}


	void Sprockets::SetDontMoveOnClick(bool _flag)
	{
	m_bDontMoveButton=_flag;
	}

	bool Sprockets::GetDontMoveOnClick()
	{	
		return m_bDontMoveButton;
	}
    


 
	bool Sprockets::GetBlit()
	 {
        return this->m_bblit;
	}

	 SDL_Surface * Sprockets::SetSurface()
	{
        return NULL; 
    }
		
	 SDL_Surface * Sprockets::GetSprocketSurface()
    {
                return m_porignalSurface;
                }
    
		
	SDL_Rect * Sprockets::GetRect()
	{
			return  &m_cBox;
	}
          
	bool Sprockets::SetCurrentArrayPostion(int _newPostion)
     {
         m_iCurrentPostion=_newPostion;
          if(  m_iCurrentPostion==_newPostion)
           {
              return true;
           }
           else
            return false;
     }

	void Sprockets::SetType(int _type)
	{
		m_iSprocketType=_type;	
	}
	void Sprockets::SetLocationZ(int _z)//DO NOT call this function call ChangeSprocketZ instead
	{
		m_iz=_z;
	}

	void Sprockets::SetBlit(bool _blit)
	{
	m_bblit=_blit;
	}
	

//************************End Of Sprocket Class Funtions*****************

//*************************Begining Of RenderList Class Funtions***********************************	
	RenderList::RenderList(std::string _name)
	{
		m_sNameOfRenenderList=_name;
		m_pLastSprocketFound=NULL;
		m_uiTotalSprocketsCreated=0;
		this->ClearError()	;
	}

	RenderList::~RenderList()
	{
		unsigned int TotalSprocketsDeleted=0;
	
		while(m_vSprocketsList.size()!=0)
		{
			DestroySprocket(m_vSprocketsList[0]->GetName());
			TotalSprocketsDeleted++;					

		}

		if (m_uiTotalSprocketsCreated!=0) 
		{
			cerr<<"*****WARING MEMORY LEAK****"<<endl;
			cerr<<"There are still "<<m_uiTotalSprocketsCreated<<" Sprockets that where not deleted"<<endl;
		}
	
	
	}


	EpeeEngineError RenderList::GetLastError()
	{
		return m_cCurrentError; 
	}
	
	void RenderList::SetLastError(EpeeEngineError _error)
	{
		m_cCurrentError.m_iErrorCode=_error.m_iErrorCode;
		m_cCurrentError.m_sError_Message=_error.m_sError_Message;
		m_cCurrentError.ObjectWhereErrorOccured=_error.ObjectWhereErrorOccured;
		cerr<<"Error Has Occured In "<<this->GetName()<<"Error: "<<m_cCurrentError.m_sError_Message<<endl;

	}
	void RenderList::ClearError()
	{
			m_cCurrentError.m_iErrorCode=EPEE_NO_ERROR;
		m_cCurrentError.m_sError_Message=" ";
		m_cCurrentError.ObjectWhereErrorOccured=NULL;
	}

	std::string RenderList::GetName()
	{
		return m_sNameOfRenenderList;
	}

	bool RenderList::InsertSprocket(Sprockets * _newSprocket,bool _new)
	{
	#if defined DEBUG_ME

			int tempz=0;
			if(m_vSprocketsList.size()!=0)
				tempz=m_vSprocketsList[m_vSprocketsList.size()-1]->GetLocationZ();


	#endif
		if (m_vSprocketsList.size()!=0 && !(m_vSprocketsList[m_vSprocketsList.size()-1]->GetLocationZ() > _newSprocket->GetLocationZ()))
		{
			//m_vSprocketsList.push_back(_newSprocket);
			for(unsigned int index2=0; index2<m_vSprocketsList.size();index2++)
			{
		
				if(_newSprocket->GetLocationZ()>=m_vSprocketsList[index2]->GetLocationZ())
				{
					m_vSprocketsList.insert(m_vSprocketsList.begin()+index2,_newSprocket);
					 _newSprocket->SetCurrentArrayPostion(index2);
					if(_new)
					{
					m_uiTotalSprocketsCreated++;
					}
					break;
				}
		
			}


		}	
		else
		{
			m_vSprocketsList.push_back(_newSprocket);
			if(_new)
			{
			m_uiTotalSprocketsCreated++;
			}
		}

	return true;

	}



bool RenderList::DestroySprocket(std::string _name)
{
	Sprockets * temp=NULL;
	bool retunval=false;
		for(unsigned int index = 0;index<m_vSprocketsList.size();index++)
	{
			if(m_vSprocketsList[index]->GetName()==_name)
			{
				if(m_pLastSprocketFound!=NULL)
				{
               if(m_pLastSprocketFound->GetName()==_name)
                    m_pLastSprocketFound=NULL;
				}
			   temp=m_vSprocketsList[index];
				m_vSprocketsList.erase(m_vSprocketsList.begin()+index);
				delete temp;
				 m_uiTotalSprocketsCreated--;
				retunval=true;
				index=m_vSprocketsList.size();

			}
		}
		if (!retunval) 
		{
		
		//	m_sCurrentError="Could Not Find And Delete Sprocket ";
		//	m_sCurrentError=m_sCurrentError+_name;
			 EpeeEngineError temperror("Could Not Find And Delete Sprocket "+_name,SPROCKET_DELETING_ERROR,this);
			 SetLastError(temperror);

		}
	return retunval;
	}

	bool RenderList::UpdateVectorlocation()
	{
	   for(unsigned int index = 0;index<m_vSprocketsList.size();index++)
		{
             m_vSprocketsList[index]->SetCurrentArrayPostion(index);
             
             
         }
     return true;
	}

	bool RenderList::ChangeSprocketZ(Sprockets * _SprocketToChange,int _newZ)
	{
		UpdateVectorlocation();
		m_vSprocketsList.erase(m_vSprocketsList.begin()+_SprocketToChange-> GetCurrentVectorPostion());
		_SprocketToChange->SetLocationZ(_newZ);
		InsertSprocket(_SprocketToChange);
	return true;
	}

	Sprockets *  RenderList::FindSprockets(std::string _name)
	{
		#if defined(DEBUG_ME)
			std::string temp_name=" ";
		#endif
		if(m_pLastSprocketFound!=NULL)
		{
	
			if(this->m_pLastSprocketFound->GetName()==_name)
			{
		    return m_pLastSprocketFound;
			 } 
		}   
		for (unsigned int index=0;index<m_vSprocketsList.size();index++)
		{
			#if defined(DEBUG_ME)
				temp_name=m_vSprocketsList[index]->GetName();
				if(temp_name==_name)
				{
                         m_pLastSprocketFound=m_vSprocketsList[index];
				    	   return m_vSprocketsList[index];
				}
			#else


			if(m_vSprocketsList[index]->GetName()==_name)
			{
			    m_pLastSprocketFound=m_vSprocketsList[index];
				 return m_vSprocketsList[index];
			}

			#endif
	

		}
		//m_sCurrentError="Could Not Find Sprocket ";
		//	m_sCurrentError=m_sCurrentError+_name;
		//cerr<<"Could Not Find Sprocket "<<_name<<endl;
		EpeeEngineError temperror("Could Not Find Sprocket "+_name,SPROCKET_NOT_FOUND,this);
		this->SetLastError(temperror);
		return NULL;
	}

	unsigned int RenderList::GetTotalSprockesCreated()
	{
		return m_uiTotalSprocketsCreated;
	}

	void RenderList::RemoveSprocketFromList(Sprockets * _sprocketToErase)
	{
	for(unsigned int index = 0;index<m_vSprocketsList.size();index++)
		{
			if(m_vSprocketsList[index]->GetName()==_sprocketToErase->GetName())
			{
			m_vSprocketsList.erase(m_vSprocketsList.begin()+index);
			break;
			}
		}
	m_pLastSprocketFound=NULL;
	m_uiTotalSprocketsCreated--;
	}
//***************************End Of RenderList Class Funtions***********************************



//**************************Begin of FileLookUp Class Funtions*****************

	FileLookUp::FileLookUp()
	{
		m_ssymbol=" ";
		m_sfilename=" ";
	}
	
	FileLookUp::FileLookUp(std::string _Symbol, std::string _fileName)
	{
		
		 m_ssymbol=_Symbol;
		 m_sfilename=_fileName;

	}
//**************************End of FileLookUp Class Funtions*****************

//**************************Begin of EpeeEngineError Class Funtions**********
	EpeeEngineError::EpeeEngineError(std::string _message,int _code,void * obj)
	{
	m_sError_Message=_message;
	m_iErrorCode=_code;
	ObjectWhereErrorOccured=obj;
	}
	EpeeEngineError::EpeeEngineError()
	{
	m_sError_Message=" ";
	m_iErrorCode=0;
	ObjectWhereErrorOccured=NULL;
	}
//**************************End of EpeeEngineError Class Funtions**********

//**************************Begin Of textBox Class Funions*****************


	textBox::textBox(int _Obj_Type,std::string _NameTextBox,int _x,int _y,int _z,std::string _TextBoxMessage,unsigned int _height,unsigned int _width,std::string _Font,int _FontPoint,unsigned int _red,unsigned int _blue ,unsigned int _green,std::string _FontPath):Sprockets(_NameTextBox,_Obj_Type)
	{
	
	 m_sTextBoxMessage=_TextBoxMessage;
	 SetLocation(_x,_y);
	 
	 SetLocationZ(_z);
	// m_sFont=_Font;
	 m_bQuality=FONT_QUALITY_LOW;
	 m_iFontPoint=_FontPoint;
		m_cColorOfText.r=_red;
			m_cColorOfText.b=_blue;
			m_cColorOfText.g=_green;
		m_sTrue_Type_Font_Location=_FontPath;//True_Type_Font_Location  is defined at the top of the file
	m_bblit=true;
	m_pLoadedFont=NULL;
	m_bEditable=false;
	m_bNumbersOnly=false;
		m_iJustify=TEXT_LEFT_JUSTIFIED;
		m_iOffsetXJustiy=0;
    //m_pLoadedFont=
		this->SetFont(_Font);
	 SetHeightWidth(_height,_width);
	 
	}

	textBox::textBox(std::string _NameTextBox, int _x, int _y,int _z,std::string _TextBoxMessage,unsigned int _height,unsigned int _width,std::string _Font,int _FontPoint,unsigned int _red,unsigned int _blue ,unsigned int _green,std::string _FontPath):Sprockets(_NameTextBox,Type_TextBox)
	{
	
	 m_sTextBoxMessage=_TextBoxMessage;
	 SetLocation(_x,_y);
	 
	 SetLocationZ(_z);
	 //m_sFont=_Font;
	 m_bQuality=FONT_QUALITY_LOW;
	 m_iFontPoint=_FontPoint;
		m_cColorOfText.r=_red;
			m_cColorOfText.b=_blue;
			m_cColorOfText.g=_green;
		m_sTrue_Type_Font_Location= _FontPath;//True_Type_Font_Location  is defined at the top of the file
	m_bblit=true;
	m_pLoadedFont=NULL;
	m_bEditable=false;
	m_bNumbersOnly=false;
	m_iJustify=TEXT_LEFT_JUSTIFIED;
	m_iOffsetXJustiy=0;
    //m_pLoadedFont=
	this->SetFont(_Font);
	this->SetHeightWidth(_height,_width);
	
	}

	
	textBox::textBox()
	{
             }

	textBox::~textBox()
	{
		if(m_pLoadedFont)
		{
			TTF_CloseFont(m_pLoadedFont);
		}
		 
	}
	
	
	bool textBox::GetClipTextHeight()
	{
		return m_bDoNotClipTextHeight;
	}

	bool textBox::GetClipTextWidth()
	{
		return m_bDoNotClipTextWidth;
	}

	void textBox::SetQuality(int _Quality)
	{
		if(_Quality!=m_bQuality && _Quality>=FONT_QUALITY_LOW && _Quality<=FONT_QUALITY_HIGH )
		{
		m_bQuality=_Quality;
			this->SetBlit(true);
		}
	}

	int textBox::GetQuality()
	{
		return m_bQuality;

	}

	void textBox::SetText(std::string _text,bool _setevent)
	{
		if (m_sTextBoxMessage!=_text)
		{
			SetBlit(true);
		}
		
		m_sTextBoxMessage=_text;
		if(GetBlit())
		{
		if(m_bDoNotClipTextHeight || m_bDoNotClipTextWidth)
		{
			if(m_bDoNotClipTextHeight )
			 {
				SetHightBasedOfRenderedText();
				
			 }
			 if(m_bDoNotClipTextWidth)
			 {
				SetWidthBasedOfRenderedText();
				
			 }
		}
		}
		
		if (_setevent) {
		
		SDL_Event event;

		event.type = SDL_USEREVENT;
		event.user.code = TEXT_BOX_CHANGED_EVENT;
		event.user.data1 = this;
		event.user.data2 = 0;
		SDL_PushEvent(&event);
		}
		SetJustifyOffset();
		
	}

	void textBox::SetHeightWidth(unsigned int _Height,unsigned int _Width)
	{
		
		 if (_Height==-1 || _Width==-1) 
		 {
			 if(_Height==-1)
			 {
				SetHightBasedOfRenderedText();
				_Height=this->GetHeight();
				m_bDoNotClipTextHeight=true;
			 }
			 else
			 {
				m_bDoNotClipTextHeight=false;
			 }
			 if(_Width==-1)
			 {
				SetWidthBasedOfRenderedText();
				_Width=this->GetWidth();
				m_bDoNotClipTextWidth=true;
			 }
			 else
			 {
				 m_bDoNotClipTextWidth=false;
			 }
		 
		
			

		}
		 else
		 {
			  m_bDoNotClipTextWidth=false;
			  m_bDoNotClipTextHeight=false;

		 }
		
			Sprockets::SetHeightWidth(_Height,_Width);
		
				
		 
		
	 }

	void textBox::SetHightBasedOfRenderedText()
	{
			int w=0,h=0;
			if (m_pLoadedFont) {
			
			if (TTF_SizeText(m_pLoadedFont,m_sTextBoxMessage.c_str(),&w,&h)) {
				return;
			}
			
	Sprockets::SetHeightWidth(h,this->GetWidth());
			}

	}		
	
	
	void textBox::SetWidthBasedOfRenderedText()
	{
			int w=0,h=0;
			if (m_pLoadedFont) {
			if (TTF_SizeText(m_pLoadedFont,m_sTextBoxMessage.c_str(),&w,&h)) {
				return;
			}
			
		Sprockets::SetHeightWidth(this->GetHeight(),w);

			}
	}


	int textBox::GetJustifyOffset()
	{
		return m_iOffsetXJustiy;
	}

	int textBox::GetTextJustification()
	{
		return m_iJustify;
	}

	void textBox::SetTextJustification(int _justify)
	{
		if (_justify==TEXT_LEFT_JUSTIFIED || _justify==TEXT_RIGHT_JUSTIFIED || _justify ==TEXT_CENTER_JUSTIFIED) {
		m_iJustify=_justify;
		 SetJustifyOffset();
		
		}
	}

	std::string textBox::GetText ()
	{
		return m_sTextBoxMessage;
	}




	int textBox::GetTextToInt()
	{
		int tempint=0;
		return GetTextToNumericData(tempint);
	}


	float textBox::GetTextToFloat()
	{		
		float tempint=0;
		return GetTextToNumericData(tempint);
	}


	bool  textBox::SetTextFromInt(int _value,bool _setevent)
	{
		return SetTextFromNumericData( _value, _setevent);
	}

	bool textBox::SetTextFromFloat(float _value,bool _setevent)
	{
	return SetTextFromNumericData( _value, _setevent);
	}


	std::string textBox::GetFont()
	{
		return m_sFont;
	}

	void textBox::SetFont(std::string _FontArg)
	{
		if(m_sFont!=_FontArg)
		{
		
		m_sFont=_FontArg;
		LoadFont();
		}
	}

	int textBox::GetFontPoint()
	{
		return m_iFontPoint;
	}

	void textBox::SetFontPoint(int _FontPointArg)
	{	if(m_iFontPoint!=_FontPointArg)
		{
		m_iFontPoint=_FontPointArg;
		LoadFont();
		}
	}

	SDL_Color textBox::GetTextColor()
	{
		return m_cColorOfText;
	}

	bool textBox::SetTextColor(unsigned int _red,unsigned int _blue ,unsigned int _green)
	{
		if(m_cColorOfText.r!=_red || m_cColorOfText.b!=_blue || m_cColorOfText.g!=_green)
		{
			m_cColorOfText.r=_red;
			m_cColorOfText.b=_blue;
			m_cColorOfText.g=_green;
			SetBlit(true);;
		}

	return true;
	}
	
	std::string textBox::GetFontPath()
	{
		return m_sTrue_Type_Font_Location;
	}

	void textBox::SetFontPath(std::string _Location)
	{
		m_sTrue_Type_Font_Location=_Location;
		LoadFont();
	}

	void textBox::SetEditable(bool _flag)
	{
		m_bEditable=_flag;

	}

	bool textBox::GetEditable()
	{
		return m_bEditable;
	}
	
	void textBox::SetNumbersOnly(bool _flag)
	{
		m_bNumbersOnly=_flag;

	}

	bool textBox::GetNumbersOnly()
	{
		return m_bNumbersOnly;
	}


	TTF_Font * textBox::GetFontPointer()
	{
             return m_pLoadedFont;
          }



	SDL_Surface * textBox::SetSurface()
	{
		if (m_pLoadedFont!=NULL) 
		{
	
		
         if(m_porignalSurface)
         {
         SDL_FreeSurface(m_porignalSurface);
	      }
			switch (m_bQuality)
			{
			case FONT_QUALITY_HIGH :
				m_porignalSurface=TTF_RenderText_Blended( m_pLoadedFont,m_sTextBoxMessage.c_str(),m_cColorOfText);
			break;
			case FONT_QUALITY_LOW:
				m_porignalSurface=TTF_RenderText_Solid( m_pLoadedFont,m_sTextBoxMessage.c_str(),m_cColorOfText);
			break;
			default:
				m_porignalSurface=TTF_RenderText_Solid( m_pLoadedFont,m_sTextBoxMessage.c_str(),m_cColorOfText);
			break;
			}
	   
        
         if(m_porignalSurface)
		 SetBlit(false);
         else
         SetBlit(true);
        return    m_porignalSurface; 
	}
	else
	{
		return NULL;
	}
	return NULL;
    }

	void textBox::LoadFont()
	{
         std::string FontToLoad=m_sTrue_Type_Font_Location+ m_sFont;
         if(m_pLoadedFont)
         {
         TTF_CloseFont(m_pLoadedFont);
         m_pLoadedFont=TTF_OpenFont(FontToLoad.c_str(),m_iFontPoint);
         }
         else
         {
            m_pLoadedFont=TTF_OpenFont(FontToLoad.c_str(),m_iFontPoint);
         }
		
		 
		 if(!m_pLoadedFont)
		{
             cerr<<"could not load font "<<FontToLoad.c_str()<<" for Sprocket "<<GetName()<<endl;               
        }
        else
        {			    
        cout<<"loaded  font "<<FontToLoad.c_str()<<" for Sprocket "<<GetName()<<endl;
        }
                           
         SetBlit(true);
         
     }

	void textBox::SetJustifyOffset()
	{
	
		std::string tempforJustiying="";
		int w=0,h=0,spacesizewidth=0;
		if (m_iJustify!=TEXT_LEFT_JUSTIFIED && m_pLoadedFont!=NULL) {
			
			
			if (TTF_SizeText(m_pLoadedFont,m_sTextBoxMessage.c_str(),&w,&h)) {
				return;
			}
			switch(m_iJustify) {
			case TEXT_RIGHT_JUSTIFIED:
				m_iOffsetXJustiy=this->GetWidth()-w;
				break;
			case TEXT_CENTER_JUSTIFIED:
					m_iOffsetXJustiy=this->GetWidth()-w;
					m_iOffsetXJustiy=m_iOffsetXJustiy/2;
				break;
		
			}
		}

	}
	template <typename datatype> 
	datatype textBox::GetTextToNumericData(datatype temp)
	{datatype tempint=0;
			std::istringstream tempstream(m_sTextBoxMessage);
			if (!(tempstream>>tempint)) {
				std::string tempstring ="Could not convert"+m_sTextBoxMessage+"to the specified data type";
				 EpeeEngineError temperror(tempstring,TEXTBOX_CONVERION_ERROR,this);
				this->SetLastError(temperror);
				return 0;
			}
			this->ClearError();
			return tempint;
	}

	template <typename datatype> 
	bool  textBox::SetTextFromNumericData(datatype _value,bool _setevent)
	{
			datatype tempint=_value;
			std::ostringstream tempstream;
			if (!(tempstream<<_value)) {
				
				std::string tempstring ="Could not convert numeric data to string";
				 EpeeEngineError temperror(tempstring,TEXTBOX_CONVERION_ERROR,this);
				this->SetLastError(temperror);
				return false;
				
			}
			this->SetText(tempstream.str(),_setevent);
			this->ClearError();
			return true;
	}

//**************************End of texBox Class Funtions*****************************

//**************************Begin of image Class Funtions****************************
	image::image (std::string _FileNameImage, std::string _NameImageHere,int _x,int _y,int _z,bool _Transparency):Sprockets( _NameImageHere,Type_Image ,_x, _y, _z)
	{
		m_sFileName=_FileNameImage;
		m_bClip=false;
		m_bTransparency=_Transparency;
			 

	}
	std::string image::GetFileName()
	{
		return m_sFileName;
	}
	void image::SetClippingRect(int _x,int _y,int _w,int _h)
	{
		ClipingRect.x=_x;
		ClipingRect.y=_y;
		ClipingRect.w=_w;
		ClipingRect.h=_h;
		m_bClip=true;
	}
	bool image::GetClip()
	{
		return m_bClip;
	}
	int image::GetClippingX()
	{
		return ClipingRect.x;
	}
	int image::GetClippingY()
	{
		return ClipingRect.y;
	}
	int image::GetClippingW()
	{
		return ClipingRect.w;
	}
	int image::GetClippingH()
	{
		return ClipingRect.h;
	}

	void image::SetTransparency (bool _Transparency)
	{
		m_bTransparency=_Transparency;
		//this->GetSprocketSurface()->flags=this->GetSprocketSurface()->flags & 0x11101111;
		//#define SDL_SRCALPHA	0x00010000
	}
	bool image::GetTransparency()
	{
		return m_bTransparency;
	}

 
	bool image::LoadFileSurface()
	{
		if(m_sFileName==" ")
		{
			cerr<<"no file name associated with "<<GetName()<<endl;
			
			return false;
		}
		m_porignalSurface=IMG_Load(m_sFileName.c_str()); 
         cout<<"Image File Name "<<m_sFileName.c_str()<<endl;
         if(m_porignalSurface)
         {
			 m_cOrgialDem.h=m_porignalSurface->h;
			m_cOrgialDem.w=m_porignalSurface->w;
			m_cOrgialDem.x=0;
				m_cOrgialDem.y=0;
			 m_cBox.h=m_porignalSurface->h;
			 m_cBox.w=m_porignalSurface->w;
                              cout<<"Loaded image correctly"<<endl;
         return true;
         }
         else
         {
             cerr<<"Loaded image INcorrectly "<<IMG_GetError()<<endl;
			 cout<<"Loaded image INcorrectly "<<IMG_GetError()<<endl;
         return false;
         }
     }

	image::image (std::string _FileNameImage, std::string _NameImageHere,int _x,int _y,int _z,int _type,bool _Transparency):Sprockets( _NameImageHere,_type ,_x, _y, _z)
	{
		m_sFileName=_FileNameImage;
		 m_bClip=false;
		m_bTransparency=_Transparency;
		
	}

	 image::image()
	{
		 
		 
	}

	image::image(std::string _FileNameImage)
	{
		m_sFileName=_FileNameImage;
		
	}
	
	SDL_Rect * image::GetClippingRect()
	{
	return &ClipingRect;
	}

	SDL_Rect * image::GetOrignalRect()
	{
	return &m_cOrgialDem;
	}
	
//**************************End of image Class Fuctions********************************


//*************************Begin of Animation Class Functions**************************

	Animation::Animation(std::string _FileName,std::string _AnimationName,int _fps,int _x,int _y, int _z,int _AnimStripFrames,int _StartFrame,int _Loop,bool _Transparency,bool _StartNow, int _NumberOfRows):image( _FileName, _AnimationName, _x, _y, _z,Type_Animation,_Transparency)
	{
		m_ianimationFPS=_fps;
		m_iFrameEverInMillSecounds=1000/m_ianimationFPS;
		if(_AnimStripFrames>=0)
		{
		m_iStripNumFrames=(_AnimStripFrames-1);
		}
		else
		{
		m_iStripNumFrames=0;
		}
		if(_NumberOfRows<0)
		{
		m_iNumberOfRows=1;
		}
		else
		{
	    m_iNumberOfRows=_NumberOfRows;
		}
		
		if (_Loop>=0) {
		m_iLoop=_Loop;
		}
		else{
		m_iLoop=1;
		}
		
		m_iPrevTime=0;
		m_iCurrentTime=SDL_GetTicks();
		m_bPlaying=_StartNow;
		JumpToFrame(_StartFrame);
		m_iNumberofTimesPlayed=0;
		m_bReversPlay=false;
		m_iframeEvent=-1;
	
	}

	void  Animation::JumpToFrame(int _Frame)
	{
		if (_Frame>=0 && _Frame<=m_iStripNumFrames) {
			m_iCurrentFrame=_Frame;
			SetClipingBoxForFrame();
		}

	}

	void Animation::UpdateTime()
	{
		
		float time=SDL_GetTicks()-m_iCurrentTime;
		CheckForNextFrame(time);
		//cout<<"Animation Upate Current Frame "<<m_iCurrentFrame<<" Time Diffrence "<<m_iCurrentTime-m_iPrevTime<<" frame pre millsecound "<<m_iFrameEverInMillSecounds<<endl;
		SetClipingBoxForFrame();

	}

	int Animation::GetFPS()
	{
		return m_ianimationFPS;
	}
	
	void Animation::SetFPS(int _fps)
	{
		m_ianimationFPS=_fps;
		m_iFrameEverInMillSecounds=1000/m_ianimationFPS;
		UpdateTime();
	
	}

	void Animation::SetClipingBoxForFrame()
	{
		
		if(m_porignalSurface)
         {
               int CurrentRow=0;
			   if(((m_iCurrentFrame+1)%(m_iStripNumFrames+1)))
			   {
				   CurrentRow=((m_iCurrentFrame+1)/(m_iStripNumFrames+1));
			   }
			   else
			   {
				   CurrentRow=((m_iCurrentFrame+1)/(m_iStripNumFrames+1));
				   CurrentRow--;
			   }
			   WidthForBoxInPixles=GetOrignalRect()->w/(m_iStripNumFrames+1);
		       HeightForBoxInPixles=GetOrignalRect()->h/m_iNumberOfRows;
		       int xpostion=0;
               if(CurrentRow!=0)
               {
               xpostion=WidthForBoxInPixles*((( (m_iCurrentFrame+1)-( CurrentRow*(m_iStripNumFrames+1) )))-1);
               }
               else
               {
                  xpostion=WidthForBoxInPixles*m_iCurrentFrame;
               }
               SetClippingRect(xpostion,HeightForBoxInPixles*CurrentRow ,WidthForBoxInPixles,HeightForBoxInPixles);
				
				
			}

	}

	void Animation::StopAnimation()
	{
		m_bPlaying=false;
	}

	void Animation::PlayAnimation()
	{
		m_bPlaying=true;
		m_iNumberofTimesPlayed=0;

	}

	void Animation::SetLoop(int _Loop)
	{
			if (_Loop>=0)
			{
				m_iLoop=_Loop;
			}
			else
			{
				m_iLoop=1;
			}
	}
		
	int Animation::GetLoop()
	{
		return m_iLoop;
	}
		
	int Animation::GetCurrentFrame()
	{
		return m_iCurrentFrame;
	}

	bool Animation::GetReversPlay()
	{
		return m_bReversPlay;
	}
		
	void Animation::SetReversPlay(bool _BackWards)
	{
		m_bReversPlay=_BackWards;
	}
		
	int Animation::GetTotalNumberOfFrames()
	{
		return ((m_iStripNumFrames+1)*m_iNumberOfRows)-1;
	}
	
	int Animation::GetTotalNumberOfRows()
	{
           return m_iNumberOfRows;
    }
       
	int Animation::GetTotalNumberOfFramesPerRow()
	{
		return m_iStripNumFrames;
	}
        
	
	int Animation::GetNumberOfTimesPlayed()
	{
		return m_iNumberofTimesPlayed;
	}
	
	void Animation::SetFrameEvent(int _frame)
	{
		m_iframeEvent=_frame;
	}
	
	int Animation::GetFrameEvent()
	{
		return m_iframeEvent;
	}
		
	bool Animation::IsPlaying()
	{
		return m_bPlaying;
	}
	
	void Animation::CheckForNextFrame(float _time)
	{
		if (_time>=m_iFrameEverInMillSecounds)
		{
			m_iCurrentTime=SDL_GetTicks();
			if ((m_iCurrentFrame<this->GetTotalNumberOfFrames() && m_bReversPlay==false)|| ((m_iCurrentFrame-1)>=0 && m_bReversPlay==true))
			{
			bool setevent=false;
				if (m_bPlaying)
				{
					if (m_bReversPlay) 
					{
						m_iCurrentFrame--;

							if (m_iCurrentFrame<=m_iframeEvent && m_iframeEvent!=-1) {
								setevent=true;
							}
							else
							{
								setevent=false;
							}

					}
					else
					{
					m_iCurrentFrame++;
					if (m_iCurrentFrame>=m_iframeEvent && m_iframeEvent!=-1) 
					{
						setevent=true;
							}
							else
							{
							setevent=false;	
							}
					}
					if (setevent && m_bPlaying) 
					{
					
						SDL_Event event;

						event.type = SDL_USEREVENT;
						event.user.code = ANIMATION_EVENT;
						event.user.data1 = this;
						event.user.data2 = 0;
						SDL_PushEvent(&event);
						m_iframeEvent=-1;

				}

						

				}
			
			}
			else
			{
				if (m_bPlaying)
                 {
						m_iNumberofTimesPlayed++;
							if (m_iNumberofTimesPlayed>=m_iLoop && m_iLoop!=0) 
                            {
								StopAnimation();
							}
						    else
							{
							
						if (m_bReversPlay) 
                        {
						m_iCurrentFrame=this->GetTotalNumberOfFrames();
						}
						else
						{
						
						m_iCurrentFrame=0;
						}
					
				             }
							

				}

			}
		SetClipingBoxForFrame();	

		}
			
			

	}




//************************End of Animanimation Class Funtions*************************

//************************Begin of Button Class Funtions******************************

	Button::Button(std::string _ButtonFileNameImage, std::string _ButtonName,int _Buttonx,int _Buttony,int _Buttonz,bool _Transparency,bool _SButtonactive):image( _ButtonFileNameImage, _ButtonName, _Buttonx, _Buttony, _Buttonz,Type_Button,_Transparency)
	{	
		m_bactive=_SButtonactive;
		m_ibuttonheight=-1;
		m_ibuttonwidth=-1;
		m_ibuttonx= -1;
		m_ibuttony=-1;
		m_bDontMoveButton=false;
	}

	Button::Button(std::string _ButtonName,int _Buttonx,int _Buttony,int _Buttonz,int m_iButtonHeight,int m_iButtonwidth,bool _Transparency,bool _SButtonactive):image(" ", _ButtonName, _Buttonx, _Buttony, _Buttonz,Type_Button,_Transparency)
	{	
   		 m_bactive=_SButtonactive;
		 m_ibuttonheight=m_iButtonHeight;
		 m_ibuttonwidth=m_iButtonwidth;
		 m_ibuttonx= _Buttonx;
		 m_ibuttony=_Buttony;
		m_bDontMoveButton=false;	
	}

	Button::Button()
	{
		
	}

	Sprockets * Button::WasClicked(int _mouselocationX, int _mouselocationY)
	{
		SDL_Rect *clipbox =GetRect();
		if(m_bactive)
		{
		
			if( m_ibuttonheight ==-1 &&  m_ibuttonwidth==-1)
			{
		
				if( ( _mouselocationX > clipbox->x ) && ( _mouselocationX < clipbox->x + clipbox->w ) && (_mouselocationY > clipbox->y ) && (_mouselocationY < clipbox->y + clipbox->h ) )
				{
				return this;
				}
		
		
			}
	
			else
			{
		
		
				if( ( _mouselocationX >  m_ibuttonx ) && ( _mouselocationX <  m_ibuttonx +  m_ibuttonwidth ) && (_mouselocationY >  m_ibuttony ) && (_mouselocationY <  m_ibuttony + m_ibuttonheight ) )
				{
				return this;
				}
		
		
			}
	
		}
	
	
	return NULL;
	
	}

//************************End of Button Class Funtions********************************

//************************Begin of ButtonTB Class Funtions****************************
ButtonTB::ButtonTB(std::string _ButtonName,int _Buttonx,int _Buttony,int _Buttonz,std::string _ButtonText ,bool _SButtonactive,unsigned int _ButtonTB_height,unsigned int _ButtonTB_width,std::string _ButtonTB_Font,int _ButtonTB_FontPoint,unsigned int _ButtonTB_red,unsigned int _ButtonTB_blue ,unsigned int _ButtonTB_green,std::string _ButtonFontPath):textBox(Type_ButtonTB,_ButtonName, _Buttonx,_Buttony,_Buttonz,_ButtonText, _ButtonTB_height, _ButtonTB_width,_ButtonTB_Font,_ButtonTB_FontPoint,_ButtonTB_red, _ButtonTB_blue ,_ButtonTB_green,_ButtonFontPath)
{
	m_bactive=_SButtonactive;
	m_ibuttonx= -1;
	m_ibuttony=-1;
	m_bDontMoveButton=false;
	
}
//************************End of ButtonTB Class Funtions******************************
double EpeeEngine::GetVersionNumberCpp()
{
	return Version_Number_cpp;
}
double EpeeEngine::GetVersionNumberH()
{
	return Version_Number_h;
}

bool EpeeEngine::ValideVersionNumberOfCppWithHeader()
{
	if (GetVersionNumberCpp()==GetVersionNumberH()) {
		return true;
	}
	else
	{
		cerr<<"****WARNING**** The version number of the Epee Engine header and cpp file do not match. This may cause Problems"<<endl;
		cerr<<"Epee Engine header file verion number "<<GetVersionNumberH()<<endl;
		cerr<<"Epee Engine Cpp file verion number "<<GetVersionNumberCpp()<<endl;
		return false;
	}
}
EpeeEngine::EpeeEngine()
{
if (ValideVersionNumberOfCppWithHeader()) {
cout<<"Epee Engine verion number "<<GetVersionNumberH()<<endl;
}
else
{
cout<<"****WARNING**** Epee Engine verion number could not be determined see error log stderr.txt"<<endl;
}
m_pscreen=NULL;
FrameRate=NULL;
//m_pfont1=NULL;
m_iScreen_Heigth=800;
m_iScreen_Width=600;
//m_iWhichScreenDrawing=1;
m_bFullScreen=false;
m_bResizeAble=false;
m_ifps=60;
m_pSoundOne=NULL;
m_pBackGroundMusic=NULL;
m_ifpstime=0;
m_iframe=0;
m_pCurrentEditedTextBox=NULL;
m_fCurrentFrameRate=0;
m_pDownedButton=NULL;
//m_pLastSprocketFound=NULL;
m_u32VideoFlags=SDL_SWSURFACE; //|SDL_ANYFORMAT;
 m_uiTotalRenderListsCreated=0;
 m_uiTotalSoundsCreated=0;
 m_LastRenderListFound=NULL;
 m_uiCurrentRenderList=NULL;
 m_bHardWareAccelration=1;
 m_cLastError.m_iErrorCode=EPEE_NO_ERROR;
 m_cLastError.m_sError_Message="No Error";
 m_cLastError.ObjectWhereErrorOccured=NULL;

}


EpeeEngine::EpeeEngine(std::vector<FileLookUp> filetable)
{
m_cfiletable = filetable;

if (ValideVersionNumberOfCppWithHeader()) {
cout<<"Epee Engine verion number "<<GetVersionNumberH()<<endl;
}
else
{
cout<<"****WARNING**** Epee Engine verion number could not be determined see error log stderr.txt"<<endl;
}
m_pscreen=NULL;
FrameRate=NULL;
//m_pfont1=NULL;
m_iScreen_Heigth=800;
m_iScreen_Width=600;
//m_iWhichScreenDrawing=1;
m_bFullScreen=false;
m_bResizeAble=false;
m_ifps=60;
m_pSoundOne=NULL;
m_pBackGroundMusic=NULL;
m_ifpstime=0;
m_iframe=0;
m_pDownedButton=NULL;
m_pCurrentEditedTextBox=NULL;
m_fCurrentFrameRate=0;
//m_pLastSprocketFound=NULL;
m_u32VideoFlags=SDL_SWSURFACE ;//|SDL_ANYFORMAT;
m_uiTotalRenderListsCreated=0;
m_uiTotalSoundsCreated=0;
m_LastRenderListFound=NULL;
m_uiCurrentRenderList=NULL;
m_bHardWareAccelration=1;
m_cLastError.m_iErrorCode=EPEE_NO_ERROR;
m_cLastError.m_sError_Message="No Error";
m_cLastError.ObjectWhereErrorOccured=NULL;
}



EpeeEngine::~EpeeEngine()	
{
	unsigned int TotalRenderListDeleted=0;
	unsigned int TotalSoundsToDeleted=0;
	RenderList* temp=NULL;
if (m_pBackGroundMusic)
	{
	Mix_FreeMusic( m_pBackGroundMusic );
	}
	
		/*if (m_pfont1)
		{
			TTF_CloseFont(m_pfont1);
			m_pfont1=NULL;
		}*/
			while(m_vRenderList.size()!=0)
				{

					
					 temp=m_vRenderList[0];
				m_vRenderList.erase(m_vRenderList.begin());
				delete temp;
					//DestroySprocket(m_vSprocketsList[0]->GetName());
					TotalRenderListDeleted++;

					

				}
				
				while(m_vSounds.size()!=0)
				
				{

					
					
					DestroySound(m_vSounds[0]->GetName());
					TotalSoundsToDeleted++;
					

				}

	//	m_vTextBoxList.clear();
			if (TTF_WasInit()) 
			TTF_Quit();
		if(SDL_WasInit(SDL_INIT_AUDIO))
		{
			Mix_CloseAudio();
			
		}
SDL_Quit();
			
if (m_uiTotalRenderListsCreated-TotalRenderListDeleted!=0) {
	cerr<<"*****WARING MEMORY LEAK****"<<endl;
	cerr<<"There are still "<<m_uiTotalRenderListsCreated<<" Render List that where not deleted"<<endl;
}

if (m_uiTotalSoundsCreated) {
	cerr<<"*****WARING MEMORY LEAK****"<<endl;
	cerr<<"There are still "<<m_uiTotalSoundsCreated<<" Sounds that where not deleted"<<endl;
}
}

bool EpeeEngine::SetUp(unsigned int Screen_Width,unsigned int Screen_Heigth,bool FullSreenMode,std::string _WindowName,bool _Resize,int _fps,unsigned int _BitDepthOfScreen,bool Anyformat)
	{
	
//std::string envVariable="SDL_VIDEODRIVER=directx";
  //  putenv(envVariable.c_str());
        CreateRenderList("Default");
SetCurrentRentderList("Default");
_Resize=false;

	if (!TTF_WasInit()) 
	{
		if(TTF_Init()==-1)
		{
			cerr<<"TTR_Init:" <<TTF_GetError()<<endl;
		}
		
	}


	 m_iScreen_Heigth=Screen_Heigth;
	 m_iScreen_Width=Screen_Width;
	// Initialize SDL's subsystems - in this case, only video.
	 if ( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0 ) 
	{
    cerr<<"Unable to init SDL: "<< SDL_GetError()<<endl;
    return false;
	}
	// Register SDL_Quit to be called at exit; makes sure things are
	// cleaned up when we quit.
	//atexit(SDL_Quit);
    
	// Attempt to create a  Screen_Height X Screen_Width window with 32bit pixels.
	if(FullSreenMode) 
	{
         
          m_u32VideoFlags= m_u32VideoFlags|SDL_FULLSCREEN;
    }
    if(_Resize)
	 m_u32VideoFlags=m_u32VideoFlags|SDL_RESIZABLE;
    if( !(_BitDepthOfScreen==8 || _BitDepthOfScreen==16 || _BitDepthOfScreen==24 ||  _BitDepthOfScreen==32 ))
	{
		cerr<<_BitDepthOfScreen<<" is not a vaild BitDepth for the display. Your screen bit depth is now 16"<<endl;
		_BitDepthOfScreen=16;
	}
	if (Anyformat) {
		 m_pscreen = SDL_SetVideoMode(Screen_Width,Screen_Heigth,_BitDepthOfScreen, m_u32VideoFlags|SDL_ANYFORMAT);
	}
	else
	{
    m_pscreen = SDL_SetVideoMode(Screen_Width,Screen_Heigth,_BitDepthOfScreen, m_u32VideoFlags);
	}
	//m_pMainScreen2 =SDL_SetVideoMode(Screen_Heigth, Screen_Width, 32, SDL_SWSURFACE);
  
  
	// If we fail, return error.
	if ( m_pscreen == NULL ) 
	{m_bFullScreen=FullSreenMode;
		m_bResizeAble=_Resize;
    cerr<<"Unable to set"<<Screen_Heigth<<"x"<<Screen_Width<<" video: "<<SDL_GetError()<<endl;
    return false;
	}

	_WindowName= _WindowName+Graphics_Engine_Credits;
	SDL_WM_SetCaption( _WindowName.c_str(),NULL);
	 m_ifps=_fps;
	SDL_initFramerate(& m_cfpsManager);
	//int temp67=SDL_getFramerate(& m_cfpsManager);
    SDL_setFramerate(& m_cfpsManager,m_ifps);
// Mix_OpenAudio(44100, AUDIO_S16, 2, 1024) == -1 ;
	if( Mix_OpenAudio(22050, AUDIO_S16, 2, 1024) == -1 ) //Check return type
	{ return false;
	}
	else
	{
		Mix_VolumeMusic(MIX_MAX_VOLUME);
	}
this->CreateTextBox("FrameRate",0,20,50," ","Current",-1,-1);
FrameRate=(textBox *)FindSprockets("FrameRate");
FrameRate->SetFontPoint(12);
FrameRate->SetQuality(FONT_QUALITY_LOW);
m_ifpstime=SDL_GetTicks();
char videodriver[256] ;


	 SDL_VideoDriverName(videodriver,255);
#if defined(_MSC_VER)
#ifndef _DEBUG
FrameRate->SetDraw(false);
#endif
#endif
	return true;
}
	

bool EpeeEngine::SetUp(std::vector<FileLookUp> filetable,unsigned int Screen_Width,unsigned int Screen_Heigth,bool FullSreenMode,std::string _WindowName,bool _Resize,int _fps,unsigned int _BitDepthOfScreen,bool Anyformat)
	{
		if(SetUp(Screen_Width,Screen_Heigth,FullSreenMode,_WindowName,_Resize,_fps,_BitDepthOfScreen,Anyformat))
		{
			m_cfiletable =filetable;
				return true;
		}
		else
			return false;


	}

bool EpeeEngine::SetAndPlayBackGroundMusic(std::string _NameOfAudio,int _NumberOfTimesToLoop,int _Volume,int _ms)
{
	std::string error;

	if (m_pBackGroundMusic)
	{
	Mix_FreeMusic( m_pBackGroundMusic );
	}
	
	
	m_pBackGroundMusic = Mix_LoadMUS( _NameOfAudio.c_str() );

	
	
	if (m_pBackGroundMusic)
	{
	if(_ms==0)
	{
	Mix_VolumeMusic( _Volume);
	
	Mix_PlayMusic( m_pBackGroundMusic, _NumberOfTimesToLoop );
	}
	else
	{
	Mix_FadeInMusic( m_pBackGroundMusic, _NumberOfTimesToLoop ,_ms);
	}
	
	return true;
	
	}
	else
	{
		//sprintf(display,"You Win $%3d",currentwin);
		//sprintf(error," %s ", Mix_GetError());
		error=Mix_GetError();
	return false;
	}
	
}


	bool EpeeEngine::IsSoundPlaying(Sound *_pSound)
	{
		if(_pSound)
		{
		return Mix_Playing(_pSound->GetChannel());
		}
		else
		{
				EpeeEngineError temperror("Null Pointer Passed in to PlaySoundNow",NULL_POINTER_PASSED,this);
				 this->SetLastError(temperror);
		
		}
		return false;
	}

	bool EpeeEngine::IsBackGoundMusicPlaying()
	{
		return Mix_PlayingMusic();
	}


bool EpeeEngine::StopBackGroundMusic(int _ms)
{

Mix_FadeOutMusic(_ms);
return true;
}



bool EpeeEngine::SetNumberOfMixingChannels(int _NumberOfChannels)
{
Mix_AllocateChannels(_NumberOfChannels);
return true;
}
bool EpeeEngine::PlaySoundNow(std::string _NameOfAudio,int _NumberOfTimesToLoop,int _Channel)
{
	std::string error;

	if (m_pSoundOne)

	{
		m_uiTotalSoundsCreated--;
		Mix_FreeChunk(m_pSoundOne);
	}

	m_pSoundOne=Mix_LoadWAV(_NameOfAudio.c_str());
	if(Mix_PlayChannel( _Channel, m_pSoundOne, _NumberOfTimesToLoop) <0)
	{
		
		EpeeEngineError temperror(Mix_GetError(),SOUND_PLAYING_ERROR,this);
				 this->SetLastError(temperror);
	
		return false;
	}
	else
	{
		m_uiTotalSoundsCreated++;
		return true;
	}


}

bool EpeeEngine::PlaySoundNow(Sound * _pSound)
{
	std::string error;

	if (_pSound)

	{
	
	if(Mix_PlayChannel( _pSound->GetChannel(), _pSound->GetMixChunkPointer(), _pSound->GetNumberOfTimesToLoop()) <0)
	{
			EpeeEngineError temperror(Mix_GetError(),SOUND_PLAYING_ERROR,this);
				 this->SetLastError(temperror);
			error=Mix_GetError();
		return false;
	}
	else
		return true;
	}
	else
	{
		
			EpeeEngineError temperror("Null Pointer Passed in to PlaySoundNow",NULL_POINTER_PASSED,this);
				 this->SetLastError(temperror);
		
		return false;
	}

}

bool EpeeEngine::FadeInSound(Sound * _pSound,int _ms)
{
	std::string error;
	if(_ms>0)
	{
	if (_pSound)

	{
	
	if(Mix_FadeInChannel( _pSound->GetChannel(), _pSound->GetMixChunkPointer(), _pSound->GetNumberOfTimesToLoop(),_ms) <0)
	{
			EpeeEngineError temperror(Mix_GetError(),SOUND_PLAYING_ERROR,this);
				 this->SetLastError(temperror);
			error=Mix_GetError();
		return false;
	}
	else
		return true;
	}
	else
	{
		
			EpeeEngineError temperror("Null Pointer Passed in to PlaySoundNow",NULL_POINTER_PASSED,this);
				 this->SetLastError(temperror);
		
		return false;
	}
	}
		EpeeEngineError temperror("Can not fade sound in with a negitve value",SOUND_PLAYING_ERROR,this);
				 this->SetLastError(temperror);
	return false;
}


	bool EpeeEngine::FadeOutSound(int _Channel,int _ms)
	{
		if(_ms>0)
		{
			Mix_FadeOutChannel(_Channel,_ms);
			return true;
		}
			EpeeEngineError temperror("Can not fade sound out with a negitve value",SOUND_PLAYING_ERROR,this);
				 this->SetLastError(temperror);
		return false;
	

	}

	bool EpeeEngine::FadeOutSound(Sound * _pSound,int _ms)
	{
	
			return FadeOutSound(_pSound->GetChannel(), _ms);		
	}





bool EpeeEngine::StopSoundNow(int _Channel)
{
	 Mix_HaltChannel(_Channel);
	return true;
}

bool EpeeEngine::StopSoundNow(Sound * _pSound)
{
	if(_pSound)
	{
	 return StopSoundNow(_pSound->GetChannel());
	}
	else
	{
		EpeeEngineError temperror("Null Pointer Passed in to PlaySoundNow",NULL_POINTER_PASSED,this);
				 this->SetLastError(temperror);
	}
	return false;
}







Sound * EpeeEngine::CreateSound(std::string _GroupName,std::string _FileName,int _Channel,int _NumberOfTimesToLoop,int _Volume)
{
Sound * temp =new Sound(_GroupName ,_FileName,_Channel,_NumberOfTimesToLoop,_Volume);
	if (temp)
	{
		if (!temp->LoadSound()) 
		{
			EpeeEngineError temperror(Mix_GetError(),SOUND_LOADING_ERROR,this);
				 this->SetLastError(temperror);
			delete temp;
			return NULL;
		}
		else
		{
		
	     m_uiTotalSoundsCreated++;
		m_vSounds.push_back(temp);
		}
	}
	
	else
	{

	EpeeEngineError temperror("Could not Create sound "+_FileName,SOUND_LOADING_ERROR,this);
				 this->SetLastError(temperror);
	}
	
	 return temp; // need to add error return
}

bool EpeeEngine::DestroySound(std::string _name)
{
	Sound * temp=NULL;
	bool retunval=false;
		for(unsigned int index = 0;index<m_vSounds.size();index++)
	{
			if(m_vSounds[index]->GetName()==_name)
			{
			   temp=m_vSounds[index];
				m_vSounds.erase(m_vSounds.begin()+index);
				//Mix_FreeChunk(temp->GetMixChunkPointer());
				delete temp;
				 m_uiTotalSoundsCreated--;
				retunval=true;
				index=m_vSounds.size();

			}
		}


	EpeeEngineError temperror("Could not find and delete sound "+_name,SOUND_DELETING_ERROR,this);
				 this->SetLastError(temperror);;
	return retunval;
}


Sound *  EpeeEngine::FindSound(std::string _name)
{
	#if defined(DEBUG_ME)
	std::string temp_name=" ";
#endif

for (unsigned int index=0;index<m_vSounds.size();index++)
{
#if defined(DEBUG_ME)
temp_name=m_vSounds[index]->GetName();
	if(temp_name==_name)
			{
			   return m_vSounds[index];

			}
#else
if(m_vSounds[index]->GetName()==_name)
			{
			   return m_vSounds[index];

			}

#endif
	

}

 EpeeEngineError temperror("Could not find sound "+_name,SOUND_NOT_FOUND,this);
				 this->SetLastError(temperror);

return NULL;
}

ButtonTB * EpeeEngine::CreateButtonTB(std::string _ButtonName,int _Buttonx,int _Buttony,int _Buttonz,std::string _ButtonText ,bool _SButtonactive,std::string  _AddtoCurrentRenderlist,unsigned int _ButtonTB_height,unsigned int _ButtonTB_width,std::string _ButtonTB_Font,int _ButtonTB_FontPoint,unsigned int _ButtonTB_red,unsigned int _ButtonTB_blue ,unsigned int _ButtonTB_green,std::string _ButtonFontPath)
{ButtonTB *temp=new ButtonTB( _ButtonName, _Buttonx, _Buttony, _Buttonz, _ButtonText , _SButtonactive, _ButtonTB_height,_ButtonTB_width, _ButtonTB_Font,_ButtonTB_FontPoint, _ButtonTB_red, _ButtonTB_blue , _ButtonTB_green, _ButtonFontPath);
if (temp!=NULL) {


temp->LoadFont();

InsertIntoSprocketList(temp,FindRenderList(_AddtoCurrentRenderlist));

 //m_uiTotalSprocketsCreated++;
return temp;
}
else
{
	return NULL;
}
}

textBox * EpeeEngine::CreateTextBox(std::string _Name,int _x,int _y,int _z,std::string _TextBoxMessage,std::string  _AddtoCurrentRenderlist,unsigned int _height,unsigned int _width,std::string _Font,int _FontPoint,unsigned int _red,unsigned int _blue ,unsigned int _green,std::string _FontPath)
{textBox *temp=new textBox( _Name, _x, _y,_z,_TextBoxMessage, _height, _width,_Font, _FontPoint, _red, _blue ,_green,_FontPath);	

if (temp!=NULL) {

temp->LoadFont();

InsertIntoSprocketList(temp,FindRenderList(_AddtoCurrentRenderlist));

 //m_uiTotalSprocketsCreated++;
return temp;
}
else
{
	return NULL;
}
}


image * EpeeEngine::CreateImage(std::string _fileName ,std::string _Name,int _x,int _y,int _z,std::string  _AddtoCurrentRenderlist,bool _Transparency)
{image *temp=new image( _fileName ,_Name, _x, _y,_z,_Transparency);
if (temp!=NULL) {

temp->LoadFileSurface();

InsertIntoSprocketList(temp,FindRenderList(_AddtoCurrentRenderlist));

 //m_uiTotalSprocketsCreated++;
return temp;
}
else
{
	return NULL;
}

}

Animation * EpeeEngine::CreateAnimation(std::string _fileName ,std::string _Name,int _x,int _y,int _z,int _NumberOfFrames,int _fps,int _StartFrame,int _Loop,int _NumberOfRowsOfFrames,bool _Transparency,bool _StartNow,std::string  _AddtoCurrentRenderlist)
{Animation * temp=new Animation( _fileName, _Name,_fps, _x, _y, _z, _NumberOfFrames,_StartFrame,_Loop,_Transparency, _StartNow,_NumberOfRowsOfFrames);
if (temp!=NULL) {

temp->LoadFileSurface();

InsertIntoSprocketList(temp,FindRenderList(_AddtoCurrentRenderlist));

// m_uiTotalSprocketsCreated++;
return temp;
}
else
{
	return NULL;
}

}
bool EpeeEngine::ChangeSprocketZ(Sprockets * _SprocketToChange,int _newZ,RenderList * _list)
{
if (_list==NULL) {
	
	if (m_uiCurrentRenderList) {
	_list=m_uiCurrentRenderList;
	}
	else
	{
		return false;
	}
}	

_list->UpdateVectorlocation();
_list->m_vSprocketsList.erase(_list->m_vSprocketsList.begin()+_SprocketToChange-> GetCurrentVectorPostion());
_SprocketToChange->SetLocationZ(_newZ);
_list->InsertSprocket(_SprocketToChange,false);
return true;

}

bool EpeeEngine::InsertRenderList(RenderList * _newRenderList)
{

m_vRenderList.push_back(_newRenderList);

	return true;

}


bool EpeeEngine::DestroyRenderList(std::string _name)
{
	RenderList * temp=NULL;
	bool retunval=false;
	if (_name=="Default") {
		return false;
	}
		for(unsigned int index = 0;index<m_vRenderList.size();index++)
	{
			if(m_vRenderList[index]->GetName()==_name)
			{
				if (_name==m_uiCurrentRenderList->GetName() ) {
			m_uiCurrentRenderList=FindRenderList("Default");
		}
				if(m_LastRenderListFound)
				{
               if(m_LastRenderListFound->GetName()==_name)
                    m_LastRenderListFound=NULL;
				}
			   temp=m_vRenderList[index];
				m_vRenderList.erase(m_vRenderList.begin()+index);
				delete temp;
				m_uiTotalRenderListsCreated--;
				retunval=true;
				index=m_vRenderList.size();
					
			}
		}
		if (!retunval) {
		
	
	 EpeeEngineError temperror("Could Not Find And Delete RenderList "+_name,RENDERLIST_DELETING_ERROR,this);
				 this->SetLastError(temperror);
//	cerr<<"Could Not Find And Delete RenderList "<<_name<<endl;
		}

	
	return retunval;
}


bool EpeeEngine::RemoveIteamFromRendableList(std::string _card,std::string _renderList)
{
RenderList * temp=FindRenderList(_renderList);

if (temp) {
	return temp->DestroySprocket(_card);
}
return false;
}



RenderList*  EpeeEngine::FindRenderList(std::string _name)
{
	#if defined(DEBUG_ME)
	std::string temp_name=" ";
#endif
	if (_name=="Current" || _name=="current") {
		return GetCurrentRenderListptr();
	}
	if(m_LastRenderListFound)
	{
	
if(m_LastRenderListFound->GetName()==_name)
{
         return m_LastRenderListFound;
         } 
	}   
for (unsigned int index=0;index<m_vRenderList.size();index++)
{
#if defined(DEBUG_ME)
temp_name=m_vRenderList[index]->GetName();
	if(temp_name==_name)
			{
                         m_LastRenderListFound=m_vRenderList[index];
			   return m_vRenderList[index];

			}
#else


                           


if(m_vRenderList[index]->GetName()==_name)
			{
               m_LastRenderListFound=m_vRenderList[index];
			   return m_vRenderList[index];

			}

#endif
	

}
	 EpeeEngineError temperror("Could Not Find Renderlist "+_name,RENDERLIST_NOT_FOUND,this);
				 this->SetLastError(temperror);

return NULL;

}



ButtonTB * EpeeEngine::FindButtonTB(std::string _name)
{
	ButtonTB *temp=(ButtonTB*)FindSprockets(_name);
	if(temp)
	{
	
	if (temp->GetType()!=Type_ButtonTB) {
 EpeeEngineError temperror(_name+" is not an ButtonTB object",SPROCKET_ERROR,this);
				 this->SetLastError(temperror);
        return NULL;
	}
	}
	
	else
		  return NULL;

	
	
	return temp;
}

textBox * EpeeEngine::FindTextBox(std::string _name)
{
	textBox *temp=(textBox*)FindSprockets(_name);
	
	if(temp)
	{
		if (temp->GetType()!=Type_TextBox) {
        EpeeEngineError temperror(_name+" is not an textBox object",SPROCKET_ERROR,this);
				 this->SetLastError(temperror);
		
		return NULL;
	}
	}
	
	else
		  return NULL;
	
	
	return (textBox*)FindSprockets(_name);
}

Button * EpeeEngine::FindButton(std::string _name)
{
       Button *temp=(Button*)FindSprockets(_name);
	if(temp)
	{
	   if (temp->GetType()!=Type_Button) {
		    EpeeEngineError temperror(_name+" is not an Button object",SPROCKET_ERROR,this);
				 this->SetLastError(temperror);
		return NULL;
	}
	   }
	else
		return NULL;
       
return (Button*)FindSprockets(_name) ;	
}

image *EpeeEngine::FindImage(std::string _name)
{
      image *temp=(image*)FindSprockets(_name);
	if(temp)
	{
	  if (temp->GetType()!=Type_Image) {
       
		 EpeeEngineError temperror(_name+" is not an image object",SPROCKET_ERROR,this);
				 this->SetLastError(temperror);
		return NULL;
	}
	}
	else
		return NULL;

      
return (image*)FindSprockets(_name) ;	
}

Animation *EpeeEngine::FindAnimation(std::string _name)
{
      Animation *temp=(Animation*)FindSprockets(_name);
	if(temp)
	{
	  if (temp->GetType()!=Type_Animation) {
       
		 EpeeEngineError temperror(_name+" is not an Animation object",SPROCKET_ERROR,this);
				 this->SetLastError(temperror);

		return NULL;
	}
	}
	else
		return NULL;

      
return (Animation*)FindSprockets(_name) ;	
}


image * EpeeEngine::CreateImageFromList(std::string _symbol,std::string _ImageName,int _x,int _y,int _z)
{
image * temp=NULL;
for(unsigned int i=0;i<m_cfiletable.size();i++)
{

 if(m_cfiletable[i].m_ssymbol==_symbol)
 {
	
    temp=this->CreateImage(m_cfiletable[i].m_sfilename.c_str(),_ImageName,_x,_y,_z);
		break;
		
 }//end of  if(m_cfiletable[i].m_scardsymbol==card)

}//end of for loop


return temp;
}



bool EpeeEngine::DrawImage(image* _ImageToDraw)
{
	SDL_Surface *image_surface=NULL;
	SDL_Surface * TempSurface=NULL;
	//SDL_Surface *TempSurface2=NULL;
	bool KeyColor=true;

	Uint32 flags=0;
	SDL_Rect ClippingRect;
	SDL_Rect * OrignalRectPonter=_ImageToDraw->GetRect();
	SDL_Rect OrignalRect;
	OrignalRect.x=OrignalRectPonter->x;
	OrignalRect.y=OrignalRectPonter->y;
	OrignalRect.h=OrignalRectPonter->h;
	OrignalRect.w=OrignalRectPonter->w;



	
		if(_ImageToDraw->GetSprocketSurface())
		{
                                              
                        
        if(_ImageToDraw->GetRotation()!=0 || _ImageToDraw->GetScalingFactorX()!=1 ||  _ImageToDraw->GetScalingFactorY()!=1 )
        { 
                             if(_ImageToDraw->GetClip())
                            {	ClippingRect.x=_ImageToDraw->GetClippingX();
					          ClippingRect.y=_ImageToDraw->GetClippingY();
                              ClippingRect.h=_ImageToDraw->GetClippingH();
					          ClippingRect.w=_ImageToDraw->GetClippingW();
							TempSurface=SDL_CreateRGBSurface(_ImageToDraw->GetSprocketSurface()->flags, ClippingRect.w,ClippingRect.h,_ImageToDraw->GetSprocketSurface()->format->BitsPerPixel,_ImageToDraw->GetSprocketSurface()->format->Rmask,_ImageToDraw->GetSprocketSurface()->format->Gmask,_ImageToDraw->GetSprocketSurface()->format->Bmask,_ImageToDraw->GetSprocketSurface()->format->Amask);
						//	if (TempSurface) {
							
							//TempSurface=SDL_DisplayFormat(TempSurface2);
						//	//SDL_FreeSurface(TempSurface);
						//	}
							if (_ImageToDraw->GetTransparency()) {
							
							_ImageToDraw->GetSprocketSurface()->flags=flags;
							_ImageToDraw->GetSprocketSurface()->flags=SDL_SWSURFACE;
							}
							if (TempSurface) {
								
							SDL_BlitSurface(_ImageToDraw->GetSprocketSurface(),&ClippingRect,TempSurface,NULL);
							flags=_ImageToDraw->GetSprocketSurface()->flags;
							KeyColor=false;
							if (_ImageToDraw->GetTransparency()) {
							
							TempSurface->flags=TempSurface->flags|SDL_SRCCOLORKEY;
							TempSurface->format->colorkey=_ImageToDraw->GetSprocketSurface()->format->colorkey;
							}
							}
							else
							{
								return false;
							}

							
                                                       }
           if(!TempSurface)
           {                               
			                               
		                                   	
			                                	image_surface= rotozoomSurfaceXY(_ImageToDraw->GetSprocketSurface(), _ImageToDraw->GetRotation(),_ImageToDraw->GetScalingFactorX(),_ImageToDraw->GetScalingFactorY() ,_ImageToDraw->GetAntiAliased());
			                                 
          }
          else
          {
             
			                                	image_surface= rotozoomSurfaceXY(TempSurface, _ImageToDraw->GetRotation(),_ImageToDraw->GetScalingFactorX(),_ImageToDraw->GetScalingFactorY() ,_ImageToDraw->GetAntiAliased());
			                                 
												
              
          }
        }
        else
        {

          _ImageToDraw->SetHeightWidth(_ImageToDraw->GetSprocketSurface()->h,_ImageToDraw->GetSprocketSurface()->w);
			if (_ImageToDraw->GetTransparency() && KeyColor) {
					if(!SetKeyColor(_ImageToDraw->GetSprocketSurface()))
					{
						 EpeeEngineError temperror(_ImageToDraw->GetName()+" Could not set the color key",RENDERING_ERROR,this);
				 this->SetLastError(temperror);
					
					}
					}
		  if (_ImageToDraw->GetClip()) {
					//This is do to save calls
					ClippingRect.x=_ImageToDraw->GetClippingX();
					ClippingRect.y=_ImageToDraw->GetClippingY();
					ClippingRect.h=_ImageToDraw->GetClippingH();
					ClippingRect.w=_ImageToDraw->GetClippingW();
					
				SDL_BlitSurface(_ImageToDraw->GetSprocketSurface(),&ClippingRect,m_pscreen,&OrignalRect);
				}
			else
			{
			
		  SDL_BlitSurface(_ImageToDraw->GetSprocketSurface(),NULL,m_pscreen,&OrignalRect);
			}
			return true;
			
        }
        
        
        if(TempSurface)
        {
                    SDL_FreeSurface(TempSurface);   

                       }



		if(image_surface)
		{
		
			
			 _ImageToDraw->SetHeightWidth(image_surface->h,image_surface->w);
			 if (_ImageToDraw->GetTransparency() && KeyColor) {
					SetKeyColor(image_surface);
					}
					SDL_BlitSurface(image_surface,NULL,m_pscreen,&OrignalRect);
				
			
			//SDL_UpdateRects(m_pscreen, 1, &(_ImageToDraw->GetRect()));
		
				SDL_FreeSurface(image_surface);
			
			return true;
		}
		else
		{
				SDL_FreeSurface(image_surface);
			
			return false;
		}
    return false;
    }
    return true;
}












 bool EpeeEngine::WriteText(textBox* _TextBox)
{//std::string temp="C:\\WINDOWS\\Fonts\\";
bool returnVal=false;
bool tanslationflag=false;
//temp=temp+_TextBox->GetFont();
SDL_Rect temprect;
temprect.h=_TextBox->GetRect()->h;
temprect.w=_TextBox->GetRect()->w;
temprect.x=_TextBox->GetRect()->x;
temprect.y=_TextBox->GetRect()->y;
temprect.x=temprect.x+_TextBox->GetJustifyOffset();
SDL_Rect temprect12;
temprect12.h=_TextBox->GetRect()->h;
temprect12.w=_TextBox->GetRect()->w;
temprect12.x=0;
temprect12.y=0;

	
/*	SDL_Color color;
	color.r = 255;
	color.g = 255;
	color.b = 255;*/
	      //  SDL_Surface *text_surface_original=NULL;

		SDL_Surface *text_surface2=NULL;
		SDL_Surface *text_surface3=NULL;
			SDL_Palette* text_surface3palette=NULL;
	if(_TextBox->GetFontPointer())
	{
		 if(_TextBox->GetBlit()==true )
            {
           _TextBox->SetSurface();
		   			
                  //text_surface2=TTF_RenderText_Solid(m_pfont1,_TextBox->GetText().c_str(),_TextBox->GetTextColor());                          
             }
              else
              {
                  if(!_TextBox->GetSprocketSurface())
                  {
                              _TextBox->SetSurface();          
				  }
                                                     
                 }
		
     if(_TextBox->GetRotation()!=0 || _TextBox->GetScalingFactorX()!=1 ||  _TextBox->GetScalingFactorY()!=1)
        {
		/*if(_TextBox->GetQuality()==FONT_QUALITY_HIGH)
		{
			Uint32 pixel;
		text_surface3= SDL_CreateRGBSurface(SDL_SWSURFACE, temprect12.w, temprect12.h, 32,0x00FF0000, 0x0000FF00, 0x000000FF,0x00000000);
		SDL_MapRGBA(&pixel,0,255,0,50);
		//pixel = 0x0000FF00;
		SDL_FillRect(text_surface3,&temprect12, pixel);	
		}
		else 
		{*/
		text_surface3=SDL_CreateRGBSurface(SDL_SWSURFACE, temprect12.w, temprect12.h, 8, 0, 0, 0, 0);
		 text_surface3palette = text_surface3->format->palette;
		text_surface3palette->colors[0].r = 255 - _TextBox->GetTextColor().r;
		text_surface3palette->colors[0].g = 255 - _TextBox->GetTextColor().g;
		text_surface3palette->colors[0].b = 255 - _TextBox->GetTextColor().b;
		text_surface3palette->colors[1].r = _TextBox->GetTextColor().r;
		text_surface3palette->colors[1].g = _TextBox->GetTextColor().g;
		text_surface3palette->colors[1].b = _TextBox->GetTextColor().b;
		SDL_SetColorKey( text_surface3, SDL_SRCCOLORKEY, 0 );
		//}
		int u=SDL_BlitSurface(_TextBox->GetSprocketSurface(),&temprect12,text_surface3,NULL);
		if(_TextBox->GetQuality()==FONT_QUALITY_HIGH)
		{
		text_surface3=SDL_DisplayFormatAlpha(text_surface3);
		}
		if (m_bFullScreen)
			{
				text_surface2= rotozoomSurfaceXY(text_surface3, _TextBox->GetRotation(),_TextBox->GetScalingFactorX(),_TextBox->GetScalingFactorY() ,0);
		      tanslationflag=true;
			}
			else
			{
				text_surface2= rotozoomSurfaceXY(text_surface3, _TextBox->GetRotation(),_TextBox->GetScalingFactorX(),_TextBox->GetScalingFactorY() ,_TextBox->GetAntiAliased());
			    tanslationflag=true;
            }
			
	
        }

        
	if(text_surface2)
    {		
	SDL_BlitSurface(text_surface2,NULL,m_pscreen,&temprect);
	//SDL_UpdateRects(m_pscreen, 1, &(_TextBox->GetRect()));
	if(text_surface3){
				SDL_FreeSurface(text_surface3);}
	SDL_FreeSurface(text_surface2);
	return true;
   }
   else if ( _TextBox->GetSprocketSurface())
   {
      
			SDL_BlitSurface(_TextBox->GetSprocketSurface(),&temprect12,m_pscreen,&temprect);
		
	//SDL_UpdateRects(m_pscreen, 1, &(_TextBox->GetRect()));
	return true;
 }
          
   else
   {
       returnVal=false;
   }
   
  

  }
	return  returnVal;
}



bool EpeeEngine::RenderSeen(bool _UpdateScreenNow)
{
    
	for(unsigned int index = 0;index<m_uiCurrentRenderList->m_vSprocketsList.size();index++)
	{
		if(m_uiCurrentRenderList->m_vSprocketsList[index]->GetLocationZ()>=0)
		{

			if(m_uiCurrentRenderList->m_vSprocketsList[index]->GetDraw())
			{
			
			switch(m_uiCurrentRenderList->m_vSprocketsList[index]->GetType()) {
			case Type_TextBox:
				WriteText((textBox *)m_uiCurrentRenderList->m_vSprocketsList[index]);
				break;
			case Type_Image:
				 DrawImage((image* )m_uiCurrentRenderList->m_vSprocketsList[index]);
				break;
			case Type_Button:
				DrawImage((image* )m_uiCurrentRenderList->m_vSprocketsList[index]);
					break;
			case Type_ButtonTB:
				WriteText((textBox *)m_uiCurrentRenderList->m_vSprocketsList[index]);
				break;
			case Type_Animation:
				((Animation*)m_uiCurrentRenderList->m_vSprocketsList[index])->UpdateTime();
				DrawImage((image* )m_uiCurrentRenderList->m_vSprocketsList[index]);
				break;
			default:
				break;
			}
			
			}
		
		}
	}
	if (_UpdateScreenNow)
	{
		 UpdateScreen();
	}
	else
	fpsDelay();
	return true;
}



 bool EpeeEngine::UpdateScreen()
{char tempfps[256];

                /// if(m_bFullScreen)
                // {  
		//SDL_Flip(m_pscreen);
                   //         }
		//else
		//{
		//SDL_UpdateRect(m_pscreen,0,0,m_iScreen_Width,m_iScreen_Heigth);
			SDL_UpdateRect(m_pscreen,0,0,0,0);
   // }
	
	
	fpsDelay();
	m_iframe++;
	float time=SDL_GetTicks()-m_ifpstime;

	//cout<<"time "<<time<<" ";
	//cout<<"frame "<<m_iframe<<" ";
	if(time>=1000)
	{
                  m_fCurrentFrameRate=m_iframe/(time/1000.f);
               sprintf(tempfps,"Frame Rate %f", m_fCurrentFrameRate);                        
               if (FrameRate!=NULL) {
				   FrameRate->SetText(tempfps);
               }   
			   
                  // cout<<"FPS "<<m_fCurrentFrameRate<<endl;
                   m_iframe=0; 
                   m_ifpstime=SDL_GetTicks();                   
                                       }
                                       else
                                       {
                                          // cout<<endl;
                                           }
	
	
	
	return true;

}
 /*
bool EpeeEngine::UpdateVectorlocateion()
{
     for(unsigned int index = 0;index<m_vSprocketsList.size();index++)
	{
             m_vSprocketsList[index]->SetCurrentArrayPostion(index);
             
             
             }
             return true;
 }*/


 void EpeeEngine::fpsDelay()
{

//float time2=SDL_GetTicks()-m_ifpstime;
//cout<<"Time Diffrence "<<time2<<"  ";
//if(m_iframe>m_ifps)
//{
           if(SDL_GetTicks()-m_ifpstime<((1000/m_ifps)*m_iframe))
           {
           //cout<<"Time Delay "<<((1000/m_ifps)*m_iframe)-(SDL_GetTicks()-m_ifpstime)<<" ";
           SDL_Delay(((1000/m_ifps)*m_iframe)-(SDL_GetTicks()-m_ifpstime));
           }
                                             
	//SDL_Delay(1000/m_ifps);	
//}

}

bool EpeeEngine::SetFps(int _fps)
{
m_ifps=_fps;
if(m_ifps==_fps)
return true;
else
return false;


}

int EpeeEngine::GetFps()
{
return m_ifps;
}



/*

bool EpeeEngine::WriteText(std::string TextToWrite,int x,int y,int point,std::string font,int text_box_height,int text_box_width)
{std::string temp="C:\\WINDOWS\\Fonts\\";
temp=temp+font;
m_pfont1=TTF_OpenFont(temp.c_str(), 12);
	SDL_Color color;
	color.r = 255;
	color.g = 255;
	color.b = 255;
	SDL_Rect dest;
		dest.x=x;
		dest.y=x;
		dest.w = text_box_width;
		dest.h = text_box_height;
	SDL_Surface *text_surface=NULL;
	if(m_pfont1)
	{
		text_surface=TTF_RenderText_Solid(m_pfont1,TextToWrite.c_str(), color);
	SDL_BlitSurface(text_surface,NULL,m_pscreen,&dest);
//SDL_UpdateRects(m_pscreen, 1, &dest);
	}
	SDL_FreeSurface(text_surface);
	TTF_CloseFont(m_pfont1);
	return true;
}
*/


Button * EpeeEngine::CreateButton(std::string _localfileName ,std::string _localName,int _localx,int _localy,int _localz,bool _Transparency,bool _localactive,std::string  _AddtoCurrentRenderlist)
 {
	// SButton butttemp ;//= new SButton();
	 Button *temp = new Button(_localfileName, _localName,_localx, _localy,_localz, _Transparency,_localactive);
	if (temp!=NULL) {

	 temp->LoadFileSurface();
InsertIntoSprocketList(temp,FindRenderList(_AddtoCurrentRenderlist));
	 return temp;
	}
	else
	{
		return NULL;
	}
}

Button * EpeeEngine::CreateButton(std::string _localName,int _localx,int _localy,int _localz,int _height,int _width,bool _Transparency, bool _localactive,std::string  _AddtoCurrentRenderlist)
{
		Button *temp = new Button(_localName,_localx, _localy,_localz, _height,_width, _Transparency,_localactive);
		//temp->SetDraw(false);
		if (temp!=NULL) {

		temp->LoadFileSurface();
		InsertIntoSprocketList(temp,FindRenderList(_AddtoCurrentRenderlist));
		return temp;
		}
		else
		{
			return NULL;
		}
	
}
Sprockets * EpeeEngine::WasAButtonClicked(int _x,int _y)
{
	
	//cout<<"index in wasAbutton clicked "<<index<<endl;
	for(int index=(m_uiCurrentRenderList->m_vSprocketsList.size()-1);index>=0;index--)
	{
		//cout<<"index in for loop wasAbutton clicked "<<index<<endl;
		if(m_uiCurrentRenderList->m_vSprocketsList[index]->GetLocationZ()>=0)
		{
			//cout<<"index in for loop in first if wasAbutton clicked "<<index<<endl;
			if(m_uiCurrentRenderList->m_vSprocketsList[index]->GetDraw()  )
			{
				//cout<<"index in for loop in secound if wasAbutton clicked "<<index<<endl;
				
					//	cout<<"button was found"<<endl;
						
					
						
						if(m_uiCurrentRenderList->m_vSprocketsList[index]->WasClicked(_x,_y))
						{
							return m_uiCurrentRenderList->m_vSprocketsList[index];
						}
					
					
				
			}
			
			
		}
		
		
	}
	return NULL;
	
}
bool EpeeEngine::EventProcessing(SDL_Event *_event)
{
		
	
	bool returnvalue=false;
     //SDL_Event event;
     Sprockets * Clicked_Button=NULL;
     double scalingfactorX=0;
     double scalingfactorY=0;
     bool add_true_subtract_falseX=true;
     bool add_true_subtract_falseY=true;
	 	bool flagtemp=false;
	 if(_event!=NULL)
	 {
    //int background=FindImage("background")->GetCurrentVectorPostion();
     
						switch (_event->type) 
						{
                               case SDL_MOUSEBUTTONUP:
                                   Clicked_Button=WasAButtonClicked(_event->button.x,_event->button.y);								 
								  if( Clicked_Button!=NULL)
								   {  
								   
								   if (Clicked_Button->GetType()==Type_TextBox) 
								   {
									   if(((textBox*)Clicked_Button)->GetEditable()==true)
									   {
										m_pCurrentEditedTextBox=(textBox*)Clicked_Button;
									   }
									   else
									   {
										   m_pCurrentEditedTextBox=NULL;
									   }
                                    }
									else
									{
										m_pCurrentEditedTextBox=NULL;
									}
									}



									if(m_pDownedButton)
                                    {
                                                       m_pDownedButton->SetLocation(m_pDownedButton->GetLocationX()-2,m_pDownedButton->GetLocationY()-2);
                                    returnvalue=true;                   
									}
									m_pDownedButton=NULL;
                                    break;
                               case SDL_MOUSEBUTTONDOWN:
                                    Clicked_Button=WasAButtonClicked(_event->button.x,_event->button.y);
                                    if( Clicked_Button)
                                    {
										bool dontmove=false;
										dontmove=Clicked_Button->GetDontMoveOnClick();
										
										
										if (!dontmove) {
										
                                        
                                     Clicked_Button->SetLocation(Clicked_Button->GetLocationX()+2,Clicked_Button->GetLocationY()+2);
                                     m_pDownedButton=Clicked_Button;
									 returnvalue=true;
										}
										
                                    }
									if (	m_pCurrentEditedTextBox) {
										m_pCurrentEditedTextBox=NULL;
									}
                                    break;
									case SDL_KEYUP:
									 flagtemp=false;
										if (	m_pCurrentEditedTextBox!=NULL) 
										{
											
											if (m_pCurrentEditedTextBox->GetNumbersOnly()==true) 
											{
											
												
											if ((_event->key.keysym.sym>=SDLK_0 && _event->key.keysym.sym<=SDLK_9) || ( _event->key.keysym.sym>=SDLK_KP0 && _event->key.keysym.sym<=SDLK_KP9)    ) 
											{
											
												flagtemp=true;
											}
										
											}
											else
											{
												flagtemp=true;
											
											}

											if(_event->key.keysym.sym==SDLK_BACKSPACE)
											{
												std::string erasestring=m_pCurrentEditedTextBox->GetText();
												int sizeofstring=m_pCurrentEditedTextBox->GetText().size();
												if (sizeofstring!=1) 
												{
												
													erasestring.erase(sizeofstring-1,1);
												}
												else
												{
													erasestring=" ";
												}
												m_pCurrentEditedTextBox->SetText(erasestring,true);

											}
											else
											{
												
												if (flagtemp)
												{ //need to only include numbers 0 -9 and a-z and A-Z
													char tempchar[3];
													std::string tempstring=" ";
												if(( _event->key.keysym.sym>=SDLK_KP0 && _event->key.keysym.sym<=SDLK_KP9) )
												{
														tempstring=StringFromNumericData((int)_event->key.keysym.sym-(int)SDLK_KP0);
														if(this->GetLastError().m_iErrorCode==EPEE_NO_ERROR)
														{
															if(m_pCurrentEditedTextBox->GetText()==" ")
															{
																	m_pCurrentEditedTextBox->SetText(tempstring,true);
															}
															else
															{
															m_pCurrentEditedTextBox->SetText(m_pCurrentEditedTextBox->GetText()+tempstring,true);
															}
														}
												}
												else
												{
												sprintf(tempchar,"%c",_event->key.keysym.sym);
												tempstring=tempchar;
												if(m_pCurrentEditedTextBox->GetText()==" ")
															{
																	m_pCurrentEditedTextBox->SetText(tempstring,true);
															}
															else
															{
															m_pCurrentEditedTextBox->SetText(m_pCurrentEditedTextBox->GetText()+tempstring,true);
															}}

												}
											}
											

										}
									
										break;
						
								
                              case SDL_VIDEORESIZE:
                              
                                   m_pscreen = SDL_SetVideoMode(_event->resize.w, _event->resize.h, 32, m_u32VideoFlags );
                                   
								   //translation newres/currentres
                                   if(m_iScreen_Width>_event->resize.w)
                                   {
                                       add_true_subtract_falseY=false;                                         
                                   }
                                   
                                   if(m_iScreen_Heigth>_event->resize.h)
                                   {
                                   add_true_subtract_falseX=false;
                                   }
                                               
                                                if( add_true_subtract_falseY)
                                                {
                                                    scalingfactorY=(float)(m_iScreen_Heigth/_event->resize.h);
                                                }
                                                else
                                                {
                                                    scalingfactorY=(m_iScreen_Heigth-_event->resize.h)*.001;
                                                } 
                                                
                                                 if( add_true_subtract_falseX)
                                                {
                                                    scalingfactorX=(_event->resize.w-m_iScreen_Width)*.001;
                                                }
                                                else
                                                {
                                                    scalingfactorX=(m_iScreen_Width-_event->resize.w)*.001;
                                                } 
                                   
                                                 
                                   for(unsigned int index = 0;index<m_uiCurrentRenderList->m_vSprocketsList.size();index++)
	                               {
                                                
                                                
                                                if( add_true_subtract_falseY)
                                                {
                                                    m_uiCurrentRenderList->m_vSprocketsList[index]->SetScalingFactorY(m_uiCurrentRenderList->m_vSprocketsList[index]->GetScalingFactorY()+scalingfactorY);
                                                }
                                                else
                                                {
                                                   m_uiCurrentRenderList->m_vSprocketsList[index]->SetScalingFactorY(m_uiCurrentRenderList->m_vSprocketsList[index]->GetScalingFactorY()-scalingfactorY);
                                                } 
                                                if( add_true_subtract_falseX)
                                                {
                                                    m_uiCurrentRenderList->m_vSprocketsList[index]->SetScalingFactorX(m_uiCurrentRenderList->m_vSprocketsList[index]->GetScalingFactorX()+scalingfactorX);
                                                }
                                                else
                                                {
                                                   m_uiCurrentRenderList->m_vSprocketsList[index]->SetScalingFactorX(m_uiCurrentRenderList->m_vSprocketsList[index]->GetScalingFactorX()-scalingfactorX);
                                                } 
                                }	
                             	 m_iScreen_Heigth=_event->resize.h;
                              m_iScreen_Width=_event->resize.w;
							 // RenderSeen(true);
                                    break;


							  
						
                            }
	}
return returnvalue;     
}

void EpeeEngine::SleepDelay(Uint32 _millisecounds)
{
     SDL_Delay(_millisecounds);
 }

unsigned int EpeeEngine::GetTotalRenderList()
{
	return m_uiTotalRenderListsCreated;
}

unsigned int EpeeEngine::GetTotalSoundsCreated()
{
	return m_uiTotalSoundsCreated;
}


void EpeeEngine::WriteRenderListToFile()
{
if (m_uiCurrentRenderList!=NULL) {

cout<<" "<<endl;
cout<<"Current Contents Of Current Render List: "<<m_uiCurrentRenderList->GetName()<<endl;
for (unsigned int index=0;index<m_uiCurrentRenderList->m_vSprocketsList.size();index++)
{
	cout<<"["<<index<<"] "<<m_uiCurrentRenderList->m_vSprocketsList[index]->GetName()<<" ("<<m_uiCurrentRenderList->m_vSprocketsList[index]->GetLocationX()<<","<<m_uiCurrentRenderList->m_vSprocketsList[index]->GetLocationY()<<","<<m_uiCurrentRenderList->m_vSprocketsList[index]->GetLocationZ()<<")"<<endl;

}
cout<<"Total Sprockets In The Render List: "<<m_uiCurrentRenderList->m_vSprocketsList.size()<<endl;


}
}


void EpeeEngine::WriteSoundListToFile()
{

cout<<" "<<endl;
cout<<"Current Contents Of Current Sound List"<<endl;
for (unsigned int index=0;index<m_vSounds.size();index++)
{
	cout<<"["<<index<<"] "<<m_vSounds[index]->GetName()<<endl;

}
cout<<"Total Sounds In The Sound List: "<<m_vSounds.size()<<endl;
if(m_pBackGroundMusic)
{
	cout<<"There is BackGround Music Object"<<endl;
}
else
{
	cout<<"There is NO BackGround Music Object"<<endl;
}


}


void EpeeEngine::TurnOnFPS()
	{
if(FrameRate)
FrameRate->SetDraw(true);

	}

void EpeeEngine::TurnOffFPS()
{
if(FrameRate)
FrameRate->SetDraw(false);
}

void EpeeEngine::ToggleFullScreen(bool _FullScreen)
{
     if(m_bFullScreen!=_FullScreen)
     {
     ChangedResolution(m_iScreen_Width,m_iScreen_Heigth,false,_FullScreen,m_bResizeAble);
     }
 }

void EpeeEngine::ChangedResolution(int _Width, int _height,bool _useCurrentFlags,bool _FullScreen,bool _Resize,bool _AnyFormat)
{
     _Resize=false;
     if(_useCurrentFlags)
     {
	 m_pscreen = SDL_SetVideoMode(_Width, _height, 32, m_u32VideoFlags );
  }
  else
  {
    m_u32VideoFlags=0;
    m_u32VideoFlags=m_u32VideoFlags|SDL_SWSURFACE;
    if(_FullScreen){
    m_u32VideoFlags=m_u32VideoFlags|SDL_FULLSCREEN;}
    
    if(_Resize){
     m_u32VideoFlags=m_u32VideoFlags|SDL_RESIZABLE;}
     if (_AnyFormat) {
		 m_u32VideoFlags=m_u32VideoFlags|SDL_ANYFORMAT;
     }
      m_pscreen = SDL_SetVideoMode(_Width, _height, 32, m_u32VideoFlags );
      m_bFullScreen=_FullScreen;
      m_bResizeAble=_Resize;
}
	m_iScreen_Heigth=_height;
	m_iScreen_Width=_Width;
	
	
}



bool EpeeEngine::GetEvent(SDL_Event * _event)
{
	if(_event!=NULL)
	{
		
	if(SDL_PollEvent(_event))
	{
	EventProcessing(_event);
		return true;
	}
	else
	{
		return false;
	}
		
	}
	
	return false;
	
}



unsigned int EpeeEngine::GetCurrentScreenHeight()
{
	return  m_iScreen_Heigth;
}
unsigned int EpeeEngine::GetCurrentScreenWidth()
{
	
	return m_iScreen_Width;	
}

float EpeeEngine::GetTimeSinceSetup()
{
return	SDL_GetTicks();
}


bool EpeeEngine::SetKeyColor(SDL_Surface * _SurfaceToKey)
{


/* Extracting color components from a 32-bit color value */
SDL_PixelFormat *fmt;
Uint32 temp, pixel;
Uint8 red, green, blue ,alpha;
int returnval=0;
fmt=_SurfaceToKey->format;
SDL_LockSurface(_SurfaceToKey);
pixel=*((Uint32*)_SurfaceToKey->pixels);
SDL_UnlockSurface(_SurfaceToKey);


/* Get Red component */
temp=pixel&fmt->Rmask; /* Isolate red component */
temp=temp>>fmt->Rshift;/* Shift it down to 8-bit */
temp=temp<<fmt->Rloss; /* Expand to a full 8-bit number */
red=(Uint8)temp;

/* Get Green component */
temp=pixel&fmt->Gmask; /* Isolate green component */
temp=temp>>fmt->Gshift;/* Shift it down to 8-bit */
temp=temp<<fmt->Gloss; /* Expand to a full 8-bit number */
green=(Uint8)temp;

/* Get Blue component */
temp=pixel&fmt->Bmask; /* Isolate blue component */
temp=temp>>fmt->Bshift;/* Shift it down to 8-bit */
temp=temp<<fmt->Bloss; /* Expand to a full 8-bit number */
blue=(Uint8)temp;

/* Get Alpha component */
temp=pixel&fmt->Amask; /* Isolate alpha component */
temp=temp>>fmt->Ashift;/* Shift it down to 8-bit */
temp=temp<<fmt->Aloss; /* Expand to a full 8-bit number */
alpha=(Uint8)temp;
 returnval=SDL_SetColorKey(_SurfaceToKey,SDL_SRCCOLORKEY|SDL_RLEACCEL,SDL_MapRGB(fmt,red,green,blue));
//printf("Pixel Color -> R: %d,  G: %d,  B: %d,  A: %d\n", red, green, blue, alpha);

 if (!returnval) {
 return true;
 }
 else
 {
	 return false;
 }
	
}


std::string EpeeEngine::GetCurrentRenderList()
	{
	return 	m_uiCurrentRenderList->GetName();
	}
	
bool EpeeEngine::SetCurrentRentderList(std::string _ListToChangeTo)
 {
	RenderList *temp=FindRenderList(_ListToChangeTo);
	if(temp)
	{
		
	m_uiCurrentRenderList=temp;
	RenderSeen(true);
	return true;
	}
	else
	{
	return false;
	}
 }

void EpeeEngine::TransferSprocketToNewRenderList(RenderList * _sorceRenderList,RenderList * _destinationRenderList,Sprockets * _sprocketToTransfer)
{
if(_sorceRenderList!=NULL && _destinationRenderList!=NULL && _sprocketToTransfer!=NULL)
{

_sorceRenderList->RemoveSprocketFromList(_sprocketToTransfer);
_destinationRenderList->InsertSprocket(_sprocketToTransfer,true);
}
}


RenderList * EpeeEngine::CreateRenderList(std::string _name)
{

if (_name!="Current" || _name !="currnet") {

RenderList *temp=new RenderList( _name);

InsertRenderList(temp);

m_uiTotalRenderListsCreated++;
return temp;
}
else
return NULL;
	}



bool EpeeEngine::InsertIntoSprocketList(Sprockets * _newSprocket,RenderList * _List)
	{
		if (_List==NULL) {
			if (m_uiCurrentRenderList!=NULL) {

				_List=m_uiCurrentRenderList;
			}
			else
				return false;
		}
		
		if (_newSprocket!=NULL  ) {


			return _List->InsertSprocket(_newSprocket);



		}
		
		return false;

	}




	Sprockets * EpeeEngine::FindSprockets(std::string _name,std::string _renderlist)
	{
		if (_renderlist=="Current") {
			return m_uiCurrentRenderList->FindSprockets(_name);
		
		}
		else
		{
			RenderList * temp =FindRenderList(_renderlist);
			if (temp) {
				return temp->FindSprockets(_name);
			
			}
				
		}
		return NULL;
	}

	RenderList * EpeeEngine::GetCurrentRenderListptr()
{
	return m_uiCurrentRenderList;
}
	image* EpeeEngine::CloneImage(image * _imageToClone,std::string _nameOfImage,std::string _RenderList,int _x,int _y,int _z )

	{
		if(_imageToClone!=NULL)
		{
		
		int x=0,y=0,z=0;
		if (_x==-1) {
			x=_imageToClone->GetLocationX();
		}
		else
		{
			x=_x;
		}
		if (_y==-1) {
			y=_imageToClone->GetLocationY();
		}
		else
		{
			y=_y;
		}
		if (_z==-1) {
			z=_imageToClone->GetLocationZ();
		}
		else
		{
			z=_z;
		}
		image * temp=CreateImage( _imageToClone->GetFileName(),_nameOfImage, _x, _y, _z,_RenderList,_imageToClone->GetTransparency());
		return temp;
		}
		else
		{
			return NULL;
		}
			return NULL;
	}

	textBox * EpeeEngine::CloneTextBox(textBox * _textBoxToClone,std::string _nameOfImage,std::string _RenderList,int _x,int _y,int _z )
	{
		if(_textBoxToClone!=NULL)
		{
		
		int x=0,y=0,z=0;
		if (_x==-1) {
			x=_textBoxToClone->GetLocationX();
		}
		else
		{
			x=_x;
		}
		if (_y==-1) {
			y=_textBoxToClone->GetLocationY();
		}
		else
		{
			y=_y;
		}
		if (_z==-1) {
			z=_textBoxToClone->GetLocationZ();
		}
		else
		{
			z=_z;
		}
		textBox * temp=CreateTextBox(_nameOfImage,x,y,z,_textBoxToClone->GetText(),_RenderList,_textBoxToClone->GetHeight(),_textBoxToClone->GetWidth(),_textBoxToClone->GetFont(),_textBoxToClone->GetFontPoint(),_textBoxToClone->GetTextColor().r,_textBoxToClone->GetTextColor().b,_textBoxToClone->GetTextColor().g,_textBoxToClone->GetFontPath());
		return temp;
		}
		else
		{
			return NULL;
		}
			return NULL;

	}

	void EpeeEngine::LoadImageFromFile(TiXmlElement *element)
	{
		if (element==NULL) {
			return;
		}
		int value=0;
		
		const char *text = NULL;
		std::string _fileName=" ";
		std::string _Name=" ";
		int _x=0;
		int _y=0;
		int _z=0;
		std::string _AddtoCurrentRenderlist="Current";
		bool _Transparency=false;
		if(element->Attribute("name"))
		{
			_Name = element->Attribute("name");
			
		
		}
		if(element->Attribute("filename"))
		{
			_fileName = element->Attribute("filename");
			
		
		}
		if(element->Attribute("x", &value))
		{

		_x = value;
		}

		if(element->Attribute("y", &value))
		{
		_y = value;
		}
			if(element->Attribute("z", &value))
		{

		_z = value;
		}

		if(element->Attribute("transparency"))
		{
			std::string temp=" ";
			temp=element->Attribute("transparency");
			if(temp!=" ")
			{
				#if defined(_MSC_VER)
				std::transform(temp.begin(),temp.end(),temp.begin(),tolower);	
				#else
				std::transform(temp.begin(),temp.end(),temp.begin(),(int(*)(int))std::tolower);
				#endif
				if (temp=="true") {
				_Transparency=true;
				}
				else
				{
				_Transparency=false;
				}
			}
	
		}
		if(element->Attribute("renderlist"))
		{
		_AddtoCurrentRenderlist= element->Attribute("renderlist");
			
		
		}
	

		if (_fileName!=" " && _Name!=" ") {
		CreateImage( _fileName , _Name,_x, _y, _z, _AddtoCurrentRenderlist, _Transparency);
		}
		else
		{
			cerr<<"Could not create image"<<_Name<<"With the file"<<_fileName<<endl;
		}
	

	}




	void EpeeEngine::LoadTextBoxFromFile(TiXmlElement *element)
	{
		if (element==NULL) {
			return;
		}
		int value=0;
		
		const char *text = NULL;
		std::string _TextMessage=" ";
		std::string _Name=" ";
		 int _x=0;
		 int _y=0;
		unsigned int _height=-1;
		unsigned int _width=-1;
		std::string _Font=True_Type_Font_Defalut;
		int _FontPoint=18;
		unsigned int _red=255;
		unsigned int _blue=255;
		unsigned int _green=255;
		std::string _FontPath=True_Type_Font_Location;
		int _z=0;
		std::string _AddtoCurrentRenderlist="Current";
		bool _Transparency=false;
		int _Quilty=FONT_QUALITY_LOW;
		if(element->Attribute("name"))
		{
			_Name = element->Attribute("name");
			
		
		}
		if(element->Attribute("textboxmessage"))
		{
			_TextMessage = element->Attribute("textboxmessage");
			
		
		}
		if(element->Attribute("x", &value))
		{

		_x = value;
		}

		if(element->Attribute("y", &value))
		{
		_y = value;
		}
			if(element->Attribute("z", &value))
		{

		_z = value;
		}
			if(element->Attribute("height", &value))
		{
		_height = value;
		}
			if(element->Attribute("width", &value))
		{

		_width = value;
		}
		if(element->Attribute("font"))
		{
			_Font = element->Attribute("font");
			
		
		}

			if(element->Attribute("fontcolorred", &value))
		{

		_red= value;
		}
				if(element->Attribute("fontcolorblue", &value))
		{

		_blue = value;
		}
		if(element->Attribute("fontcolorgreen", &value))
		{

		_green = value;
		}
		if(element->Attribute("fontpath"))
		{
		_FontPath= element->Attribute("fontpath");
		}

		if(element->Attribute("fontpoint", &value))
		{

		_FontPoint = value;
		}

		if(element->Attribute("renderlist"))
		{
		_AddtoCurrentRenderlist= element->Attribute("renderlist");
			
		
		}
		if(element->Attribute("textquality", &value))
		{//std::string TempQuality=value;
		//	if(TempQuality.f

		_Quilty = value;
		}

	

		if (_Name!=" ") {
		textBox* created=CreateTextBox( _Name, _x, _y, _z, _TextMessage, _AddtoCurrentRenderlist, _height, _width, _Font, _FontPoint,_red, _blue , _green, _FontPath );
		if(created)
		{
			created->SetQuality(_Quilty);
		}
		}
		else
		{
			cerr<<"Could not create TextBox"<<_Name<<endl;
		}
	
/*
		if(element->Attribute("transparency"))
		{
			std::string temp=" ";
			temp=element->Attribute("transparency");
			if(temp!=" ")
			{
				transform(temp.begin(),temp.end(),temp.begin(),tolower);
				if (temp=="true") {
				_Transparency=true;
				}
				else
				{
				_Transparency=false;
				}
			}
	
		}*/



	}

	void EpeeEngine::LoadButtonFromFile(TiXmlElement *element)
	{
		if (element==NULL) {
			return;
		}
		int value=0;
		
		const char *text = NULL;
		std::string _fileName=" ";
		std::string _Name=" ";
		 int _x=0;
		 int _y=0;
		int _height=20;
		int _width=20;
		bool _active=true;
		int _z=0;
		std::string _AddtoCurrentRenderlist="Current";
		bool _Transparency=false;
		if(element->Attribute("name"))
		{
			_Name = element->Attribute("name");
			
		
		}
		if(element->Attribute("filename"))
		{
			_fileName = element->Attribute("filename");
			
		
		}
		if(element->Attribute("x", &value))
		{

		_x = value;
		}

		if(element->Attribute("y", &value))
		{
		_y = value;
		}
			if(element->Attribute("z", &value))
		{

		_z = value;
		}

		if(element->Attribute("transparency"))
		{
			std::string temp=" ";
			temp=element->Attribute("transparency");
			if(temp!=" ")
			{
				#if defined(_MSC_VER)
				std::transform(temp.begin(),temp.end(),temp.begin(),tolower);	
				#else
				std::transform(temp.begin(),temp.end(),temp.begin(),(int(*)(int))std::tolower);
				#endif
				if (temp=="true") {
				_Transparency=true;
				}
				else
				{
				_Transparency=false;
				}
			}
	
		}
			if(element->Attribute("active"))
		{
			std::string temp=" ";
			temp=element->Attribute("active");
			if(temp!=" ")
			{
				#if defined(_MSC_VER)
				std::transform(temp.begin(),temp.end(),temp.begin(),tolower);	
				#else
				std::transform(temp.begin(),temp.end(),temp.begin(),(int(*)(int))std::tolower);
				#endif
				if (temp=="true") {
				_active=true;
				}
				else
				{
				_active=false;
				}
			}
	
		}
		if(element->Attribute("renderlist"))
		{
		_AddtoCurrentRenderlist= element->Attribute("renderlist");
			
		
		}
			if(element->Attribute("height", &value))
		{
		_height = value;
		}
			if(element->Attribute("width", &value))
		{

		_width = value;
		}
	

		if (_Name!=" ") {
			if (_fileName!=" ") {
			CreateButton(_fileName , _Name,_x,_y, _z, _Transparency, _active, _AddtoCurrentRenderlist);
			}
			else
			{
				
			CreateButton(_Name,_x, _y,_z, _height, _width, _Transparency, _active, _AddtoCurrentRenderlist);
			}
	
		}
		else
		{
			cerr<<"Could not create Button"<<_Name<<endl;
		}
	

	}


		void EpeeEngine::LoadButtonTBFromFile(TiXmlElement *element)
	{
		if (element==NULL) {
			return;
		}
		int value=0;
		
		const char *text = NULL;
		std::string _TextMessage=" ";
		std::string _Name=" ";
		 int _x=0;
		 int _y=0;
		unsigned int _height=-1;
		unsigned int _width=-1;
		bool _active=true;
		std::string _Font=True_Type_Font_Defalut;
		int _FontPoint=18;
		unsigned int _red=255;
		unsigned int _blue=255;
		unsigned int _green=255;
		std::string _FontPath=True_Type_Font_Location;
		int _z=0;
		std::string _AddtoCurrentRenderlist="Current";
		bool _Transparency=false;
			int _Quilty=FONT_QUALITY_LOW;
		if(element->Attribute("name"))
		{
			_Name = element->Attribute("name");
			
		
		}
		if(element->Attribute("textonbutton"))
		{
			_TextMessage = element->Attribute("textonbutton");
			
		
		}
		if(element->Attribute("x", &value))
		{

		_x = value;
		}

		if(element->Attribute("y", &value))
		{
		_y = value;
		}
			if(element->Attribute("z", &value))
		{

		_z = value;
		}
			if(element->Attribute("height", &value))
		{
		_height = value;
		}
			if(element->Attribute("width", &value))
		{

		_width = value;
		}
		if(element->Attribute("font"))
		{
			_Font = element->Attribute("font");
			
		
		}

			if(element->Attribute("fontcolorred", &value))
		{

		_red= value;
		}
				if(element->Attribute("fontcolorblue", &value))
		{

		_blue = value;
		}
		if(element->Attribute("fontcolorgreen", &value))
		{

		_green = value;
		}
		if(element->Attribute("fontpath"))
		{
		_FontPath= element->Attribute("fontpath");
		}

		if(element->Attribute("fontpoint", &value))
		{

		_FontPoint = value;
		}

		if(element->Attribute("renderlist"))
		{
		_AddtoCurrentRenderlist= element->Attribute("renderlist");
			
		
		}
		if(element->Attribute("active"))
		{
			std::string temp=" ";
			temp=element->Attribute("active");
			if(temp!=" ")
			{
				#if defined(_MSC_VER)
				std::transform(temp.begin(),temp.end(),temp.begin(),tolower);	
				#else
				std::transform(temp.begin(),temp.end(),temp.begin(),(int(*)(int))std::tolower);
				#endif
				if (temp=="true") {
				_active=true;
				}
				else
				{
				_active=false;
				}
			}
	
		}
		if(element->Attribute("textquality", &value))
		{//std::string TempQuality=value;
		//	if(TempQuality.f

		_Quilty = value;
		}
	

		if (_Name!=" ") {
			ButtonTB* created=CreateButtonTB(_Name,_x,_y,_z,_TextMessage ,_active,_AddtoCurrentRenderlist,_height,_width,_Font,_FontPoint,_red,_blue ,_green,_FontPath);
		if(created)
		{
			created->SetQuality(_Quilty);
		}
		}
		else
		{
			cerr<<"Could not create TextBox"<<_Name<<endl;
		}
	





	}


		void EpeeEngine::LoadAnimationFromFile(TiXmlElement *element)
		{
			if (element==NULL) {
			return;
		}
		int value=0;
		
		const char *text = NULL;
		std::string _fileName=" ";
		std::string _Name=" ";
		 int _x=0;
		 int _y=0;
		int _z=0;
		std::string _AddtoCurrentRenderlist="Current";
		bool _Transparency=false;

		int _NumberofFrames=0;
		int _NumberofRowsofFrames=1;
        int _fps=0;
		int _StartFrame=0;
		int _Loop=1;
		bool _StartNow=true;
		



		if(element->Attribute("name"))
		{
			_Name = element->Attribute("name");
			
		
		}
		if(element->Attribute("filename"))
		{
			_fileName = element->Attribute("filename");
			
		
		}
		if(element->Attribute("x", &value))
		{

		_x = value;
		}

		if(element->Attribute("y", &value))
		{
		_y = value;
		}
			if(element->Attribute("z", &value))
		{

		_z = value;
		}

		if(element->Attribute("transparency"))
		{
			std::string temp=" ";
			temp=element->Attribute("transparency");
			if(temp!=" ")
			{
					#if defined(_MSC_VER)
				std::transform(temp.begin(),temp.end(),temp.begin(),tolower);	
				#else
				std::transform(temp.begin(),temp.end(),temp.begin(),(int(*)(int))std::tolower);
				#endif
				if (temp=="true") {
				_Transparency=true;
				}
				else
				{
				_Transparency=false;
				}
			}
	
		}
		if(element->Attribute("renderlist"))
		{
		_AddtoCurrentRenderlist= element->Attribute("renderlist");
			
		
		}
			if(element->Attribute("numberofframes", &value))
		{

		_NumberofFrames = value;
		}
		if(element->Attribute("rowsofframes", &value))
		{

			_NumberofRowsofFrames = value;
		}
		
		if(element->Attribute("fps", &value))
		{

		_fps = value;
		}

		if(element->Attribute("startingframe", &value))
		{

		_StartFrame = value;
		}

			if(element->Attribute("numberofloops", &value))
		{

		_Loop = value;
		}
			if(element->Attribute("playnow"))
		{
			std::string temp=" ";
			temp=element->Attribute("playnow");
			if(temp!=" ")
			{
				#if defined(_MSC_VER)
				std::transform(temp.begin(),temp.end(),temp.begin(),tolower);	
				#else
				std::transform(temp.begin(),temp.end(),temp.begin(),(int(*)(int))std::tolower);
				#endif
				if (temp=="true") {
				_StartNow=true;
				}
				else
				{
				_StartNow=false;
				}
			}
	
		}

				

		if (_fileName!=" " && _Name!=" " && _NumberofFrames!=0) {
		CreateAnimation( _fileName , _Name, _x, _y, _z, _NumberofFrames, _fps, _StartFrame,_Loop,_NumberofRowsofFrames ,_Transparency, _StartNow,  _AddtoCurrentRenderlist);
	
	
		}
		else
		{
			cerr<<"Could not create Animation"<<_Name<<"With the file"<<_fileName<<endl;
		}

			

		}







		



bool EpeeEngine::LoadConfigurationFile(std::string _FileName)
{



TiXmlDocument document(_FileName.c_str());
bool success = document.LoadFile();
if(!success)
{
	cerr<<_FileName<<" Had a parsing error: "<<document.ErrorDesc()<<endl;
return false;
}
int value = 0;
const char *text = NULL;
TiXmlElement *parent = document.FirstChildElement("Sprockets");
TiXmlElement * element=NULL;
if (parent) {

element=parent->FirstChildElement();
}
else
{
	document.Clear();
	return false;
}


int count=0;
while(element)
{
	
std::string element_name(element->Value());
	#if defined(_MSC_VER)
	std::transform(element_name.begin(),element_name.end(),element_name.begin(),tolower);
	#else
	std::transform(element_name.begin(),element_name.end(),element_name.begin(),(int(*)(int))std::tolower);
	#endif
//std::transform(element_name.begin(),element_name.end(),element_name.begin(),(int(*)(int))std::tolower);
if(element_name == "image")
{

LoadImageFromFile(element);
}
if(element_name == "textbox")
{

LoadTextBoxFromFile(element);
}
if(element_name == "button")
{

LoadButtonFromFile(element);
}
if(element_name == "buttontb")
{

LoadButtonTBFromFile(element);
}
if(element_name == "animation")
{

LoadAnimationFromFile(element);
}

/*if(element_name == "setup")
{
if(m_pscreen==NULL)
{

LoadSetupFormFile(element);
}
}*/
count++;


element = element->NextSiblingElement();

}


//cout<<"number Of loops "<<count<<endl;


document.Clear();
		return true;
		


	}

/*
template <typename datatype> datatype EpeeEngine::StringToNumericData(std::string _stringtoconvert,datatype temp)
	{datatype tempint=0;

			std::istringstream tempstream(_stringtoconvert);
			if (!(tempstream>>tempint)) {
				std::string tempstring ="Could not convert"+_stringtoconvert+"to the specified data type";
				 EpeeEngineError temperror(tempstring,TEXTBOX_CONVERION_ERROR,this);
				 this->SetLastError(temperror);
				return 0;
			}
			this->ClearError();
			return tempint;
	}
	
template <typename datatype> std::string  EpeeEngine::StringFromNumericData(datatype _value)
	{datatype tempint=_value;
			std::ostringstream tempstream;
			if (!(tempstream<<_value)) {
				
				std::string tempstring ="Could not convert numeric data to string";
				 EpeeEngineError temperror(tempstring,TEXTBOX_CONVERION_ERROR,this);
				this->SetLastError(temperror);
				return "NULL";
				
			}
			this->ClearError();
			return tempstream.str(); 
			
			
	}*/

void EpeeEngine::SetLastError(EpeeEngineError _error)
	{
	m_cLastError.m_iErrorCode=_error.m_iErrorCode;
	m_cLastError.m_sError_Message=_error.m_sError_Message;
	m_cLastError.ObjectWhereErrorOccured=_error.ObjectWhereErrorOccured;
	if (_error.m_iErrorCode!=EPEE_NO_ERROR) {
	
	cerr<<m_cLastError.m_sError_Message<<endl;
	}
	}
void EpeeEngine::ClearError()
	{
		m_cLastError.m_iErrorCode=EPEE_NO_ERROR;
		m_cLastError.m_sError_Message=" ";
		m_cLastError.ObjectWhereErrorOccured=NULL;
	}
