Index: trunk/src/game/Bag.cpp
===================================================================
--- trunk/src/game/Bag.cpp (revision 177)
+++ trunk/src/game/Bag.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -42,5 +42,5 @@
     for(int i = 0; i < MAX_BAG_SIZE; ++i)
         if (m_bagslot[i])
-             delete m_bagslot[i];
+            delete m_bagslot[i];
 }
 
@@ -72,5 +72,5 @@
     Object::_Create( guidlow, 0, HIGHGUID_CONTAINER );
 
-    SetUInt32Value(OBJECT_FIELD_ENTRY, itemid);
+    SetEntry(itemid);
     SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
 
@@ -86,5 +86,5 @@
     SetUInt32Value(CONTAINER_FIELD_NUM_SLOTS, itemProto->ContainerSlots);
 
-    // Cleanning 20 slots
+    // Cleaning 20 slots
     for (uint8 i = 0; i < MAX_BAG_SIZE; i++)
     {
@@ -214,4 +214,5 @@
             if(m_bagslot[i]->GetGUID() == guid)
                 return i;
+
     return NULL_SLOT;
 }
@@ -221,5 +222,5 @@
     if( slot < GetBagSize() )
         return m_bagslot[slot];
-        
+
     return NULL;
 }
Index: trunk/src/game/Level3.cpp
===================================================================
--- trunk/src/game/Level3.cpp (revision 235)
+++ trunk/src/game/Level3.cpp (revision 260)
@@ -136,4 +136,5 @@
     HandleReloadSpellScriptsCommand("a");
     SendGlobalSysMessage("DB tables `*_scripts` reloaded.");
+    HandleReloadDbScriptStringCommand("a");
     return true;
 }
@@ -599,4 +600,12 @@
         SendGlobalSysMessage("DB table `spell_scripts` reloaded.");
 
+    return true;
+}
+
+bool ChatHandler::HandleReloadDbScriptStringCommand(const char* arg)
+{
+    sLog.outString( "Re-Loading Script strings from `db_script_string`...");
+    objmgr.LoadDbScriptStrings();
+    SendGlobalSysMessage("DB table `db_script_string` reloaded.");
     return true;
 }
@@ -1768,5 +1777,6 @@
         // search highest talent rank
         uint32 spellid = 0;
-        for(int rank = 4; rank >= 0; --rank)
+        int rank = 4;
+        for(; rank >= 0; --rank)
         {
             if(talentInfo->RankID[rank]!=0)
@@ -4646,89 +4656,147 @@
 }
 
-bool ChatHandler::HandleShutDownCommand(const char* args)
+bool ChatHandler::HandleServerShutDownCancelCommand(const char* args)
+{
+    sWorld.ShutdownCancel();
+    return true;
+}
+
+bool ChatHandler::HandleServerShutDownCommand(const char* args)
 {
     if(!*args)
         return false;
 
-    if(std::string(args)=="cancel")
-    {
-        sWorld.ShutdownCancel();
+    char* time_str = strtok ((char*) args, " ");
+    char* exitcode_str = strtok (NULL, "");
+
+    int32 time = atoi (time_str);
+
+    ///- Prevent interpret wrong arg value as 0 secs shutdown time
+    if(time == 0 && (time_str[0]!='0' || time_str[1]!='\0') || time < 0)
+        return false;
+
+    if (exitcode_str)
+    {
+        int32 exitcode = atoi (exitcode_str);
+
+        // Handle atoi() errors
+        if (exitcode == 0 && (exitcode_str[0] != '0' || exitcode_str[1] != '\0'))
+            return false;
+
+        // Exit code should be in range of 0-125, 126-255 is used
+        // in many shells for their own return codes and code > 255
+        // is not supported in many others
+        if (exitcode < 0 || exitcode > 125)
+            return false;
+
+        sWorld.ShutdownServ (time, 0, exitcode);
     }
     else
-    {
-        int32 time = atoi(args);
-
-        ///- Prevent interpret wrong arg value as 0 secs shutdown time
-        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
+        sWorld.ShutdownServ(time,0,SHUTDOWN_EXIT_CODE);
+    return true;
+}
+
+bool ChatHandler::HandleServerRestartCommand(const char* args)
+{
+    if(!*args)
+        return false;
+
+    char* time_str = strtok ((char*) args, " ");
+    char* exitcode_str = strtok (NULL, "");
+
+    int32 time = atoi (time_str);
+
+    ///- Prevent interpret wrong arg value as 0 secs shutdown time
+    if(time == 0 && (time_str[0]!='0' || time_str[1]!='\0') || time < 0)
+        return false;
+
+    if (exitcode_str)
+    {
+        int32 exitcode = atoi (exitcode_str);
+
+        // Handle atoi() errors
+        if (exitcode == 0 && (exitcode_str[0] != '0' || exitcode_str[1] != '\0'))
             return false;
 
-        sWorld.ShutdownServ(time);
-    }
-    return true;
-}
-
-bool ChatHandler::HandleRestartCommand(const char* args)
+        // Exit code should be in range of 0-125, 126-255 is used
+        // in many shells for their own return codes and code > 255
+        // is not supported in many others
+        if (exitcode < 0 || exitcode > 125)
+            return false;
+
+        sWorld.ShutdownServ (time, SHUTDOWN_MASK_RESTART, exitcode);
+    }
+    else
+        sWorld.ShutdownServ(time, SHUTDOWN_MASK_RESTART, RESTART_EXIT_CODE);
+    return true;
+}
+
+bool ChatHandler::HandleServerIdleRestartCommand(const char* args)
 {
     if(!*args)
         return false;
 
-    if(std::string(args)=="cancel")
-    {
-        sWorld.ShutdownCancel();
+    char* time_str = strtok ((char*) args, " ");
+    char* exitcode_str = strtok (NULL, "");
+
+    int32 time = atoi (time_str);
+
+    ///- Prevent interpret wrong arg value as 0 secs shutdown time
+    if(time == 0 && (time_str[0]!='0' || time_str[1]!='\0') || time < 0)
+        return false;
+
+    if (exitcode_str)
+    {
+        int32 exitcode = atoi (exitcode_str);
+
+        // Handle atoi() errors
+        if (exitcode == 0 && (exitcode_str[0] != '0' || exitcode_str[1] != '\0'))
+            return false;
+
+        // Exit code should be in range of 0-125, 126-255 is used
+        // in many shells for their own return codes and code > 255
+        // is not supported in many others
+        if (exitcode < 0 || exitcode > 125)
+            return false;
+
+        sWorld.ShutdownServ (time, SHUTDOWN_MASK_RESTART|SHUTDOWN_MASK_IDLE, exitcode);
     }
     else
-    {
-        int32 time = atoi(args);
-
-        ///- Prevent interpret wrong arg value as 0 secs shutdown time
-        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
+        sWorld.ShutdownServ(time,SHUTDOWN_MASK_RESTART|SHUTDOWN_MASK_IDLE,RESTART_EXIT_CODE);
+    return true;
+}
+
+bool ChatHandler::HandleServerIdleShutDownCommand(const char* args)
+{
+    if(!*args)
+        return false;
+
+    char* time_str = strtok ((char*) args, " ");
+    char* exitcode_str = strtok (NULL, "");
+
+    int32 time = atoi (time_str);
+
+    ///- Prevent interpret wrong arg value as 0 secs shutdown time
+    if(time == 0 && (time_str[0]!='0' || time_str[1]!='\0') || time < 0)
+        return false;
+
+    if (exitcode_str)
+    {
+        int32 exitcode = atoi (exitcode_str);
+
+        // Handle atoi() errors
+        if (exitcode == 0 && (exitcode_str[0] != '0' || exitcode_str[1] != '\0'))
             return false;
 
-        sWorld.ShutdownServ(time, SHUTDOWN_MASK_RESTART);
-    }
-    return true;
-}
-
-bool ChatHandler::HandleIdleRestartCommand(const char* args)
-{
-    if(!*args)
-        return false;
-
-    if(std::string(args)=="cancel")
-    {
-        sWorld.ShutdownCancel();
+        // Exit code should be in range of 0-125, 126-255 is used
+        // in many shells for their own return codes and code > 255
+        // is not supported in many others
+        if (exitcode < 0 || exitcode > 125)
+            return false;
+
+        sWorld.ShutdownServ (time, SHUTDOWN_MASK_IDLE, exitcode);
     }
     else
-    {
-        int32 time = atoi(args);
-
-        ///- Prevent interpret wrong arg value as 0 secs shutdown time
-        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
-            return false;
-
-        sWorld.ShutdownServ(time,SHUTDOWN_MASK_RESTART+SHUTDOWN_MASK_IDLE);
-    }
-    return true;
-}
-
-bool ChatHandler::HandleIdleShutDownCommand(const char* args)
-{
-    if(!*args)
-        return false;
-
-    if(std::string(args)=="cancel")
-    {
-        sWorld.ShutdownCancel();
-    }
-    else
-    {
-        int32 time = atoi(args);
-
-        ///- Prevent interpret wrong arg value as 0 secs shutdown time
-        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
-            return false;
-
-        sWorld.ShutdownServ(time,SHUTDOWN_MASK_IDLE);
-    }
+        sWorld.ShutdownServ(time,SHUTDOWN_MASK_IDLE,SHUTDOWN_EXIT_CODE);
     return true;
 }
Index: trunk/src/game/WaypointMovementGenerator.cpp
===================================================================
--- trunk/src/game/WaypointMovementGenerator.cpp (revision 229)
+++ trunk/src/game/WaypointMovementGenerator.cpp (revision 260)
@@ -22,9 +22,9 @@
 creature_movement Table
 
-alter table creature_movement add `text1` varchar(255) default NULL;
-alter table creature_movement add `text2` varchar(255) default NULL;
-alter table creature_movement add `text3` varchar(255) default NULL;
-alter table creature_movement add `text4` varchar(255) default NULL;
-alter table creature_movement add `text5` varchar(255) default NULL;
+alter table creature_movement add `textid1` int(11) NOT NULL default '0';
+alter table creature_movement add `textid2` int(11) NOT NULL default '0';
+alter table creature_movement add `textid3` int(11) NOT NULL default '0';
+alter table creature_movement add `textid4` int(11) NOT NULL default '0';
+alter table creature_movement add `textid5` int(11) NOT NULL default '0';
 alter table creature_movement add `emote` int(10) unsigned default '0';
 alter table creature_movement add `spell` int(5) unsigned default '0';
@@ -149,20 +149,19 @@
                 if(behavior->model1 != 0)
                     creature.SetDisplayId(behavior->model1);
-                if(!behavior->text[0].empty())
+                if(behavior->textid[0])
                 {
-                    // Only one text is set
-                    if( !behavior->text[1].empty() )
+                    // Not only one text is set
+                    if( behavior->textid[1] )
                     {
                         // Select one from max 5 texts (0 and 1 already checked)
                         int i = 2;
-                        for( ; i < 5; ++i )
-                            if( behavior->text[i].empty() )
+                        for( ; i < MAX_WAYPOINT_TEXT; ++i )
+                            if( !behavior->textid[i] )
                                 break;
 
-                        creature.Say(behavior->text[rand() % i].c_str(), 0, 0);
-
+                        creature.Say(behavior->textid[rand() % i], 0, 0);
                     }
                     else
-                        creature.Say(behavior->text[0].c_str(), 0, 0);
+                        creature.Say(behavior->textid[0], 0, 0);
                 }
             }                                               // wpBehaviour found
Index: trunk/src/game/GameObject.h
===================================================================
--- trunk/src/game/GameObject.h (revision 230)
+++ trunk/src/game/GameObject.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -358,5 +358,5 @@
         } raw;
     };
-    char   *ScriptName;
+    uint32 ScriptId;
 };
 
Index: trunk/src/game/CreatureAIImpl.h
===================================================================
--- trunk/src/game/CreatureAIImpl.h (revision 102)
+++ trunk/src/game/CreatureAIImpl.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 #ifndef CREATUREAIIMPL_H
Index: trunk/src/game/SpellHandler.cpp
===================================================================
--- trunk/src/game/SpellHandler.cpp (revision 252)
+++ trunk/src/game/SpellHandler.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -55,4 +55,10 @@
     }
 
+    if(pItem->GetGUID() != item_guid)
+    {
+        pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
+        return;
+    }
+
     sLog.outDetail("WORLD: CMSG_USE_ITEM packet, bagIndex: %u, slot: %u, spell_count: %u , cast_count: %u, Item: %u, data length = %i", bagIndex, slot, spell_count, cast_count, pItem->GetEntry(), recvPacket.size());
 
@@ -238,5 +244,5 @@
 
             pItem->SetUInt64Value(ITEM_FIELD_GIFTCREATOR, 0);
