Esempio n. 1
0
fixed_t *DmgFactors::CheckFactor(FName type)
{
	fixed_t *pdf = CheckKey(type);
	if (pdf == NULL && type != NAME_None)
	{
		pdf = CheckKey(NAME_None);
	}
	return pdf;
}
Esempio n. 2
0
int DmgFactors::Apply(FName type, int damage)
{
	auto pdf = CheckKey(type);
	if (pdf == NULL && type != NAME_None)
	{
		pdf = CheckKey(NAME_None);
	}
	if (!pdf) return damage;
	return int(damage * *pdf);
}
Esempio n. 3
0
void UpdateCassette()
{
#if 1
	if (CheckKey(GLFW_KEY_PAGE_UP))
	{
		playDown=1;
		recDown=playDown;
		ClearKey(GLFW_KEY_PAGE_UP);
		cntPos=0;
		casCount=0;
		casLevel=0;		
	}
#endif
	if (CheckKey(GLFW_KEY_PAGE_DOWN))
	{
		playDown=1;
		recDown=0;
		ClearKey(GLFW_KEY_PAGE_DOWN);
		cntPos=0;
		casCount=0;
		casLevel=0;
	}
	if (CheckKey(GLFW_KEY_END))
	{
		playDown=0;
		recDown=0;
		ClearKey(GLFW_KEY_END);
		cntPos=0;
		casCount=0;
		casLevel=0;		
	}

	// Cassette deck
	if (playDown)
	{
		VIA0_PinSetPIN_PA(VIA0_PinGetPIN_PA()&0xBF);
	}
	if (playDown && recDown && (!VIA0_PinGetPIN_CA2())) // SAVING
	{
		uint8_t newRecLevel = (VIA1_PinGetPIN_PB()&0x08)>>3;
		casCount++;
		if (newRecLevel!=casLevel)
		{
			//printf("Level Changed %08X\n",casCount);
			cntMax=cntPos;
			cntBuffer[cntPos++]=casCount;
			casCount=0;
			casLevel=newRecLevel;
		}
	}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::WarmStartResource(/*[in]*/ long lKey)
{
    AFX_MANAGE_STATE(AfxGetStaticModuleState())

	BOOL bHandled = FALSE;

	HRESULT hr = Adapt_WarmStartResource(lKey, &bHandled);
	if (FAILED(hr) || bHandled == TRUE) {
		return hr;
	}

    hr = CheckKey(lKey, TRUE);
    if (FAILED(hr)) {
        return hr;
    }

	hr = myConnection.SendCommand(FALSE, CMD_WARM_START, NULL, 0);

	if (SUCCEEDED(hr))
	{
		myConnection.CheckVersion();
		if (myConnection.IsLogon())
          CCommissioningMgt::ibnConfigurationChanged();
	}

    return hr;
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::StopTaskOnResource(/*[in]*/ long lKey, BSTR sTask)
{
    AFX_MANAGE_STATE(AfxGetStaticModuleState())

	BOOL bHandled = FALSE;

	HRESULT hr = Adapt_StopTaskOnResource(lKey,sTask, &bHandled);
	if (FAILED(hr) || bHandled == TRUE) {
		return hr;
	}

    hr = CheckKey(lKey, TRUE);
    if (FAILED(hr)) {
        return hr;
    }

    hr = E_FAIL;
    CString strTask = sTask;
    long taskid = 0;
    strTask.MakeLower();

    if (CSC_LookupTask(strTask, taskid)) 
	{
		IEC_UINT uTask = TRANSLATE_SHORT((IEC_UINT)taskid);

		hr = myConnection.SendCommand(TRUE, CMD_STOP_TASK, (BYTE *)&uTask, sizeof(uTask));
    }

    return hr;
}
Esempio n. 6
0
void iteminfor_pick()
{
	view_item(IVT_PICK,"무슨 아이템을 줍겠습니까?");
	while(1)
	{
		int key_ = waitkeyinput(true);
		if( (key_ >= 'a' && key_ <= 'z') || (key_ >= 'A' && key_ <= 'Z') )
		{
			CheckKey(key_);
		}
		else if(key_ == VK_DOWN)//-----이동키-------
		{
			changemove(32);  //위
		}
		else if(key_ == VK_UP)
		{
			changemove(-32); //아래
		}
		else if(key_ == VK_PRIOR)
		{
			changemove(-WindowHeight);
		}
		else if(key_ == VK_NEXT)
		{
			changemove(WindowHeight);
		}						//-----이동키끝-------
		else if( key_ == ',' )
		{
			AllCheckKey();
		}
		else if(key_ == VK_RETURN)
		{
			changedisplay(DT_GAME);
			list<item>::iterator it = env[current_level].GetPositiontoitem(you.position);
			list<item>::iterator end = env[current_level].GetPositiontoitemend(you.position);
			for(;it != end;)
			{
				list<item>::iterator temp = it++;
				if(GetItemofKey(temp,end))
				{	
					if(you.additem(&(*temp)))
					{
						env[current_level].DeleteItem(temp);
						you.time_delay+=you.GetNormalDelay();
						you.TurnEnd();
						it = env[current_level].GetPositiontoitem(you.position);
						end = env[current_level].GetPositiontoitemend(you.position);
					}
					else
						break;
				}
			}
			break;
		}
		else if(key_ == VK_ESCAPE)
			break;

	}
	changedisplay(DT_GAME);
}
Esempio n. 7
0
LSTATUS CreateSkinKeys()
{
	LSTATUS rtn = 0;
	TCHAR filename[MAX_PATH];
	TCHAR fullpath[MAX_PATH];
	TCHAR imagpath[MAX_PATH];

	GetModuleFileName( NULL, filename, MAX_PATH );
	_snwprintf( fullpath, MAX_PATH, L"\"%s\" \"%%1\"", filename );
	_snwprintf( imagpath, MAX_PATH, L"%s,0", filename );

	if ( ! CheckKey( L"SOFTWARE\\Classes\\.sks" ) )		// Shareaza
		rtn = CreateKey( L"SOFTWARE\\Classes\\.sks", L"", L"Envy.Package" );
	rtn = CreateKey( L"SOFTWARE\\Classes\\.psk", L"", L"Envy.Package" );
	rtn = CreateKey( L"SOFTWARE\\Classes\\.env", L"", L"Envy.Package" );
	rtn = CreateKey( L"SOFTWARE\\Classes\\.envy", L"", L"Envy.Package" );
	if ( rtn != ERROR_SUCCESS ) return rtn;
	rtn = CreateKey( L"SOFTWARE\\Classes\\Envy.Package", L"", L"Envy Package" );
	if ( rtn != ERROR_SUCCESS ) return rtn;
	rtn = CreateKey( L"SOFTWARE\\Classes\\Envy.Package\\DefaultIcon", L"", imagpath );
	if ( rtn != ERROR_SUCCESS ) return rtn;
	rtn = CreateKey( L"SOFTWARE\\Classes\\Envy.Package\\shell", L"", L"open" );
	if ( rtn != ERROR_SUCCESS ) return rtn;
	rtn = CreateKey( L"SOFTWARE\\Classes\\Envy.Package\\shell\\open\\command", L"", fullpath );
	if ( rtn != ERROR_SUCCESS ) return rtn;
	rtn = CreateKey( L"SOFTWARE\\Classes\\Envy.Package\\shell\\skininstall", L"", L"Install Envy Package" );
	if ( rtn != ERROR_SUCCESS ) return rtn;
	rtn = CreateKey( L"SOFTWARE\\Classes\\Envy.Package\\shell\\skininstall\\command", L"", fullpath );
	if ( rtn != ERROR_SUCCESS ) return rtn;

	return ERROR_SUCCESS;
}
Esempio n. 8
0
void Dispatcher::DispatchImmediate(EventType eventID, const WorkArguments eventData) {
    // std::cout << "DispatchImmediate " << eventID << "\t" << eventData << std::endl;
    CheckKey(eventID);

    // If there's nothing to deliver this event to just drop it
    if (mapped_events->at(eventID)->size() == 0) {
        return;
    }

    for (auto it = mapped_events->at(eventID)->begin(); it != mapped_events->at(eventID)->end(); it++) {

        // Remove nullptr Subscriber* from the processing
        if (*it == nullptr) {
            // everything else is read-only so we only REALLY need to get the mutex when we edit it
            std::lock_guard<std::recursive_mutex> lock(mapped_event_mutex);
            it = mapped_events->at(eventID)->erase(it);
            continue;
        }

        if ((*it)->_serialized) {
            std::lock_guard<std::recursive_mutex> lock(thread_queue_mutex);
            thread_queue->push_back(WorkPair(*it, eventData));
        } else {
            std::lock_guard<std::recursive_mutex> lock2(nonserial_queue_mutex);
            nonserial_queue->push_back(WorkPair(*it, eventData));
        }
    }

    thread_signal.notify_one();
}
// Process a key-up or -down event.  A key is "registered" when it is
// pressed and then released, with no other keypresses or releases in
// between.  Registered keys are passed to CheckKey() to see if it
// should trigger a visibility toggle, an immediate reboot, or be
// queued to be processed next time the foreground thread wants a key
// (eg, for the menu).
//
// We also keep track of which keys are currently down so that
// CheckKey can call IsKeyPressed to see what other keys are held when
// a key is registered.
//
// updown == 1 for key down events; 0 for key up events
void RecoveryUI::process_key(int key_code, int updown) {
    bool register_key = false;
    bool long_press = false;
    bool reboot_enabled;

    pthread_mutex_lock(&key_queue_mutex);
    key_pressed[key_code] = updown;
    if (updown) {
        ++key_down_count;
        key_last_down = key_code;
        key_long_press = false;
        pthread_t th;
        key_timer_t* info = new key_timer_t;
        info->ui = this;
        info->key_code = key_code;
        info->count = key_down_count;
        pthread_create(&th, NULL, &RecoveryUI::time_key_helper, info);
        pthread_detach(th);
    } else {
        if (key_last_down == key_code) {
            long_press = key_long_press;
            register_key = true;
        }
        key_last_down = -1;
    }
    reboot_enabled = enable_reboot;
    pthread_mutex_unlock(&key_queue_mutex);

    if (register_key) {
        NextCheckKeyIsLong(long_press);
        switch (CheckKey(key_code)) {
        case RecoveryUI::IGNORE:
            break;

        case RecoveryUI::TOGGLE:
            ShowText(!IsTextVisible());
            break;

        case RecoveryUI::REBOOT:
#ifdef ANDROID_RB_RESTART
            if (reboot_enabled) {
                android_reboot(ANDROID_RB_RESTART, 0, 0);
            }
#endif
            break;

        case RecoveryUI::ENQUEUE:
            EnqueueKey(key_code);
            break;

        case RecoveryUI::MOUNT_SYSTEM:
#ifndef NO_RECOVERY_MOUNT
            ensure_path_mounted("/system");
            Print("Mounted /system.");
#endif
            break;
        }
    }
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::GetMinMaxHistoryIDs(/*[in]*/ long lKey, long *pFirst, long *pLast)
{
    HRESULT hr = CheckKey(lKey);
    if (FAILED(hr)) {
        return hr;
    }

    return E_NOTIMPL;
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::GetHistoryMessage(/*[in]*/ long lKey, long idHistory, BSTR * psMessage, DATE * pdt)
{
    HRESULT hr = CheckKey(lKey);
    if (FAILED(hr)) {
        return hr;
    }

    return E_NOTIMPL;
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::put_MaxHistoryLength(/*[in]*/ long lKey, long newVal)
{
    HRESULT hr = CheckKey(lKey, TRUE);
    if (FAILED(hr)) {
        return hr;
    }

    return E_NOTIMPL;
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::ClearHistoryBuffer(/*[in]*/ long lKey)
{
    HRESULT hr = CheckKey(lKey, TRUE);
    if (FAILED(hr)) {
        return hr;
    }

    return E_NOTIMPL;
}
Esempio n. 14
0
static void AppTask(void *pvParameters) {
  uint16_t cntMs;
  
  cntMs = 0;
  for(;;) {
    if (cntMs>1000) {
      LED3_Neg();
      cntMs = 0;
    }
    CheckKey();
    FRTOS1_vTaskDelay(10/portTICK_RATE_MS);
    cntMs += 10;
  }
}
Esempio n. 15
0
void GameManager::AI()
{
	CheckKey();
	if (GameStart() && !GamePause() && !GameOver())
	{
		Produce(_T("Enemy"));
		Produce(_T("Cloud"));
		Produce(_T("Angela"));
		CheckCollision();
		MoveIt();
		Fire();
		TrashRecycle();
	}
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::Disconnect(/*[in]*/ long lKey)
{
    HRESULT hr = CheckKey(lKey);
    if (FAILED(hr)) {
        return hr;
    }

    if (m_hThread != NULL) {
        ConnectControlMessages(FALSE);
        StopThread();
    }

    return S_OK;
}
Esempio n. 17
0
void CShootingScene::DrawImage(void)
{
	CheckKey();
	m_BackGroundImageLeft.DrawImage();
	m_Player.DrawImage();
	
	m_PlayerShotManager.DrawShot();

	
	m_Enemy.DrawImage();
	m_BackGroundImageRight.DrawImage();
	m_h.DrawImage();
	m_PlayerShotManager.MoveShot();
	m_PlayerShotManager.CheckShot();
	m_PlayerShotManager.DeleteShot();
}
Esempio n. 18
0
void Play()
{
  playingState = PS_NEXT_SONG;

  currentFile = 1;

 #if defined(__AVR_ATmega1280__)
   // If play/stop button is pressed during boot, enter recording.
  if (0== PSKey)
  {
  	 delay(20);
	 while(0 == PSKey);
	 delay(20);
        Record();
  }
  #endif
  
  //cyclely play 
  while(1)
  {

	 //CheckPlay();
	 CheckKey();
	 	 
	 if(1 ==playStop)
	 {
	 	if(OpenFile(currentFile))
	 	{	
			//if open failed, then try it again
	 		if(OpenFile(currentFile))
			{
				playStop = 0;
				playingState = PS_NEXT_SONG;
  				currentFile = 1;
				continue;
			}
	 	}
		
		PlayCurrentFile();
		if (playingState == PS_PREVIOUS_SONG) currentFile--;
	    if (playingState == PS_NEXT_SONG) currentFile++;
    	if (currentFile==0) currentFile = 1;
     	//if (playingState == PS_END_OF_SONG) playingState = PS_NORMAL; 
		Mp3SoftReset();
	 }
  }
}
Esempio n. 19
0
LSTATUS DeleteSkinKeys()
{
	if ( ! CheckKey( L"SOFTWARE\\Classes\\Shareaza.Package" ) )
		DeleteKey( L"SOFTWARE\\Classes\\.sks", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\.psk", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\.env", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\.envy", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\Envy.Package\\shell\\open\\command", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\Envy.Package\\shell\\open", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\Envy.Package\\shell\\skininstall\\command", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\Envy.Package\\shell\\skininstall", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\Envy.Package\\shell", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\Envy.Package\\DefaultIcon", L"" );
	DeleteKey( L"SOFTWARE\\Classes\\Envy.Package", L"" );

	return ERROR_SUCCESS;
}
Esempio n. 20
0
// Process a key-up or -down event.  A key is "registered" when it is
// pressed and then released, with no other keypresses or releases in
// between.  Registered keys are passed to CheckKey() to see if it
// should trigger a visibility toggle, an immediate reboot, or be
// queued to be processed next time the foreground thread wants a key
// (eg, for the menu).
//
// We also keep track of which keys are currently down so that
// CheckKey can call IsKeyPressed to see what other keys are held when
// a key is registered.
//
// updown == 1 for key down events; 0 for key up events
void RecoveryUI::process_key(int key_code, int updown) {
    bool register_key = false;
    bool long_press = false;

    pthread_mutex_lock(&key_queue_mutex);
    key_pressed[key_code] = updown;
    if (updown) {
        ++key_down_count;
        key_last_down = key_code;
        key_long_press = false;
        pthread_t th;
        key_timer_t* info = new key_timer_t;
        info->ui = this;
        info->key_code = key_code;
        info->count = key_down_count;
        pthread_create(&th, NULL, &RecoveryUI::time_key_helper, info);
        pthread_detach(th);
    } else {
        if (key_last_down == key_code) {
            long_press = key_long_press;
            register_key = true;
        }
        key_last_down = -1;
    }
    pthread_mutex_unlock(&key_queue_mutex);

    if (register_key) {
        NextCheckKeyIsLong(long_press);
        switch (CheckKey(key_code)) {
          case RecoveryUI::IGNORE:
            break;

          case RecoveryUI::TOGGLE:
            ShowText(!IsTextVisible());
            break;

          case RecoveryUI::REBOOT:
            android_reboot(ANDROID_RB_RESTART, 0, 0);
            break;

          case RecoveryUI::ENQUEUE:
            EnqueueKey(key_code);
            break;
        }
    }
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::Connect(/*[in]*/ long lKey)
{
    HRESULT hr = CheckKey(lKey);
    if (FAILED(hr)) {
        return hr;
    }

    hr = S_OK;
    if (SUCCEEDED(hr) && Is_Proxy_Connected()) {
        hr = StartThread();
        if (SUCCEEDED(hr))
            hr = ConnectControlMessages(TRUE);
    }

    return hr;
}
Esempio n. 22
0
void Parser::ParamList(Decl& d) {
	if(!Key(')'))
		for(;;) {
			if(Key(t_elipsis)) {
				Elipsis(d);
				break;
			}
			else
				d.param.Add() = Declaration().Top();
			if(Key(t_elipsis)) {
				Elipsis(d);
				break;
			}
			if(Key(')')) break;
			CheckKey(',');
		}
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::Logout(/*[in]*/ long lKey)
{
	BOOL bHandled = FALSE;

	HRESULT hr = Adapt_Logout(lKey, &bHandled);
	if (FAILED(hr) || bHandled == TRUE) {
		return hr;
	}

    hr = CheckKey(lKey);
    if (FAILED(hr)) {
        return hr;
    }

    m_lSessionKey = 0;
    return S_OK;
}
//------------------------------------------------------------------*
STDMETHODIMP
    CControlMgt::StopAllTasksOnResource(/*[in]*/ long lKey)
{
    AFX_MANAGE_STATE(AfxGetStaticModuleState())
    
	BOOL bHandled = FALSE;

	HRESULT hr = Adapt_StopAllTasksOnResource(lKey, &bHandled);
	if (FAILED(hr) || bHandled == TRUE) {
		return hr;
	}
	
	hr = CheckKey(lKey, TRUE);
    if (FAILED(hr)) {
        return hr;
    }

    return myConnection.SendCommand(FALSE, CMD_STOP_ALL_TASKS, NULL, 0);
}
Esempio n. 25
0
/** This function is called when the player is playing a song
 and there is free processor time. The basic task of this
 function is to implement the player user interface. */
void AvailableProcessorTime()
{

	do
	{
  		CheckKey();
  
 		 //IPODCommandProcess();
		 
		if(0 == playStop)
		{
			GREEN_LED_ON();
		}	
	}while(0 == playStop);
	
  	//do other things
	ControlLed();

}
Esempio n. 26
0
String Parser::TemplateParams(String& param)
{
	const char *pos = lex.Pos();
	CheckKey('<');
	int level = 1;
	String id;
	bool gp = true;
	for(;;) {
		if(lex.IsId() && gp)
			id = lex.GetId();
		else
		if(Key(',')) {
			ScAdd(param, id);
			id.Clear();
			gp = true;
		}
		else
		if(Key('=')) {
			if(!id.IsEmpty()) {
				ScAdd(param, id);
				id.Clear();
			}
			gp = false;
		}
		else
		if(Key('>')) {
			level--;
			if(level <= 0) {
				ScAdd(param, id);
				break;
			}
		}
		else
		if(Key('<'))
			level++;
		else
			++lex;
	}
	return String(pos, lex.Pos());
}
// Process a key-up or -down event.  A key is "registered" when it is
// pressed and then released, with no other keypresses or releases in
// between.  Registered keys are passed to CheckKey() to see if it
// should trigger a visibility toggle, an immediate reboot, or be
// queued to be processed next time the foreground thread wants a key
// (eg, for the menu).
//
// We also keep track of which keys are currently down so that
// CheckKey can call IsKeyPressed to see what other keys are held when
// a key is registered.
//
// updown == 1 for key down events; 0 for key up events
void RecoveryUI::process_key(int key_code, int updown) {
    bool register_key = false;

    pthread_mutex_lock(&key_queue_mutex);
    key_pressed[key_code] = updown;
    if (updown) {
        key_last_down = key_code;
    } else {
        if (key_last_down == key_code)
            register_key = true;
        key_last_down = -1;
    }
    pthread_mutex_unlock(&key_queue_mutex);

    if (register_key) {
        switch (CheckKey(key_code)) {
          case RecoveryUI::IGNORE:
            break;

          case RecoveryUI::TOGGLE:
            ShowText(!IsTextVisible());
            break;

          case RecoveryUI::REBOOT:
            android_reboot(ANDROID_RB_RESTART, 0, 0);
            break;

          case RecoveryUI::ENQUEUE:
            pthread_mutex_lock(&key_queue_mutex);
            const int queue_max = sizeof(key_queue) / sizeof(key_queue[0]);
            if (key_queue_len < queue_max) {
                key_queue[key_queue_len++] = key_code;
                pthread_cond_signal(&key_queue_cond);
            }
            pthread_mutex_unlock(&key_queue_mutex);
            break;
        }
    }
}
Esempio n. 28
0
uint
O2KeyDB::
AddKey(O2Key &k)
{
	// ret
	//	1: new
	//	2: update
	uint ret = 0;

	if (!CheckKey(k))
		return (0);
	k.makeidkeyhash();

//	hashBitsetT d = k.hash.bits ^ SelfNodeID.bits;
//	k.distance = d.bit_length();
	k.distance = hash_xor_bitlength(k.hash, SelfNodeID);

	if (!IP0Port0)
		k.date = time(NULL);

	Lock();
	{
		O2Keys::iterator it = Keys.find(k.idkeyhash);
		if (it == Keys.end()) {
			Keys.insert(k);
			ret = 1;
		}
		else {
			k.marge(*it);
			Keys.replace(it, k);
			ret = 2;
		}
	}
	Unlock();
	return (ret);
}
Esempio n. 29
0
void CSelfTestMenu::OnButton13(int iEvent, unsigned char * pEventData, int iDataLen)
{
	TDateTime curDate;
	char chValue[64];
	UINT8 nKeyTime = 1;
	while(1)
	{
		curDate = TDateTime::CurrentDateTime();
		memset(chValue, 0, sizeof(chValue));
		sprintf(chValue, "   %s", curDate.FormatString(YYYYMMDDHHMMSS).c_str());
		
		CaProgressBar proBar(chValue);
		proBar.Show();
		
		if(CheckKey(nKeyTime)==SUCCESS)
		{
			break;
		}
		CommonSleep(1000);
	}
	
	this->ReFresh();
	return;
}
Esempio n. 30
0
int main(int argc,char**argv)
{
	double	atStart,now,remain;

	/// Initialize GLFW 
	glfwInit(); 

	// Open registers OpenGL window 
	if( !(windows[REGISTER_WINDOW]=glfwCreateWindow( REGISTER_WIDTH, REGISTER_HEIGHT, "cpu",NULL,NULL)) ) 
	{ 
		glfwTerminate(); 
		return 1; 
	} 

	glfwSetWindowPos(windows[REGISTER_WINDOW],600,740);

	glfwMakeContextCurrent(windows[REGISTER_WINDOW]);
	setupGL(REGISTER_WINDOW,REGISTER_WIDTH,REGISTER_HEIGHT);

	// Open timing OpenGL window 
	if( !(windows[TIMING_WINDOW]=glfwCreateWindow( TIMING_WIDTH, TIMING_HEIGHT, "timing",NULL,NULL)) ) 
	{ 
		glfwTerminate(); 
		return 1; 
	} 

	glfwSetWindowPos(windows[TIMING_WINDOW],600,300);

	glfwMakeContextCurrent(windows[TIMING_WINDOW]);
	setupGL(TIMING_WINDOW,TIMING_WIDTH,TIMING_HEIGHT);

	// Open invaders OpenGL window 
	if( !(windows[MAIN_WINDOW]=glfwCreateWindow( WIDTH, HEIGHT, "invaders",NULL,NULL)) ) 
	{ 
		glfwTerminate(); 
		return 1; 
	} 

	glfwSetWindowPos(windows[MAIN_WINDOW],300,300);
	
	glfwMakeContextCurrent(windows[MAIN_WINDOW]);
	setupGL(MAIN_WINDOW,WIDTH,HEIGHT);

	glfwSwapInterval(0);			// Disable VSYNC

	glfwSetKeyCallback(windows[MAIN_WINDOW],kbHandler);
	glfwSetScrollCallback(windows[TIMING_WINDOW],mwHandler);

	atStart=glfwGetTime();
	//////////////////

	if (InitialiseMemory())
		return -1;
	
	PinSetRESET(1);
	PIN_BUFFER_RESET=1;
	PinSetO1(1);			// Run with reset high for a few cycles to perform a full cpu reset
	PinSetO1(0);
	PinSetO2(1);
	PinSetO2(0);
	PinSetO1(1);
	PinSetO1(0);
	PinSetO2(1);
	PinSetO2(0);
	PinSetO1(1);
	PinSetO1(0);
	PinSetO2(1);
	PinSetO2(0);
	PinSetRESET(0);			// RESET CPU
	PIN_BUFFER_RESET=0;

	//dumpInstruction=100000;

	int stopTheClock=0;
	while (!glfwGetKey(windows[MAIN_WINDOW],GLFW_KEY_ESCAPE))
	{
		
		if (!stopTheClock)
		{
			masterClock++;
			if ((masterClock%4)==0)
				pixelClock++;

			if ((masterClock%10)==0)
			{
								// I8080 emulation works off positive edge trigger. So we need to supply the same sort of
								// clock.
				PIN_BUFFER_O2=0;
				PIN_BUFFER_O1=1;
				PinSetO1(1);		// Execute a cpu step
				if (bTimingEnabled)
					RecordPins();
				PIN_BUFFER_O1=0;
				PinSetO1(0);
				if (bTimingEnabled)
					RecordPins();
				PIN_BUFFER_O2=1;
				PinSetO2(1);
				if (bTimingEnabled)
					RecordPins();
				PIN_BUFFER_O2=0;
				PinSetO2(0);

				if (!MEM_Handler())
				{
					stopTheClock=1;
				}
				if (bTimingEnabled)
					RecordPins();

				PinSetINT(0);		// clear interrupt state
				PIN_BUFFER_INT=0;
				cpuClock++;
			}
			if (pixelClock==30432+10161)		// Based on 19968000 Mhz master clock + mame notes
			{
				NEXTINT=0xCF;
				PinSetINT(1);
				PIN_BUFFER_INT=1;
			}
			if (pixelClock==71008+10161)
			{
				NEXTINT=0xD7;
				PinSetINT(1);
				PIN_BUFFER_INT=1;
			}
		}
		if (pixelClock>=83200 || stopTheClock)
		{
			if (pixelClock>=83200)
				pixelClock=0;

			if (glfwWindowShouldClose(windows[TIMING_WINDOW]))
			{
				bTimingEnabled=0;
				glfwHideWindow(windows[TIMING_WINDOW]);
			}
			if (glfwWindowShouldClose(windows[REGISTER_WINDOW]))
			{
				bRegisterEnabled=0;
				glfwHideWindow(windows[REGISTER_WINDOW]);
			}

            		glfwMakeContextCurrent(windows[MAIN_WINDOW]);
			ShowScreen(MAIN_WINDOW,WIDTH,HEIGHT);
			glfwSwapBuffers(windows[MAIN_WINDOW]);
				
			if (bTimingEnabled)
			{
				glfwMakeContextCurrent(windows[TIMING_WINDOW]);
				DrawTiming(videoMemory[TIMING_WINDOW],TIMING_WIDTH);
				ShowScreen(TIMING_WINDOW,TIMING_WIDTH,TIMING_HEIGHT);
				glfwSwapBuffers(windows[TIMING_WINDOW]);
			}
			if (bRegisterEnabled)
			{
				glfwMakeContextCurrent(windows[REGISTER_WINDOW]);
				DrawRegister(videoMemory[REGISTER_WINDOW],REGISTER_WIDTH);
				ShowScreen(REGISTER_WINDOW,REGISTER_WIDTH,REGISTER_HEIGHT);
				glfwSwapBuffers(windows[REGISTER_WINDOW]);
			}
        
			glfwPollEvents();
			
			g_traceStep=0;
			if (CheckKey(GLFW_KEY_PAUSE))
			{
				g_instructionStep^=1;
				if (stopTheClock && !g_instructionStep)
					stopTheClock=0;
				ClearKey(GLFW_KEY_PAUSE);
			}
			if (stopTheClock && CheckKey('S'))
			{
				stopTheClock=0;
				ClearKey('S');
			}
			if (stopTheClock && CheckKey('T'))
			{
				stopTheClock=0;
				g_traceStep=1;
				ClearKey('T');
			}

			now=glfwGetTime();

			remain = now-atStart;

			while ((remain<0.02f))
			{
				now=glfwGetTime();

				remain = now-atStart;
			}
			atStart=glfwGetTime();
		}
	}
	
	return 0;

}