void CharactersLoop(CONNECT_INFO* cfg, Ref< UsersPool > OnlineUsers, Ref< CrossThreadQueue< string > > OutputQueue) {
	RakPeerInterface* rakServer = RakNetworkFactory::GetRakPeerInterface();

	PacketFileLogger* msgFileHandler = NULL;
	if (cfg->logFile) {
		msgFileHandler = new PacketFileLogger();
		rakServer->AttachPlugin(msgFileHandler);
	}

	InitSecurity(rakServer, cfg->useEncryption);
	SocketDescriptor socketDescriptor(cfg->listenPort, 0);

	if (rakServer->Startup(8, 30, &socketDescriptor, 1)) {
		stringstream s;
		s << "characters started! Listening on: " << cfg->listenPort << "\n";
		OutputQueue->Insert(s.str());
	} else exit(2);
	rakServer->SetMaximumIncomingConnections(8);

	if (msgFileHandler != NULL) msgFileHandler->StartLog(".\\logs\\char");

	Packet* packet;

	while (!LUNIterminate) {
		RakSleep(30);	// This sleep keeps RakNet responsive
		packet = rakServer->Receive();
		if (packet == NULL) continue;
		PrintPacketInfo(packet, msgFileHandler);
		// create and send packets back here according to the one we got

		switch (packet->data[0]) {
			case ID_LEGO_PACKET:

				switch (packet->data[1]) {
					case LUNI_INITAW:
						if (packet->data[3] == 0) {	// thats just a formality so far since no other numbers occured for this case
							auto v = OpenPacket(".\\char\\init_aw.bin");
							ServerSendPacket(rakServer, v, packet->systemAddress);
						}
						break;

					case LUNI_CHARACTER:

						switch (packet->data[3]) {
							case LUNI_CHARACTER_CHARSDATA: // char response: 05, 06
								// char traffic only - byte 8 defines number of characters, if there are no characters the user automatically gets to the character creation screen
							{
								//giving client characters list
								auto v = OpenPacket(".\\char\\char_aw2.bin");
								ServerSendPacket(rakServer, v, packet->systemAddress);

							#ifdef DEBUG
								/*StringCompressor* sc = StringCompressor::Instance();
								Ref<char> output = new char[256];
								RakNet::BitStream* bs = new RakNet::BitStream(v.data(), v.size(), false);
								if (sc->DecodeString(output.Get(), 256, bs))
									cout << ("\n the TEST: " + RawDataToString((uchar*)output.Get(), 256) + "\n");
								else cout << ("\n the Test failure :(\n");*/
								RakNet::BitStream bs(v.data(), v.size(), false);
								vector< uchar > out(v.size() *2);
								bs.ReadCompressed(out.data(), out.size(), true);
								//cout << "\n the Test: " << RawDataToString( s.Get(), v.size() ) << endl;
								//SavePacket("theTest.bin", out);
							#endif
							}
								break;

							case LUNI_CHARACTER_CREATEDNEW:
							{
								CharacterCreation cc(CleanPacket(packet->data, packet->length));

								stringstream s;
								s << "\nSomebody wants to create a character with name: " << cc.GetName() << endl;
								s << "re-Serialization: " << RawDataToString(cc.Serialize(), cc.GetGeneratedPacketSize()) << endl;
								OutputQueue->Insert(s.str());
								// response: 05, 06
								// since we can't build our own packets yet we can't send a response here (because it is dependent on the user input)
								vector< uchar > reply(2);
								reply.push_back(5);
								reply.push_back(6);
								ServerSendPacket(rakServer, reply, packet->systemAddress);
							}
								break;

							case 4: // is this sent from the client once the user wants to enter world?
							{
								auto usr = OnlineUsers->Find(packet->systemAddress);
								if (usr != NULL) {
									usr->numredir++;
									//character id is received
									vector< uchar > t;
									for (int i = 8; i <= 11; i++) t.push_back(packet->data[i]);
									usr->nextcid = *(ulong*)t.data();

								#ifdef DEBUG
									stringstream s;
									s << "\nCharacter logging in world with id: " << usr->nextcid;
									if ( usr->nextcid == 2397732190 ) s << " CheekyMonkey!\n";
									else if ( usr->nextcid == 2444680020 ) s << " monkeybrown!\n";
									else if ( usr->nextcid == 1534792735 ) s << " GruntMonkey!\n";
									else if ( usr->nextcid == 1457240027 ) s << " Shafantastic!\n";
									else s << " Unknow cid: " << usr->nextcid << endl;
									OutputQueue->Insert(s.str());
								#endif
								}

								auto v = OpenPacket(".\\char\\char_aw_redirect.bin");
								if (v.size() > 0) {
									// ip starts at byte 8, port starts at byte 0x29
									if (cfg->redirectIp[0] != 0)
										memcpy(v.data() + 0x8, cfg->redirectIp, sizeof(cfg->redirectIp) - 3);	// NOTE: the IP can currently only be 13 characters long here since there are some non-zero bytes directly after the IP and I don't want to delete them (is it safe to overwrite them?)
									if (cfg->redirectPort > 0)
										memcpy(v.data() + 0x29, &cfg->redirectPort, sizeof(cfg->redirectPort));
									ServerSendPacket(rakServer, v, packet->systemAddress);
								}
								rakServer->CloseConnection(packet->systemAddress, true);
							}
								break;

							case LUNI_CHARACTER_DELETED:
								stringstream s;
								s << "\n Case LUNI_CHARACTER_DELETED: " << RawDataToString(packet->data, packet->length) << endl;
								OutputQueue->Insert(s.str());
								break;
						}

						break;

					default:
						stringstream s;
						s << "\ncharacters received unknow pakcet: " << RawDataToString(packet->data, packet->length) << endl;
						OutputQueue->Insert(s.str());
				}

				break;

			case ID_NEW_INCOMING_CONNECTION:
			#ifdef DEBUG
				OutputQueue->Insert("\n Characters is receiving a new connection...\n");
			#endif
				break;

			case ID_DISCONNECTION_NOTIFICATION:
			{
				auto usr = OnlineUsers->Find(packet->systemAddress);
				if (OnlineUsers->Remove(packet->systemAddress))
					OutputQueue->Insert("Disconnected " + usr->GetUsername() + "\n");
			}
				break;

			default:
				stringstream s;
				s << "\ncharacters received unknow pakcet: " << RawDataToString(packet->data, packet->length) << endl;
				OutputQueue->Insert(s.str());
		}
	}
}
void CharactersLoop(CONNECT_INFO* cfg, Ref< UsersPool > OnlineUsers, Ref< CrossThreadQueue< string > > OutputQueue) {
    // Initialize the RakPeerInterface used throughout the entire server
    RakPeerInterface* rakServer = RakNetworkFactory::GetRakPeerInterface();

    // Initialize the PacketFileLogger plugin (for the logs)
    PacketFileLogger* msgFileHandler = NULL;
    if (cfg->logFile) {
        msgFileHandler = new PacketFileLogger();
        rakServer->AttachPlugin(msgFileHandler);
    }

    // Initialize security IF user has enabled it in config.ini
    InitSecurity(rakServer, cfg->useEncryption);

    // Initialize the SocketDescriptor
    SocketDescriptor socketDescriptor(cfg->listenPort, 0);

    // If the startup of the server is successful, print it to the console
    // Otherwise, quit the server (as the char server is REQUIRED for the
    // server to function properly)
    if (rakServer->Startup(8, 30, &socketDescriptor, 1)) {
        stringstream s;
        s << "Characters started! Listening on: " << cfg->listenPort << "\n";
        OutputQueue->Insert(s.str());
    } else exit(2);

    // Set max incoming connections to 8
    rakServer->SetMaximumIncomingConnections(8);

    // If msgFileHandler is not NULL, save logs of char server
    if (msgFileHandler != NULL) msgFileHandler->StartLog(".\\logs\\char");

    // Initialize the Packet class for the packets
    Packet* packet;

    // This will be used in the saving of packets below...
    int i = 0;

    while (!LUNIterminate) {
        RakSleep(30);	// This sleep keeps RakNet responsive
        packet = rakServer->Receive(); // Recieve the packets from the server
        if (packet == NULL) continue; // If packet is NULL, just continue without processing anything
        PrintPacketInfo(packet, msgFileHandler); // Save packet info

        // This will save all packets recieved from the client if running from DEBUG
#ifdef DEBUG
        stringstream packetName;
        packetName << ".//Saves//Packet" << i << ".bin";

        SavePacket(packetName.str(), (char *)packet->data, packet->length);
        i++;
#endif

        switch (packet->data[0]) {
        case ID_LEGO_PACKET:

            switch (packet->data[1]) {
            case GENERAL:
                if (packet->data[3] == VERSION_CONFIRM) {	// thats just a formality so far since no other numbers occured for this case
                    SendInitPacket(rakServer, packet->systemAddress, false);
                }
                break;

            case SERVER:

                switch (packet->data[3]) {
                case CLIENT_VALIDATION:
                {
                    cout << "Recieved client validation..." << endl;
                    break;
                }

                case CLIENT_CHARACTER_LIST_REQUEST:
                {
                    auto usr = OnlineUsers->Find(packet->systemAddress);
                    if (usr->nameInUse == 0) {
                        cout << "Sending char packet...";
                        SendCharPacket(rakServer, packet->systemAddress, usr);
                    }
                    break;
                }

                case CLIENT_CHARACTER_CREATE_REQUEST:
                {
                    // Find online user by systemAddress
                    auto usr = OnlineUsers->Find(packet->systemAddress);

                    // Make SURE user is not null!!!!!!
                    if (usr != NULL) {
                        AddCharToDatabase(rakServer, packet->systemAddress, packet->data, packet->length, usr);
                    }
                    else {
                        cout << "ERROR SAVING USER: User is null." << endl;
                    }

                    // If the username is in use, do NOT send the char packet. Otherwise, send it
                    if (usr->nameInUse == 0) {
                        SendCharPacket(rakServer, packet->systemAddress, usr);
                    }
                }
                break;

                case CLIENT_CHARACTER_DELETE_REQUEST:
                {
                    // Find online user
                    auto usr = OnlineUsers->Find(packet->systemAddress);

                    // Send the delete packet
                    SendDeletePacket(rakServer, packet->systemAddress, usr, packet->data, packet->length);
                    break;
                }

                case CLIENT_LOGIN_REQUEST:
                {
                    // Find online user using systemAddress
                    auto usr = OnlineUsers->Find(packet->systemAddress);

                    // If user exists, continue
                    if (usr != NULL) {
                        usr->numredir++; // Add to the number of redirects that the character has
                        // Get Character ID
                        vector< uchar > t;
                        for (int i = 8; i <= 11; i++) t.push_back(packet->data[i]);
                        usr->nextcid = *(ulong*)t.data();

                        // If DEBUG is on, and user had ID of one of these (It probably won't)
                        // Print who the char is logging in with
#ifdef DEBUG
                        stringstream s;
                        s << "\nCharacter logging in world with id: " << usr->nextcid;
                        if ( usr->nextcid == 2397732190 ) s << " CheekyMonkey!\n";
                        else if ( usr->nextcid == 2444680020 ) s << " monkeybrown!\n";
                        else if ( usr->nextcid == 1534792735 ) s << " GruntMonkey!\n";
                        else if ( usr->nextcid == 1457240027 ) s << " Shafantastic!\n";
                        else s << "Unknown Character ID: " << usr->nextcid << endl;
                        OutputQueue->Insert(s.str());
#endif
                    }

                    // Open the packet to redirect the character to the world server
                    auto v = OpenPacket(".\\char\\char_aw_redirect.bin");
                    if (v.size() > 0) {
                        // IP Address starts at byte 0x08, Port number starts at byte 0x29
                        // Copy the redirectId to the packet
                        if (cfg->redirectIp[0] != 0)
                            memcpy(v.data() + 0x8, cfg->redirectIp, sizeof(cfg->redirectIp) - 3);	// NOTE: the IP can currently only be 13 characters long here since there are some non-zero bytes directly after the IP and I don't want to delete them (is it safe to overwrite them?)
                        // Copy the redirectPort to the packet
                        if (cfg->redirectPort > 0)
                            memcpy(v.data() + 0x29, &cfg->redirectPort, sizeof(cfg->redirectPort));
                        ServerSendPacket(rakServer, v, packet->systemAddress);
                    }

                    // Close connections to the char server for now
                    rakServer->CloseConnection(packet->systemAddress, true);
                }
                break;
                }

                break;

            // If packet ID (3rd byte) is unidentified, print the packet data
            default:
                stringstream s;

                // If packet is unidentified, print data to console
                s << "\nCharacters received unknown packet: " << RawDataToString(packet->data, packet->length) << endl;
                OutputQueue->Insert(s.str());
            }

            break;

        // Recieving a new connection to the char server
        case ID_NEW_INCOMING_CONNECTION:
#ifdef DEBUG
            OutputQueue->Insert("\n Characters is receiving a new connection...\n");
#endif
            break;

        // User disconnected from the char server
        case ID_DISCONNECTION_NOTIFICATION:
        {
            auto usr = OnlineUsers->Find(packet->systemAddress);
            if (OnlineUsers->Remove(packet->systemAddress))
                OutputQueue->Insert("Disconnected " + usr->GetUsername() + "\n");
        }
        break;

        // Default msg (if packet is unidentified)
        default:
            stringstream s;
            s << "\nCharacters received unknown packet: " << RawDataToString(packet->data, packet->length) << endl;
            OutputQueue->Insert(s.str());
        }
    }
}
int main(int argc, char **argv)
{
	printf("A simple client interface for the advanced autopatcher.\n");
	printf("Use DirectoryDeltaTransfer for a simpler version of an autopatcher.\n");
	printf("Difficulty: Intermediate\n\n");

	printf("Client starting...");
	SystemAddress serverAddress=UNASSIGNED_SYSTEM_ADDRESS;
	AutopatcherClient autopatcherClient;
	FileListTransfer fileListTransfer;
	autopatcherClient.SetFileListTransferPlugin(&fileListTransfer);
	unsigned short localPort=0;
	if (argc>=6)
	{
		localPort=atoi(argv[5]);
	}
#ifdef USE_TCP
	PacketizedTCP packetizedTCP;
	if (packetizedTCP.Start(localPort,1)==false)
	{
		printf("Failed to start TCP. Is the port already in use?");
		return 1;
	}
	packetizedTCP.AttachPlugin(&autopatcherClient);
	packetizedTCP.AttachPlugin(&fileListTransfer);
#else
	RakPeerInterface *rakPeer;
	rakPeer = RakNetworkFactory::GetRakPeerInterface();
	SocketDescriptor socketDescriptor(localPort,0);
	rakPeer->Startup(1,0,&socketDescriptor, 1);
	// Plugin will send us downloading progress notifications if a file is split to fit under the MTU 10 or more times
	rakPeer->SetSplitMessageProgressInterval(10);
	rakPeer->AttachPlugin(&autopatcherClient);
	rakPeer->AttachPlugin(&fileListTransfer);
#endif
	printf("started\n");
	char buff[512];
	if (argc<2)
	{
		printf("Enter server IP: ");
		gets(buff);
		if (buff[0]==0)
			//	strcpy(buff, "94.198.81.195");
			strcpy(buff, "127.0.0.1");
	}
	else
		strcpy(buff, argv[1]);

#ifdef USE_TCP
	packetizedTCP.Connect(buff,60000,false);
#else
	rakPeer->Connect(buff, 60000, 0, 0);
#endif

	printf("Connecting...\n");
	char appDir[512];
	if (argc<3)
	{
		printf("Enter application directory: ");
		gets(appDir);
		if (appDir[0]==0)
		{
			strcpy(appDir, "C:/temp2");
		}
	}
	else
		strcpy(appDir, argv[2]);
	char appName[512];
	if (argc<4)
	{
		printf("Enter application name: ");
		gets(appName);
		if (appName[0]==0)
			strcpy(appName, "TestApp");
	}
	else
		strcpy(appName, argv[3]);

	bool patchImmediately=argc>=5 && argv[4][0]=='1';

	if (patchImmediately==false)
		printf("Hit 'q' to quit, 'p' to patch, 'c' to cancel the patch. 'r' to reconnect. 'd' to disconnect.\n");
	else
		printf("Hit 'q' to quit, 'c' to cancel the patch.\n");

	char ch;
	Packet *p;
	while (1)
	{
#ifdef USE_TCP
		SystemAddress notificationAddress;
		notificationAddress=packetizedTCP.HasCompletedConnectionAttempt();
		if (notificationAddress!=UNASSIGNED_SYSTEM_ADDRESS)
		{
			printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
			serverAddress=notificationAddress;
		}
		notificationAddress=packetizedTCP.HasNewIncomingConnection();
		if (notificationAddress!=UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_NEW_INCOMING_CONNECTION\n");
		notificationAddress=packetizedTCP.HasLostConnection();
		if (notificationAddress!=UNASSIGNED_SYSTEM_ADDRESS)
			printf("ID_CONNECTION_LOST\n");


		p=packetizedTCP.Receive();
		while (p)
		{
			if (p->data[0]==ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR)
			{
				char buff[256];
				RakNet::BitStream temp(p->data, p->length, false);
				temp.IgnoreBits(8);
				stringCompressor->DecodeString(buff, 256, &temp);
				printf("ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR\n");
				printf("%s\n", buff);
			}
			else if (p->data[0]==ID_AUTOPATCHER_FINISHED)
				printf("ID_AUTOPATCHER_FINISHED\n");
			else if (p->data[0]==ID_AUTOPATCHER_RESTART_APPLICATION)
				printf("Launch \"AutopatcherClientRestarter.exe autopatcherRestart.txt\"\nQuit this application immediately after to unlock files.\n");

			packetizedTCP.DeallocatePacket(p);
			p=packetizedTCP.Receive();
		}
#else
		p=rakPeer->Receive();
		while (p)
		{
			if (p->data[0]==ID_DISCONNECTION_NOTIFICATION)
				printf("ID_DISCONNECTION_NOTIFICATION\n");
			else if (p->data[0]==ID_CONNECTION_LOST)
				printf("ID_CONNECTION_LOST\n");
			else if (p->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
			{
				printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				serverAddress=p->systemAddress;
			}
			else if (p->data[0]==ID_CONNECTION_ATTEMPT_FAILED)
				printf("ID_CONNECTION_ATTEMPT_FAILED\n");
			else if (p->data[0]==ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR)
			{
				char buff[256];
				RakNet::BitStream temp(p->data, p->length, false);
				temp.IgnoreBits(8);
				stringCompressor->DecodeString(buff, 256, &temp);
				printf("ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR\n");
				printf("%s\n", buff);
			}
			else if (p->data[0]==ID_AUTOPATCHER_FINISHED)
				printf("ID_AUTOPATCHER_FINISHED\n");
			else if (p->data[0]==ID_AUTOPATCHER_RESTART_APPLICATION)
				printf("Launch \"AutopatcherClientRestarter.exe autopatcherRestart.txt\"\nQuit this application immediately after to unlock files.\n");

			rakPeer->DeallocatePacket(p);
			p=rakPeer->Receive();
		}
#endif

		if (kbhit())
			ch=getch();
		else
			ch=0;

		if (ch=='q')
			break;
		else if (ch=='r')
		{
#ifdef USE_TCP
			packetizedTCP.Connect(buff,60000,false);
#else
			rakPeer->Connect(buff, 60000, 0, 0);
#endif
		}
		else if (ch=='d')
		{
#ifdef USE_TCP
			packetizedTCP.CloseConnection(serverAddress);
#else
			rakPeer->CloseConnection(serverAddress, true);
#endif
		}
		else if (ch=='p' || (serverAddress!=UNASSIGNED_SYSTEM_ADDRESS && patchImmediately==true))
		{
			patchImmediately=false;
			char lastUpdateDate[128];
			char restartFile[512];
			strcpy(restartFile, appDir);
			strcat(restartFile, "/autopatcherRestart.txt");
		//	printf("Enter last update date (only newer updates retrieved) or nothing to get all updates\n");
		//	gets(lastUpdateDate);
			lastUpdateDate[0]=0;

			if (autopatcherClient.PatchApplication(appName, appDir, lastUpdateDate, serverAddress, &transferCallback, restartFile, argv[0]))
			{
				printf("Patching process starting.\n");
			}
			else
			{
				printf("Failed to start patching.\n");
			}
		}
		else if (ch=='c')
		{
			autopatcherClient.Clear();
			printf("Autopatcher cleared.\n");
		}

		RakSleep(30);
	}

	// Dereference so the destructor doesn't crash
	autopatcherClient.SetFileListTransferPlugin(0);

#ifdef USE_TCP
	packetizedTCP.Stop();
#else
	rakPeer->Shutdown(500,0);
	RakNetworkFactory::DestroyRakPeerInterface(rakPeer);
#endif
	return 1;
}
int main(void)
{
	printf("DEPRECIATED - Use LightweightDatabase instead\n");

	BitStream bitStream;
	char str[256];
	char ch;
	MasterClient masterClient;
	RakPeerInterface *testGameServerOrClient;
	unsigned int serverListSize, index;
	bool identiferFound;
	const char *outputString;
	int outputInt;
	Packet *p;

	// Create a fake game
	testGameServerOrClient = RakNetworkFactory::GetRakPeerInterface();
	testGameServerOrClient->Initialize(8, 60003, 0);
	testGameServerOrClient->SetMaximumIncomingConnections(8);
	testGameServerOrClient->AttachPlugin(&masterClient);

	printf("This project shows how to use the master client.\n");
	printf("The master client is used by game servers to advertise themselves.\n");
	printf("On the master server and by game clients to download a list of game servers\n");
	printf("Difficulty: Intermediate\n\n");

	if (masterClient.Connect("127.0.0.1", 60000))
		printf("Master client connecting...\n");
	else
		printf("Master client failed to start or connect.\n");

	printf("(Q)uit\n(q)uery master server\n(l)ist server\n(d)elist server\n(D)isconnect from the master server.\n(a)dd rule\n(r)emove rule\n(p)ing server list\n(C)onnect to the master server.\n(c)onnect to another game, using NAT punch-through with master server, bypassing most NATs\n(SPACE) print server list\n");
	char buff[256];
	while (1)
	{
		if (kbhit())
		{
			READCHAR(buff);
			if (ch=='Q')
				break;
			if (ch=='q')
			{
				masterClient.ClearQueryRules();
				printf("Enter query key 1/2 or enter for none: ");
				gets(str);
				masterClient.AddQueryRule(str);
				printf("Enter query key 2/2 or enter for none: ");
				gets(str);
				masterClient.AddQueryRule(str);
				masterClient.QueryMasterServer();
				printf("Server queried.  Press space to see server list.\n");
			}
			else if (ch=='l')
			{
				printf("Uploading game server.  Query to see it.\n");
				masterClient.ListServer();
			}
			else if (ch=='d')
			{
				printf("Server delisted.  Query to update our own list.\n");
				masterClient.DelistServer();
			}
			else if (ch=='D')
			{
				printf("Disconnected.\n");
				PlayerID playerId;
				testGameServerOrClient->IPToPlayerID("127.0.0.1", 60000, &playerId);
				testGameServerOrClient->CloseConnection(playerId, true, 0);
			}
			else if (ch=='C')
			{
				if (masterClient.Connect("127.0.0.1", 60000))
					printf("Master client connecting...\n");
				else
					printf("Master client failed to start or connect.\n");
			}
			else if (ch=='a')
			{
				printf("Adding sample rules.  Query to update our own list.\n");
				masterClient.PostRule("Game name", "My big game o' death.", 0);
				masterClient.PostRule("Game type", "Death match", 0);
				masterClient.PostRule("Score",0, 100);
			}
			else if (ch=='r')
			{
				printf("Removing rules. Query to update our own list.\n");
				masterClient.RemoveRule("Game type");
				masterClient.RemoveRule("Game name");
				masterClient.RemoveRule("Score");
			}
			else if (ch=='p')
			{
				printf("Pinging any servers in our list\n");
				masterClient.PingServers();
			}
			else if (ch=='c')
			{
				char ip[22];
				printf("Sending connection attempt notification to master server\n");
				printf("Enter IP of server from game list: ");
				gets(ip);
				printf("Enter port: ");
				gets(str);
				if (ip[0]!=0 && str[0]!=0)
				{
					masterClient.ConnectionAttemptNotification(ip, atoi(str));
					printf("Sent connection attempt notification to the server the master server\n");
				}
				else
				{
					printf("Aborting...");
				}				
			}
			else if (ch==' ')
			{
				serverListSize=masterClient.GetServerListSize();
				if (serverListSize==0)
				{
					printf("No servers in list\n");
				}
				else
				{
					for (index=0; index < serverListSize; index++)
					{
						printf("%i. ", index);
						outputString=masterClient.GetServerListRuleAsString(index, "IP", &identiferFound);
						if (identiferFound)
							printf("%s:", outputString);
						else
							printf("NO_IP:");
						outputInt=masterClient.GetServerListRuleAsInt(index, "Port", &identiferFound);
						if (identiferFound)
							printf("%i ", outputInt);
						else
							printf("NO_PORT ");
						outputInt=masterClient.GetServerListRuleAsInt(index, "Ping", &identiferFound);
						if (identiferFound)
							printf("%i ", outputInt);
						else
							printf("NO_PING ");
						outputString=masterClient.GetServerListRuleAsString(index, "Game type", &identiferFound);
						if (identiferFound)
							printf("%s ", outputString);
						else
							printf("NO_GT ");
						outputString=masterClient.GetServerListRuleAsString(index, "Game name", &identiferFound);
						if (identiferFound)
							printf("%s ", outputString);
						else
							printf("NO_GN ");
						outputInt=masterClient.GetServerListRuleAsInt(index, "Score", &identiferFound);
						if (identiferFound)
							printf("%i\n", outputInt);
						else
							printf("NO_SCORE\n");
					}
				}
			}
			ch=0;
		}

		p = testGameServerOrClient->Receive();
		while (p)
		{
			// Ignore any game packets.  The master server plugin handles everything.
			testGameServerOrClient->DeallocatePacket(p);
			// Call Receive every update to keep the plugin going
			p = testGameServerOrClient->Receive();
		}

#ifdef _WIN32
		Sleep(30);
#else
		usleep(30 * 1000);
#endif
	}

	masterClient.Disconnect();
	RakNetworkFactory::DestroyRakPeerInterface(testGameServerOrClient);

	return 0;
}