-            pItem->SetUInt32Value(OBJECT_FIELD_ENTRY, entry);
+            pItem->SetEntry(entry);
             pItem->SetUInt32Value(ITEM_FIELD_FLAGS, flags);
             pItem->SetState(ITEM_CHANGED, pUser);
@@ -260,5 +266,4 @@
 
     uint64 guid;
-    uint32 spellId = OPEN_CHEST;
 
     recv_data >> guid;
@@ -323,5 +328,5 @@
 
     Spell *spell = new Spell(_player, spellInfo, false);
-    spell->m_cast_count = cast_count;                       //set count of casts
+    spell->m_cast_count = cast_count;                       // set count of casts
     spell->prepare(&targets);
 }
Index: trunk/src/game/MapManager.h
===================================================================
--- trunk/src/game/MapManager.h (revision 206)
+++ trunk/src/game/MapManager.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -28,4 +28,5 @@
 #include "Map.h"
 #include "GridStates.h"
+
 class Transport;
 
@@ -45,5 +46,5 @@
         // only const version for outer users
         Map const* GetBaseMap(uint32 id) const { return const_cast<MapManager*>(this)->_GetBaseMap(id); }
-        void DeleteInstance(uint32 mapid, uint32 instanceId, uint8 mode);
+        void DeleteInstance(uint32 mapid, uint32 instanceId);
 
         inline uint16 GetAreaFlag(uint32 mapid, float x, float y) const
Index: trunk/src/game/Chat.cpp
===================================================================
--- trunk/src/game/Chat.cpp (revision 233)
+++ trunk/src/game/Chat.cpp (revision 260)
@@ -64,14 +64,42 @@
     };
 
+    static ChatCommand serverIdleRestartCommandTable[] =
+    {
+        { "cancel",         SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerShutDownCancelCommand,"", NULL },
+        { ""   ,            SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerIdleRestartCommand,   "", NULL },
+        { NULL,             0,                  false, NULL,                                           "", NULL }
+    };
+
+    static ChatCommand serverIdleShutdownCommandTable[] =
+    {
+        { "cancel",         SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerShutDownCancelCommand,"", NULL },
+        { ""   ,            SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerIdleShutDownCommand,  "", NULL },
+        { NULL,             0,                  false, NULL,                                           "", NULL }
+    };
+
+    static ChatCommand serverRestartCommandTable[] =
+    {
+        { "cancel",         SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerShutDownCancelCommand,"", NULL },
+        { ""   ,            SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerRestartCommand,       "", NULL },
+        { NULL,             0,                  false, NULL,                                           "", NULL }
+    };
+
+    static ChatCommand serverShutdownCommandTable[] =
+    {
+        { "cancel",         SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerShutDownCancelCommand,"", NULL },
+        { ""   ,            SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleServerShutDownCommand,      "", NULL },
+        { NULL,             0,                  false, NULL,                                           "", NULL }
+    };
+
     static ChatCommand serverCommandTable[] =
     {
         { "corpses",        SEC_GAMEMASTER,     true,  &ChatHandler::HandleServerCorpsesCommand,       "", NULL },
         { "exit",           SEC_CONSOLE,        true,  &ChatHandler::HandleServerExitCommand,          "", NULL },
-        { "idlerestart",    SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleIdleRestartCommand,         "", NULL },
-        { "idleshutdown",   SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleIdleShutDownCommand,        "", NULL },
+        { "idlerestart",    SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverIdleRestartCommandTable },
+        { "idleshutdown",   SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverShutdownCommandTable },
         { "info",           SEC_PLAYER,         true,  &ChatHandler::HandleServerInfoCommand,          "", NULL },
         { "motd",           SEC_PLAYER,         true,  &ChatHandler::HandleServerMotdCommand,          "", NULL },
-        { "restart",        SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleRestartCommand,             "", NULL },
-        { "shutdown",       SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleShutDownCommand,            "", NULL },
+        { "restart",        SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverRestartCommandTable },
+        { "shutdown",       SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverShutdownCommandTable },
         { "set",            SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverSetCommandTable },
         { NULL,             0,                  false, NULL,                                           "", NULL }
Index: trunk/src/game/ItemEnchantmentMgr.cpp
===================================================================
--- trunk/src/game/ItemEnchantmentMgr.cpp (revision 206)
+++ trunk/src/game/ItemEnchantmentMgr.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
Index: trunk/src/game/Map.h
===================================================================
--- trunk/src/game/Map.h (revision 257)
+++ trunk/src/game/Map.h (revision 260)
@@ -106,5 +106,5 @@
     float startLocZ;
     float startLocO;
-    char const* script;
+    uint32 script_id;
 };
 
@@ -344,5 +344,5 @@
         void CreateInstanceData(bool load);
         bool Reset(uint8 method);
-        std::string GetScript() { return i_script; }
+        uint32 GetScriptId() { return i_script_id; }
         InstanceData* GetInstanceData() { return i_data; }
         void PermBindAllPlayers(Player *player);
@@ -356,8 +356,5 @@
         bool m_unloadWhenEmpty;
         InstanceData* i_data;
-        std::string i_script;
-        // only online players that are inside the instance currently
-        // TODO ? - use the grid instead to access the players
-        PlayerList i_Players;
+        uint32 i_script_id;
 };
 
Index: trunk/src/game/WaypointManager.cpp
===================================================================
--- trunk/src/game/WaypointManager.cpp (revision 207)
+++ trunk/src/game/WaypointManager.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -25,4 +25,5 @@
 #include "ProgressBar.h"
 #include "MapManager.h"
+#include "ObjectMgr.h"
 
 INSTANTIATE_SINGLETON_1(WaypointManager);
@@ -30,13 +31,22 @@
 bool WaypointBehavior::isEmpty()
 {
-    return emote == 0 && spell == 0 && model1 == 0 && model2 == 0 && text[0].empty() &&
-        text[1].empty() && text[2].empty() && text[3].empty() && text[4].empty();
+    if (emote || spell || model1 || model2)
+        return false;
+
+    for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
+        if(textid[i])
+            return false;
+
+    return true;
 }
 
 WaypointBehavior::WaypointBehavior(const WaypointBehavior &b)
 {
-    emote = b.emote; spell = b.spell; model1 = b.model1; model2 = b.model2;
-    text[0] = b.text[0]; text[1] = b.text[1]; text[2] = b.text[2];
-    text[3] = b.text[3]; text[4] = b.text[4];
+    emote = b.emote;
+    spell = b.spell;
+    model1 = b.model1;
+    model2 = b.model2;
+    for(int i=0; i < MAX_WAYPOINT_TEXT; ++i)
+        textid[i] = b.textid[i];
 }
 
@@ -67,5 +77,5 @@
     }
 
-    result = WorldDatabase.Query("SELECT position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, text1, text2, text3, text4, text5, id, point FROM creature_movement");
+    result = WorldDatabase.Query("SELECT position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, id, point FROM creature_movement");
     if(result)
     {
@@ -114,9 +124,31 @@
             be.emote            = fields[7].GetUInt32();
             be.spell            = fields[8].GetUInt32();
-            be.text[0]          = fields[9].GetCppString();
-            be.text[1]          = fields[10].GetCppString();
-            be.text[2]          = fields[11].GetCppString();
-            be.text[3]          = fields[12].GetCppString();
-            be.text[4]          = fields[13].GetCppString();
+
+            // load and store without holes in array
+            int j = 0;
+            for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
+            {
+                be.textid[j]        = fields[9+i].GetUInt32();
+                if(be.textid[j])
+                {
+                    if (be.textid[j] < MIN_DB_SCRIPT_STRING_ID || be.textid[j] >= MAX_DB_SCRIPT_STRING_ID)
+                    {
+                        sLog.outErrorDb( "Table `db_script_string` not have string id  %u", be.textid[j]);
+                        continue;
+                    }
+
+                    if (!objmgr.GetTrinityStringLocale (be.textid[j]))
+                    {
+                        sLog.outErrorDb("ERROR: Waypoint path %d (point %d), have invalid text id (%i) in `textid%d, ignored.",
+                            id, point, be.textid[j], i+1);
+                        continue;
+                    }
+
+                    ++j;                                    // to next internal field
+                }
+            }
+            // fill array tail
+            for(; j < MAX_WAYPOINT_TEXT; ++j)
+                be.textid[j] = 0;
 
             // save memory by not storing empty behaviors
@@ -266,9 +298,9 @@
         if(!node.behavior) node.behavior = new WaypointBehavior();
 
-        if(field == "text1") node.behavior->text[0] = text ? text : "";
-        if(field == "text2") node.behavior->text[1] = text ? text : "";
-        if(field == "text3") node.behavior->text[2] = text ? text : "";
-        if(field == "text4") node.behavior->text[3] = text ? text : "";
-        if(field == "text5") node.behavior->text[4] = text ? text : "";
+//        if(field == "text1") node.behavior->text[0] = text ? text : "";
+//        if(field == "text2") node.behavior->text[1] = text ? text : "";
+//        if(field == "text3") node.behavior->text[2] = text ? text : "";
+//        if(field == "text4") node.behavior->text[3] = text ? text : "";
+//        if(field == "text5") node.behavior->text[4] = text ? text : "";
         if(field == "emote") node.behavior->emote   = text ? atoi(text) : 0;
         if(field == "spell") node.behavior->spell   = text ? atoi(text) : 0;
Index: trunk/src/game/GMTicketMgr.h
===================================================================
--- trunk/src/game/GMTicketMgr.h (revision 229)
+++ trunk/src/game/GMTicketMgr.h (revision 260)
@@ -51,5 +51,8 @@
             m_text = text ? text : "";
             m_lastUpdate = time(NULL);
-            CharacterDatabase.PExecute("UPDATE character_ticket SET ticket_text = '%s' WHERE guid = '%u'", m_text.c_str(), m_guid);
+
+            std::string escapedString = m_text;
+            CharacterDatabase.escape_string(escapedString);
+            CharacterDatabase.PExecute("UPDATE character_ticket SET ticket_text = '%s' WHERE guid = '%u'", escapedString.c_str(), m_guid);
         }
 
@@ -63,5 +66,9 @@
             CharacterDatabase.BeginTransaction();
             DeleteFromDB();
-            CharacterDatabase.PExecute("INSERT INTO character_ticket (guid, ticket_text) VALUES ('%u', '%s')", m_guid, GetText());
+
+            std::string escapedString = m_text;
+            CharacterDatabase.escape_string(escapedString);
+
+            CharacterDatabase.PExecute("INSERT INTO character_ticket (guid, ticket_text) VALUES ('%u', '%s')", m_guid, escapedString.c_str());
             CharacterDatabase.CommitTransaction();
         }
Index: trunk/src/game/CreatureAISelector.cpp
===================================================================
--- trunk/src/game/CreatureAISelector.cpp (revision 174)
+++ trunk/src/game/CreatureAISelector.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
Index: trunk/src/game/ArenaTeam.cpp
===================================================================
--- trunk/src/game/ArenaTeam.cpp (revision 247)
+++ trunk/src/game/ArenaTeam.cpp (revision 260)
Index: trunk/src/game/World.cpp
===================================================================
--- trunk/src/game/World.cpp (revision 230)
+++ trunk/src/game/World.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -67,4 +67,5 @@
 
 volatile bool World::m_stopEvent = false;
+uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
 volatile uint32 World::m_worldLoopCounter = 0;
 
@@ -543,5 +544,4 @@
         m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
 
-
     m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
     /// \todo Add MonsterSight and GuarderSight (with meaning) in Trinityd.conf or put them as define
@@ -606,5 +606,4 @@
     }
 
-
     if(reload)
     {
@@ -770,6 +769,6 @@
     m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
 
-    // always use declined names in the Russian client
-    m_configs[CONFIG_DECLINED_NAMES_USED] = 
+    // always use declined names in the russian client
+    m_configs[CONFIG_DECLINED_NAMES_USED] =
         (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
 
@@ -966,4 +965,7 @@
     DetectDBCLang();
 
+    sLog.outString( "Loading Script Names...");
+    objmgr.LoadScriptNames();
+
     sLog.outString( "Loading InstanceTemplate" );
     objmgr.LoadInstanceTemplate();
@@ -1081,8 +1083,7 @@
     sLog.outString( "Loading Tavern Area Triggers..." );
     objmgr.LoadTavernAreaTriggers();
-    
+
     sLog.outString( "Loading AreaTrigger script names..." );
     objmgr.LoadAreaTriggerScripts();
-
 
     sLog.outString( "Loading Graveyard-zone links...");
@@ -1165,5 +1166,5 @@
     sLog.outString( "Loading Npc Text Id..." );
     objmgr.LoadNpcTextId();                                 // must be after load Creature and NpcText
-    
+
     sLog.outString( "Loading Npc Options..." );
     objmgr.LoadNpcOptions();
@@ -1193,4 +1194,7 @@
     objmgr.LoadEventScripts();                              // must be after load Creature/Gameobject(Template/Data)
 
+    sLog.outString( "Loading Scripts text locales..." );    // must be after Load*Scripts calls
+    objmgr.LoadDbScriptStrings();
+
     sLog.outString( "Initializing Scripts..." );
     if(!LoadScriptingModule())
@@ -1263,4 +1267,5 @@
     sLog.outString( "WORLD: World initialized" );
 }
+
 void World::DetectDBCLang()
 {
@@ -1463,5 +1468,7 @@
     }
 
-    MapManager::Instance().DoDelayedMovesAndRemoves(); ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
+    /// </ul>
+    ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
+    MapManager::Instance().DoDelayedMovesAndRemoves();
 
     // update the instance reset times
@@ -1583,4 +1590,6 @@
         }
 
