cwmWorldState->savenewworld( "binary" );  clConsole.PrepareProgress( "Closing sockets" );
clConsole.PrepareProgress( "Shutting down network" );
int main( int argc, char *argv[] ){#if defined(_DEBUG)//	InstallCrashHandler( HANDLER_CONSOLE, GSTSO_PARAMS | GSTSO_MODULE | GSTSO_SYMBOL | GSTSO_SRCLINE );//	SetCustomMessage("A crash occurred. Please send this bug report to developers\n");#endif	QApplication app( argc, argv, false ); // we need one instance	// Parse our arguments	if (argc > 1)	{		for (int index=1; index < argc ; index++)		{			QString param( argv[ index ] );			checkparm( param );		}	}		if( bDeamon )	{		// Under unix we go to deamon mode		cout << "Going into deamon mode, returning local control to terminal" <<endl;		init_deamon();		// set up our console redirection		fstream fconsole;		fconsole.open("console.txt", ios::out);		clConsole.setStreams(NULL, (dynamic_cast<ostream*>(&fconsole)), NULL, NULL);		}	#if defined(__unix__)	// We can use SIGHUP, SIGINT, and SIGWINCH as we should never recive them	// So we will use SIGHUP to reload our scripts (kinda a standard for sighup to be reload)	// We will use a SIGUSR2 to be world save	// and SIGUSR1 for an Account reload	signal( SIGUSR2,&signal_handler );	signal( SIGHUP,&signal_handler );	signal( SIGUSR1,&signal_handler );	signal( SIGTERM,&signal_handler );	signal( SIGPIPE, SIG_IGN );	#endif		#define CIAO_IF_ERROR if (error==1) { cNetwork::instance()->shutdown(); DeleteClasses(); exit(-1); }	int i;	unsigned long tempSecs;	unsigned long loopSecs;	unsigned long tempTime;	unsigned int uiNextCheckConn=0;//CheckConnection rate - AntiChrist ( thnx to LB )	unsigned long CheckClientIdle=0;	int r;	uiCurrentTime = serverstarttime = getNormalizedTime();	// Print a seperator somehow	clConsole.send( QString( "\n%1 %2 %3 \n\n" ).arg( wp_version.productstring.c_str() ).arg( wp_version.betareleasestring.c_str() ).arg( wp_version.verstring.c_str() ) );	clConsole.send( "Copyright (C) 1997, 98 Marcus Rating (Cironian)\n");	clConsole.send( "This program is free software; you can redistribute it and/or modify\n");	clConsole.send( "it under the terms of the GNU General Public License as published by\n");	clConsole.send( "the Free Software Foundation; either version 2 of the License, or\n");	clConsole.send( "(at your option) any later version.\n\n");	clConsole.send( "Compiled on %s (%s %s)\n",__DATE__,__TIME__, wp_version.timezonestring.c_str() );	clConsole.send( "Programmed by: %s\n", wp_version.codersstring.c_str() );	clConsole.send( "\n" );		QString consoleTitle = QString( "%1 %2 %3" ).arg( wp_version.productstring.c_str() ).arg( wp_version.betareleasestring.c_str() ).arg( wp_version.verstring.c_str() );	clConsole.setConsoleTitle( consoleTitle );	StartClasses();	clConsole.PrepareProgress( "Starting up Network" );	cNetwork::startup();	clConsole.ProgressDone();	CIAO_IF_ERROR;	// Check out the MULPath	QDir mulPath( SrvParams->mulPath() );	if( !mulPath.exists() )	{		QString uoPath = getUOPath();		if( uoPath != QString::null )		{			SrvParams->setMulPath( uoPath );			delete Map;			Map = new Maps( uoPath );		}	}	DefManager->load();	startPython( argc, argv );	ScriptManager->load();	clConsole.send( "\n" );	QTranslator translator(0); // must be valid thru app life.	QString languageFile = SrvParams->getString("General", "Language File", "", true);	if ( !languageFile.isEmpty() )	{		translator.load( languageFile, "." );		app.installTranslator( &translator );	}	//Now lets load the custom scripts, if they have them defined...	i=0;	CIAO_IF_ERROR;	SetGlobalVars();	SkillVars();	// Set Creator Variables	clConsole.PrepareProgress( "Loading skills" );	loadskills();	clConsole.ProgressDone();	// Need to load the ACLs before we load any account	cCommands::instance()->loadACLs();	Accounts::instance()->load();	keeprun = 1;	//keeprun = cNetwork::instance()->kr; //LB. for some technical reasons global varaibles CANT be changed in constructors in c++.	//error = cNetwork::instance()->faul; // i hope i can find a cleaner solution for that, but this works !!!	// has to here and not at the cal cause it would get overriten later	CIAO_IF_ERROR;	// Try to cache the tiledata.mul	if( !TileCache::instance()->load( SrvParams->mulPath() ) )	{		error = 1;		CIAO_IF_ERROR;	}	cAllTerritories::getInstance()->load();	CIAO_IF_ERROR;	// Hardcoded for now.	Map->registerMap(0, "map0.mul", 768, 512, "statics0.mul", "staidx0.mul");	Map->registerMap(1, "map0.mul", 768, 512, "statics0.mul", "staidx0.mul");	Map->registerMap(2, "map2.mul", 288, 200, "statics2.mul", "staidx2.mul");//	Map->registerMap(3, "map2.mul", 288, 200, "statics2.mul", "staidx2.mul");	if (keeprun==0) { cNetwork::instance()->shutdown(); DeleteClasses(); exit(-1); }			srand(uiCurrentTime); // initial randomization call//	read_in_teleport();	CIAO_IF_ERROR;	serverstarttime = getNormalizedTime();	// Try to open our driver	if( !persistentBroker->openDriver( "mysql" ) )	{		cNetwork::instance()->shutdown();		DeleteClasses();		exit(-1);	}	// Establish the connection to our database (persistent!)	if( !persistentBroker->connect( SrvParams->databaseHost(), SrvParams->databaseName(), SrvParams->databaseUsername(), SrvParams->databasePassword() ) )	{		cNetwork::instance()->shutdown();		DeleteClasses();		exit(-1);	}	// Registers our Built-in types into factory.	cChar::registerInFactory();	cItem::registerInFactory();	cBook::registerInFactory();	cSpellBook::registerInFactory();	cCorpse::registerInFactory();	cBoat::registerInFactory();	cHouse::registerInFactory();	try	{		cwmWorldState->loadnewworld( "binary" );	}	catch( QString error )	{		clConsole.ChangeColor( WPC_RED );		clConsole.send( "\nERROR" );		clConsole.ChangeColor( WPC_NORMAL );		clConsole.send( ": " + error + "\n" );		clConsole.send( "Press any key to continue..." );		cNetwork::instance()->shutdown();		DeleteClasses();		getchar();		exit(-1);			}	clConsole.PrepareProgress( "Postprocessing" );	// this loop is for things that have to be done after *all* items and chars have been loaded (Duke)	P_ITEM pi;		QPtrList< cItem > deleteItems;	AllItemsIterator iter;	for( iter.Begin(); !iter.atEnd(); ++iter )	//for( iter = cwmWorldState->contmap.begin(); iter != cwmWorldState->contmap.end(); ++iter )	{		pi = iter.GetData();		SERIAL contserial = reinterpret_cast<SERIAL>(pi->container());		// 1. Handle the Container Value		if( isItemSerial( contserial ) )		{			P_ITEM pCont = FindItemBySerial( contserial );			if( pCont )			{				pCont->addItem( pi, false, true, true );			}			else			{				// Queue this item up for deletion				deleteItems.append( pi );				continue; // Skip further processing			}		}		else if( isCharSerial( contserial ) )		{			P_CHAR pCont = FindCharBySerial( contserial );			if( pCont )			{				pCont->addItem( (cChar::enLayer)pi->layer(), pi, true, true );			}			else			{				deleteItems.append( pi );				continue; // Skip further processing			}		}		else // Add to Map Regions		{			int max_x = Map->mapTileWidth(pi->pos.map) * 8;			int max_y = Map->mapTileHeight(pi->pos.map) * 8;			if ( pi->pos.x > max_x || pi->pos.y > max_y ) 			{				// these are invalid locations, delete them!				deleteItems.append( pi );			}			else				cMapObjects::getInstance()->add(pi);			continue;		}		// If this item has a multiserial then add it to the multi		if( isItemSerial( pi->multis ) )		{			cMulti *pMulti = dynamic_cast< cMulti* >( FindItemBySerial( pi->multis ) );			if( pMulti )				pMulti->addItem( pi );		}		// "Store Random value", whatever it does...		if( pi->container() && pi->container()->isItem() )			StoreItemRandomValue(pi, "none");		// effect on dex ? like plate eg.		if( pi->dx2 && pi->container() && pi->container()->isChar() )		{			P_CHAR pChar = dynamic_cast< P_CHAR >( pi->container() );			if( pChar )				pChar->chgDex( pi->dx2 );		}	}	// Post Process Characters	AllCharsIterator charIter;	for( charIter.Begin(); !charIter.atEnd(); ++charIter )	{		P_CHAR pChar = charIter.GetData();		if( pChar )		{			// Find Owner			if( pChar->owner() )			{				SERIAL owner = (SERIAL)pChar->owner();								P_CHAR pOwner = FindCharBySerial( owner );				if( pOwner )				{					pChar->setOwnerOnly( pOwner );					pOwner->addFollower( pChar, true );				}				else				{					clConsole.send( QString( "The owner of Serial 0x%1 is invalid: %2" ).arg( pChar->serial, 16 ).arg( owner, 16 ) );					pChar->setOwnerOnly( 0 );				}			}			// Find Guarding			if( pChar->guarding() )			{				SERIAL guarding = (SERIAL)pChar->guarding();				P_CHAR pGuarding = FindCharBySerial( guarding );				if( pGuarding )				{					pChar->setGuardingOnly( pGuarding );					pGuarding->addGuard( pChar, true );				}				else				{					clConsole.send( QString( "The guard target of Serial 0x%1 is invalid: %2" ).arg( pChar->serial, 16 ).arg( guarding, 16 ) );					pChar->setGuardingOnly( 0 );				}			}			// Set Skills (non-real)			for( UINT8 i = 0; i < TRUESKILLS; ++i )				Skills->updateSkillLevel( pChar, i );			if( isItemSerial( pChar->multis ) )			{				cMulti *pMulti = dynamic_cast< cMulti* >( FindItemBySerial( pChar->multis ) );				if( pMulti )					pMulti->addChar( pChar );			}			cTerritory *region = cAllTerritories::getInstance()->region( pChar->pos.x, pChar->pos.y );			pChar->setRegion( region );			// Now that we have our owner set correctly			// do the charflags			setcharflag( pChar );		}	}	clConsole.ProgressDone();	clConsole.PrepareProgress( "Deleting lost items" );	// Do we have to delete items?	for( P_ITEM pItem = deleteItems.first(); pItem; pItem = deleteItems.next() )		quickdelete( pItem );	clConsole.ProgressDone();	if( deleteItems.count() > 0 )	{		clConsole.send( QString::number( deleteItems.count() ) + " deleted due to invalid container or position.\n" );		deleteItems.clear();	}	SpawnRegions::instance()->load();	Resources::instance()->load();	MakeMenus::instance()->load();	ContextMenus::instance()->reload();	clConsole.PrepareProgress( "Resetting all Trade windows" ); // Should automatically be done whenever a char disconnects	Trade->clearalltrades();	clConsole.ProgressDone();	clConsole.PrepareProgress( "Initializing Multis" );	InitMultis();	clConsole.ProgressDone();	starttime=uiCurrentTime;	endtime=0;	lclock=0;	clConsole.PrepareProgress( "Initializing GM Pages" );	clConsole.ProgressDone();	cwmWorldState->announce(SrvParams->announceWorldSaves());	init_creatures(); // This initializes *fixed* data that should DEFINETLY be swaped out to the scripts !!!	Magic->load(); // Load the new magic system	NewMagic->load();	clConsole.PrepareProgress( "Loading IP Blocking rules" );	cNetwork::instance()->load();	clConsole.ProgressDone();    if (SrvParams->EnableRA())		RemoteAdmin::initialize( SrvParams->ra_port() );	item_char_test(); //LB	if( SrvParams->serverLog() )		savelog( "Server startup", "server.log" );	uiCurrentTime = getNormalizedTime();	serverstarttime = getNormalizedTime(); // dont remove, its absolutly necassairy that its 3 times in the startup sequence for several timing reasons.	CIAO_IF_ERROR;    // print allowed clients		clConsole.send( "Allowed clients: " );	if( SrvParams->clientsAllowed().contains( "ALL" ) )		clConsole.send( "All\n\n" );	else		clConsole.send( SrvParams->clientsAllowed().join( ", " ) + "\n\n" );	clConsole.send( QString( "Wolfpack running on port %1\n" ).arg( SrvParams->port() ) );	PyThreadState *_save;	// Start the Console Input thread	cConsoleThread consoleThread;	if( !bDeamon )		consoleThread.start();	// This is our main loop	while( keeprun )	{				// Python threading - start		_save = PyEval_SaveThread();		switch( SrvParams->niceLevel() )		{			case 0: break;	// very unnice - hog all cpu time			case 1: if ( cNetwork::instance()->count() != 0) ZThread::Thread::sleep(10); else ZThread::Thread::sleep(100); break;			case 2: ZThread::Thread::sleep(10); break;			case 3: ZThread::Thread::sleep(40); break;// very nice			case 4: if ( cNetwork::instance()->count() != 0 ) ZThread::Thread::sleep(10); else ZThread::Thread::sleep(4000); break; // anti busy waiting			case 5: if ( cNetwork::instance()->count() != 0 ) ZThread::Thread::sleep(40); else ZThread::Thread::sleep(5000); break;			default: ZThread::Thread::sleep(10); break;		}		// Python threading - end		PyEval_RestoreThread(_save);		// It's more likely that we have a new key-press now		// Checking every 25 loops should be enough.		#if !defined( __unix__ )		if( !bDeamon && loopTimeCount % 25 == 0 )		{			commandMutex.acquire();			if( commandQueue.count() > 0 )			{								// Interpret Command				interpretCommand( commandQueue[0] );				commandQueue.erase( commandQueue.begin() );			}			commandMutex.release();		}		#endif		if( loopTimeCount >= 1000 )		{			loopTimeCount = 0;			loopTime = 0;		}		++loopTimeCount;		loopSecs = getNormalizedTime();  // Starting time		if( networkTimeCount >= 1000 )		{			networkTimeCount = 0;			networkTime = 0;		}		tempSecs = getNormalizedTime();		// Process any Network Events		cNetwork::instance()->poll();		for( cUOSocket *mSock = cNetwork::instance()->first(); mSock; mSock = cNetwork::instance()->next() )		{			P_CHAR player = mSock->player();			if ( player && !player->isGM() && player->clientidletime() && player->clientidletime() < uiCurrentTime )			{				clConsole.send("Player %s disconnected due to inactivity !\n", player->name.latin1());				cUOTxMessageWarning packet;				packet.setReason( cUOTxMessageWarning::Idle );				mSock->send( &packet );				mSock->disconnect();			}		}        if (SrvParams->EnableRA())           RemoteAdmin::instance()->processNextEvent();		tempTime = getNormalizedTime() - tempSecs ;		networkTime += tempTime;		++networkTimeCount;		if( timerTimeCount >= 1000 )		{			timerTimeCount = 0;			timerTime = 0;		}		tempSecs = getNormalizedTime() ;				checktimers();		uiCurrentTime = getNormalizedTime();		tempTime = getNormalizedTime() - tempSecs;		timerTime += tempTime;		++timerTimeCount;		if( autoTimeCount >= 1000 )		{			autoTimeCount = 0;			autoTime = 0;		}				tempSecs = getNormalizedTime() ;				checkauto();		tempTime = getNormalizedTime() - tempSecs;		autoTime += tempTime;		++autoTimeCount;		tempTime = getNormalizedTime() - loopSecs;		loopTime += tempTime;				qApp->processEvents( 40 );	}	if( !bDeamon )		consoleThread.interrupt();	sysbroadcast("The server is shutting down.");	if ( SrvParams->EnableRA() )		RemoteAdmin::stop();	if (SrvParams->html()>0)	{		clConsole.send("Writing offline HTML page...");		offlinehtml();//HTML	// lb, the if prevents a crash on shutdown if html deactivated ...		clConsole.send(" Done.\n");	}	// No need for progress bar	Magic->unload();	NewMagic->unload();		cwmWorldState->savenewworld( "binary" );	clConsole.PrepareProgress( "Closing sockets" );	cNetwork::shutdown();	clConsole.ProgressDone();			DefManager->unload();	clConsole.PrepareProgress( "Saving Wolfpack.xml" );	SrvParams->flush();	clConsole.ProgressDone();	clConsole.send("\n");	clConsole.send("Done!\n");	if (NewErrorsLogged())		clConsole.send("New ERRORS have been logged. Please send the error*.log and critical*.log files to the dev team !\n");	if (NewWarningsLogged())		clConsole.send("New WARNINGS have been logged. Probably scripting errors. See the warnings*.log for details !\n");	if (error) {		clConsole.send("ERROR: Server terminated by error!\n");		if( SrvParams->serverLog() ) 			savelog("Server terminated by error","server.log");	} else {		clConsole.send("WOLFPACK: Server shutdown complete!\n");				if( SrvParams->serverLog() ) 			savelog("Server shutdown","server.log");	}	clConsole.PrepareProgress( "Deleting Classes" );	// Notice, from this point down no global class is valid!!	DeleteClasses();	clConsole.ProgressDone();	stopPython();	return 0;}