+        //if(source && !source->IsInWorld()) source = NULL;
+
         Object* target = NULL;
 
@@ -1610,4 +1619,6 @@
         }
 
+        //if(target && !target->IsInWorld()) target = NULL;
+
         switch (step.script->command)
         {
@@ -1637,5 +1648,5 @@
                 {
                     case 0:                                 // Say
-                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
+                        ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
                         break;
                     case 1:                                 // Whisper
@@ -1645,11 +1656,11 @@
                             break;
                         }
-                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
+                        ((Creature *)source)->Whisper(step.script->dataint,unit_target);
                         break;
                     case 2:                                 // Yell
-                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
+                        ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
                         break;
                     case 3:                                 // Emote text
-                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
+                        ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
                         break;
                     default:
@@ -1702,5 +1713,5 @@
                 }
                 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
-                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
+                ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
                 break;
             case SCRIPT_COMMAND_FLAG_SET:
@@ -1852,5 +1863,5 @@
                 go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
 
-                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
+                go->GetMap()->Add(go);
                 break;
             }
@@ -2374,5 +2385,5 @@
 
     ///- if there is a shutdown timer
-    if(m_ShutdownTimer > 0 && elapsed > 0)
+    if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
     {
         ///- ... and it is overdue, stop the world (set m_stopEvent)
@@ -2380,5 +2391,5 @@
         {
             if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
-                m_stopEvent = true;
+                m_stopEvent = true;                         // exist code already set
             else
                 m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
@@ -2395,7 +2406,12 @@
 
 /// Shutdown the server
-void World::ShutdownServ(uint32 time, uint32 options)
-{
+void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
+{
+    // ignore if server shutdown at next tick
+    if(m_stopEvent)
+        return;
+
     m_ShutdownMask = options;
+    m_ExitCode = exitcode;
 
     ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
@@ -2403,5 +2419,5 @@
     {
         if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
-            m_stopEvent = true;
+            m_stopEvent = true;                             // exist code already set
         else
             m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
@@ -2448,5 +2464,6 @@
 void World::ShutdownCancel()
 {
-    if(!m_ShutdownTimer)
+    // nothing cancel or too later
+    if(!m_ShutdownTimer || m_stopEvent)
         return;
 
@@ -2455,7 +2472,8 @@
     m_ShutdownMask = 0;
     m_ShutdownTimer = 0;
+    m_ExitCode = SHUTDOWN_EXIT_CODE;                       // to default value
     SendServerMessage(msgid);
 
-    DEBUG_LOG("Server %s canceled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
+    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
 }
 
@@ -2502,4 +2520,5 @@
         if(!itr->second->Update(diff))                      // As interval = 0
         {
+            RemoveQueuedPlayer (itr->second);
             delete itr->second;
             m_sessions.erase(itr);
Index: trunk/src/game/ItemEnchantmentMgr.h
===================================================================
--- trunk/src/game/ItemEnchantmentMgr.h (revision 102)
+++ trunk/src/game/ItemEnchantmentMgr.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
Index: trunk/src/game/Item.h
===================================================================
--- trunk/src/game/Item.h (revision 102)
+++ trunk/src/game/Item.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -229,5 +229,4 @@
         bool GemsFitSockets() const;
 
-        uint32 GetEntry() const { return GetUInt32Value(OBJECT_FIELD_ENTRY); }
         uint32 GetCount() const { return GetUInt32Value (ITEM_FIELD_STACK_COUNT); }
         void SetCount(uint32 value) { SetUInt32Value (ITEM_FIELD_STACK_COUNT, value); }
Index: trunk/src/game/Mail.cpp
===================================================================
--- trunk/src/game/Mail.cpp (revision 229)
+++ trunk/src/game/Mail.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -188,5 +188,4 @@
                 return;
             }
-
             if (mailItem.item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED) || mailItem.item->GetUInt32Value(ITEM_FIELD_DURATION))
             {
@@ -195,9 +194,9 @@
             }
 
-			if(COD && mailItem.item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
-			{
-				pl->SendMailResult(0, 0, MAIL_ERR_CANT_SEND_WRAPPED_COD);
-				return;
-			}
+            if(COD && mailItem.item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
+            {
+                pl->SendMailResult(0, 0, MAIL_ERR_CANT_SEND_WRAPPED_COD);
+                return;
+            }
         }
     }
Index: trunk/src/game/Creature.cpp
===================================================================
--- trunk/src/game/Creature.cpp (revision 230)
+++ trunk/src/game/Creature.cpp (revision 260)
@@ -178,5 +178,5 @@
     float x,y,z,o;
     GetRespawnCoord(x, y, z, &o);
-    MapManager::Instance().GetMap(GetMapId(), this)->CreatureRelocation(this,x,y,z,o);
+    GetMap()->CreatureRelocation(this,x,y,z,o);
 }
 
@@ -210,5 +210,5 @@
     }
 
-    SetUInt32Value(OBJECT_FIELD_ENTRY, Entry);              // normal entry always
+    SetEntry(Entry);                                        // normal entry always
     m_creatureInfo = cinfo;                                 // map mode related always
 
@@ -353,5 +353,5 @@
                 lootForBody         = false;
 
-                if(m_originalEntry != GetUInt32Value(OBJECT_FIELD_ENTRY))
+                if(m_originalEntry != GetEntry())
                     UpdateEntry(m_originalEntry);
 
@@ -372,7 +372,7 @@
 
                 //Call AI respawn virtual function
-                AI()->JustRespawned();
-
-                MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
+                i_AI->JustRespawned();
+
+                GetMap()->Add(this);
             }
             break;
@@ -436,5 +436,5 @@
                 // do not allow the AI to be changed during update
                 m_AI_locked = true;
-                AI()->UpdateAI(diff);
+                i_AI->UpdateAI(diff);
                 m_AI_locked = false;
             }
@@ -2097,7 +2097,12 @@
 }
 
-char const* Creature::GetScriptName() const
-{
-    return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptName;
+std::string Creature::GetScriptName()
+{
+    return objmgr.GetScriptName(GetScriptId());
+}
+
+uint32 Creature::GetScriptId()
+{
+    return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
 }
 
Index: trunk/src/game/CreatureAIRegistry.cpp
===================================================================
--- trunk/src/game/CreatureAIRegistry.cpp (revision 174)
+++ trunk/src/game/CreatureAIRegistry.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
Index: trunk/src/game/Map.cpp
===================================================================
--- trunk/src/game/Map.cpp (revision 257)
+++ trunk/src/game/Map.cpp (revision 260)
@@ -1714,5 +1714,5 @@
     if (mInstance)
     {
-        i_script = mInstance->script;
+        i_script_id = mInstance->script_id;
         i_data = Script->CreateInstanceData(this);
     }
@@ -1731,5 +1731,5 @@
             if(data)
             {
-                sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
+                sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
                 i_data->Load(data);
             }
@@ -1739,5 +1739,5 @@
     else
     {
-        sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
+        sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
         i_data->Initialize();
     }
Index: trunk/src/game/Creature.h
===================================================================
--- trunk/src/game/Creature.h (revision 230)
+++ trunk/src/game/Creature.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -206,8 +206,9 @@
     uint32  MechanicImmuneMask;
     uint32  flags_extra;
-    char const* ScriptName;
+    uint32  ScriptID;
     uint32 GetRandomValidModelId() const;
     uint32 GetFirstValidModelId() const;
-    
+
+    // helpers
     SkillType GetRequiredLootSkill() const
     {
@@ -219,5 +220,5 @@
             return SKILL_SKINNING;                          // normal case
     }
-    
+
     bool isTameable() const
     {
@@ -499,5 +500,7 @@
         CreatureInfo const *GetCreatureInfo() const { return m_creatureInfo; }
         CreatureDataAddon const* GetCreatureAddon() const;
-        char const* GetScriptName() const;
+
+        std::string GetScriptName();
+        uint32 GetScriptId();
 
         void prepareGossipMenu( Player *pPlayer, uint32 gossipid = 0 );
@@ -525,5 +528,5 @@
         // overwrite WorldObject function for proper name localization
         const char* GetNameForLocaleIdx(int32 locale_idx) const;
-    
+
         void setDeathState(DeathState s);                   // overwrite virtual Unit::setDeathState
 
Index: trunk/src/game/PlayerDump.cpp
===================================================================
--- trunk/src/game/PlayerDump.cpp (revision 112)
+++ trunk/src/game/PlayerDump.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -278,5 +278,5 @@
     // for guid set stop if set is empty
     if(guids && guids->empty())
-        return;                                        // nothing to do
+        return;                                             // nothing to do
 
     // setup for guids case start position
@@ -344,5 +344,5 @@
     FILE *fout = fopen(file.c_str(), "w");
     if (!fout)
-		return DUMP_FILE_OPEN_ERROR;
+        return DUMP_FILE_OPEN_ERROR;
 
     std::string dump = GetDump(guid);
@@ -372,7 +372,8 @@
         }
     }
+
     FILE *fin = fopen(file.c_str(), "r");
     if(!fin)
-		return DUMP_FILE_OPEN_ERROR;
+        return DUMP_FILE_OPEN_ERROR;
 
     QueryResult * result = NULL;
@@ -391,5 +392,6 @@
         else incHighest = false;
     }
-    else guid = objmgr.m_hiCharGuid;
+    else
+        guid = objmgr.m_hiCharGuid;
 
     // normalize the name if specified and check if it exists
@@ -469,5 +471,5 @@
             case DTT_CHAR_TABLE:
                 if(!changenth(line, 1, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 break;
 
@@ -475,21 +477,17 @@
             {
                 if(!changenth(line, 1, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
 
                 // guid, data field:guid, items
                 if(!changenth(line, 2, chraccount))
-					ROLLBACK(DUMP_FILE_BROKEN);
-
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 std::string vals = getnth(line, 3);
                 if(!changetoknth(vals, OBJECT_FIELD_GUID+1, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 for(uint16 field = PLAYER_FIELD_INV_SLOT_HEAD; field < PLAYER_FARSIGHT; field++)
                     if(!changetokGuid(vals, field+1, items, objmgr.m_hiItemGuid, true))
-						ROLLBACK(DUMP_FILE_BROKEN);
-
+                        ROLLBACK(DUMP_FILE_BROKEN);
                 if(!changenth(line, 3, vals.c_str()))
-					ROLLBACK(DUMP_FILE_BROKEN);
-
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 if (name == "")
                 {
@@ -504,9 +502,9 @@
                                                             // rename on login: `at_login` field 30 in raw field list
                         if(!changenth(line, 30, "1"))
-							ROLLBACK(DUMP_FILE_BROKEN);
+                            ROLLBACK(DUMP_FILE_BROKEN);
                     }
                 }
                 else if(!changenth(line, 4, name.c_str()))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
 
                 break;
@@ -515,11 +513,11 @@
             {
                 if(!changenth(line, 1, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
 
                 // bag, item
                 if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid, true))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changeGuid(line, 4, items, objmgr.m_hiItemGuid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changeGuid(line, 4, items, objmgr.m_hiItemGuid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 break;
             }
@@ -528,15 +526,14 @@
                 // item, owner, data field:item, owner guid
                 if(!changeGuid(line, 1, items, objmgr.m_hiItemGuid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changenth(line, 2, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changenth(line, 2, newguid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 std::string vals = getnth(line,3);
                 if(!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, objmgr.m_hiItemGuid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changenth(line, 3, vals.c_str()))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changenth(line, 3, vals.c_str()))
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 break;
             }
@@ -545,7 +542,7 @@
                 // guid,item_guid,
                 if(!changenth(line, 1, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 break;
             }
@@ -570,7 +567,7 @@
                 // item, entry, owner, ...
                 if(!changenth(line, 1, newpetid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changenth(line, 3, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changenth(line, 3, newguid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
 
                 break;
@@ -583,10 +580,10 @@
                 std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
                 if(petids_iter == petids.end())             // couldn't find new inserted id
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
 
                 snprintf(newpetid, 20, "%d", petids_iter->second);
 
                 if(!changenth(line, 1, newpetid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
 
                 break;
@@ -596,7 +593,7 @@
                 // id,messageType,stationery,sender,receiver
                 if(!changeGuid(line, 1, mails, objmgr.m_mailid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changenth(line, 5, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changenth(line, 5, newguid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 break;
             }
@@ -605,9 +602,9 @@
                 // mail_id,item_guid,item_template,receiver
                 if(!changeGuid(line, 1, mails, objmgr.m_mailid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
-					ROLLBACK(DUMP_FILE_BROKEN);
-				if(!changenth(line, 4, newguid))
-					ROLLBACK(DUMP_FILE_BROKEN);
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
+                if(!changenth(line, 4, newguid))
+                    ROLLBACK(DUMP_FILE_BROKEN);
                 break;
             }
@@ -618,5 +615,5 @@
 
         if(!CharacterDatabase.Execute(line.c_str()))
-			ROLLBACK(DUMP_FILE_BROKEN);
+            ROLLBACK(DUMP_FILE_BROKEN);
     }
 
Index: trunk/src/game/Chat.h
===================================================================
--- trunk/src/game/Chat.h (revision 233)
+++ trunk/src/game/Chat.h (revision 260)
@@ -176,4 +176,5 @@
         bool HandleModifyRepCommand(const char* args);
         bool HandleModifyArenaCommand(const char* args);
+        bool HandleModifyGenderCommand(const char* args);
 
         bool HandleNpcAddCommand(const char* args);
@@ -192,4 +193,5 @@
         bool HandleNpcSpawnDistCommand(const char* args);
         bool HandleNpcSpawnTimeCommand(const char* args);
+        bool HandleNpcTameCommand(const char* args);
         bool HandleNpcTextEmoteCommand(const char* args);
         bool HandleNpcUnFollowCommand(const char* args);
@@ -216,4 +218,5 @@
         bool HandleReloadCreatureQuestRelationsCommand(const char* args);
         bool HandleReloadCreatureQuestInvRelationsCommand(const char* args);
+        bool HandleReloadDbScriptStringCommand(const char* args);
         bool HandleReloadGameGraveyardZoneCommand(const char* args);
         bool HandleReloadGameObjectScriptsCommand(const char* args);
@@ -271,8 +274,13 @@
         bool HandleServerCorpsesCommand(const char* args);
         bool HandleServerExitCommand(const char* args);
+        bool HandleServerIdleRestartCommand(const char* args);
+        bool HandleServerIdleShutDownCommand(const char* args);
         bool HandleServerInfoCommand(const char* args);
         bool HandleServerMotdCommand(const char* args);
+        bool HandleServerRestartCommand(const char* args);
         bool HandleServerSetMotdCommand(const char* args);
         bool HandleServerSetLogLevelCommand(const char* args);
+        bool HandleServerShutDownCommand(const char* args);
+        bool HandleServerShutDownCancelCommand(const char* args);
 
         bool HandleAddHonorCommand(const char* args);
@@ -328,9 +336,4 @@
         bool HandleBanListCharacterCommand(const char* args);
         bool HandleBanListIPCommand(const char* args);
-        bool HandleIdleRestartCommand(const char* args);
-        bool HandleIdleShutDownCommand(const char* args);
-        bool HandleShutDownCommand(const char* args);
-        bool HandleRestartCommand(const char* args);
-        bool HandleSecurityCommand(const char* args);
         bool HandleGoXYCommand(const char* args);
         bool HandleGoXYZCommand(const char* args);
@@ -366,5 +369,4 @@
         bool HandleAddItemCommand(const char* args);
         bool HandleAddItemSetCommand(const char* args);
-        bool HandleModifyGenderCommand(const char* args);
         bool HandlePetTpCommand(const char* args);
         bool HandlePetUnlearnCommand(const char* args);
Index: trunk/src/game/ItemHandler.cpp
===================================================================
--- trunk/src/game/ItemHandler.cpp (revision 229)
+++ trunk/src/game/ItemHandler.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -314,7 +314,7 @@
             if (il)
             {
-                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
+                if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty())
                     Name = il->Name[loc_idx];
-                if (il->Description.size() > loc_idx && !il->Description[loc_idx].empty())
+                if (il->Description.size() > size_t(loc_idx) && !il->Description[loc_idx].empty())
                     Description = il->Description[loc_idx];
             }
@@ -361,4 +361,6 @@
             data << pProto->Damage[i].DamageType;
         }
+
+        // resistances (7)
         data << pProto->Armor;
         data << pProto->HolyRes;
@@ -368,8 +370,9 @@
         data << pProto->ShadowRes;
         data << pProto->ArcaneRes;
+
         data << pProto->Delay;
         data << pProto->Ammo_type;
-
-        data << (float)pProto->RangedModRange;
+        data << pProto->RangedModRange;
+
         for(int s = 0; s < 5; s++)
         {
@@ -977,5 +980,5 @@
             if (il)
             {
-                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
+                if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty())
                     Name = il->Name[loc_idx];
             }
@@ -1028,5 +1031,5 @@
     }
 
-    if(item==gift)                                          // not possible with pacjket from real client
+    if(item==gift)                                          // not possable with pacjket from real client
     {
         _player->SendEquipError( EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, NULL );
@@ -1073,14 +1076,14 @@
     CharacterDatabase.BeginTransaction();
     CharacterDatabase.PExecute("INSERT INTO character_gifts VALUES ('%u', '%u', '%u', '%u')", GUID_LOPART(item->GetOwnerGUID()), item->GetGUIDLow(), item->GetEntry(), item->GetUInt32Value(ITEM_FIELD_FLAGS));
-    item->SetUInt32Value(OBJECT_FIELD_ENTRY, gift->GetUInt32Value(OBJECT_FIELD_ENTRY));
+    item->SetEntry(gift->GetEntry());
 
     switch (item->GetEntry())
     {
-        case 5042:  item->SetUInt32Value(OBJECT_FIELD_ENTRY,  5043); break;
-        case 5048:  item->SetUInt32Value(OBJECT_FIELD_ENTRY,  5044); break;
-        case 17303: item->SetUInt32Value(OBJECT_FIELD_ENTRY, 17302); break;
-        case 17304: item->SetUInt32Value(OBJECT_FIELD_ENTRY, 17305); break;
-        case 17307: item->SetUInt32Value(OBJECT_FIELD_ENTRY, 17308); break;
-        case 21830: item->SetUInt32Value(OBJECT_FIELD_ENTRY, 21831); break;
+        case 5042:  item->SetEntry( 5043); break;
+        case 5048:  item->SetEntry( 5044); break;
+        case 17303: item->SetEntry(17302); break;
+        case 17304: item->SetEntry(17305); break;
+        case 17307: item->SetEntry(17308); break;
+        case 21830: item->SetEntry(21831); break;
     }
     item->SetUInt64Value(ITEM_FIELD_GIFTCREATOR, _player->GetGUID());
Index: trunk/src/game/Formulas.h
===================================================================
--- trunk/src/game/Formulas.h (revision 111)
+++ trunk/src/game/Formulas.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -30,5 +30,5 @@
         inline uint32 hk_honor_at_level(uint32 level, uint32 count=1)
         {
-            return (uint32) ceil(count*(-0.53177f + 0.59357f * exp((level +23.54042f) / 26.07859f )));
+            return (uint32)ceil(count*(-0.53177f + 0.59357f * exp((level +23.54042f) / 26.07859f )));
         }
     }
@@ -81,4 +81,5 @@
         inline uint32 BaseGain(uint32 pl_level, uint32 mob_level, ContentLevels content)
         {
+            //TODO: need modifier for CONTENT_71_80 different from CONTENT_61_70?
             const uint32 nBaseExp = content == CONTENT_1_60 ? 45 : 235;
             if( mob_level >= pl_level )
Index: trunk/src/game/GMTicketHandler.cpp
===================================================================
--- trunk/src/game/GMTicketHandler.cpp (revision 229)
+++ trunk/src/game/GMTicketHandler.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -67,6 +67,4 @@
     recv_data >> ticketText;
 
-    CharacterDatabase.escape_string(ticketText);
-
     if(GMTicket* ticket = ticketmgr.GetGMTicket(GetPlayer()->GetGUIDLow()))
         ticket->SetText(ticketText.c_str());
@@ -106,7 +104,5 @@
     sLog.outDebug("TicketCreate: map %u, x %f, y %f, z %f, text %s, unk1 %u, unk2 %u", map, x, y, z, ticketText.c_str(), unk1, unk2);
 
-    CharacterDatabase.escape_string(ticketText);
-
-    if(GMTicket* ticket = ticketmgr.GetGMTicket(GetPlayer()->GetGUIDLow()))
+    if(ticketmgr.GetGMTicket(GetPlayer()->GetGUIDLow()))
     {
         WorldPacket data( SMSG_GMTICKET_CREATE, 4 );
Index: trunk/src/game/CreatureAI.cpp
===================================================================
--- trunk/src/game/CreatureAI.cpp (revision 207)
+++ trunk/src/game/CreatureAI.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
Index: trunk/src/game/World.h
===================================================================
--- trunk/src/game/World.h (revision 229)
+++ trunk/src/game/World.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -52,4 +52,11 @@
 };
 
+enum ShutdownExitCode
+{
+    SHUTDOWN_EXIT_CODE = 0,
+    ERROR_EXIT_CODE    = 1,
+    RESTART_EXIT_CODE  = 2,
+};
+
 /// Timers for different object refresh rates
 enum WorldTimers
@@ -62,6 +69,5 @@
     WUPDATE_CORPSES     = 5,
     WUPDATE_EVENTS      = 6,
-    WUPDATE_COUNT       = 7,
-
+    WUPDATE_COUNT       = 7
 };
 
@@ -106,4 +112,6 @@
     CONFIG_INSTANCE_IGNORE_RAID,
     CONFIG_BATTLEGROUND_CAST_DESERTER,
+    CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE,
+    CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY,
     CONFIG_INSTANCE_RESET_TIME_HOUR,
     CONFIG_INSTANCE_UNLOAD_DELAY,
@@ -144,4 +152,5 @@
     CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF,
     CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF,
+    CONFIG_DETECT_POS_COLLISION,
     CONFIG_RESTRICTED_LFG_CHANNEL,
     CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL,
@@ -317,18 +326,18 @@
 struct CliCommandHolder
 {
-	typedef void Print(const char*);
-
-	char *m_command;
-	Print* m_print;
-
-	CliCommandHolder(const char *command, Print* zprint)
-		: m_print(zprint)
-	{
-		size_t len = strlen(command)+1;
-		m_command = new char[len];
-		memcpy(m_command, command, len);
-	}
-
-	~CliCommandHolder() { delete[] m_command; }
+    typedef void Print(const char*);
+
+    char *m_command;
+    Print* m_print;
+
+    CliCommandHolder(const char *command, Print* zprint)
+        : m_print(zprint)
+    {
+        size_t len = strlen(command)+1;
+        m_command = new char[len];
+        memcpy(m_command, command, len);
+    }
+
+    ~CliCommandHolder() { delete[] m_command; }
 };
 
@@ -337,5 +346,4 @@
 {
     public:
-        static volatile bool m_stopEvent;
         static volatile uint32 m_worldLoopCounter;
 
@@ -345,5 +353,4 @@
         WorldSession* FindSession(uint32 id) const;
         void AddSession(WorldSession *s);
-
         bool RemoveSession(uint32 id);
         /// Get the number of current active sessions
@@ -408,5 +415,5 @@
         void LoadConfigSettings(bool reload = false);
 
-        void SendWorldText(int32 string_id, ...); 
+        void SendWorldText(int32 string_id, ...);
         void SendGlobalMessage(WorldPacket *packet, WorldSession *self = 0, uint32 team = 0);
         void SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self = 0, uint32 team = 0);
@@ -415,9 +422,11 @@
 
         /// Are we in the middle of a shutdown?
-        uint32 GetShutdownMask() const { return m_ShutdownMask; }
         bool IsShutdowning() const { return m_ShutdownTimer > 0; }
-        void ShutdownServ(uint32 time, uint32 options = 0);
+        void ShutdownServ(uint32 time, uint32 options, uint8 exitcode);
         void ShutdownCancel();
         void ShutdownMsg(bool show = false, Player* player = NULL);
+        static uint8 GetExitCode() { return m_ExitCode; }
+        static void StopNow(uint8 exitcode) { m_stopEvent = true; m_ExitCode = exitcode; }
+        static bool IsStopped() { return m_stopEvent; }
 
         void Update(time_t diff);
@@ -454,5 +463,5 @@
         void KickAllQueued();
         BanReturn BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author);
-		bool RemoveBanAccount(BanMode mode, std::string nameOrIP);
+        bool RemoveBanAccount(BanMode mode, std::string nameOrIP);
 
         void ScriptsStart(std::map<uint32, std::multimap<uint32, ScriptInfo> > const& scripts, uint32 id, Object* source, Object* target);
@@ -482,11 +491,11 @@
         LocaleConstant GetAvailableDbcLocale(LocaleConstant locale) const { if(m_availableDbcLocaleMask & (1 << locale)) return locale; else return m_defaultDbcLocale; }
 
-		//used World DB version
-		void LoadDBVersion();
-		char const* GetDBVersion() { return m_DBVersion.c_str(); }
-
-		//used Script version
-		void SetScriptsVersion(char const* version) { m_ScriptsVersion = version ? version : "unknown scripting library"; }
-		char const* GetScriptsVersion() { return m_ScriptsVersion.c_str(); }
+        //used World DB version
+        void LoadDBVersion();
+        char const* GetDBVersion() { return m_DBVersion.c_str(); }
+
+        //used Script version
+        void SetScriptsVersion(char const* version) { m_ScriptsVersion = version ? version : "unknown scripting library"; }
+        char const* GetScriptsVersion() { return m_ScriptsVersion.c_str(); }
 
     protected:
@@ -499,4 +508,9 @@
         void ResetDailyQuests();
     private:
+        static volatile bool m_stopEvent;
+        static uint8 m_ExitCode;
+        uint32 m_ShutdownTimer;
+        uint32 m_ShutdownMask;
+
         time_t m_startTime;
         time_t m_gameTime;
@@ -526,7 +540,4 @@
         std::set<uint32> m_forbiddenMapIds;
 
-        uint32 m_ShutdownTimer;
-        uint32 m_ShutdownMask;
-
         // for max speed access
         static float m_MaxVisibleDistanceForCreature;
@@ -546,12 +557,12 @@
         //Player Queue
         Queue m_QueuedPlayer;
-        
+
         //sessions that are added async
         void AddSession_(WorldSession* s);
         ZThread::LockedQueue<WorldSession*, ZThread::FastMutex> addSessQueue;
 
-		//used versions
-		std::string m_DBVersion;
-		std::string m_ScriptsVersion;
+        //used versions
+        std::string m_DBVersion;
+        std::string m_ScriptsVersion;
 };
 
Index: trunk/src/game/Item.cpp
===================================================================
--- trunk/src/game/Item.cpp (revision 102)
+++ trunk/src/game/Item.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -180,5 +180,5 @@
                     return true;
                 case ITEM_SUBCLASS_SOUL_CONTAINER:
-                    if(!(pProto->BagFamily & BAG_FAMILY_MASK_SHARDS))
+                    if(!(pProto->BagFamily & BAG_FAMILY_MASK_SOUL_SHARDS))
                         return false;
                     return true;
@@ -248,5 +248,5 @@
     Object::_Create( guidlow, 0, HIGHGUID_ITEM );
 
-    SetUInt32Value(OBJECT_FIELD_ENTRY, itemid);
+    SetEntry(itemid);
     SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
 
@@ -430,5 +430,5 @@
 ItemPrototype const *Item::GetProto() const
 {
-    return objmgr.GetItemPrototype(GetUInt32Value(OBJECT_FIELD_ENTRY));
+    return objmgr.GetItemPrototype(GetEntry());
 }
 
@@ -763,7 +763,5 @@
 {
     // Better lost small time at check in comparison lost time at item save to DB.
-    if( GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET)==id &&
-        GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET)==duration &&
-        GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET)==charges )
+    if((GetEnchantmentId(slot) == id) && (GetEnchantmentDuration(slot) == duration) && (GetEnchantmentCharges(slot) == charges))
         return;
 
@@ -776,5 +774,5 @@
 void Item::SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration)
 {
-    if(GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET)==duration)
+    if(GetEnchantmentDuration(slot) == duration)
         return;
 
@@ -785,4 +783,7 @@
 void Item::SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges)
 {
+    if(GetEnchantmentCharges(slot) == charges)
+        return;
+
     SetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_CHARGES_OFFSET,charges);
     SetState(ITEM_CHANGED);
@@ -791,9 +792,9 @@
 void Item::ClearEnchantment(EnchantmentSlot slot)
 {
-    if(!GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET))
-        return;
-
-    for(int x=0;x<3;x++)
-        SetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + x,0);
+    if(!GetEnchantmentId(slot))
+        return;
+
+    for(uint8 x = 0; x < 3; ++x)
+        SetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + x, 0);
     SetState(ITEM_CHANGED);
 }
Index: trunk/src/game/MapManager.cpp
===================================================================
--- trunk/src/game/MapManager.cpp (revision 257)
+++ trunk/src/game/MapManager.cpp (revision 260)
@@ -223,5 +223,5 @@
 }
 
-void MapManager::DeleteInstance(uint32 mapid, uint32 instanceId, uint8 mode)
+void MapManager::DeleteInstance(uint32 mapid, uint32 instanceId)
 {
     Map *m = _GetBaseMap(mapid);
Index: trunk/src/game/ObjectMgr.h
===================================================================
--- trunk/src/game/ObjectMgr.h (revision 206)
+++ trunk/src/game/ObjectMgr.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -85,5 +85,5 @@
     uint32 datalong;
     uint32 datalong2;
-    std::string datatext;
+    int32  dataint;
     float x;
     float y;
@@ -128,4 +128,11 @@
 
 typedef UNORDERED_MAP<uint64/*(instance,guid) pair*/,time_t> RespawnTimes;
+
+
+// mangos string ranges
+#define MIN_TRINITY_STRING_ID    1
+#define MAX_TRINITY_STRING_ID    2000000000
+#define MIN_DB_SCRIPT_STRING_ID MAX_TRINITY_STRING_ID
+#define MAX_DB_SCRIPT_STRING_ID 2000010000
 
 struct TrinityStringLocale
@@ -208,6 +215,6 @@
     CONDITION_QUESTTAKEN            = 9,                    // quest_id     0,      for condition true while quest active.
     CONDITION_AD_COMMISSION_AURA    = 10,                   // 0            0,      for condition true while one from AD ñommission aura active
-	CONDITION_NO_AURA               = 11,                   // spell_id     effindex
-	CONDITION_ACTIVE_EVENT          = 12,                   // event_id
+    CONDITION_NO_AURA               = 11,                   // spell_id     effindex
+    CONDITION_ACTIVE_EVENT          = 12,                   // event_id
 };
 
@@ -251,5 +258,5 @@
 // NPC gossip text id
 typedef UNORDERED_MAP<uint32, uint32> CacheNpcTextIdMap;
-
+typedef std::list<GossipOption> CacheNpcOptionList;
 
 typedef UNORDERED_MAP<uint32, VendorItemData> CacheVendorItemMap;
@@ -300,7 +307,8 @@
         typedef UNORDERED_MAP<uint32, Quest*> QuestMap;
 
+
         typedef UNORDERED_MAP<uint32, AreaTrigger> AreaTriggerMap;
 
-        typedef UNORDERED_MAP<uint32, std::string> AreaTriggerScriptMap;
+        typedef UNORDERED_MAP<uint32, uint32> AreaTriggerScriptMap;
 
         typedef UNORDERED_MAP<uint32, ReputationOnKillEntry> RepOnKillMap;
@@ -309,4 +317,6 @@
 
         typedef UNORDERED_MAP<uint32, PetCreateSpellEntry> PetCreateSpellMap;
+
+        typedef std::vector<std::string> ScriptNameMap;
 
         Player* GetPlayer(const char* name) const { return ObjectAccessor::Instance().FindPlayerByName(name);}
@@ -477,5 +487,5 @@
         AreaTrigger const* GetGoBackTrigger(uint32 Map) const;
 
-        const char* GetAreaTriggerScriptName(uint32 id);
+        uint32 GetAreaTriggerScriptId(uint32 trigger_id);
 
         ReputationOnKillEntry const* GetReputationOnKilEntry(uint32 id) const
@@ -523,5 +533,6 @@
 
         bool LoadTrinityStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value);
-        bool LoadTrinityStrings() { return LoadTrinityStrings(WorldDatabase,"trinity_string",1,std::numeric_limits<int32>::max()); }
+        bool LoadTrinityStrings() { return LoadTrinityStrings(WorldDatabase,"trinity_string",MIN_TRINITY_STRING_ID,MAX_TRINITY_STRING_ID); }
+	void LoadDbScriptStrings();
         void LoadPetCreateSpells();
         void LoadCreatureLocales();
@@ -593,4 +604,6 @@
         uint32 GenerateItemTextID();
         uint32 GeneratePetNumber();
+        uint32 GenerateArenaTeamId();
+        uint32 GenerateGuildId();
         
         void LoadPlayerInfoInCache();
@@ -669,5 +682,4 @@
             return &itr->second;
         }
-        
         NpcOptionLocale const* GetNpcOptionLocale(uint32 entry) const
         {
@@ -694,5 +706,5 @@
         const char *GetTrinityString(int32 entry, int locale_idx) const;
         const char *GetTrinityStringForDBCLocale(int32 entry) const { return GetTrinityString(entry,DBCLocaleIndex); }
-		int32 GetDBCLocaleIndex() const { return DBCLocaleIndex; }
+	int32 GetDBCLocaleIndex() const { return DBCLocaleIndex; }
         void SetDBCLocaleIndex(uint32 lang) { DBCLocaleIndex = GetIndexForLocale(LocaleConstant(lang)); }
 
@@ -733,5 +745,5 @@
         LocaleConstant GetLocaleForIndex(int i);
         // guild bank tabs
-        const uint32 GetGuildBankTabPrice(uint8 Index) { return Index < GUILD_BANK_MAX_TABS ? mGuildBankTabPrice[Index] : 0; }
+        uint32 GetGuildBankTabPrice(uint8 Index) const { return Index < GUILD_BANK_MAX_TABS ? mGuildBankTabPrice[Index] : 0; }
 
         uint16 GetConditionId(ConditionType condition, uint32 value1, uint32 value2);
@@ -754,5 +766,5 @@
         bool AddGameTele(GameTele& data);
         bool DeleteGameTele(std::string name);
-        
+
         CacheNpcOptionList const& GetNpcOptions() const { return m_mCacheNpcOptionList; }
 
@@ -762,5 +774,5 @@
             if(iter == m_mCacheNpcTextIdMap.end())
                 return 0;
-            
+
             return iter->second;
         }
@@ -783,13 +795,23 @@
             return &iter->second;
         }
-        void AddVendorItem(uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, bool savetodb = true);
-        bool RemoveVendorItem(uint32 entry,uint32 item, bool savetodb = true);
-        bool IsVendorItemValid( uint32 vendor_entry, uint32 item, uint32 maxcount, uint32 ptime, uint32 ExtendedCost, Player* pl = NULL, std::set<uint32>* skip_vendors = NULL, uint32 ORnpcflag = 0) const;
-
+        void AddVendorItem(uint32 entry,uint32 item, uint32 maxcount, uint32 incrtime, uint32 ExtendedCost, bool savetodb = true); // for event
+        bool RemoveVendorItem(uint32 entry,uint32 item, bool savetodb = true); // for event
+        bool IsVendorItemValid( uint32 vendor_entry, uint32 item, uint32 maxcount, uint32 ptime, uint32 ExtendedCost, Player* pl = NULL, std::set<uint32>* skip_vendors = NULL, uint32 ORnpcflag = 0 ) const;
+
+        void LoadScriptNames();
+        ScriptNameMap &GetScriptNames() { return m_scriptNames; }
+        const char * GetScriptName(uint32 id) { return id < m_scriptNames.size() ? m_scriptNames[id].c_str() : ""; }
+        uint32 GetScriptId(const char *name);
     protected:
+
+        // first free id for selected id type
         uint32 m_auctionid;
         uint32 m_mailid;
         uint32 m_ItemTextId;
-
+        uint32 m_arenaTeamId;
+        uint32 m_guildId;
+        uint32 m_hiPetNumber;
+
+        // first free low guid for seelcted guid type
         uint32 m_hiCharGuid;
         uint32 m_hiCreatureGuid;
@@ -800,7 +822,5 @@
         uint32 m_hiCorpseGuid;
 
-        uint32 m_hiPetNumber;
-
-        QuestMap mQuestTemplates;
+        QuestMap            mQuestTemplates;
 
         typedef UNORDERED_MAP<uint32, GossipText*> GossipTextMap;
@@ -849,4 +869,6 @@
         GameTeleMap         m_GameTeleMap;
 
+        ScriptNameMap       m_scriptNames;
+
         typedef             std::vector<LocaleConstant> LocalForIndex;
         LocalForIndex        m_LocalForIndex;
@@ -856,4 +878,5 @@
     private:
         void LoadScripts(ScriptMapMap& scripts, char const* tablename);
+        void CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids);
         void ConvertCreatureAddonAuras(CreatureDataAddon* addon, char const* table, char const* guidEntryStr);
         void LoadQuestRelationsHelper(QuestRelations& map,char const* table);
@@ -908,6 +931,8 @@
 
 // scripting access functions
-bool TRINITY_DLL_SPEC LoadTrinityStrings(DatabaseType& db, char const* table,int32 start_value = -1, int32 end_value = std::numeric_limits<int32>::min());
-TRINITY_DLL_SPEC const char* GetAreaTriggerScriptNameById(uint32 id);
+TRINITY_DLL_SPEC bool LoadTrinityStrings(DatabaseType& db, char const* table,int32 start_value = -1, int32 end_value = std::numeric_limits<int32>::min());
+TRINITY_DLL_SPEC uint32 GetAreaTriggerScriptId(uint32 trigger_id);
+TRINITY_DLL_SPEC uint32 GetScriptId(const char *name);
+TRINITY_DLL_SPEC ObjectMgr::ScriptNameMap& GetScriptNames();
 
 #endif
Index: trunk/src/game/Level2.cpp
===================================================================
--- trunk/src/game/Level2.cpp (revision 230)
+++ trunk/src/game/Level2.cpp (revision 260)
@@ -2362,6 +2362,6 @@
     // Check
     // Remember: "show" must also be the name of a column!
-    if( (show != "emote") && (show != "spell") && (show != "text1") && (show != "text2")
-        && (show != "text3") && (show != "text4") && (show != "text5")
+    if( (show != "emote") && (show != "spell") && (show != "textid1") && (show != "textid2")
+        && (show != "textid3") && (show != "textid4") && (show != "textid5")
         && (show != "waittime") && (show != "del") && (show != "move") && (show != "add")
         && (show != "model1") && (show != "model2") && (show != "orientation"))
@@ -2703,4 +2703,11 @@
         PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
         SetSentErrorMessage(true);
+        return false;
+    }
+
+    // set in game textids not supported
+    if( show == "textid1" || show == "textid2" || show == "textid3" ||
+        show == "textid4" || show == "textid5" )
+    {
         return false;
     }
@@ -2843,5 +2850,5 @@
 
         QueryResult *result =
-            WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, text1, text2, text3, text4, text5, model1, model2 FROM creature_movement WHERE wpguid = %u",
+            WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, model1, model2 FROM creature_movement WHERE wpguid = %u",
             target->GetGUIDLow() );
         if(!result)
@@ -2855,5 +2862,5 @@
             PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetGUID());
 
-            result = WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, text1, text2, text3, text4, text5, model1, model2 FROM creature_movement WHERE (abs(position_x - %f) <= %s ) and (abs(position_y - %f) <= %s ) and (abs(position_z - %f) <= %s )",
+            result = WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, model1, model2 FROM creature_movement WHERE (abs(position_x - %f) <= %s ) and (abs(position_y - %f) <= %s ) and (abs(position_z - %f) <= %s )",
                 target->GetPositionX(), maxDIFF, target->GetPositionY(), maxDIFF, target->GetPositionZ(), maxDIFF);
             if(!result)
@@ -2872,9 +2879,7 @@
             uint32 emote            = fields[3].GetUInt32();
             uint32 spell            = fields[4].GetUInt32();
-            const char * text1      = fields[5].GetString();
-            const char * text2      = fields[6].GetString();
-            const char * text3      = fields[7].GetString();
-            const char * text4      = fields[8].GetString();
-            const char * text5      = fields[9].GetString();
+            uint32 textid[MAX_WAYPOINT_TEXT];
+            for(int i = 0;  i < MAX_WAYPOINT_TEXT; ++i)
+                textid[i]           = fields[5+i].GetUInt32();
             uint32 model1           = fields[10].GetUInt32();
             uint32 model2           = fields[11].GetUInt32();
@@ -2889,9 +2894,6 @@
             PSendSysMessage(LANG_WAYPOINT_INFO_EMOTE, emote);
             PSendSysMessage(LANG_WAYPOINT_INFO_SPELL, spell);
-            PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 1, text1);
-            PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 2, text2);
-            PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 3, text3);
-            PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 4, text4);
-            PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 5, text5);
+            for(int i = 0;  i < MAX_WAYPOINT_TEXT; ++i)
+                PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, i+1, textid[i], (textid[i] ? GetTrinityString(textid[i]) : ""));
 
         }while( result->NextRow() );
@@ -3214,6 +3216,6 @@
 
     QueryResult *result = WorldDatabase.PQuery(
-    //          0      1           2           3           4            5       6       7         8      9      10     11     12     13     14     15
-        "SELECT point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, text1, text2, text3, text4, text5, id FROM creature_movement WHERE id = '%u' ORDER BY point", lowguid );
+    //          0      1           2           3           4            5       6       7         8      9      10       11       12       13       14       15
+        "SELECT point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, id FROM creature_movement WHERE id = '%u' ORDER BY point", lowguid );
 
     if (!result)
@@ -3232,5 +3234,5 @@
 
         outfile << "INSERT INTO creature_movement ";
-        outfile << "( id, point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, text1, text2, text3, text4, text5 ) VALUES ";
+        outfile << "( id, point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5 ) VALUES ";
 
         outfile << "( ";
@@ -3257,63 +3259,13 @@
         outfile << fields[9].GetUInt32();                   // spell
         outfile << ", ";
-        const char *tmpChar = fields[10].GetString();
-        if( !tmpChar )
-        {
-            outfile << "NULL";                              // text1
-        }
-        else
-        {
-            outfile << "'";
-            outfile << tmpChar;                             // text1
-            outfile << "'";
-        }
+        outfile << fields[10].GetUInt32();                  // textid1
         outfile << ", ";
-        tmpChar = fields[11].GetString();
-        if( !tmpChar )
-        {
-            outfile << "NULL";                              // text2
-        }
-        else
-        {
-            outfile << "'";
-            outfile << tmpChar;                             // text2
-            outfile << "'";
-        }
+        outfile << fields[11].GetUInt32();                  // textid2
         outfile << ", ";
-        tmpChar = fields[12].GetString();
-        if( !tmpChar )
-        {
-            outfile << "NULL";                              // text3
-        }
-        else
-        {
-            outfile << "'";
-            outfile << tmpChar;                             // text3
-            outfile << "'";
-        }
+        outfile << fields[12].GetUInt32();                  // textid3
         outfile << ", ";
-        tmpChar = fields[13].GetString();
-        if( !tmpChar )
-        {
-            outfile << "NULL";                              // text4
-        }
-        else
-        {
-            outfile << "'";
-            outfile << tmpChar;                             // text4
-            outfile << "'";
-        }
+        outfile << fields[13].GetUInt32();                  // textid4
         outfile << ", ";
-        tmpChar = fields[14].GetString();
-        if( !tmpChar )
-        {
-            outfile << "NULL";                              // text5
-        }
-        else
-        {
-            outfile << "'";
-            outfile << tmpChar;                             // text5
-            outfile << "'";
-        }
+        outfile << fields[14].GetUInt32();                  // textid5
         outfile << ");\n ";
 
Index: trunk/src/game/ItemPrototype.h
===================================================================
--- trunk/src/game/ItemPrototype.h (revision 257)
+++ trunk/src/game/ItemPrototype.h (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -100,5 +100,7 @@
     ITEM_FLAGS_USEABLE_IN_ARENA               = 0x00200000,
     ITEM_FLAGS_THROWABLE                      = 0x00400000, // not used in game for check trow possibility, only for item in game tooltip
-    ITEM_FLAGS_SPECIALUSE                     = 0x00800000  // last used flag in 2.3.0
+    ITEM_FLAGS_SPECIALUSE                     = 0x00800000, // last used flag in 2.3.0
+    ITEM_FLAGS_BOA                            = 0x08000000, // bind on account
+    ITEM_FLAGS_MILLABLE                       = 0x20000000
 };
 
@@ -107,7 +109,7 @@
     BAG_FAMILY_MASK_ARROWS                    = 0x00000001,
     BAG_FAMILY_MASK_BULLETS                   = 0x00000002,
-    BAG_FAMILY_MASK_SHARDS                    = 0x00000004,
+    BAG_FAMILY_MASK_SOUL_SHARDS               = 0x00000004,
     BAG_FAMILY_MASK_LEATHERWORKING_SUPP       = 0x00000008,
-    BAG_FAMILY_MASK_UNUSED                    = 0x00000010, // not used currently
+    BAG_FAMILY_MASK_INSCRIPTION_SUPP          = 0x00000010,
     BAG_FAMILY_MASK_HERBS                     = 0x00000020,
     BAG_FAMILY_MASK_ENCHANTING_SUPP           = 0x00000040,
@@ -117,10 +119,8 @@
     BAG_FAMILY_MASK_MINING_SUPP               = 0x00000400,
     BAG_FAMILY_MASK_SOULBOUND_EQUIPMENT       = 0x00000800,
-    BAG_FAMILY_MASK_VANITY_PETS               = 0x00001000
-};
-
-/* TODO: Not entirely positive on need for this??
-enum SOCKET_CONTENT ();
-*/
+    BAG_FAMILY_MASK_VANITY_PETS               = 0x00001000,
+    BAG_FAMILY_MASK_CURRENCY_TOKENS           = 0x00002000,
+    BAG_FAMILY_MASK_QUEST_ITEMS               = 0x00004000
+};
 
 enum SocketColor
@@ -276,5 +276,5 @@
 };
 
-#define MAX_ITEM_SUBCLASS_ARMOR                  10
+#define MAX_ITEM_SUBCLASS_ARMOR                   10
 
 enum ItemSubclassReagent
@@ -390,4 +390,20 @@
 
 #define MAX_ITEM_SUBCLASS_JUNK                    6
+
+enum ItemSubclassGlyph
+{
+    ITEM_SUBCLASS_GLYPH_WARRIOR                 = 1,
+    ITEM_SUBCLASS_GLYPH_PALADIN                 = 2,
+    ITEM_SUBCLASS_GLYPH_HUNTER                  = 3,
+    ITEM_SUBCLASS_GLYPH_ROGUE                   = 4,
+    ITEM_SUBCLASS_GLYPH_PRIEST                  = 5,
+    ITEM_SUBCLASS_GLYPH_DEATH_KNIGHT            = 6,
+    ITEM_SUBCLASS_GLYPH_SHAMAN                  = 7,
+    ITEM_SUBCLASS_GLYPH_MAGE                    = 8,
+    ITEM_SUBCLASS_GLYPH_WARLOCK                 = 9,
+    ITEM_SUBCLASS_GLYPH_DRUID                   = 11
+};
+
+#define MAX_ITEM_SUBCLASS_GLYPH                   12
 
 const uint32 MaxItemSubclassValues[MAX_ITEM_CLASS] =
@@ -525,5 +541,5 @@
     uint32 RequiredDisenchantSkill;
     float  ArmorDamageModifier;
-    char* ScriptName;
+    uint32 ScriptId;
     uint32 DisenchantID;
     uint32 FoodType;
Index: trunk/src/game/WaypointManager.h
===================================================================
--- trunk/src/game/WaypointManager.h (revision 206)
+++ trunk/src/game/WaypointManager.h (revision 260)
@@ -26,9 +26,10 @@
 #include "Utilities/UnorderedMap.h"
 
+#define MAX_WAYPOINT_TEXT 5
 struct WaypointBehavior
 {
     uint32 emote;
     uint32 spell;
-    std::string text[5];
+    int32  textid[MAX_WAYPOINT_TEXT];
     uint32 model1;
     uint32 model2;
Index: trunk/src/game/AuctionHouse.cpp
===================================================================
--- trunk/src/game/AuctionHouse.cpp (revision 229)
+++ trunk/src/game/AuctionHouse.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -90,6 +90,6 @@
         return false;
     }
-    data << auction->Id;
-    data << pItem->GetUInt32Value(OBJECT_FIELD_ENTRY);
+    data << (uint32) auction->Id;
+    data << (uint32) pItem->GetEntry();
 
     for (uint8 i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; i++)
@@ -246,5 +246,5 @@
         return;
     }
-    // prevent sending bag with items (cheat: can be placed in bag after adding equipped empty bag to auction)
+    // prevent sending bag with items (cheat: can be placed in bag after adding equiped empty bag to auction)
     if(!it)
     {
@@ -717,5 +717,5 @@
                                             if (il)
                                             {
-                                                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
+                                                if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty())
                                                     name = il->Name[loc_idx];
                                             }
Index: trunk/src/game/ObjectMgr.cpp
===================================================================
--- trunk/src/game/ObjectMgr.cpp (revision 230)
+++ trunk/src/game/ObjectMgr.cpp (revision 260)
@@ -11,10 +11,10 @@
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
@@ -22,4 +22,5 @@
 #include "Database/DatabaseEnv.h"
 #include "Database/SQLStorage.h"
+#include "Database/SQLStorageImpl.h"
 
 #include "Log.h"
@@ -117,6 +118,10 @@
     m_hiDoGuid          = 1;
     m_hiCorpseGuid      = 1;
-
     m_hiPetNumber       = 1;
+    m_ItemTextId        = 1;
+    m_mailid            = 1;
+    m_auctionid         = 1;
+    m_guildId           = 1;
+    m_arenaTeamId       = 1;
 
     mGuildBankTabPrice.resize(GUILD_BANK_MAX_TABS);
@@ -416,5 +421,5 @@
 
         //prepare mail data... :
-        uint32 itemTextId = this->CreateItemText( msgAuctionWonBody.str() );
+        uint32 itemTextId = CreateItemText( msgAuctionWonBody.str() );
 
         // set owner to bidder (to prevent delete item with sender char deleting)
@@ -467,5 +472,5 @@
         sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
 
-        uint32 itemTextId = this->CreateItemText( msgAuctionSalePendingBody.str() );
+        uint32 itemTextId = CreateItemText( msgAuctionSalePendingBody.str() );
 
         WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, auction->owner, msgAuctionSalePendingSubject.str(), itemTextId, NULL, 0, 0, MAIL_CHECK_MASK_AUCTION);
@@ -499,5 +504,5 @@
         sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
 
-        uint32 itemTextId = this->CreateItemText( auctionSuccessfulBody.str() );
+        uint32 itemTextId = CreateItemText( auctionSuccessfulBody.str() );
 
         uint32 profit = auction->bid + auction->deposit - auctionCut;
@@ -546,5 +551,4 @@
         // will delete item or place to receiver mail list
         WorldSession::SendMailTo(owner, MAIL_AUCTION, MAIL_STATIONERY_AUCTION, auction->location, GUID_LOPART(owner_guid), subject.str(), 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
-
     }
     // owner not found
@@ -564,6 +568,6 @@
 void ObjectMgr::LoadCreatureLocales()
 {
-    mCreatureLocaleMap.clear();
-    
+    mCreatureLocaleMap.clear();                              // need for reload case
+
     QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,subname_loc1,name_loc2,subname_loc2,name_loc3,subname_loc3,name_loc4,subname_loc4,name_loc5,subname_loc5,name_loc6,subname_loc6,name_loc7,subname_loc7,name_loc8,subname_loc8 FROM locales_creature");
 
@@ -624,5 +628,5 @@
     sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
 }
-
+   
 void ObjectMgr::LoadNpcOptionLocales()
 {
@@ -693,7 +697,17 @@
 }
 
+struct SQLCreatureLoader : public SQLStorageLoaderBase<SQLCreatureLoader>
+{
+    template<class D>
+    void convert_from_str(uint32 field_pos, char *src, D &dst)
+    {
+        dst = D(objmgr.GetScriptId(src));
+    }
+};
+
 void ObjectMgr::LoadCreatureTemplates()
 {
-    sCreatureStorage.Load();
+    SQLCreatureLoader loader;
+    loader.Load(sCreatureStorage);
 
     sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
@@ -1513,5 +1527,5 @@
         aItem->location = fields[11].GetUInt8();
         //check if sold item exists
-        if ( this->GetAItem( aItem->item_guidlow ) )
+        if ( GetAItem( aItem->item_guidlow ) )
         {
             GetAuctionsMap( aItem->location )->AddAuction(aItem);
@@ -1533,6 +1547,6 @@
 void ObjectMgr::LoadItemLocales()
 {
-    mItemLocaleMap.clear();
-    
+    mItemLocaleMap.clear();                                 // need for reload case
+
     QueryResult *result = WorldDatabase.Query("SELECT entry,name_loc1,description_loc1,name_loc2,description_loc2,name_loc3,description_loc3,name_loc4,description_loc4,name_loc5,description_loc5,name_loc6,description_loc6,name_loc7,description_loc7,name_loc8,description_loc8 FROM locales_item");
 
@@ -1595,7 +1609,17 @@
 }
 
+struct SQLItemLoader : public SQLStorageLoaderBase<SQLItemLoader>
+{
+    template<class D>
+    void convert_from_str(uint32 field_pos, char *src, D &dst)
+    {
+        dst = D(objmgr.GetScriptId(src));
+    }
+};
+
 void ObjectMgr::LoadItemPrototypes()
 {
-    sItemStorage.Load ();
+    SQLItemLoader loader;
+    loader.Load(sItemStorage);
     sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
     sLog.outString();
@@ -2507,5 +2531,5 @@
             if (sWorld.getConfig(CONFIG_EXPANSION) < 1 && (race == RACE_BLOODELF || race == RACE_DRAENEI))
                 continue;
-                
+
             // skip expansion classes if not playing with expansion
             if (sWorld.getConfig(CONFIG_EXPANSION) < 2 && class_ == CLASS_DEATH_KNIGHT)
@@ -3556,5 +3580,5 @@
 void ObjectMgr::LoadQuestLocales()
 {
-    mQuestLocaleMap.clear();
+    mQuestLocaleMap.clear();                                // need for reload case
 
     QueryResult *result = WorldDatabase.Query("SELECT entry,"
@@ -3750,5 +3774,5 @@
     scripts.clear();                                        // need for reload support
 
-    QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
+    QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
 
     uint32 count = 0;
@@ -3772,14 +3796,14 @@
         Field *fields = result->Fetch();
         ScriptInfo tmp;
-        tmp.id = fields[0].GetUInt32();
-        tmp.delay = fields[1].GetUInt32();
-        tmp.command = fields[2].GetUInt32();
-        tmp.datalong = fields[3].GetUInt32();
+        tmp.id        = fields[0].GetUInt32();
+        tmp.delay     = fields[1].GetUInt32();
+        tmp.command   = fields[2].GetUInt32();
+        tmp.datalong  = fields[3].GetUInt32();
         tmp.datalong2 = fields[4].GetUInt32();
-        tmp.datatext = fields[5].GetCppString();
-        tmp.x = fields[6].GetFloat();
-        tmp.y = fields[7].GetFloat();
-        tmp.z = fields[8].GetFloat();
-        tmp.o = fields[9].GetFloat();
+        tmp.dataint   = fields[5].GetInt32();
+        tmp.x         = fields[6].GetFloat();
+        tmp.y         = fields[7].GetFloat();
+        tmp.z         = fields[8].GetFloat();
+        tmp.o         = fields[9].GetFloat();
 
         // generic command args check
@@ -3793,4 +3817,16 @@
                     continue;
                 }
+                if(tmp.dataint==0)
+                {
+                    sLog.outErrorDb("Table `%s` has invalid talk text id (dataint = %i) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,tmp.id);
+                    continue;
+                }
+                if(tmp.dataint < MIN_DB_SCRIPT_STRING_ID || tmp.dataint >= MAX_DB_SCRIPT_STRING_ID)
+                {
+                    sLog.outErrorDb("Table `%s` has out of range text id (dataint = %i expected %u-%u) in SCRIPT_COMMAND_TALK for script id %u",tablename,tmp.dataint,MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID,tmp.id);
+                    continue;
+                }
+
+                // if(!objmgr.GetMangosStringLocale(tmp.dataint)) will checked after db_script_string loading
                 break;
             }
@@ -4157,6 +4193,6 @@
 void ObjectMgr::LoadPageTextLocales()
 {
-    mPageTextLocaleMap.clear();
-    
+    mPageTextLocaleMap.clear();                             // need for reload case
+
     QueryResult *result = WorldDatabase.Query("SELECT entry,text_loc1,text_loc2,text_loc3,text_loc4,text_loc5,text_loc6,text_loc7,text_loc8 FROM locales_page_text");
 
@@ -4207,7 +4243,17 @@
 }
 
+struct SQLInstanceLoader : public SQLStorageLoaderBase<SQLInstanceLoader>
+{
+    template<class D>
+    void convert_from_str(uint32 field_pos, char *src, D &dst)
+    {
+        dst = D(objmgr.GetScriptId(src));
+    }
+};
+
 void ObjectMgr::LoadInstanceTemplate()
 {
-    sInstanceTemplate.Load();
+    SQLInstanceLoader loader;
+    loader.Load(sInstanceTemplate);
 
     for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
@@ -4325,6 +4371,6 @@
 void ObjectMgr::LoadNpcTextLocales()
 {
-    mNpcTextLocaleMap.clear();
-    
+    mNpcTextLocaleMap.clear();                              // need for reload case
+
     QueryResult *result = WorldDatabase.Query("SELECT entry,"
         "Text0_0_loc1,Text0_1_loc1,Text1_0_loc1,Text1_1_loc1,Text2_0_loc1,Text2_1_loc1,Text3_0_loc1,Text3_1_loc1,Text4_0_loc1,Text4_1_loc1,Text5_0_loc1,Text5_1_loc1,Text6_0_loc1,Text6_1_loc1,Text7_0_loc1,Text7_1_loc1,"
@@ -4623,5 +4669,5 @@
 
         uint32 Trigger_ID      = fields[0].GetUInt32();
-        std::string scriptName = fields[1].GetCppString();
+        const char *scriptName = fields[1].GetString();
 
         AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
@@ -4631,5 +4677,5 @@
             continue;
         }
-        mAreaTriggerScripts[Trigger_ID] = scriptName;
+        mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
     } while( result->NextRow() );
 
@@ -4639,4 +4685,5 @@
     sLog.outString( ">> Loaded %u areatrigger scripts", count );
 }
+
 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
 {
@@ -4697,9 +4744,9 @@
 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
 {
-    uint32 mount_entry = 0;
-    uint32 mount_id = 0;
+    uint16 mount_entry = 0;
+    uint16 mount_id = 0;
 
     TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
-    if (node)
+    if(node)
     {
         if (team == ALLIANCE) mount_entry = node->alliance_mount_type;
@@ -4940,5 +4987,4 @@
     }
 
-            // find now nearest graveyard at same map
     if(entryNear)
         return entryNear;
@@ -5181,5 +5227,4 @@
     {
         m_hiCharGuid = (*result)[0].GetUInt32()+1;
-
         delete result;
     }
@@ -5189,15 +5234,9 @@
     {
         m_hiCreatureGuid = (*result)[0].GetUInt32()+1;
-
         delete result;
     }
 
-    result = CharacterDatabase.Query( "SELECT MAX(id) FROM character_pet" );
-    if( result )
-    {
-        m_hiPetGuid = (*result)[0].GetUInt32()+1;
-
-        delete result;
-    }
+    // pet guids are not saved to DB, set to 0 (pet guid != pet id)
+    m_hiPetGuid = 0;
 
     result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
@@ -5205,5 +5244,4 @@
     {
         m_hiItemGuid = (*result)[0].GetUInt32()+1;
-
         delete result;
     }
@@ -5219,5 +5257,4 @@
     {
         m_hiGoGuid = (*result)[0].GetUInt32()+1;
-
         delete result;
     }
@@ -5227,31 +5264,20 @@
     {
         m_auctionid = (*result)[0].GetUInt32()+1;
-
         delete result;
     }
-    else
-    {
-        m_auctionid = 0;
-    }
+
     result = CharacterDatabase.Query( "SELECT MAX(id) FROM mail" );
     if( result )
     {
         m_mailid = (*result)[0].GetUInt32()+1;
-
         delete result;
     }
-    else
-    {
-        m_mailid = 0;
-    }
+
     result = CharacterDatabase.Query( "SELECT MAX(id) FROM item_text" );
     if( result )
     {
-        m_ItemTextId = (*result)[0].GetUInt32();
-
+        m_ItemTextId = (*result)[0].GetUInt32()+1;
         delete result;
     }
-    else
-        m_ItemTextId = 0;
 
     result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
@@ -5259,40 +5285,70 @@
     {
         m_hiCorpseGuid = (*result)[0].GetUInt32()+1;
-
         delete result;
     }
+
+    result = CharacterDatabase.Query("SELECT MAX(arenateamid) FROM arena_team");
+    if (result)
+    {
+        m_arenaTeamId = (*result)[0].GetUInt32()+1;
+        delete result;
+    }
+
+    result = CharacterDatabase.Query( "SELECT MAX(guildid) FROM guild" );
+    if (result)
+    {
+        m_guildId = (*result)[0].GetUInt32()+1;
+        delete result;
+    }
+}
+
+uint32 ObjectMgr::GenerateArenaTeamId()
+{
+    if(m_arenaTeamId>=0xFFFFFFFE)
+    {
+        sLog.outError("Arena team ids overflow!! Can't continue, shutting down server. ");
+        World::StopNow(ERROR_EXIT_CODE);
+    }
+    return m_arenaTeamId++;
+}
+
+uint32 ObjectMgr::GenerateGuildId()
+{
+    if(m_guildId>=0xFFFFFFFE)
+    {
+        sLog.outError("Guild ids overflow!! Can't continue, shutting down server. ");
+        World::StopNow(ERROR_EXIT_CODE);
+    }
+    return m_guildId++;
 }
 
 uint32 ObjectMgr::GenerateAuctionID()
 {
-    ++m_auctionid;
-    if(m_auctionid>=0xFFFFFFFF)
+    if(m_auctionid>=0xFFFFFFFE)
     {
         sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
-        sWorld.m_stopEvent = true;
-    }
-    return m_auctionid;
+        World::StopNow(ERROR_EXIT_CODE);
+    }
+    return m_auctionid++;
 }
 
 uint32 ObjectMgr::GenerateMailID()
 {
-    ++m_mailid;
-    if(m_mailid>=0xFFFFFFFF)
+    if(m_mailid>=0xFFFFFFFE)
     {
         sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
-        sWorld.m_stopEvent = true;
-    }
-    return m_mailid;
+        World::StopNow(ERROR_EXIT_CODE);
+    }
+    return m_mailid++;
 }
 
 uint32 ObjectMgr::GenerateItemTextID()
 {
-    ++m_ItemTextId;
-    if(m_ItemTextId>=0xFFFFFFFF)
+    if(m_ItemTextId>=0xFFFFFFFE)
     {
         sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
-        sWorld.m_stopEvent = true;
-    }
-    return m_ItemTextId;
+        World::StopNow(ERROR_EXIT_CODE);
+    }
+    return m_ItemTextId++;
 }
 
@@ -5316,59 +5372,52 @@
     {
         case HIGHGUID_ITEM:
-            ++m_hiItemGuid;
-            if(m_hiItemGuid>=0xFFFFFFFF)
+            if(m_hiItemGuid>=0xFFFFFFFE)
             {
                 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
-                sWorld.m_stopEvent = true;
-            }
-            return m_hiItemGuid;
+                World::StopNow(ERROR_EXIT_CODE);
+            }
+            return m_hiItemGuid++;
         case HIGHGUID_UNIT:
-            ++m_hiCreatureGuid;
-            if(m_hiCreatureGuid>=0x00FFFFFF)
+            if(m_hiCreatureGuid>=0x00FFFFFE)
             {
                 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
-                sWorld.m_stopEvent = true;
-            }
-            return m_hiCreatureGuid;
+                World::StopNow(ERROR_EXIT_CODE);
+            }
+            return m_hiCreatureGuid++;
         case HIGHGUID_PET:
-            ++m_hiPetGuid;
-            if(m_hiPetGuid>=0x00FFFFFF)
+            if(m_hiPetGuid>=0x00FFFFFE)
             {
                 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
-                sWorld.m_stopEvent = true;
-            }
-            return m_hiPetGuid;
+                World::StopNow(ERROR_EXIT_CODE);
+            }
+            return m_hiPetGuid++;
         case HIGHGUID_PLAYER:
-            ++m_hiCharGuid;
-            if(m_hiCharGuid>=0xFFFFFFFF)
+            if(m_hiCharGuid>=0xFFFFFFFE)
             {
                 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
-                sWorld.m_stopEvent = true;
-            }
-            return m_hiCharGuid;
+                World::StopNow(ERROR_EXIT_CODE);
+            }
+            return m_hiCharGuid++;
         case HIGHGUID_GAMEOBJECT:
-            ++m_hiGoGuid;
-            if(m_hiGoGuid>=0x00FFFFFF)
+            if(m_hiGoGuid>=0x00FFFFFE)
             {
                 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
-                sWorld.m_stopEvent = true;
-            }
-            return m_hiGoGuid;
+                World::StopNow(ERROR_EXIT_CODE);
+            }
+            return m_hiGoGuid++;
         case HIGHGUID_CORPSE:
-            ++m_hiCorpseGuid;
-            if(m_hiCorpseGuid>=0xFFFFFFFF)
+            if(m_hiCorpseGuid>=0xFFFFFFFE)
             {
                 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
-                sWorld.m_stopEvent = true;
-            }
-            return m_hiCorpseGuid;
+                World::StopNow(ERROR_EXIT_CODE);
+            }
+            return m_hiCorpseGuid++;
         case HIGHGUID_DYNAMICOBJECT:
-            ++m_hiDoGuid;
-            if(m_hiDoGuid>=0xFFFFFFFF)
+            if(m_hiDoGuid>=0xFFFFFFFE)
             {
                 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
-                sWorld.m_stopEvent = true;
-            }
-            return m_hiDoGuid;
+                World::StopNow(ERROR_EXIT_CODE);
+            }
+            return m_hiDoGuid++;
         default:
             ASSERT(0);
@@ -5381,6 +5430,6 @@
 void ObjectMgr::LoadGameObjectLocales()
 {
-    mGameObjectLocaleMap.clear();
-    
+    mGameObjectLocaleMap.clear();                           // need for reload case
+
     QueryResult *result = WorldDatabase.Query("SELECT entry,"
         "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
@@ -5450,7 +5499,17 @@
 }
 
+struct SQLGameObjectLoader : public SQLStorageLoaderBase<SQLGameObjectLoader>
+{
+    template<class D>
+    void convert_from_str(uint32 field_pos, char *src, D &dst)
+    {
+        dst = D(objmgr.GetScriptId(src));
+    }
+};
+
 void ObjectMgr::LoadGameobjectInfo()
 {
-    sGOStorage.Load();
+    SQLGameObjectLoader loader;
+    loader.Load(sGOStorage);
 
     // some checks
@@ -6625,10 +6684,10 @@
 }
 
-const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
-{
-    AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
+uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
+{
+    AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
     if(i!= mAreaTriggerScripts.end())
-        return i->second.c_str();
-    return "";
+        return i->second;
+    return 0;
 }
 
@@ -6675,8 +6734,8 @@
             return false;
         }
-		case CONDITION_NO_AURA:
-			return !player->HasAura(value1, value2);
-		case CONDITION_ACTIVE_EVENT:
-			return gameeventmgr.IsActiveEvent(value1);
+        case CONDITION_NO_AURA:
+            return !player->HasAura(value1, value2);
+        case CONDITION_ACTIVE_EVENT:
+            return gameeventmgr.IsActiveEvent(value1);
         default:
             return false;
@@ -6799,28 +6858,28 @@
             break;
         }
-		case CONDITION_NO_AURA:
-		{
-			if(!sSpellStore.LookupEntry(value1))
-			{
-				sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
-				return false;
-			}
-			if(value2 > 2)
-			{
-				sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
-				return false;
-			}
-			break;
-		}
-		case CONDITION_ACTIVE_EVENT:
-		{
-			GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
-			if(value1 >=events.size() || !events[value1].isValid())
-			{
-				sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
-				return false;
-			}
-			break;
-		}
+        case CONDITION_NO_AURA:
+        {
+            if(!sSpellStore.LookupEntry(value1))
+            {
+                sLog.outErrorDb("Aura condition requires to have non existing spell (Id: %d), skipped", value1);
+                return false;
+            }
+            if(value2 > 2)
+            {
+                sLog.outErrorDb("Aura condition requires to have non existing effect index (%u) (must be 0..2), skipped", value2);
+                return false;
+            }
+            break;
+        }
+        case CONDITION_ACTIVE_EVENT:
+        {
+            GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
+            if(value1 >=events.size() || !events[value1].isValid())
+            {
+                sLog.outErrorDb("Active event condition requires existed event id (%u), skipped", value1);
+                return false;
+            }
+            break;
+        }
     }
     return true;
@@ -6952,5 +7011,5 @@
         if(itr->first > new_id)
             new_id = itr->first;
-    
+
     // use next
     ++new_id;
@@ -6992,5 +7051,5 @@
 void ObjectMgr::LoadTrainerSpell()
 {
-    // For reload case 
+    // For reload case
     for (CacheTrainerSpellMap::iterator itr = m_mCacheTrainerSpellMap.begin(); itr != m_mCacheTrainerSpellMap.end(); ++itr)
         itr->second.Clear();
@@ -7083,5 +7142,5 @@
 void ObjectMgr::LoadVendors()
 {
-    // For reload case 
+    // For reload case
     for (CacheVendorItemMap::iterator itr = m_mCacheVendorItemMap.begin(); itr != m_mCacheVendorItemMap.end(); ++itr)
         itr->second.Clear();
@@ -7190,4 +7249,5 @@
         "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
         "FROM npc_option");
+
     if( !result )
     {
@@ -7342,8 +7402,82 @@
 }
 
+void ObjectMgr::LoadScriptNames()
+{
+    m_scriptNames.push_back("");
+    QueryResult *result = WorldDatabase.Query(
+      "SELECT DISTINCT(ScriptName) FROM creature_template WHERE ScriptName <> '' "
+      "UNION "
+      "SELECT DISTINCT(ScriptName) FROM gameobject_template WHERE ScriptName <> '' "
+      "UNION "
+      "SELECT DISTINCT(ScriptName) FROM item_template WHERE ScriptName <> '' "
+      "UNION "
+      "SELECT DISTINCT(ScriptName) FROM areatrigger_scripts WHERE ScriptName <> '' "
+      "UNION "
+      "SELECT DISTINCT(script) FROM instance_template WHERE script <> ''");
+    if(result)
+    {
+        do
+        {
+            m_scriptNames.push_back((*result)[0].GetString());
+        } while (result->NextRow());
+        delete result;
+    }
+
+    std::sort(m_scriptNames.begin(), m_scriptNames.end());
+}
+
+uint32 ObjectMgr::GetScriptId(const char *name)
+{
+    // use binary search to find the script name in the sorted vector
+    // assume "" is the first element
+    if(!name) return 0;
+    ScriptNameMap::const_iterator itr =
+        std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name);
+    if(itr == m_scriptNames.end()) return 0;
+    return itr - m_scriptNames.begin();
+}
+
+void ObjectMgr::CheckScripts(ScriptMapMap const& scripts,std::set<int32>& ids)
+{
+    for(ScriptMapMap::const_iterator itrMM = scripts.begin(); itrMM != scripts.end(); ++itrMM)
+    {
+        for(ScriptMap::const_iterator itrM = itrMM->second.begin(); itrM != itrMM->second.end(); ++itrM)
+        {
+            if(itrM->second.dataint)
+            {
+                if(!GetTrinityStringLocale (itrM->second.dataint))
+                    sLog.outErrorDb( "Table `db_script_string` has not existed string id  %u", *itrM);
+
+                if(ids.count(itrM->second.dataint))
+                    ids.erase(itrM->second.dataint);
+            }
+        }
+    }
+}
+
+void ObjectMgr::LoadDbScriptStrings()
+{
+    LoadTrinityStrings(WorldDatabase,"db_script_string",MIN_DB_SCRIPT_STRING_ID,MAX_DB_SCRIPT_STRING_ID);
+
+    std::set<int32> ids;
+
+    for(int32 i = MIN_DB_SCRIPT_STRING_ID; i < MAX_DB_SCRIPT_STRING_ID; ++i)
+        if(GetTrinityStringLocale(i))
+            ids.insert(i);
+
+    CheckScripts(sQuestEndScripts,ids);
+    CheckScripts(sQuestStartScripts,ids);
+    CheckScripts(sSpellScripts,ids);
+    CheckScripts(sGameObjectScripts,ids);
+    CheckScripts(sEventScripts,ids);
+
+    for(std::set<int32>::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
+        sLog.outErrorDb( "Table `db_script_string` has unused string id  %u", *itr);
+}
+
 // Functions for scripting access
-const char* GetAreaTriggerScriptNameById(uint32 id)
-{
-    return objmgr.GetAreaTriggerScriptName(id);
+uint32 GetAreaTriggerScriptId(uint32 trigger_id)
+{
+    return objmgr.GetAreaTriggerScriptId(trigger_id);
 }
 
@@ -7360,2 +7494,12 @@
     return objmgr.LoadTrinityStrings(db,table,end_value,start_value);
 }
+
+uint32 TRINITY_DLL_SPEC GetScriptId(const char *name)
+{
+    return objmgr.GetScriptId(name);
+}
+
+ObjectMgr::ScriptNameMap & GetScriptNames()
+{
+    return objmgr.GetScriptNames();
+}
