Index: trunk/src/game/SpellEffects.cpp
===================================================================
--- trunk/src/game/SpellEffects.cpp (revision 257)
+++ trunk/src/game/SpellEffects.cpp (revision 272)
@@ -334,24 +334,11 @@
                         break;
                     }
-                    // must only affect demons (also undead?)
+                    // must only affect demons
                     case 45072:
                     {
-                        if(unitTarget->GetCreatureType() != CREATURE_TYPE_DEMON
-                            || unitTarget->GetCreatureType() != CREATURE_TYPE_UNDEAD)
+                        if(unitTarget->GetCreatureType() != CREATURE_TYPE_DEMON)
                             return;
                         break;
                     }
-                    // gruul's shatter
-                    case 33671:
-                    {
-                        // don't damage self and only players
-                        if(unitTarget->GetGUID() == m_caster->GetGUID() || unitTarget->GetTypeId() != TYPEID_PLAYER)
-                            return;
-
-                        float radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[0]));
-                        if(!radius) return;
-                        float distance = m_caster->GetDistance2d(unitTarget);
-                        damage = (distance > radius ) ? 0 : (int32)(m_spellInfo->EffectBasePoints[0]*((radius - distance)/radius));
-                    }break;
                 }
                 break;
@@ -1172,5 +1159,5 @@
                     m_caster->CastSpell(m_caster, 45009, true);
                     return;
-                }
+                }                
                 case 45030:                                 // Impale Emissary
                 {
@@ -1275,5 +1262,5 @@
                         //Polymorph Cast Visual Rank 1
                         const uint32 spell_list[6] = {32813, 32816, 32817, 32818, 32819, 32820};
-                        unitTarget->CastSpell( unitTarget, spell_list[urand(0, 5)], true);
+                        unitTarget->CastSpell( unitTarget, spell_list[urand(0, 5)], true); 
                     }
                     return;
@@ -2251,5 +2238,5 @@
         m_caster->ModifyPower(POWER_MANA,gain);
         //send log
-        m_caster->SendEnergizeSpellLog(m_caster, m_spellInfo->Id,gain,POWER_MANA);
+        m_caster->SendEnergizeSpellLog(m_caster, m_spellInfo->Id,gain,POWER_MANA,false);
     }
 }
@@ -2267,5 +2254,5 @@
                     /*do not uncomment .
                     if(bg->GetTypeID()==BATTLEGROUND_WS)
-                        bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
+                        bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
                     sLog.outDebug("Send Event Horde Flag Picked Up");
                     break;
@@ -2280,5 +2267,5 @@
                     /*do not uncomment ... (it will cause crash, because of null targetobject!) anyway this is a bad way to call that event, because it would cause recursion
                     if(bg->GetTypeID()==BATTLEGROUND_WS)
-                        bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
+                        bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
                     sLog.outDebug("Send Event Alliance Flag Picked Up");
                     break;
@@ -2291,10 +2278,10 @@
                     case 23385:                                 // Alliance Flag Returns
                         if(bg->GetTypeID()==BATTLEGROUND_WS)
-                            bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
+                            bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
                         sLog.outDebug("Alliance Flag Returned");
                         break;
                     case 23386:                                   // Horde Flag Returns
                         if(bg->GetTypeID()==BATTLEGROUND_WS)
-                            bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
+                            bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
                         sLog.outDebug("Horde Flag Returned");
                         break;*/
@@ -2302,5 +2289,5 @@
                     /*
                     if(bg->GetTypeID()==BATTLEGROUND_EY)
-                        bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
+                        bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
                     */
                     break;
@@ -2651,5 +2638,4 @@
     float radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i]));
     Unit *caster = m_originalCasterGUID ? m_originalCaster : m_caster;
-    if(!caster) return;
 
     if(Player* modOwner = caster->GetSpellModOwner())
@@ -2681,5 +2667,5 @@
 
     // Some level depends spells
-    int multiplier = 0;
+    int multiplier  = 0;
     int level_diff = 0;
     switch (m_spellInfo->Id)
@@ -2688,15 +2674,15 @@
         case 9512:
             level_diff = m_caster->getLevel() - 40;
-            multiplier = 2;
+            multiplier  = 2;
             break;
         // Blood Fury
         case 24571:
             level_diff = m_caster->getLevel() - 60;
-            multiplier = 10;
+            multiplier  = 10;
             break;
         // Burst of Energy
         case 24532:
             level_diff = m_caster->getLevel() - 60;
-            multiplier = 4;
+            multiplier  = 4;
             break;
         default:
@@ -3760,5 +3746,5 @@
         ((Player*)unitTarget)->TeleportTo(mapid, fx, fy, fz, -m_caster->GetOrientation(), TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (unitTarget==m_caster ? TELE_TO_SPELL : 0));
     else
-        m_caster->GetMap()->CreatureRelocation((Creature*)m_caster, fx, fy, fz, -m_caster->GetOrientation());
+        MapManager::Instance().GetMap(mapid, m_caster)->CreatureRelocation((Creature*)m_caster, fx, fy, fz, -m_caster->GetOrientation());
 }
 
@@ -3781,5 +3767,5 @@
         return;
 
-    sLog.outDebug("SpellEffect::AddHonor called for spell_id %u , that rewards %d honor points to player: %u", m_spellInfo->Id, damage, ((Player*)unitTarget)->GetGUIDLow());
+    sLog.outDebug("SpellEffect::AddHonor called for spell_id %u , that rewards %d honor points to player: %u", m_spellInfo->Id, this->damage, ((Player*)unitTarget)->GetGUIDLow());
 
     // TODO: find formula for honor reward based on player's level!
@@ -3787,5 +3773,5 @@
     // now fixed only for level 70 players:
     if (((Player*)unitTarget)->getLevel() == 70)
-        ((Player*)unitTarget)->RewardHonor(NULL, 1, damage);
+        ((Player*)unitTarget)->RewardHonor(NULL, 1, this->damage);
 }
 
@@ -4002,5 +3988,5 @@
 
     // add to world
-    pet->GetMap()->Add((Creature*)pet);
+    MapManager::Instance().GetMap(pet->GetMapId(), pet)->Add((Creature*)pet);
 
     // visual effect for levelup
@@ -4032,5 +4018,5 @@
                 return;
 
-            OldSummon->GetMap()->Remove((Creature*)OldSummon,false);
+            MapManager::Instance().GetMap(OldSummon->GetMapId(), OldSummon)->Remove((Creature*)OldSummon,false);
             OldSummon->SetMapId(m_caster->GetMapId());
 
@@ -4039,5 +4025,5 @@
 
             OldSummon->Relocate(px, py, pz, OldSummon->GetOrientation());
-            m_caster->GetMap()->Add((Creature*)OldSummon);
+            MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster)->Add((Creature*)OldSummon);
 
             if(m_caster->GetTypeId() == TYPEID_PLAYER && OldSummon->isControlled() )
@@ -4122,8 +4108,8 @@
     if(m_caster->GetTypeId() == TYPEID_UNIT)
     {
-        if ( ((Creature*)m_caster)->isTotem() )
-            NewSummon->GetCharmInfo()->SetReactState(REACT_AGGRESSIVE);
-        else
-            NewSummon->GetCharmInfo()->SetReactState(REACT_DEFENSIVE);
+		if ( ((Creature*)m_caster)->isTotem() )
+			NewSummon->GetCharmInfo()->SetReactState(REACT_AGGRESSIVE);
+		else
+			NewSummon->GetCharmInfo()->SetReactState(REACT_DEFENSIVE);
     }
 
@@ -4447,5 +4433,4 @@
             ((Player*)m_caster)->AddComboPoints(unitTarget, 1);
     }
-
     // Mangle (Cat): CP
     if(m_spellInfo->SpellFamilyName==SPELLFAMILY_DRUID && (m_spellInfo->SpellFamilyFlags==0x0000040000000000LL))
@@ -4454,4 +4439,5 @@
             ((Player*)m_caster)->AddComboPoints(unitTarget,1);
     }
+
 
     // take ammo
@@ -5449,5 +5435,5 @@
 }
 
-void Spell::EffectResurrect(uint32 /*effIndex*/)
+void Spell::EffectResurrect(uint32 i)
 {
     if(!unitTarget)
@@ -5670,5 +5656,5 @@
     int32 targetLevel = creature->getLevel();
 
-    uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill();
+    uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill(); 
 
     ((Player*)m_caster)->SendLoot(creature->GetGUID(),LOOT_SKINNING);
@@ -5697,5 +5683,5 @@
 
     if(m_caster->GetTypeId() != TYPEID_PLAYER)
-        m_caster->GetMap()->CreatureRelocation((Creature*)m_caster,x,y,z,m_caster->GetOrientation());
+        MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster)->CreatureRelocation((Creature*)m_caster,x,y,z,m_caster->GetOrientation());
 
     // not all charge effects used in negative spells
@@ -6133,5 +6119,5 @@
             linkedGO->SetOwnerGUID(m_caster->GetGUID() );
 
-            linkedGO->GetMap()->Add(linkedGO);
+            MapManager::Instance().GetMap(linkedGO->GetMapId(), linkedGO)->Add(linkedGO);
         }
         else
Index: trunk/src/game/Bag.cpp
===================================================================
--- trunk/src/game/Bag.cpp (revision 260)
+++ trunk/src/game/Bag.cpp (revision 272)
@@ -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 );
 
-    SetEntry(itemid);
+    SetUInt32Value(OBJECT_FIELD_ENTRY, itemid);
     SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
 
@@ -86,5 +86,5 @@
     SetUInt32Value(CONTAINER_FIELD_NUM_SLOTS, itemProto->ContainerSlots);
 
-    // Cleaning 20 slots
+    // Cleanning 20 slots
     for (uint8 i = 0; i < MAX_BAG_SIZE; i++)
     {
@@ -214,5 +214,4 @@
             if(m_bagslot[i]->GetGUID() == guid)
                 return i;
-
     return NULL_SLOT;
 }
@@ -222,5 +221,5 @@
     if( slot < GetBagSize() )
         return m_bagslot[slot];
-
+        
     return NULL;
 }
Index: trunk/src/game/Level3.cpp
===================================================================
--- trunk/src/game/Level3.cpp (revision 260)
+++ trunk/src/game/Level3.cpp (revision 272)
@@ -136,5 +136,4 @@
     HandleReloadSpellScriptsCommand("a");
     SendGlobalSysMessage("DB tables `*_scripts` reloaded.");
-    HandleReloadDbScriptStringCommand("a");
     return true;
 }
@@ -600,12 +599,4 @@
         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;
 }
@@ -1777,6 +1768,5 @@
         // search highest talent rank
         uint32 spellid = 0;
-        int rank = 4;
-        for(; rank >= 0; --rank)
+        for(int rank = 4; rank >= 0; --rank)
         {
             if(talentInfo->RankID[rank]!=0)
@@ -4656,147 +4646,89 @@
 }
 
-bool ChatHandler::HandleServerShutDownCancelCommand(const char* args)
-{
-    sWorld.ShutdownCancel();
-    return true;
-}
-
-bool ChatHandler::HandleServerShutDownCommand(const char* args)
+bool ChatHandler::HandleShutDownCommand(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'))
+    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;
 
-        // 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)
+        sWorld.ShutdownServ(time);
+    }
+    return true;
+}
+
+bool ChatHandler::HandleRestartCommand(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, 0, exitcode);
+        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();
     }
     else
-        sWorld.ShutdownServ(time,0,SHUTDOWN_EXIT_CODE);
-    return true;
-}
-
-bool ChatHandler::HandleServerRestartCommand(const char* args)
+    {
+        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;
 
-    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'))
+    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;
 
-        // 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;
-
-    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
-        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;
-
-        // 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
-        sWorld.ShutdownServ(time,SHUTDOWN_MASK_IDLE,SHUTDOWN_EXIT_CODE);
+        sWorld.ShutdownServ(time,SHUTDOWN_MASK_IDLE);
+    }
     return true;
 }
Index: trunk/src/game/WaypointMovementGenerator.cpp
===================================================================
--- trunk/src/game/WaypointMovementGenerator.cpp (revision 263)
+++ trunk/src/game/WaypointMovementGenerator.cpp (revision 272)
@@ -22,9 +22,9 @@
 creature_movement Table
 
-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 `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 `emote` int(10) unsigned default '0';
 alter table creature_movement add `spell` int(5) unsigned default '0';
@@ -149,19 +149,20 @@
                 if(behavior->model1 != 0)
                     creature.SetDisplayId(behavior->model1);
-                if(behavior->textid[0])
+                if(!behavior->text[0].empty())
                 {
-                    // Not only one text is set
-                    if( behavior->textid[1] )
+                    // Only one text is set
+                    if( !behavior->text[1].empty() )
                     {
                         // Select one from max 5 texts (0 and 1 already checked)
                         int i = 2;
-                        for( ; i < MAX_WAYPOINT_TEXT; ++i )
-                            if( !behavior->textid[i] )
+                        for( ; i < 5; ++i )
+                            if( behavior->text[i].empty() )
                                 break;
 
-                        creature.Say(behavior->textid[rand() % i], 0, 0);
+                        creature.Say(behavior->text[rand() % i].c_str(), 0, 0);
+
                     }
                     else
-                        creature.Say(behavior->textid[0], 0, 0);
+                        creature.Say(behavior->text[0].c_str(), 0, 0);
                 }
             }                                               // wpBehaviour found
Index: trunk/src/game/GameObject.h
===================================================================
--- trunk/src/game/GameObject.h (revision 260)
+++ trunk/src/game/GameObject.h (revision 272)
@@ -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;
     };
-    uint32 ScriptId;
+    char   *ScriptName;
 };
 
Index: trunk/src/game/Object.h
===================================================================
--- trunk/src/game/Object.h (revision 268)
+++ trunk/src/game/Object.h (revision 272)
@@ -456,5 +456,5 @@
         GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime);
         bool isActive() const { return m_isActive; }
-        void setActive(bool isActive);
+        virtual void setActive(bool isActive);
     protected:
         explicit WorldObject();
Index: trunk/src/game/CreatureAIImpl.h
===================================================================
--- trunk/src/game/CreatureAIImpl.h (revision 260)
+++ trunk/src/game/CreatureAIImpl.h (revision 272)
@@ -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 267)
+++ trunk/src/game/SpellHandler.cpp (revision 272)
@@ -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,10 +55,4 @@
     }
 
-    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());
 
@@ -244,5 +238,5 @@
 
             pItem->SetUInt64Value(ITEM_FIELD_GIFTCREATOR, 0);
-            pItem->SetEntry(entry);
+            pItem->SetUInt32Value(OBJECT_FIELD_ENTRY, entry);
             pItem->SetUInt32Value(ITEM_FIELD_FLAGS, flags);
             pItem->SetState(ITEM_CHANGED, pUser);
@@ -266,4 +260,5 @@
 
     uint64 guid;
+    uint32 spellId = OPEN_CHEST;
 
     recv_data >> guid;
@@ -328,5 +323,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);
 }
@@ -369,9 +364,8 @@
                 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_BIND_SIGHT)
             {
-                // Fix me: creature may be killed during player aura cancel
                 _player->RemoveAurasDueToSpellByCancel(spellId);
                 if (_player->GetCharm())
                     _player->GetCharm()->RemoveAurasDueToSpellByCancel(spellId);
-                else if (_player->GetFarsightTarget() && _player->GetFarsightTarget()->GetTypeId() != TYPEID_DYNAMICOBJECT)
+                else if (_player->GetFarsightTarget()->GetTypeId() != TYPEID_DYNAMICOBJECT)
                     ((Unit*)_player->GetFarsightTarget())->RemoveAurasDueToSpellByCancel(spellId);
                 return;
Index: trunk/src/game/MapManager.h
===================================================================
--- trunk/src/game/MapManager.h (revision 260)
+++ trunk/src/game/MapManager.h (revision 272)
@@ -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,5 +28,4 @@
 #include "Map.h"
 #include "GridStates.h"
-
 class Transport;
 
@@ -46,5 +45,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);
+        void DeleteInstance(uint32 mapid, uint32 instanceId, uint8 mode);
 
         inline uint16 GetAreaFlag(uint32 mapid, float x, float y) const
Index: trunk/src/game/Chat.cpp
===================================================================
--- trunk/src/game/Chat.cpp (revision 260)
+++ trunk/src/game/Chat.cpp (revision 272)
@@ -64,42 +64,14 @@
     };
 
-    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,  NULL,                                           "", serverIdleRestartCommandTable },
-        { "idleshutdown",   SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverShutdownCommandTable },
+        { "idlerestart",    SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleIdleRestartCommand,         "", NULL },
+        { "idleshutdown",   SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleIdleShutDownCommand,        "", NULL },
         { "info",           SEC_PLAYER,         true,  &ChatHandler::HandleServerInfoCommand,          "", NULL },
         { "motd",           SEC_PLAYER,         true,  &ChatHandler::HandleServerMotdCommand,          "", NULL },
-        { "restart",        SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverRestartCommandTable },
-        { "shutdown",       SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverShutdownCommandTable },
+        { "restart",        SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleRestartCommand,             "", NULL },
+        { "shutdown",       SEC_ADMINISTRATOR,  true,  &ChatHandler::HandleShutDownCommand,            "", NULL },
         { "set",            SEC_ADMINISTRATOR,  true,  NULL,                                           "", serverSetCommandTable },
         { NULL,             0,                  false, NULL,                                           "", NULL }
Index: trunk/src/game/ItemEnchantmentMgr.cpp
===================================================================
--- trunk/src/game/ItemEnchantmentMgr.cpp (revision 260)
+++ trunk/src/game/ItemEnchantmentMgr.cpp (revision 272)
@@ -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 268)
+++ trunk/src/game/Map.h (revision 272)
@@ -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
  */
 
@@ -34,5 +34,4 @@
 #include "SharedDefines.h"
 #include "GameSystem/GridRefManager.h"
-#include "MapRefManager.h"
 
 #include <bitset>
@@ -106,5 +105,5 @@
     float startLocZ;
     float startLocO;
-    uint32 script_id;
+    char const* script;
 };
 
@@ -128,5 +127,4 @@
 class TRINITY_DLL_SPEC Map : public GridRefManager<NGridType>, public Trinity::ObjectLevelLockable<Map, ZThread::Mutex>
 {
-    friend class MapReference;
     public:
         Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode);
@@ -240,16 +238,4 @@
         GameObject* GetGameObjectInMap(uint64 guid);
 
-        bool HavePlayers() const { return !m_mapRefManager.isEmpty(); }
-        uint32 GetPlayersCountExceptGMs() const;
-        bool PlayersNearGrid(uint32 x,uint32 y) const;
-        bool ActiveObjectsNearGrid(uint32 x, uint32 y) const;
-
-        void AddActiveObject(WorldObject* obj) { i_activeObjects.insert(obj); }
-        void RemoveActiveObject(WorldObject* obj) { i_activeObjects.erase(obj); }
-
-        void SendToPlayers(WorldPacket const* data) const;
-
-        typedef MapRefManager PlayerList;
-        PlayerList const& GetPlayers() const { return m_mapRefManager; }
         template<class T> void SwitchGridContainers(T* obj, bool active);
     private:
@@ -292,5 +278,4 @@
         inline void setNGrid(NGridType* grid, uint32 x, uint32 y);
 
-        void UpdateActiveCells(const float &x, const float &y, const uint32 &t_diff);
     protected:
         typedef Trinity::ObjectLevelLockable<Map, ZThread::Mutex>::Lock Guard;
@@ -302,5 +287,4 @@
         uint32 m_unloadTimer;
 
-        MapRefManager m_mapRefManager;
     private:
         typedef GridReadGuard ReadGuard;
@@ -313,5 +297,4 @@
         time_t i_gridExpiry;
 
-        std::set<WorldObject *> i_activeObjects;
         std::set<WorldObject *> i_objectsToRemove;
 
@@ -343,4 +326,6 @@
 {
     public:
+        typedef std::list<Player *> PlayerList;                 // online players only
+
         InstanceMap(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode);
         ~InstanceMap();
@@ -350,11 +335,15 @@
         void CreateInstanceData(bool load);
         bool Reset(uint8 method);
-        uint32 GetScriptId() { return i_script_id; }
+        std::string GetScript() { return i_script; }
         InstanceData* GetInstanceData() { return i_data; }
         void PermBindAllPlayers(Player *player);
+        PlayerList const& GetPlayers() const { return i_Players;}
+        void SendToPlayers(WorldPacket const* data) const;
         time_t GetResetTime();
         void UnloadAll(bool pForce);
         bool CanEnter(Player* player);
-        void SendResetWarnings(uint32 timeLeft) const;
+        uint32 GetPlayersCountExceptGMs() const;
+        uint32 HavePlayers() const { return !i_Players.empty(); }
+        void SendResetWarnings(uint32 timeLeft);
         void SetResetSchedule(bool on);
     private:
@@ -362,5 +351,8 @@
         bool m_unloadWhenEmpty;
         InstanceData* i_data;
-        uint32 i_script_id;
+        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;
 };
 
@@ -368,4 +360,6 @@
 {
     public:
+        typedef std::list<Player *> PlayerList;                 // online players only
+
         BattleGroundMap(uint32 id, time_t, uint32 InstanceId);
         ~BattleGroundMap();
@@ -376,4 +370,6 @@
         void SetUnload();
         void UnloadAll(bool pForce);
+    private:
+        PlayerList i_Players;
 };
 
Index: trunk/src/game/ObjectAccessor.h
===================================================================
--- trunk/src/game/ObjectAccessor.h (revision 268)
+++ trunk/src/game/ObjectAccessor.h (revision 272)
@@ -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
  */
 
@@ -187,5 +187,4 @@
 
         void Update(uint32 diff);
-        void UpdatePlayers(uint32 diff);
 
         Corpse* GetCorpseForPlayerGUID(uint64 guid);
@@ -195,4 +194,6 @@
         Corpse* ConvertCorpseForPlayer(uint64 player_guid);
 
+        bool ActiveObjectsNearGrid(uint32 x,uint32 y,uint32 m_id,uint32 i_id) const;
+
         static void UpdateObject(Object* obj, Player* exceptPlayer);
         static void _buildUpdateObject(Object* obj, UpdateDataMapType &);
@@ -200,4 +201,7 @@
         static void UpdateObjectVisibility(WorldObject* obj);
         static void UpdateVisibilityForPlayer(Player* player);
+
+        void AddActiveObject(WorldObject*);
+        void RemoveActiveObject(WorldObject*);
     private:
         struct WorldObjectChangeAccumulator
@@ -224,4 +228,5 @@
         void _update(void);
         std::set<Object *> i_objects;
+        std::set<WorldObject *> i_activeobjects;
         LockType i_playerGuard;
         LockType i_updateGuard;
Index: trunk/src/game/WaypointManager.cpp
===================================================================
--- trunk/src/game/WaypointManager.cpp (revision 263)
+++ trunk/src/game/WaypointManager.cpp (revision 272)
@@ -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,5 +25,4 @@
 #include "ProgressBar.h"
 #include "MapManager.h"
-#include "ObjectMgr.h"
 
 INSTANTIATE_SINGLETON_1(WaypointManager);
@@ -31,22 +30,13 @@
 bool WaypointBehavior::isEmpty()
 {
-    if (emote || spell || model1 || model2)
-        return false;
-
-    for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
-        if(textid[i])
-            return false;
-
-    return true;
+    return emote == 0 && spell == 0 && model1 == 0 && model2 == 0 && text[0].empty() &&
+        text[1].empty() && text[2].empty() && text[3].empty() && text[4].empty();
 }
 
 WaypointBehavior::WaypointBehavior(const WaypointBehavior &b)
 {
-    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];
+    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];
 }
 
@@ -77,5 +67,5 @@
     }
 
-    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");
+    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");
     if(result)
     {
@@ -124,31 +114,9 @@
             be.emote            = fields[7].GetUInt32();
             be.spell            = fields[8].GetUInt32();
-
-            // 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;
+            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();
 
             // save memory by not storing empty behaviors
@@ -298,9 +266,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/GridNotifiers.h
===================================================================
--- trunk/src/game/GridNotifiers.h (revision 267)
+++ trunk/src/game/GridNotifiers.h (revision 272)
@@ -699,38 +699,17 @@
     // Creature checks
 
-    class NearestHostileUnitInAttackDistanceCheck
-    {
-        public:
-            explicit NearestHostileUnitInAttackDistanceCheck(Creature const* creature, float dist = 0) : m_creature(creature) 
-            {
-                m_range = (dist == 0 ? 9999 : dist);
-                m_force = (dist == 0 ? false : true);
-            }
-            bool operator()(Unit* u)
-            {
-                // TODO: addthreat for every enemy in range?
-                if(!m_creature->IsWithinDistInMap(u, m_range))
-                    return false;
-
-                if(m_force)
-                {
-                    if(!m_creature->canAttack(u))
-                        return false;
-                }
-                else
-                {
-                    if(!m_creature->canStartAttack(u))
-                        return false;
-                }
-
-                m_range = m_creature->GetDistance(u);
-                return true;
-            }
-            float GetLastRange() const { return m_range; }
-        private:
-            Creature const *m_creature;
-            float m_range;
-            bool m_force;
-            NearestHostileUnitInAttackDistanceCheck(NearestHostileUnitInAttackDistanceCheck const&);
+    class InAttackDistanceFromAnyHostileCreatureCheck
+    {
+        public:
+            explicit InAttackDistanceFromAnyHostileCreatureCheck(Unit* funit) : i_funit(funit) {}
+            bool operator()(Creature* u)
+            {
+                if(u->isAlive() && u->IsHostileTo(i_funit) && i_funit->IsWithinDistInMap(u, u->GetAttackDistance(i_funit)))
+                    return true;
+
+                return false;
+            }
+        private:
+            Unit* const i_funit;
     };
 
Index: trunk/src/game/StatSystem.cpp
===================================================================
--- trunk/src/game/StatSystem.cpp (revision 257)
+++ trunk/src/game/StatSystem.cpp (revision 272)
@@ -385,5 +385,5 @@
         weapon_maxdamage = lvl*1.25*att_speed;
     }
-    else if(!IsUseEquipedWeapon(attType==BASE_ATTACK))      //check if player not in form but still can't use weapon (broken/etc)
+    else if(!IsUseEquippedWeapon(attType==BASE_ATTACK))      //check if player not in form but still can't use weapon (broken/etc)
     {
         weapon_mindamage = BASE_MINDAMAGE;
Index: trunk/src/game/GMTicketMgr.h
===================================================================
--- trunk/src/game/GMTicketMgr.h (revision 263)
+++ trunk/src/game/GMTicketMgr.h (revision 272)
@@ -51,8 +51,5 @@
             m_text = text ? text : "";
             m_lastUpdate = time(NULL);
-
-            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);
+            CharacterDatabase.PExecute("UPDATE character_ticket SET ticket_text = '%s' WHERE guid = '%u'", m_text.c_str(), m_guid);
         }
 
@@ -66,9 +63,5 @@
             CharacterDatabase.BeginTransaction();
             DeleteFromDB();
-
-            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.PExecute("INSERT INTO character_ticket (guid, ticket_text) VALUES ('%u', '%s')", m_guid, GetText());
             CharacterDatabase.CommitTransaction();
         }
Index: trunk/src/game/Unit.h
===================================================================
--- trunk/src/game/Unit.h (revision 266)
+++ trunk/src/game/Unit.h (revision 272)
@@ -16,5 +16,5 @@
  * 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
  */
 
@@ -763,5 +763,5 @@
         void CombatStop(bool cast = false);
         void CombatStopWithPets(bool cast = false);
-        Unit* SelectNearbyTarget(float dist = ATTACK_DISTANCE) const;
+        Unit* SelectNearbyTarget() const;
 
         void addUnitState(uint32 f) { m_state |= f; }
@@ -934,5 +934,5 @@
 
         void SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical = false);
-        void SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage,Powers powertype);
+        void SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage,Powers powertype, bool critical = false);
         uint32 SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell = false, bool useSpellDamage = true);
         void CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem = NULL, Aura* triggeredByAura = NULL, uint64 originalCaster = 0);
@@ -1040,5 +1040,4 @@
         void RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer);
         void RemoveAurasDueToSpellByCancel(uint32 spellId);
-        void RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo);
         void RemoveNotOwnSingleTargetAuras();
 
@@ -1372,10 +1371,8 @@
 
         void ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, AuraTypeSet const& procAuraTypes, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage, SpellSchoolMask damageSchoolMask );
-        bool IsTriggeredAtSpellProcEvent( SpellEntry const* spellProto, SpellEntry const* procSpell, uint32 procFlag, WeaponAttackType attType, bool isVictim, uint32& cooldown );
-        bool HandleDummyAuraProc(   Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 cooldown);
-        bool HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, WeaponAttackType attType, uint32 cooldown);
-        bool HandleHasteAuraProc(   Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 procFlag, uint32 cooldown);
-        bool HandleOverrideClassScriptAuraProc(Unit *pVictim, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 cooldown);
-        bool HandleMeandingAuraProc(Aura* triggeredByAura);
+        bool HandleDummyAuraProc(Unit *pVictim, SpellEntry const *spellProto, uint32 effIndex, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag,uint32 cooldown);
+        bool HandleProcTriggerSpell(Unit *pVictim,uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags,WeaponAttackType attType,uint32 cooldown);
+        bool HandleHasteAuraProc(Unit *pVictim, SpellEntry const *spellProto, uint32 effIndex, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag,uint32 cooldown);
+        bool HandleOverrideClassScriptAuraProc(Unit *pVictim, int32 scriptId, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell,uint32 cooldown);
 
         uint32 m_state;                                     // Even derived shouldn't modify
Index: trunk/src/game/CreatureAISelector.cpp
===================================================================
--- trunk/src/game/CreatureAISelector.cpp (revision 260)
+++ trunk/src/game/CreatureAISelector.cpp (revision 272)
@@ -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/SpellAuras.h
===================================================================
--- trunk/src/game/SpellAuras.h (revision 257)
+++ trunk/src/game/SpellAuras.h (revision 272)
@@ -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 TRINITY_SPELLAURAS_H
@@ -186,10 +186,13 @@
         void HandleModRating(bool apply, bool Real);
         void HandleModTargetResistance(bool apply, bool Real);
+        void HandleAuraAttackPowerAttacker(bool apply, bool Real);
         void HandleAuraModAttackPowerPercent(bool apply, bool Real);
         void HandleAuraModRangedAttackPowerPercent(bool apply, bool Real);
         void HandleAuraModRangedAttackPowerOfStatPercent(bool apply, bool Real);
         void HandleSpiritOfRedemption(bool apply, bool Real);
+        void HandleAuraHealingPct(bool apply, bool Real);
         void HandleModManaRegen(bool apply, bool Real);
         void HandleComprehendLanguage(bool apply, bool Real);
+        void HandleAuraHealing(bool apply, bool Real);
         void HandleShieldBlockValue(bool apply, bool Real);
         void HandleModSpellCritChanceShool(bool apply, bool Real);
@@ -251,5 +254,5 @@
             uint8 slot = GetAuraSlot();
 
-            // only aura in slot with charges and without stack limitation
+            // only aura inslot with charges and without stack limitation
             if (slot < MAX_AURAS && m_procCharges >= 1 && GetSpellProto()->StackAmount==0)
                 SetAuraApplication(slot, m_procCharges - 1);
Index: trunk/src/game/World.cpp
===================================================================
--- trunk/src/game/World.cpp (revision 260)
+++ trunk/src/game/World.cpp (revision 272)
@@ -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,5 +67,4 @@
 
 volatile bool World::m_stopEvent = false;
-uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
 volatile uint32 World::m_worldLoopCounter = 0;
 
@@ -544,4 +543,5 @@
         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,4 +606,5 @@
     }
 
+
     if(reload)
     {
@@ -769,6 +770,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);
 
@@ -965,7 +966,4 @@
     DetectDBCLang();
 
-    sLog.outString( "Loading Script Names...");
-    objmgr.LoadScriptNames();
-
     sLog.outString( "Loading InstanceTemplate" );
     objmgr.LoadInstanceTemplate();
@@ -1083,7 +1081,8 @@
     sLog.outString( "Loading Tavern Area Triggers..." );
     objmgr.LoadTavernAreaTriggers();
-
+    
     sLog.outString( "Loading AreaTrigger script names..." );
     objmgr.LoadAreaTriggerScripts();
+
 
     sLog.outString( "Loading Graveyard-zone links...");
@@ -1166,5 +1165,5 @@
     sLog.outString( "Loading Npc Text Id..." );
     objmgr.LoadNpcTextId();                                 // must be after load Creature and NpcText
-
+    
     sLog.outString( "Loading Npc Options..." );
     objmgr.LoadNpcOptions();
@@ -1194,7 +1193,4 @@
     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())
@@ -1267,5 +1263,4 @@
     sLog.outString( "WORLD: World initialized" );
 }
-
 void World::DetectDBCLang()
 {
@@ -1468,7 +1463,5 @@
     }
 
-    /// </ul>
-    ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
-    MapManager::Instance().DoDelayedMovesAndRemoves();
+    MapManager::Instance().DoDelayedMovesAndRemoves(); ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
 
     // update the instance reset times
@@ -1590,6 +1583,4 @@
         }
 
-        //if(source && !source->IsInWorld()) source = NULL;
-
         Object* target = NULL;
 
@@ -1619,6 +1610,4 @@
         }
 
-        //if(target && !target->IsInWorld()) target = NULL;
-
         switch (step.script->command)
         {
@@ -1648,5 +1637,5 @@
                 {
                     case 0:                                 // Say
-                        ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
+                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
                         break;
                     case 1:                                 // Whisper
@@ -1656,11 +1645,11 @@
                             break;
                         }
-                        ((Creature *)source)->Whisper(step.script->dataint,unit_target);
+                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
                         break;
                     case 2:                                 // Yell
-                        ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
+                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
                         break;
                     case 3:                                 // Emote text
-                        ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
+                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
                         break;
                     default:
@@ -1713,5 +1702,5 @@
                 }
                 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
-                ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
+                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
                 break;
             case SCRIPT_COMMAND_FLAG_SET:
@@ -1863,5 +1852,5 @@
                 go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
 
-                go->GetMap()->Add(go);
+                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
                 break;
             }
@@ -2385,5 +2374,5 @@
 
     ///- if there is a shutdown timer
-    if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
+    if(m_ShutdownTimer > 0 && elapsed > 0)
     {
         ///- ... and it is overdue, stop the world (set m_stopEvent)
@@ -2391,5 +2380,5 @@
         {
             if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
-                m_stopEvent = true;                         // exist code already set
+                m_stopEvent = true;
             else
                 m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
@@ -2406,12 +2395,7 @@
 
 /// Shutdown the server
-void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
-{
-    // ignore if server shutdown at next tick
-    if(m_stopEvent)
-        return;
-
+void World::ShutdownServ(uint32 time, uint32 options)
+{
     m_ShutdownMask = options;
-    m_ExitCode = exitcode;
 
     ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
@@ -2419,5 +2403,5 @@
     {
         if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
-            m_stopEvent = true;                             // exist code already set
+            m_stopEvent = true;
         else
             m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
@@ -2464,6 +2448,5 @@
 void World::ShutdownCancel()
 {
-    // nothing cancel or too later
-    if(!m_ShutdownTimer || m_stopEvent)
+    if(!m_ShutdownTimer)
         return;
 
@@ -2472,8 +2455,7 @@
     m_ShutdownMask = 0;
     m_ShutdownTimer = 0;
-    m_ExitCode = SHUTDOWN_EXIT_CODE;                       // to default value
     SendServerMessage(msgid);
 
-    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
+    DEBUG_LOG("Server %s canceled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
 }
 
@@ -2520,5 +2502,4 @@
         if(!itr->second->Update(diff))                      // As interval = 0
         {
-            RemoveQueuedPlayer (itr->second);
             delete itr->second;
             m_sessions.erase(itr);
Index: trunk/src/game/CharacterHandler.cpp
===================================================================
--- trunk/src/game/CharacterHandler.cpp (revision 262)
+++ trunk/src/game/CharacterHandler.cpp (revision 272)
@@ -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
  */
 
@@ -65,5 +65,5 @@
     res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADGROUP,           "SELECT leaderGuid FROM group_member WHERE memberGuid ='%u'", GUID_LOPART(m_guid));
     res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES,  "SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
-    res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADAURAS,           "SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'", GUID_LOPART(m_guid));
+    res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADAURAS,           "SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'", GUID_LOPART(m_guid));
     res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADSPELLS,          "SELECT spell,slot,active,disabled FROM character_spell WHERE guid = '%u'", GUID_LOPART(m_guid));
     res &= SetPQuery(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS,     "SELECT quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4 FROM character_queststatus WHERE guid = '%u'", GUID_LOPART(m_guid));
@@ -181,5 +181,4 @@
     std::string name;
     uint8 race_,class_;
-
     recv_data >> name;
 
@@ -216,5 +215,4 @@
     ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_);
     ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race_);
-
     if( !classEntry || !raceEntry )
     {
@@ -610,5 +608,5 @@
     }
 
-    if (!pCurrChar->GetMap()->Add(pCurrChar))
+    if (!MapManager::Instance().GetMap(pCurrChar->GetMapId(), pCurrChar)->Add(pCurrChar))
     {
         AreaTrigger const* at = objmgr.GetGoBackTrigger(pCurrChar->GetMapId());
@@ -1002,14 +1000,14 @@
     uint64 guid;
 
-    CHECK_PACKET_SIZE(recv_data, 8);
+    CHECK_PACKET_SIZE(recv_data, 8+6);
     recv_data >> guid;
 
     // not accept declined names for unsupported languages
     std::string name;
-    if(!objmgr.GetPlayerNameByGUID(guid, name))
-    {
-        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
-        data << uint32(1);
-        data << uint64(guid);
+    if(!objmgr.GetPlayerNameByGUID(guid,name))
+    {
+        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
+        data << (uint32)1;
+        data << guid;
         SendPacket(&data);
         return;
@@ -1017,9 +1015,9 @@
 
     std::wstring wname;
-    if(!Utf8toWStr(name, wname))
-    {
-        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
-        data << uint32(1);
-        data << uint64(guid);
+    if(!Utf8toWStr(name,wname))
+    {
+        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
+        data << (uint32)1;
+        data << guid;
         SendPacket(&data);
         return;
@@ -1028,7 +1026,7 @@
     if(!isCyrillicCharacter(wname[0]))                      // name already stored as only single alphabet using
     {
-        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
-        data << uint32(1);
-        data << uint64(guid);
+        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
+        data << (uint32)1;
+        data << guid;
         SendPacket(&data);
         return;
@@ -1038,12 +1036,11 @@
     DeclinedName declinedname;
 
-    CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
     recv_data >> name2;
 
-    if(name2 != name)                                       // character have different name
-    {
-        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
-        data << uint32(1);
-        data << uint64(guid);
+    if(name2!=name)                                         // character have different name
+    {
+        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
+        data << (uint32)1;
+        data << guid;
         SendPacket(&data);
         return;
@@ -1052,11 +1049,10 @@
     for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
     {
-        CHECK_PACKET_SIZE(recv_data, recv_data.rpos() + 1);
         recv_data >> declinedname.name[i];
         if(!normalizePlayerName(declinedname.name[i]))
         {
-            WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
-            data << uint32(1);
-            data << uint64(guid);
+            WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
+            data << (uint32)1;
+            data << guid;
             SendPacket(&data);
             return;
@@ -1064,9 +1060,9 @@
     }
 
-    if(!ObjectMgr::CheckDeclinedNames(GetMainPartOfName(wname, 0), declinedname))
-    {
-        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
-        data << uint32(1);
-        data << uint64(guid);
+    if(!ObjectMgr::CheckDeclinedNames(GetMainPartOfName(wname,0),declinedname))
+    {
+        WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
+        data << (uint32)1;
+        data << guid;
         SendPacket(&data);
         return;
@@ -1079,10 +1075,10 @@
     CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", GUID_LOPART(guid));
     CharacterDatabase.PExecute("INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES ('%u','%s','%s','%s','%s','%s')",
-        GUID_LOPART(guid), declinedname.name[0].c_str(), declinedname.name[1].c_str(), declinedname.name[2].c_str(), declinedname.name[3].c_str(), declinedname.name[4].c_str());
+        GUID_LOPART(guid), declinedname.name[0].c_str(),declinedname.name[1].c_str(),declinedname.name[2].c_str(),declinedname.name[3].c_str(),declinedname.name[4].c_str());
     CharacterDatabase.CommitTransaction();
 
-    WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT, 4+8);
-    data << uint32(0);                                      // OK
-    data << uint64(guid);
+    WorldPacket data(SMSG_SET_PLAYER_DECLINED_NAMES_RESULT,4+8);
+    data << (uint32)0;                                      // OK
+    data << guid;
     SendPacket(&data);
 }
Index: trunk/src/game/ItemEnchantmentMgr.h
===================================================================
--- trunk/src/game/ItemEnchantmentMgr.h (revision 260)
+++ trunk/src/game/ItemEnchantmentMgr.h (revision 272)
@@ -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/BattleGround.h
===================================================================
--- trunk/src/game/BattleGround.h (revision 257)
+++ trunk/src/game/BattleGround.h (revision 272)
@@ -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
  */
 
@@ -96,6 +96,5 @@
     RESPAWN_ONE_DAY                 = 86400,                // secs
     RESPAWN_IMMEDIATELY             = 0,                    // secs
-    BUFF_RESPAWN_TIME               = 180,                  // secs
-    BG_HONOR_SCORE_TICKS            = 330                   // points
+    BUFF_RESPAWN_TIME               = 180                  // secs
 };
 
@@ -435,4 +434,5 @@
 
         virtual void AddPlayer(Player *plr);                // must be implemented in BG subclass
+
         virtual void RemovePlayerAtLeave(uint64 guid, bool Transport, bool SendPacket);
                                                             // can be extended in in BG subclass
Index: trunk/src/game/Item.h
===================================================================
--- trunk/src/game/Item.h (revision 260)
+++ trunk/src/game/Item.h (revision 272)
@@ -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,4 +229,5 @@
         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/SpellAuras.cpp
===================================================================
--- trunk/src/game/SpellAuras.cpp (revision 257)
+++ trunk/src/game/SpellAuras.cpp (revision 272)
@@ -171,8 +171,8 @@
     &Aura::HandleNoImmediateEffect,                         //113 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN implemented in Unit::MeleeDamageBonus
     &Aura::HandleNoImmediateEffect,                         //114 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT implemented in Unit::MeleeDamageBonus
-    &Aura::HandleNoImmediateEffect,                         //115 SPELL_AURA_MOD_HEALING                 implemented in Unit::SpellBaseHealingBonusForVictim
+    &Aura::HandleAuraHealing,                               //115 SPELL_AURA_MOD_HEALING
     &Aura::HandleNoImmediateEffect,                         //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT
     &Aura::HandleNoImmediateEffect,                         //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE     implemented in Unit::MagicSpellHitResult
-    &Aura::HandleNoImmediateEffect,                         //118 SPELL_AURA_MOD_HEALING_PCT             implemented in Unit::SpellHealingBonus
+    &Aura::HandleAuraHealingPct,                            //118 SPELL_AURA_MOD_HEALING_PCT
     &Aura::HandleUnused,                                    //119 SPELL_AURA_SHARE_PET_TRACKING useless
     &Aura::HandleAuraUntrackable,                           //120 SPELL_AURA_UNTRACKABLE
@@ -192,5 +192,5 @@
     &Aura::HandleAuraModRegenInterrupt,                     //134 SPELL_AURA_MOD_MANA_REGEN_INTERRUPT
     &Aura::HandleModHealingDone,                            //135 SPELL_AURA_MOD_HEALING_DONE
-    &Aura::HandleNoImmediateEffect,                         //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT   implemented in Unit::SpellHealingBonus
+    &Aura::HandleAuraHealingPct,                            //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT   implemented in Unit::SpellHealingBonus
     &Aura::HandleModTotalPercentStat,                       //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE
     &Aura::HandleHaste,                                     //138 SPELL_AURA_MOD_HASTE
@@ -221,5 +221,5 @@
     &Aura::HandleNoImmediateEffect,                         //163 SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE
     &Aura::HandleUnused,                                    //164 useless, only one test spell
-    &Aura::HandleNoImmediateEffect,                         //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonus
+    &Aura::HandleAuraAttackPowerAttacker,                   //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonus
     &Aura::HandleAuraModAttackPowerPercent,                 //166 SPELL_AURA_MOD_ATTACK_POWER_PCT
     &Aura::HandleAuraModRangedAttackPowerPercent,           //167 SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT
@@ -2000,14 +2000,4 @@
         }
 
-        // Waiting to Resurrect
-        if(GetId()==2584)
-        {
-            // Waiting to resurrect spell cancel, we must remove player from resurrect queue
-            if(m_target->GetTypeId() == TYPEID_PLAYER)
-                if(BattleGround *bg = ((Player*)m_target)->GetBattleGround())
-                    bg->RemovePlayerFromResurrectQueue(m_target->GetGUID());
-            return;
-        }
-
         // Dark Fiend
         if(GetId()==45934)
@@ -2305,8 +2295,4 @@
 void Aura::HandleAuraMounted(bool apply, bool Real)
 {
-    // only at real add/remove aura
-    if(!Real)
-        return;
-
     if(apply)
     {
@@ -2708,7 +2694,5 @@
             else
             {
-                                                            // Will use the default model here
-                if (uint32 modelid = ci->GetRandomValidModelId())
-                    m_target->SetDisplayId(modelid);
+                if (uint32 modelid = ci->GetRandomValidModelId()) m_target->SetDisplayId(modelid);
 
                 // Dragonmaw Illusion (set mount model also)
@@ -3606,5 +3590,5 @@
 /***                  MODIFY SPEED                     ***/
 /*********************************************************/
-void Aura::HandleAuraModIncreaseSpeed(bool /*apply*/, bool Real)
+void Aura::HandleAuraModIncreaseSpeed(bool apply, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -3615,5 +3599,5 @@
 }
 
-void Aura::HandleAuraModIncreaseMountedSpeed(bool /*apply*/, bool Real)
+void Aura::HandleAuraModIncreaseMountedSpeed(bool apply, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -3654,5 +3638,5 @@
 }
 
-void Aura::HandleAuraModIncreaseSwimSpeed(bool /*apply*/, bool Real)
+void Aura::HandleAuraModIncreaseSwimSpeed(bool apply, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -3663,5 +3647,5 @@
 }
 
-void Aura::HandleAuraModDecreaseSpeed(bool /*apply*/, bool Real)
+void Aura::HandleAuraModDecreaseSpeed(bool apply, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -3674,5 +3658,5 @@
 }
 
-void Aura::HandleAuraModUseNormalSpeed(bool /*apply*/, bool Real)
+void Aura::HandleAuraModUseNormalSpeed(bool apply, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -4359,5 +4343,5 @@
 }
 
-void Aura::HandleModSpellDamagePercentFromStat(bool /*apply*/, bool Real)
+void Aura::HandleModSpellDamagePercentFromStat(bool apply, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4370,5 +4354,5 @@
 }
 
-void Aura::HandleModSpellHealingPercentFromStat(bool /*apply*/, bool Real)
+void Aura::HandleModSpellHealingPercentFromStat(bool apply, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4388,5 +4372,5 @@
 }
 
-void Aura::HandleModSpellDamagePercentFromAttackPower(bool /*apply*/, bool Real)
+void Aura::HandleModSpellDamagePercentFromAttackPower(bool apply, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4399,5 +4383,5 @@
 }
 
-void Aura::HandleModSpellHealingPercentFromAttackPower(bool /*apply*/, bool Real)
+void Aura::HandleModSpellHealingPercentFromAttackPower(bool apply, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4408,5 +4392,5 @@
 }
 
-void Aura::HandleModHealingDone(bool /*apply*/, bool Real)
+void Aura::HandleModHealingDone(bool apply, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4448,5 +4432,5 @@
 }
 
-void Aura::HandleAuraModResistenceOfStatPercent(bool /*apply*/, bool Real)
+void Aura::HandleAuraModResistenceOfStatPercent(bool apply, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4583,5 +4567,5 @@
 }
 
-void Aura::HandleModPowerRegenPCT(bool /*apply*/, bool Real)
+void Aura::HandleModPowerRegenPCT(bool apply, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4597,5 +4581,5 @@
 }
 
-void Aura::HandleModManaRegen(bool /*apply*/, bool Real)
+void Aura::HandleModManaRegen(bool apply, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4684,5 +4668,5 @@
 /********************************/
 
-void Aura::HandleAuraModParryPercent(bool /*apply*/, bool Real)
+void Aura::HandleAuraModParryPercent(bool apply, bool Real)
 {
     if(m_target->GetTypeId()!=TYPEID_PLAYER)
@@ -4692,5 +4676,5 @@
 }
 
-void Aura::HandleAuraModDodgePercent(bool /*apply*/, bool Real)
+void Aura::HandleAuraModDodgePercent(bool apply, bool Real)
 {
     if(m_target->GetTypeId()!=TYPEID_PLAYER)
@@ -4701,5 +4685,5 @@
 }
 
-void Aura::HandleAuraModBlockPercent(bool /*apply*/, bool Real)
+void Aura::HandleAuraModBlockPercent(bool apply, bool Real)
 {
     if(m_target->GetTypeId()!=TYPEID_PLAYER)
@@ -4710,5 +4694,5 @@
 }
 
-void Aura::HandleAuraModRegenInterrupt(bool /*apply*/, bool Real)
+void Aura::HandleAuraModRegenInterrupt(bool apply, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4778,5 +4762,5 @@
 }
 
-void Aura::HandleModSpellCritChanceShool(bool /*apply*/, bool Real)
+void Aura::HandleModSpellCritChanceShool(bool apply, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4858,4 +4842,37 @@
 
     m_target->HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(m_modifier.m_amount), apply);
+}
+
+void Aura::HandleAuraAttackPowerAttacker(bool apply, bool Real)
+{
+    // spells required only Real aura add/remove
+    if(!Real)
+        return;
+    Unit *caster = GetCaster();
+
+    if (!caster)
+        return;
+
+    // Hunter's Mark
+    if (m_spellProto->SpellFamilyName == SPELLFAMILY_HUNTER && m_spellProto->SpellFamilyFlags & 0x0000000000000400LL)
+    {
+        // Check Improved Hunter's Mark bonus on caster
+        Unit::AuraList const& mOverrideClassScript = caster->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
+        for(Unit::AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
+        {
+            Modifier* mod = (*i)->GetModifier();
+            // mproved Hunter's Mark script from 5236 to 5240
+            if (mod->m_miscvalue >= 5236 && mod->m_miscvalue <= 5240)
+            {
+                // Get amount of ranged bonus for this spell..
+                int32 ranged_bonus = caster->CalculateSpellDamage(m_spellProto, 1, m_spellProto->EffectBasePoints[1], m_target);
+                // Set melee attack power bonus % from ranged depends from Improved mask aura
+                m_modifier.m_amount = mod->m_amount * ranged_bonus / 100;
+                m_currentBasePoints = m_modifier.m_amount;
+                break;
+            }
+        }
+        return;
+    }
 }
 
@@ -5307,5 +5324,5 @@
 }
 
-void Aura::HandleAuraModExpertise(bool /*apply*/, bool Real)
+void Aura::HandleAuraModExpertise(bool apply, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -5330,4 +5347,15 @@
     if (m_target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_SPELL)==SPELL_SCHOOL_MASK_SPELL)
         m_target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,m_modifier.m_amount, apply);
+}
+
+//HandleNoImmediateEffect auras implementation to support new stat system
+void Aura::HandleAuraHealing(bool apply, bool Real)
+{
+    //m_target->HandleStatModifier(UNIT_MOD_HEALING, TOTAL_VALUE, float(m_modifier.m_amount), apply);
+}
+
+void Aura::HandleAuraHealingPct(bool apply, bool Real)
+{
+    //m_target->HandleStatModifier(UNIT_MOD_HEALING, TOTAL_PCT, float(m_modifier.m_amount), apply);
 }
 
Index: trunk/src/game/Mail.cpp
===================================================================
--- trunk/src/game/Mail.cpp (revision 260)
+++ trunk/src/game/Mail.cpp (revision 272)
@@ -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,4 +188,5 @@
                 return;
             }
+
             if (mailItem.item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED) || mailItem.item->GetUInt32Value(ITEM_FIELD_DURATION))
             {
@@ -194,9 +195,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/SharedDefines.h
===================================================================
--- trunk/src/game/SharedDefines.h (revision 262)
+++ trunk/src/game/SharedDefines.h (revision 272)
@@ -249,5 +249,5 @@
 #define SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY    0x00008000            // 15 remove auras on immunity
 #define SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE 0x00010000            // 16 unaffected by school immunity
-#define SPELL_ATTR_EX_UNAUTOCASTABLE_BY_PET       0x00020000            // 17
+#define SPELL_ATTR_EX_UNK17                       0x00020000            // 17
 #define SPELL_ATTR_EX_UNK18                       0x00040000            // 18
 #define SPELL_ATTR_EX_UNK19                       0x00080000            // 19
Index: trunk/src/game/Creature.cpp
===================================================================
--- trunk/src/game/Creature.cpp (revision 267)
+++ trunk/src/game/Creature.cpp (revision 272)
@@ -123,5 +123,5 @@
 m_lootMoney(0), m_lootRecipient(0),
 m_deathTimer(0), m_respawnTime(0), m_respawnDelay(25), m_corpseDelay(60), m_respawnradius(0.0f),
-m_gossipOptionLoaded(false), m_emoteState(0), m_isPet(false), m_isTotem(false), m_isAggressive(true),
+m_gossipOptionLoaded(false), m_emoteState(0), m_isPet(false), m_isTotem(false),
 m_regenTimer(2000), m_defaultMovementType(IDLE_MOTION_TYPE), m_equipmentId(0),
 m_AlreadyCallAssistence(false), m_regenHealth(true), m_AI_locked(false), m_isDeadByDefault(false),
@@ -148,5 +148,9 @@
     i_AI = NULL;
 
-    DeletePossessedAI();
+    if (i_AI_possessed)
+    {
+        delete i_AI_possessed;
+        i_AI_possessed = NULL;
+    }
 }
 
@@ -178,5 +182,5 @@
     float x,y,z,o;
     GetRespawnCoord(x, y, z, &o);
-    GetMap()->CreatureRelocation(this,x,y,z,o);
+    MapManager::Instance().GetMap(GetMapId(), this)->CreatureRelocation(this,x,y,z,o);
 }
 
@@ -210,5 +214,5 @@
     }
 
-    SetEntry(Entry);                                        // normal entry always
+    SetUInt32Value(OBJECT_FIELD_ENTRY, Entry);              // normal entry always
     m_creatureInfo = cinfo;                                 // map mode related always
 
@@ -294,5 +298,4 @@
     SetUInt32Value(UNIT_DYNAMIC_FLAGS,GetCreatureInfo()->dynamicflags);
 
-    SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
     SetModifierValue(UNIT_MOD_ARMOR,             BASE_VALUE, float(GetCreatureInfo()->armor));
     SetModifierValue(UNIT_MOD_RESISTANCE_HOLY,   BASE_VALUE, float(GetCreatureInfo()->resistance1));
@@ -325,10 +328,4 @@
         SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
 
-    if(isTotem() || isCivilian() || GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_TRIGGER
-        || GetCreatureType() == CREATURE_TYPE_CRITTER)
-        m_isAggressive = false;
-    else
-        m_isAggressive = true;
-
     return true;
 }
@@ -360,5 +357,5 @@
                 lootForBody         = false;
 
-                if(m_originalEntry != GetEntry())
+                if(m_originalEntry != GetUInt32Value(OBJECT_FIELD_ENTRY))
                     UpdateEntry(m_originalEntry);
 
@@ -379,7 +376,7 @@
 
                 //Call AI respawn virtual function
-                i_AI->JustRespawned();
-
-                GetMap()->Add(this);
+                AI()->JustRespawned();
+
+                MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
             }
             break;
@@ -443,5 +440,5 @@
                 // do not allow the AI to be changed during update
                 m_AI_locked = true;
-                i_AI->UpdateAI(diff);
+                AI()->UpdateAI(diff);
                 m_AI_locked = false;
             }
@@ -563,10 +560,7 @@
 }
 
-void Creature::DeletePossessedAI()
+void Creature::DisablePossessedAI()
 {
     if (!i_AI_possessed) return;
-
-    delete i_AI_possessed;
-    i_AI_possessed = NULL;
 
     // Signal the old AI that it's been re-enabled
@@ -1418,4 +1412,6 @@
     SetPower(POWER_MANA,data->curmana);
 
+    SetMeleeDamageSchool(SpellSchools(GetCreatureInfo()->dmgschool));
+
     // checked at creature_template loading
     m_defaultMovementType = MovementGeneratorType(data->movementType);
@@ -1542,17 +1538,4 @@
 {
     return IsWithinDistInMap(u, sWorld.getConfig(CONFIG_SIGHT_MONSTER));
-}
-
-bool Creature::canStartAttack(Unit const* who) const
-{
-    if(!who->isInAccessiblePlaceFor(this)
-        || !canFly() && GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE
-        || !IsWithinDistInMap(who, GetAttackDistance(who)))
-        return false;
-
-    if(!canAttack(who))
-        return false;
-
-    return IsWithinLOSInMap(who);
 }
 
@@ -1836,28 +1819,4 @@
 }
 
-Unit* Creature::SelectNearestTarget(float dist) const
-{
-    CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
-    Cell cell(p);
-    cell.data.Part.reserved = ALL_DISTRICT;
-    cell.SetNoCreate();
-
-    Unit *target = NULL;
-
-    {
-        Trinity::NearestHostileUnitInAttackDistanceCheck u_check(this, dist);
-        Trinity::UnitLastSearcher<Trinity::NearestHostileUnitInAttackDistanceCheck> searcher(target, u_check);
-
-        TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::NearestHostileUnitInAttackDistanceCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
-        TypeContainerVisitor<Trinity::UnitLastSearcher<Trinity::NearestHostileUnitInAttackDistanceCheck>, GridTypeMapContainer >  grid_unit_searcher(searcher);
-
-        CellLock<GridReadGuard> cell_lock(cell, p);
-        cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
-        cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
-    }
-
-    return target;
-}
-
 void Creature::CallAssistence()
 {
@@ -2139,12 +2098,7 @@
 }
 
-std::string Creature::GetScriptName()
-{
-    return objmgr.GetScriptName(GetScriptId());
-}
-
-uint32 Creature::GetScriptId()
-{
-    return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptID;
+char const* Creature::GetScriptName() const
+{
+    return ObjectMgr::GetCreatureTemplate(GetEntry())->ScriptName;
 }
 
Index: trunk/src/game/CreatureAIRegistry.cpp
===================================================================
--- trunk/src/game/CreatureAIRegistry.cpp (revision 260)
+++ trunk/src/game/CreatureAIRegistry.cpp (revision 272)
@@ -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 268)
+++ trunk/src/game/Map.cpp (revision 272)
@@ -36,5 +36,4 @@
 #include "ScriptCalls.h"
 #include "Group.h"
-#include "MapRefManager.h"
 
 #include "MapInstanced.h"
@@ -451,6 +450,4 @@
 bool Map::Add(Player *player)
 {
-    player->GetMapRef().link(this, player);
-
     player->SetInstanceId(GetInstanceId());
 
@@ -595,68 +592,6 @@
 }
 
-void Map::UpdateActiveCells(const float &x, const float &y, const uint32 &t_diff)
-{
-    CellPair standing_cell(Trinity::ComputeCellPair(x, y));
-
-    // Check for correctness of standing_cell, it also avoids problems with update_cell
-    if (standing_cell.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || standing_cell.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
-        return;
-
-    // will this reduce the speed?
-    Trinity::ObjectUpdater updater(t_diff);
-    // for creature
-    TypeContainerVisitor<Trinity::ObjectUpdater, GridTypeMapContainer  > grid_object_update(updater);
-    // for pets
-    TypeContainerVisitor<Trinity::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
-
-    // the overloaded operators handle range checking
-    // so ther's no need for range checking inside the loop
-    CellPair begin_cell(standing_cell), end_cell(standing_cell);
-    begin_cell << 1; begin_cell -= 1;               // upper left
-    end_cell >> 1; end_cell += 1;                   // lower right
-
-    for(uint32 x = begin_cell.x_coord; x <= end_cell.x_coord; ++x)
-    {
-        for(uint32 y = begin_cell.y_coord; y <= end_cell.y_coord; ++y)
-        {
-            // marked cells are those that have been visited
-            // don't visit the same cell twice
-            uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
-            if(!isCellMarked(cell_id))
-            {
-                markCell(cell_id);
-                CellPair pair(x,y);
-                Cell cell(pair);
-                cell.data.Part.reserved = CENTER_DISTRICT;
-                cell.SetNoCreate();
-                CellLock<NullGuard> cell_lock(cell, pair);
-                cell_lock->Visit(cell_lock, grid_object_update,  *this);
-                cell_lock->Visit(cell_lock, world_object_update, *this);
-            }
-        }
-    }
-}
-
 void Map::Update(const uint32 &t_diff)
 {
-    resetMarkedCells();
-
-    // update cells around players
-    for(MapRefManager::iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
-    {
-        Player* plr = iter->getSource();
-        if(plr->IsInWorld())
-            UpdateActiveCells(plr->GetPositionX(), plr->GetPositionY(), t_diff);
-    }
-
-    // update cells around active objects
-    // clone the active object list, because update might remove from it
-    std::set<WorldObject *> activeObjects(i_activeObjects);
-    for(std::set<WorldObject *>::iterator iter = activeObjects.begin(); iter != activeObjects.end(); ++iter)
-    {
-        if((*iter)->IsInWorld())
-            UpdateActiveCells((*iter)->GetPositionX(), (*iter)->GetPositionY(), t_diff);
-    }
-
     // Don't unload grids if it's battleground, since we may have manually added GOs,creatures, those doesn't load from DB at grid re-load !
     // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
@@ -676,5 +611,4 @@
 void Map::Remove(Player *player, bool remove)
 {
-    player->GetMapRef().unlink();
     CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
     if(p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
@@ -826,11 +760,6 @@
         AddCreatureToMoveList(creature,x,y,z,ang);
         // in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
-        if(creature->isActive())
-        {
-            if(creature->isPossessedByPlayer())
-                EnsureGridLoadedForPlayer(new_cell, (Player*)creature->GetCharmer(), false);
-            else
-                EnsureGridLoadedForPlayer(new_cell, NULL, false);
-        }
+        if(creature->isPossessedByPlayer())
+            EnsureGridLoadedForPlayer(new_cell, (Player*)creature->GetCharmer(), false);
     }
     else
@@ -981,5 +910,5 @@
 
     {
-        if(!pForce && PlayersNearGrid(x, y) )
+        if(!pForce && ObjectAccessor::Instance().ActiveObjectsNearGrid(x, y, i_id, i_InstanceId) )
             return false;
 
@@ -1490,71 +1419,4 @@
 }
 
-uint32 Map::GetPlayersCountExceptGMs() const
-{
-    uint32 count = 0;
-    for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
-        if(!itr->getSource()->isGameMaster())
-            ++count;
-    return count;
-}
-
-void Map::SendToPlayers(WorldPacket const* data) const
-{
-    for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
-        itr->getSource()->GetSession()->SendPacket(data);
-}
-
-bool Map::PlayersNearGrid(uint32 x, uint32 y) const
-{
-    CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
-    CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
-    cell_min << 2;
-    cell_min -= 2;
-    cell_max >> 2;
-    cell_max += 2;
-
-    for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
-    {
-        Player* plr = iter->getSource();
-
-        CellPair p = Trinity::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
-        if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
-            (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
-            return true;
-    }
-
-    return false;
-}
-
-bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const
-{
-    CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
-    CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
-    cell_min << 2;
-    cell_min -= 2;
-    cell_max >> 2;
-    cell_max += 2;
-
-    for(MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
-    {
-        Player* plr = iter->getSource();
-
-        CellPair p = Trinity::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY());
-        if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
-            (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
-            return true;
-    }
-
-    for(std::set<WorldObject*>::const_iterator itr = i_activeObjects.begin(); itr != i_activeObjects.end(); ++itr)
-    {
-        CellPair p = Trinity::ComputeCellPair((*itr)->GetPositionX(), (*itr)->GetPositionY());
-        if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
-            (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
-            return true;
-    }
-
-    return false;
-}
-
 template void Map::Add(Corpse *);
 template void Map::Add(Creature *);
@@ -1592,5 +1454,5 @@
 bool InstanceMap::CanEnter(Player *player)
 {
-    if(player->GetMapRef().getTarget() == this)
+    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
     {
         sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
@@ -1709,4 +1571,5 @@
         SetResetSchedule(false);
 
+        i_Players.push_back(player);
         player->SendInitWorldStates();
         sLog.outDetail("MAP: Player '%s' entered the instance '%u' of map '%s'", player->GetName(), GetInstanceId(), GetMapName());
@@ -1733,7 +1596,7 @@
 {
     sLog.outDetail("MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
+    i_Players.remove(player);
     SetResetSchedule(true);
-    //if last player set unload timer
-    if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
+    if(!m_unloadTimer && i_Players.empty())
         m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
     Map::Remove(player, remove);
@@ -1762,5 +1625,5 @@
     if (mInstance)
     {
-        i_script_id = mInstance->script_id;
+        i_script = mInstance->script;
         i_data = Script->CreateInstanceData(this);
     }
@@ -1779,5 +1642,5 @@
             if(data)
             {
-                sLog.outDebug("Loading instance data for `%s` with id %u", objmgr.GetScriptName(i_script_id), i_InstanceId);
+                sLog.outDebug("Loading instance data for `%s` with id %u", i_script.c_str(), i_InstanceId);
                 i_data->Load(data);
             }
@@ -1787,5 +1650,5 @@
     else
     {
-        sLog.outDebug("New instance data, \"%s\" ,initialized!", objmgr.GetScriptName(i_script_id));
+        sLog.outDebug("New instance data, \"%s\" ,initialized!",i_script.c_str());
         i_data->Initialize();
     }
@@ -1800,11 +1663,11 @@
     // the instance must be deleted from the DB by InstanceSaveManager
 
-    if(HavePlayers())
+    if(!i_Players.empty())
     {
         if(method == INSTANCE_RESET_ALL)
         {
             // notify the players to leave the instance so it can be reset
-            for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
-                itr->getSource()->SendResetFailedNotify(GetId());
+            for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
+                (*itr)->SendResetFailedNotify(GetId());
         }
         else
@@ -1813,6 +1676,6 @@
             {
                 // set the homebind timer for players inside (1 minute)
-                for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
-                    itr->getSource()->m_InstanceValid = false;
+                for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
+                    (*itr)->m_InstanceValid = false;
             }
 
@@ -1830,5 +1693,14 @@
     }
 
-    return m_mapRefManager.isEmpty();
+    return i_Players.empty();
+}
+
+uint32 InstanceMap::GetPlayersCountExceptGMs() const
+{
+    uint32 count = 0;
+    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
+        if(!(*itr)->isGameMaster())
+            ++count;
+    return count;
 }
 
@@ -1844,21 +1716,23 @@
     Group *group = player->GetGroup();
     // group members outside the instance group don't get bound
-    for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
-    {
-        Player* plr = itr->getSource();
-        // players inside an instance cannot be bound to other instances
-        // some players may already be permanently bound, in this case nothing happens
-        InstancePlayerBind *bind = plr->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
-        if(!bind || !bind->perm)
-        {
-            plr->BindToInstance(save, true);
-            WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
-            data << uint32(0);
-            plr->GetSession()->SendPacket(&data);
-        }
-
-        // if the leader is not in the instance the group will not get a perm bind
-        if(group && group->GetLeaderGUID() == plr->GetGUID())
-            group->BindToInstance(save, true);
+    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
+    {
+        if(*itr)
+        {
+            // players inside an instance cannot be bound to other instances
+            // some players may already be permanently bound, in this case nothing happens
+            InstancePlayerBind *bind = (*itr)->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
+            if(!bind || !bind->perm)
+            {
+                (*itr)->BindToInstance(save, true);
+                WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
+                data << uint32(0);
+                (*itr)->GetSession()->SendPacket(&data);
+            }
+
+            // if the leader is not in the instance the group will not get a perm bind
+            if(group && group->GetLeaderGUID() == (*itr)->GetGUID())
+                group->BindToInstance(save, true);
+        }
     }
 }
@@ -1872,12 +1746,9 @@
 void InstanceMap::UnloadAll(bool pForce)
 {
-    if(HavePlayers())
+    if(!i_Players.empty())
     {
         sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
-        for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
-        {
-            Player* plr = itr->getSource();
-            plr->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
-        }
+        for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
+            if(*itr) (*itr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
     }
 
@@ -1888,8 +1759,8 @@
 }
 
-void InstanceMap::SendResetWarnings(uint32 timeLeft) const
-{
-    for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
-        itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
+void InstanceMap::SendResetWarnings(uint32 timeLeft)
+{
+    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
+        (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
 }
 
@@ -1899,5 +1770,5 @@
     // the reset time is only scheduled when there are no payers inside
     // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
-    if(!HavePlayers() && !IsRaid() && !IsHeroic())
+    if(i_Players.empty() && !IsRaid() && !IsHeroic())
     {
         InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
@@ -1907,4 +1778,10 @@
 }
 
+void InstanceMap::SendToPlayers(WorldPacket const* data) const
+{
+    for(PlayerList::const_iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
+        (*itr)->GetSession()->SendPacket(data);
+}
+
 /* ******* Battleground Instance Maps ******* */
 
@@ -1920,5 +1797,5 @@
 bool BattleGroundMap::CanEnter(Player * player)
 {
-    if(player->GetMapRef().getTarget() == this)
+    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
     {
         sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
@@ -1941,4 +1818,5 @@
         if(!CanEnter(player))
             return false;
+        i_Players.push_back(player);
         // reset instance validity, battleground maps do not homebind
         player->m_InstanceValid = true;
@@ -1950,4 +1828,5 @@
 {
     sLog.outDetail("MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to other map", player->GetName(), GetInstanceId(), GetMapName());
+    i_Players.remove(player);
     Map::Remove(player, remove);
 }
@@ -1960,12 +1839,13 @@
 void BattleGroundMap::UnloadAll(bool pForce)
 {
-    while(HavePlayers())
-    {
-        Player * plr = m_mapRefManager.getFirst()->getSource();
-        if(plr) (plr)->TeleportTo(plr->m_homebindMapId, plr->m_homebindX, plr->m_homebindY, plr->m_homebindZ, plr->GetOrientation());
+    while(!i_Players.empty())
+    {
+        PlayerList::iterator itr = i_Players.begin();
+        Player * plr = *itr;
+        if(plr) (plr)->TeleportTo((*itr)->m_homebindMapId, (*itr)->m_homebindX, (*itr)->m_homebindY, (*itr)->m_homebindZ, (*itr)->GetOrientation());
         // TeleportTo removes the player from this map (if the map exists) -> calls BattleGroundMap::Remove -> invalidates the iterator.
         // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
         // note that this remove is not needed if the code works well in other places
-        plr->GetMapRef().unlink();
+        i_Players.remove(plr);
     }
 
Index: trunk/src/game/Object.cpp
===================================================================
--- trunk/src/game/Object.cpp (revision 268)
+++ trunk/src/game/Object.cpp (revision 272)
@@ -991,6 +991,6 @@
 WorldObject::~WorldObject()
 {
-    if(m_isActive && !isType(TYPEMASK_PLAYER) && IsInWorld())
-        GetMap()->RemoveActiveObject(this);
+    if(m_isActive && IsInWorld())
+        ObjectAccessor::Instance().RemoveActiveObject(this);
 }
 
@@ -998,14 +998,13 @@
 {
     // if already in the same activity state as we try to set, do nothing
-    if(isActive == m_isActive || isType(TYPEMASK_PLAYER))
+    if(isActive == m_isActive)
         return;
-
     m_isActive = isActive;
     if(IsInWorld())
     {
         if(isActive)
-            GetMap()->AddActiveObject(this);
+            ObjectAccessor::Instance().AddActiveObject(this);
         else
-            GetMap()->RemoveActiveObject(this);
+            ObjectAccessor::Instance().RemoveActiveObject(this);
     }
 }
@@ -1014,12 +1013,12 @@
 {
     Object::AddToWorld();
-    if(m_isActive && !isType(TYPEMASK_PLAYER))
-        GetMap()->AddActiveObject(this);
+    if(m_isActive)
+        ObjectAccessor::Instance().AddActiveObject(this);
 }
 
 void WorldObject::RemoveFromWorld()
 {
-    if(m_isActive && !isType(TYPEMASK_PLAYER))
-        GetMap()->RemoveActiveObject(this);
+    if(m_isActive)
+        ObjectAccessor::Instance().RemoveActiveObject(this);
     Object::RemoveFromWorld();
 }
Index: trunk/src/game/GridStates.cpp
===================================================================
--- trunk/src/game/GridStates.cpp (revision 268)
+++ trunk/src/game/GridStates.cpp (revision 272)
@@ -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
  */
 
@@ -37,5 +37,5 @@
     if( info.getTimeTracker().Passed() )
     {
-        if( grid.ActiveObjectsInGrid() == 0 && !m.ActiveObjectsNearGrid(x, y) )
+        if( grid.ActiveObjectsInGrid() == 0 && !ObjectAccessor::Instance().ActiveObjectsNearGrid(x, y, m.GetId(), m.GetInstanceId()) )
         {
             ObjectGridStoper stoper(grid);
@@ -51,5 +51,5 @@
 
 void
-IdleState::Update(Map &m, NGridType &grid, GridInfo &, const uint32 &x, const uint32 &y, const uint32 &) const
+IdleState::Update(Map &m, NGridType &grid, GridInfo &info, const uint32 &x, const uint32 &y, const uint32 &) const
 {
     m.ResetGridExpiry(grid);
Index: trunk/src/game/MapInstanced.h
===================================================================
--- trunk/src/game/MapInstanced.h (revision 257)
+++ trunk/src/game/MapInstanced.h (revision 272)
@@ -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
  */
 
@@ -31,5 +31,5 @@
         typedef UNORDERED_MAP< uint32, Map* > InstancedMaps;
 
-        MapInstanced(uint32 id, time_t expiry);
+        MapInstanced(uint32 id, time_t, uint32 aInstanceId);
         ~MapInstanced() {}
 
Index: trunk/src/game/Creature.h
===================================================================
--- trunk/src/game/Creature.h (revision 267)
+++ trunk/src/game/Creature.h (revision 272)
@@ -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,9 +206,8 @@
     uint32  MechanicImmuneMask;
     uint32  flags_extra;
-    uint32  ScriptID;
+    char const* ScriptName;
     uint32 GetRandomValidModelId() const;
     uint32 GetFirstValidModelId() const;
-
-    // helpers
+    
     SkillType GetRequiredLootSkill() const
     {
@@ -220,5 +219,5 @@
             return SKILL_SKINNING;                          // normal case
     }
-
+    
     bool isTameable() const
     {
@@ -427,6 +426,4 @@
         bool canSwim() const { return GetCreatureInfo()->InhabitType & INHABIT_WATER; }
         bool canFly()  const { return GetCreatureInfo()->InhabitType & INHABIT_AIR; }
-        bool isAggressive() const { return m_isAggressive; }
-        void SetAggressive(bool agg) { m_isAggressive = agg; }
         ///// TODO RENAME THIS!!!!!
         bool isCanTrainingOf(Player* player, bool msg) const;
@@ -461,5 +458,5 @@
         bool AIM_Initialize();
         void InitPossessedAI();
-        void DeletePossessedAI();
+        void DisablePossessedAI();
 
         void AI_SendMoveToPacket(float x, float y, float z, uint32 time, uint32 MovementFlags, uint8 type);
@@ -502,7 +499,5 @@
         CreatureInfo const *GetCreatureInfo() const { return m_creatureInfo; }
         CreatureDataAddon const* GetCreatureAddon() const;
-
-        std::string GetScriptName();
-        uint32 GetScriptId();
+        char const* GetScriptName() const;
 
         void prepareGossipMenu( Player *pPlayer, uint32 gossipid = 0 );
@@ -530,5 +525,5 @@
         // overwrite WorldObject function for proper name localization
         const char* GetNameForLocaleIdx(int32 locale_idx) const;
-
+    
         void setDeathState(DeathState s);                   // overwrite virtual Unit::setDeathState
 
@@ -558,8 +553,6 @@
         bool canSeeOrDetect(Unit const* u, bool detect, bool inVisibleList) const;
         bool IsWithinSightDist(Unit const* u) const;
-        bool canStartAttack(Unit const* u) const;
         float GetAttackDistance(Unit const* pl) const;
 
-        Unit* SelectNearestTarget(float dist = 0) const;
         void CallAssistence();
         void SetNoCallAssistence(bool val) { m_AlreadyCallAssistence = val; }
@@ -641,5 +634,4 @@
         bool m_isPet;                                       // set only in Pet::Pet
         bool m_isTotem;                                     // set only in Totem::Totem
-        bool m_isAggressive;
         void RegenerateMana();
         void RegenerateHealth();
Index: trunk/src/game/PlayerDump.cpp
===================================================================
--- trunk/src/game/PlayerDump.cpp (revision 263)
+++ trunk/src/game/PlayerDump.cpp (revision 272)
@@ -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,8 +372,7 @@
         }
     }
-
     FILE *fin = fopen(file.c_str(), "r");
     if(!fin)
-        return DUMP_FILE_OPEN_ERROR;
+		return DUMP_FILE_OPEN_ERROR;
 
     QueryResult * result = NULL;
@@ -392,6 +391,5 @@
         else incHighest = false;
     }
-    else
-        guid = objmgr.m_hiCharGuid;
+    else guid = objmgr.m_hiCharGuid;
 
     // normalize the name if specified and check if it exists
@@ -471,5 +469,5 @@
             case DTT_CHAR_TABLE:
                 if(!changenth(line, 1, newguid))
-                    ROLLBACK(DUMP_FILE_BROKEN);
+					ROLLBACK(DUMP_FILE_BROKEN);
                 break;
 
@@ -477,17 +475,21 @@
             {
                 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 == "")
                 {
@@ -502,9 +504,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;
@@ -513,11 +515,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;
             }
@@ -526,14 +528,15 @@
                 // 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;
             }
@@ -542,7 +545,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;
             }
@@ -567,7 +570,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;
@@ -580,10 +583,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;
@@ -593,7 +596,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;
             }
@@ -602,9 +605,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;
             }
@@ -615,5 +618,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 260)
+++ trunk/src/game/Chat.h (revision 272)
@@ -176,5 +176,4 @@
         bool HandleModifyRepCommand(const char* args);
         bool HandleModifyArenaCommand(const char* args);
-        bool HandleModifyGenderCommand(const char* args);
 
         bool HandleNpcAddCommand(const char* args);
@@ -193,5 +192,4 @@
         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);
@@ -218,5 +216,4 @@
         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);
@@ -274,13 +271,8 @@
         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);
@@ -336,4 +328,9 @@
         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);
@@ -369,4 +366,5 @@
         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 260)
+++ trunk/src/game/ItemHandler.cpp (revision 272)
@@ -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() > size_t(loc_idx) && !il->Name[loc_idx].empty())
+                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
                     Name = il->Name[loc_idx];
-                if (il->Description.size() > size_t(loc_idx) && !il->Description[loc_idx].empty())
+                if (il->Description.size() > loc_idx && !il->Description[loc_idx].empty())
                     Description = il->Description[loc_idx];
             }
@@ -361,6 +361,4 @@
             data << pProto->Damage[i].DamageType;
         }
-
-        // resistances (7)
         data << pProto->Armor;
         data << pProto->HolyRes;
@@ -370,9 +368,8 @@
         data << pProto->ShadowRes;
         data << pProto->ArcaneRes;
-
         data << pProto->Delay;
         data << pProto->Ammo_type;
-        data << pProto->RangedModRange;
-
+
+        data << (float)pProto->RangedModRange;
         for(int s = 0; s < 5; s++)
         {
@@ -980,5 +977,5 @@
             if (il)
             {
-                if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty())
+                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
                     Name = il->Name[loc_idx];
             }
@@ -1031,5 +1028,5 @@
     }
 
-    if(item==gift)                                          // not possable with pacjket from real client
+    if(item==gift)                                          // not possible with pacjket from real client
     {
         _player->SendEquipError( EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, NULL );
@@ -1076,14 +1073,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->SetEntry(gift->GetEntry());
+    item->SetUInt32Value(OBJECT_FIELD_ENTRY, gift->GetUInt32Value(OBJECT_FIELD_ENTRY));
 
     switch (item->GetEntry())
     {
-        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;
+        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;
     }
     item->SetUInt64Value(ITEM_FIELD_GIFTCREATOR, _player->GetGUID());
Index: trunk/src/game/Formulas.h
===================================================================
--- trunk/src/game/Formulas.h (revision 263)
+++ trunk/src/game/Formulas.h (revision 272)
@@ -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,5 +81,4 @@
         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/Totem.cpp
===================================================================
--- trunk/src/game/Totem.cpp (revision 265)
+++ trunk/src/game/Totem.cpp (revision 272)
@@ -98,7 +98,4 @@
         default: break;
     }
-
-    if(GetEntry() == SENTRY_TOTEM_ENTRY)
-        SetAggressive(true);
 }
 
Index: trunk/src/game/Player.h
===================================================================
--- trunk/src/game/Player.h (revision 268)
+++ trunk/src/game/Player.h (revision 272)
@@ -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
  */
 
@@ -34,5 +34,4 @@
 #include "WorldSession.h"
 #include "Pet.h"
-#include "MapReference.h"
 #include "Util.h"                                           // for Tokens typedef
 
@@ -781,5 +780,5 @@
 
 /// Type of environmental damages
-enum EnviromentalDamage
+enum EnvironmentalDamageType
 {
     DAMAGE_EXHAUSTED = 0,
@@ -898,4 +897,6 @@
         void AddToWorld();
         void RemoveFromWorld();
+        // always active
+        void setActive(bool) {}
 
         void SetViewport(uint64 guid, bool movable);
@@ -1124,5 +1125,5 @@
         uint32 GetArmorProficiency() const { return m_ArmorProficiency; }
         bool IsInFeralForm() const { return m_form == FORM_CAT || m_form == FORM_BEAR || m_form == FORM_DIREBEAR; }
-        bool IsUseEquipedWeapon( bool mainhand ) const
+        bool IsUseEquippedWeapon( bool mainhand ) const
         {
             // disarm applied only to mainhand weapon
@@ -1306,5 +1307,5 @@
                 SetMoney (GetMoney() > uint32(-d) ? GetMoney() + d : 0);
             else
-                SetMoney (GetMoney() < uint32(MAX_MONEY_AMOUNT - d) ? GetMoney() + d : MAX_MONEY_AMOUNT);
+                SetMoney (GetMoney() < MAX_MONEY_AMOUNT - d ? GetMoney() + d : MAX_MONEY_AMOUNT);
 
             // "At Gold Limit"
@@ -1428,4 +1429,5 @@
         PlayerSpellMap const& GetSpellMap() const { return m_spells; }
         PlayerSpellMap      & GetSpellMap()       { return m_spells; }
+        ActionButtonList const& GetActionButtonList() const { return m_actionButtons; }
 
         void AddSpellMod(SpellModifier* mod, bool apply);
@@ -1517,6 +1519,6 @@
         void SendUpdateToOutOfRangeGroupMembers();
 
-        void SetInGuild(uint32 GuildId) { SetUInt32Value(PLAYER_GUILDID, GuildId); Player::SetUInt32ValueInDB(PLAYER_GUILDID, GuildId, GetGUID()); }
-        void SetRank(uint32 rankId){ SetUInt32Value(PLAYER_GUILDRANK, rankId); Player::SetUInt32ValueInDB(PLAYER_GUILDRANK, rankId, GetGUID()); }
+        void SetInGuild(uint32 GuildId) { SetUInt32Value(PLAYER_GUILDID, GuildId); Player::SetUInt32ValueInDB(PLAYER_GUILDID, GuildId, this->GetGUID()); }
+        void SetRank(uint32 rankId){ SetUInt32Value(PLAYER_GUILDRANK, rankId); Player::SetUInt32ValueInDB(PLAYER_GUILDRANK, rankId, this->GetGUID()); }
         void SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; }
         uint32 GetGuildId() { return GetUInt32Value(PLAYER_GUILDID);  }
@@ -1531,5 +1533,5 @@
         {
             SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * 6), ArenaTeamId);
-            SetUInt32ValueInDB(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * 6), ArenaTeamId, GetGUID());
+            SetUInt32ValueInDB(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * 6), ArenaTeamId, this->GetGUID());
         }
         uint32 GetArenaTeamId(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * 6)); }
@@ -1607,5 +1609,5 @@
         void SendLogXPGain(uint32 GivenXP,Unit* victim,uint32 RestXP);
 
-        //Low Level Packets
+		//Low Level Packets
         void PlaySound(uint32 Sound, bool OnlySelf);
         //notifiers
@@ -1639,5 +1641,5 @@
         void KillPlayer();
         uint32 GetResurrectionSpellId();
-        void ResurrectPlayer(float restore_percent, bool applySickness = false);
+        void ResurrectPlayer(float restore_percent, bool updateToWorld = true, bool applySickness = false);
         void BuildPlayerRepop();
         void RepopAtGraveyard();
@@ -1761,5 +1763,5 @@
         void SetRegularAttackTime();
         void SetBaseModValue(BaseModGroup modGroup, BaseModType modType, float value) { m_auraBaseMod[modGroup][modType] = value; }
-        void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply);
+        void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply, bool affectStats = true);
         float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const;
         float GetTotalBaseModValue(BaseModGroup modGroup) const;
@@ -1768,5 +1770,5 @@
         void _RemoveAllStatBonuses();
 
-        void _ApplyWeaponDependentAuraMods(Item *item, WeaponAttackType attackType, bool apply);
+        void _ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply);
         void _ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply);
         void _ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply);
@@ -1933,8 +1935,8 @@
 
         /*********************************************************/
-        /***              ENVIROMENTAL SYSTEM                  ***/
-        /*********************************************************/
-
-        void EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage);
+        /***              ENVIRONMENTAL SYSTEM                  ***/
+        /*********************************************************/
+
+        void EnvironmentalDamage(uint64 guid, EnvironmentalDamageType type, uint32 damage);
 
         /*********************************************************/
@@ -2061,6 +2063,4 @@
 
         GridReference<Player> &GetGridRef() { return m_gridRef; }
-        MapReference &GetMapRef() { return m_mapRef; }
-
         bool isAllowedToLoot(Creature* creature);
 
@@ -2308,5 +2308,4 @@
 
         GridReference<Player> m_gridRef;
-        MapReference m_mapRef;
 };
 
Index: trunk/src/game/GMTicketHandler.cpp
===================================================================
--- trunk/src/game/GMTicketHandler.cpp (revision 263)
+++ trunk/src/game/GMTicketHandler.cpp (revision 272)
@@ -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,6 @@
     recv_data >> ticketText;
 
+    CharacterDatabase.escape_string(ticketText);
+
     if(GMTicket* ticket = ticketmgr.GetGMTicket(GetPlayer()->GetGUIDLow()))
         ticket->SetText(ticketText.c_str());
@@ -104,5 +106,7 @@
     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);
 
-    if(ticketmgr.GetGMTicket(GetPlayer()->GetGUIDLow()))
+    CharacterDatabase.escape_string(ticketText);
+
+    if(GMTicket* ticket = ticketmgr.GetGMTicket(GetPlayer()->GetGUIDLow()))
     {
         WorldPacket data( SMSG_GMTICKET_CREATE, 4 );
Index: trunk/src/game/CreatureAI.cpp
===================================================================
--- trunk/src/game/CreatureAI.cpp (revision 260)
+++ trunk/src/game/CreatureAI.cpp (revision 272)
@@ -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/SpellMgr.h
===================================================================
--- trunk/src/game/SpellMgr.h (revision 264)
+++ trunk/src/game/SpellMgr.h (revision 272)
@@ -285,5 +285,5 @@
 }
 
-//bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2);
+bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2);
 
 inline bool IsSealSpell(SpellEntry const *spellInfo)
@@ -301,6 +301,5 @@
 
 int32 CompareAuraRanks(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2);
-bool IsSingleFromSpellSpecificPerCaster(uint32 spellSpec1, uint32 spellSpec2);
-bool IsSingleFromSpellSpecificPerTarget(uint32 spellSpec1, uint32 spellSpec2);
+bool IsSingleFromSpellSpecificPerCaster(uint32 spellSpec1,uint32 spellSpec2);
 bool IsPassiveSpell(uint32 spellId);
 
@@ -770,5 +769,5 @@
         bool IsRankSpellDueToSpell(SpellEntry const *spellInfo_1,uint32 spellId_2) const;
         static bool canStackSpellRanks(SpellEntry const *spellInfo);
-        bool IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2, bool sameCaster) const;
+        bool IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) const;
 
         SpellEntry const* SelectAuraRankForPlayerLevel(SpellEntry const* spellInfo, uint32 playerLevel) const;
Index: trunk/src/game/GameEvent.cpp
===================================================================
--- trunk/src/game/GameEvent.cpp (revision 259)
+++ trunk/src/game/GameEvent.cpp (revision 272)
@@ -1504,5 +1504,5 @@
     CharacterDatabase.PExecute("DELETE FROM game_event_save WHERE event_id = '%u'",event_id);
     if(mGameEvent[event_id].nextstart)
-        CharacterDatabase.PExecute("INSERT INTO game_event_save (event_id, state, next_start) VALUES ('%u','%u',FROM_UNIXTIME("I64FMTD"))",event_id,mGameEvent[event_id].state,(uint64)(mGameEvent[event_id].nextstart));
+        CharacterDatabase.PExecute("INSERT INTO game_event_save (event_id, state, next_start) VALUES ('%u','%u',FROM_UNIXTIME("I64FMTD"))",event_id,mGameEvent[event_id].state,mGameEvent[event_id].nextstart);
     else
         CharacterDatabase.PExecute("INSERT INTO game_event_save (event_id, state, next_start) VALUES ('%u','%u','0000-00-00 00:00:00')",event_id,mGameEvent[event_id].state);
Index: trunk/src/game/World.h
===================================================================
--- trunk/src/game/World.h (revision 260)
+++ trunk/src/game/World.h (revision 272)
@@ -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,11 +52,4 @@
 };
 
-enum ShutdownExitCode
-{
-    SHUTDOWN_EXIT_CODE = 0,
-    ERROR_EXIT_CODE    = 1,
-    RESTART_EXIT_CODE  = 2,
-};
-
 /// Timers for different object refresh rates
 enum WorldTimers
@@ -69,5 +62,6 @@
     WUPDATE_CORPSES     = 5,
     WUPDATE_EVENTS      = 6,
-    WUPDATE_COUNT       = 7
+    WUPDATE_COUNT       = 7,
+
 };
 
@@ -112,6 +106,4 @@
     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,
@@ -152,5 +144,4 @@
     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,
@@ -326,18 +317,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; }
 };
 
@@ -346,4 +337,5 @@
 {
     public:
+        static volatile bool m_stopEvent;
         static volatile uint32 m_worldLoopCounter;
 
@@ -353,4 +345,5 @@
         WorldSession* FindSession(uint32 id) const;
         void AddSession(WorldSession *s);
+
         bool RemoveSession(uint32 id);
         /// Get the number of current active sessions
@@ -415,5 +408,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);
@@ -422,11 +415,9 @@
 
         /// 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, uint8 exitcode);
+        void ShutdownServ(uint32 time, uint32 options = 0);
         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);
@@ -463,5 +454,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);
@@ -491,11 +482,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:
@@ -508,9 +499,4 @@
         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;
@@ -540,4 +526,7 @@
         std::set<uint32> m_forbiddenMapIds;
 
+        uint32 m_ShutdownTimer;
+        uint32 m_ShutdownMask;
+
         // for max speed access
         static float m_MaxVisibleDistanceForCreature;
@@ -557,12 +546,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 260)
+++ trunk/src/game/Item.cpp (revision 272)
@@ -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_SOUL_SHARDS))
+                    if(!(pProto->BagFamily & BAG_FAMILY_MASK_SHARDS))
                         return false;
                     return true;
@@ -248,5 +248,5 @@
     Object::_Create( guidlow, 0, HIGHGUID_ITEM );
 
-    SetEntry(itemid);
+    SetUInt32Value(OBJECT_FIELD_ENTRY, itemid);
     SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
 
@@ -430,5 +430,5 @@
 ItemPrototype const *Item::GetProto() const
 {
-    return objmgr.GetItemPrototype(GetEntry());
+    return objmgr.GetItemPrototype(GetUInt32Value(OBJECT_FIELD_ENTRY));
 }
 
@@ -763,5 +763,7 @@
 {
     // Better lost small time at check in comparison lost time at item save to DB.
-    if((GetEnchantmentId(slot) == id) && (GetEnchantmentDuration(slot) == duration) && (GetEnchantmentCharges(slot) == charges))
+    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 )
         return;
 
@@ -774,5 +776,5 @@
 void Item::SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration)
 {
-    if(GetEnchantmentDuration(slot) == duration)
+    if(GetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_DURATION_OFFSET)==duration)
         return;
 
@@ -783,7 +785,4 @@
 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);
@@ -792,9 +791,9 @@
 void Item::ClearEnchantment(EnchantmentSlot slot)
 {
-    if(!GetEnchantmentId(slot))
-        return;
-
-    for(uint8 x = 0; x < 3; ++x)
-        SetUInt32Value(ITEM_FIELD_ENCHANTMENT + slot*MAX_ENCHANTMENT_OFFSET + x, 0);
+    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);
     SetState(ITEM_CHANGED);
 }
Index: trunk/src/game/GameObject.cpp
===================================================================
--- trunk/src/game/GameObject.cpp (revision 246)
+++ trunk/src/game/GameObject.cpp (revision 272)
@@ -1281,5 +1281,5 @@
     {
         trigger->setFaction(14);
-        trigger->CastSpell(target, spell, true, 0, 0, target->GetGUID());
+        trigger->CastSpell(target, spell, true);
     }
     //trigger->setDeathState(JUST_DIED);
Index: trunk/src/game/MapManager.cpp
===================================================================
--- trunk/src/game/MapManager.cpp (revision 260)
+++ trunk/src/game/MapManager.cpp (revision 272)
@@ -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
  */
 
@@ -112,5 +112,5 @@
         if (entry && entry->Instanceable())
         {
-            m = new MapInstanced(id, i_gridCleanUpDelay);
+            m = new MapInstanced(id, i_gridCleanUpDelay, 0);
         }
         else
@@ -223,5 +223,5 @@
 }
 
-void MapManager::DeleteInstance(uint32 mapid, uint32 instanceId)
+void MapManager::DeleteInstance(uint32 mapid, uint32 instanceId, uint8 mode)
 {
     Map *m = _GetBaseMap(mapid);
@@ -246,6 +246,4 @@
     if( !i_timer.Passed() )
         return;
-
-    ObjectAccessor::Instance().UpdatePlayers(i_timer.GetCurrent());
 
     for(MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
@@ -339,5 +337,5 @@
         for(MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr)
             if(mitr->second->IsDungeon())
-                ret += ((InstanceMap*)mitr->second)->GetPlayers().getSize();
+                ret += ((InstanceMap*)mitr->second)->GetPlayers().size();
     }
     return ret;
Index: trunk/src/game/Unit.cpp
===================================================================
--- trunk/src/game/Unit.cpp (revision 267)
+++ trunk/src/game/Unit.cpp (revision 272)
@@ -1149,4 +1149,6 @@
             if ( GetSpellSchoolMask(spellInfo) & SPELL_SCHOOL_MASK_NORMAL )
             {
+                uint32 modDamage=*damage;
+
                 // apply spellmod to Done damage
                 if(Player* modOwner = GetSpellModOwner())
@@ -1433,5 +1435,5 @@
     if(!this || !pVictim)
         return 0;
-    if(!isAlive() || !pVictim->isAlive())
+    if(!this->isAlive() || !pVictim->isAlive())
         return 0;
 
@@ -3781,4 +3783,5 @@
         {
             m_ccAuras.push_back(Aur);
+            RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CC);
         }
     }
@@ -3896,15 +3899,14 @@
         if(!is_triggered_by_spell)
         {
-            bool sameCaster = Aur->GetCasterGUID() == (*i).second->GetCasterGUID();
-            if( spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId, sameCaster) )
-            {
-                //some spells should be not removed by lower rank of them
-                // what is this spell?
-                if (!sameCaster
-                    &&(spellProto->Effect[effIndex]==SPELL_EFFECT_APPLY_AREA_AURA_PARTY)
-                    &&(spellProto->DurationIndex==21)
-                    &&(spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
-                    &&(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0))
-                    return false;
+            SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
+
+            bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
+
+            if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
+            {
+                // cannot remove higher rank
+                if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
+                    if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
+                        return false;
 
                 // Its a parent aura (create this aura in ApplyModifier)
@@ -3920,4 +3922,37 @@
                 else
                     next =  m_Auras.begin();
+            }
+            else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
+            {
+                // Its a parent aura (create this aura in ApplyModifier)
+                if ((*i).second->IsInUse())
+                {
+                    sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
+                    continue;
+                }
+                RemoveAurasDueToSpell(i_spellId);
+
+                if( m_Auras.empty() )
+                    break;
+                else
+                    next =  m_Auras.begin();
+            }
+            // Potions stack aura by aura (elixirs/flask already checked)
+            else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
+            {
+                if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
+                {
+                    if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
+                        return false;                       // cannot remove higher rank
+
+                    // Its a parent aura (create this aura in ApplyModifier)
+                    if ((*i).second->IsInUse())
+                    {
+                        sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
+                        continue;
+                    }
+                    RemoveAura(i);
+                    next = i;
+                }
             }
         }
@@ -4094,15 +4129,10 @@
 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
 {
-    Aura* Aur = i->second;
-    SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
-
-    Unit* caster = NULL;
-    if (IsSingleTargetSpell(AurSpellInfo))
-    {
-        caster = Aur->GetCaster();
-        if(caster)
+    if (IsSingleTargetSpell((*i).second->GetSpellProto()))
+    {
+        if(Unit* caster = (*i).second->GetCaster())
         {
             AuraList& scAuras = caster->GetSingleCastAuras();
-            scAuras.remove(Aur);
+            scAuras.remove((*i).second);
         }
         else
@@ -4113,6 +4143,5 @@
     }
 
-    // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
-    if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
+    if ((*i).second->GetModifier()->m_auraname < TOTAL_AURAS)
     {
         m_modAuras[(*i).second->GetModifier()->m_auraname].remove((*i).second);
@@ -4126,4 +4155,6 @@
     }
 
+    // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
+    Aura* Aur = i->second;
     // Set remove mode
     Aur->SetRemoveMode(mode);
@@ -4133,20 +4164,11 @@
     ++m_removedAuras;                                       // internal count used by unit update
 
-    // Statue unsummoned at aura remove
+    // Status unsummoned at aura remove
     Totem* statue = NULL;
-    bool caster_channeled = false;
-    if(IsChanneledSpell(AurSpellInfo))
-    {
-        if(!caster)                                         // can be already located for IsSingleTargetSpell case
-            caster = Aur->GetCaster();
-
-        if(caster)
-        {
+    if(IsChanneledSpell(Aur->GetSpellProto()))
+        if(Unit* caster = Aur->GetCaster())
             if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
                 statue = ((Totem*)caster);
-            else
-                caster_channeled = caster==this;
-        }
-    }
+
 
     if(const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(-(int32)Aur->GetSpellProto()->Id))
@@ -4165,7 +4187,4 @@
     Aur->_RemoveAura();
     delete Aur;
-
-    if(caster_channeled)
-        RemoveAurasAtChanneledTarget (AurSpellInfo);
 
     if(statue)
@@ -4594,8 +4613,6 @@
 }
 
-bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 cooldown)
-{
-    SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
-
+bool Unit::HandleHasteAuraProc(Unit *pVictim, SpellEntry const *hasteSpell, uint32 /*effIndex*/, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 cooldown)
+{
     Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
         ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
@@ -4657,9 +4674,6 @@
 }
 
-bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 cooldown)
-{
-    SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
-    uint32 effIndex = triggeredByAura->GetEffIndex ();
-
+bool Unit::HandleDummyAuraProc(Unit *pVictim, SpellEntry const *dummySpell, uint32 effIndex, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 cooldown)
+{
     Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
         ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
@@ -6249,4 +6263,5 @@
                             return false;
 
+                        uint32 spell = 0;
                         switch(triggeredByAura->GetSpellProto()->Id)
                         {
@@ -6278,4 +6293,5 @@
 
                         // overwrite non existing triggered spell call in spell.dbc
+                        uint32 spell = 0;
                         switch(triggeredByAura->GetSpellProto()->Id)
                         {
@@ -6477,8 +6493,6 @@
 }
 
-bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
-{
-    int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
-
+bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, int32 scriptId, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
+{
     if(!pVictim || !pVictim->isAlive())
         return false;
@@ -7246,5 +7260,5 @@
 }
 
-void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
+void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype, bool critical)
 {
     WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
@@ -7346,5 +7360,5 @@
     AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
     for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
-        if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
+        if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto))
             TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
 
@@ -8194,5 +8208,5 @@
 
     // ..done (for creature type by mask) in taken
-    AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
+    AuraList const& mDamageDoneCreature = this->GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
     for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
         if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
@@ -8262,5 +8276,5 @@
     // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT  included in weapon damage
 
-    AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
+    AuraList const& mDamageDoneVersus = this->GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
     for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
         if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
@@ -8492,6 +8506,5 @@
         target->SetStandState(PLAYER_STATE_NONE);
 
-    if(!target->isInCombat() && target->GetTypeId() != TYPEID_PLAYER
-        && ((Creature*)target)->isAggressive() && ((Creature*)target)->AI())
+    if(!target->isInCombat() && target->GetTypeId() != TYPEID_PLAYER && ((Creature*)target)->AI())
         ((Creature*)target)->AI()->AttackStart(this);
 
@@ -8542,7 +8555,4 @@
 {
     assert(target);
-
-    if(!IsHostileTo(target))
-        return false;
 
     if(!target->isAttackableByAOE() || target->hasUnitState(UNIT_STAT_DIED))
@@ -8721,5 +8731,5 @@
     if(IsInWorld())
     {
-        Map *m = GetMap();
+        Map *m = MapManager::Instance().GetMap(GetMapId(), this);
 
         if(GetTypeId()==TYPEID_PLAYER)
@@ -9130,11 +9140,4 @@
     }
 
-    // search nearby enemy before enter evade mode
-    if(Unit *target = ((Creature*)this)->SelectNearestTarget())
-    {
-        ((Creature*)this)->AI()->AttackStart(target);
-        return true;
-    }
-
     // enter in evade mode in other case
     ((Creature*)this)->AI()->EnterEvadeMode();
@@ -9790,4 +9793,6 @@
 }
 
+
+
 CharmInfo* Unit::InitCharmInfo(Unit *charm)
 {
@@ -9953,13 +9958,15 @@
 struct ProcTriggeredData
 {
-    ProcTriggeredData(Aura* _triggeredByAura, uint32 _cooldown)
-        : triggeredByAura(_triggeredByAura),
+    ProcTriggeredData(SpellEntry const * _spellInfo, uint32 _spellParam, Aura* _triggeredByAura, uint32 _cooldown)
+        : spellInfo(_spellInfo), spellParam(_spellParam), triggeredByAura(_triggeredByAura),
         triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex())),
         cooldown(_cooldown)
-    {}
-
-    Aura* triggeredByAura;                                  // triggred aura, can be invalidate at triggered aura proccessing
-    Unit::spellEffectPair triggeredByAura_SpellPair;        // spell pair, used for re-find aura (by pointer comparison in range)
-    uint32 cooldown;                                        // possible hidden cooldown
+        {}
+
+    SpellEntry const * spellInfo;
+    uint32 spellParam;
+    Aura* triggeredByAura;
+    Unit::spellEffectPair triggeredByAura_SpellPair;
+    uint32 cooldown;
 };
 
@@ -9978,11 +9985,85 @@
             next = i; ++next;
 
-            Aura* i_aura = *i;
-
-            uint32 cooldown;                                // returned at next line
-            if(!IsTriggeredAtSpellProcEvent(i_aura->GetSpellProto(), procSpell, procFlag,attType,isVictim,cooldown))
+            SpellEntry const *spellProto = (*i)->GetSpellProto();
+            if(!spellProto)
                 continue;
 
-            procTriggered.push_back( ProcTriggeredData(i_aura, cooldown) );
+            SpellProcEventEntry const *spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
+            if(!spellProcEvent)
+            {
+                // used to prevent spam in log about same non-handled spells
+                static std::set<uint32> nonHandledSpellProcSet;
+
+                if(spellProto->procFlags != 0 && nonHandledSpellProcSet.find(spellProto->Id)==nonHandledSpellProcSet.end())
+                {
+                    sLog.outError("ProcDamageAndSpell: spell %u (%s aura source) not have record in `spell_proc_event`)",spellProto->Id,(isVictim?"a victim's":"an attacker's"));
+                    nonHandledSpellProcSet.insert(spellProto->Id);
+                }
+
+                // spell.dbc use totally different flags, that only can create problems if used.
+                continue;
+            }
+
+            // Check spellProcEvent data requirements
+            if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, procSpell,procFlag))
+                continue;
+
+            // Check if current equipment allows aura to proc
+            if(!isVictim && GetTypeId() == TYPEID_PLAYER )
+            {
+                if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
+                {
+                    Item *item = ((Player*)this)->GetWeaponForAttack(attType,true);
+
+                    if(!item || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
+                        continue;
+                }
+                else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
+                {
+                    // Check if player is wearing shield
+                    Item *item = ((Player*)this)->GetShield(true);
+                    if(!item || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
+                        continue;
+                }
+            }
+
+            float chance = (float)spellProto->procChance;
+
+            if(Player* modOwner = GetSpellModOwner())
+                modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
+
+            if(!isVictim && spellProcEvent->ppmRate != 0)
+            {
+                uint32 WeaponSpeed = GetAttackTime(attType);
+                chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
+            }
+
+            if(roll_chance_f(chance))
+            {
+                uint32 cooldown = spellProcEvent->cooldown;
+
+                uint32 i_spell_eff = (*i)->GetEffIndex();
+
+                int32 i_spell_param;
+                switch(*aur)
+                {
+                    case SPELL_AURA_PROC_TRIGGER_SPELL:
+                        i_spell_param = procFlag;
+                        break;
+                    case SPELL_AURA_DUMMY:
+                    case SPELL_AURA_PRAYER_OF_MENDING:
+                    case SPELL_AURA_MOD_HASTE:
+                        i_spell_param = i_spell_eff;
+                        break;
+                    case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
+                        i_spell_param = (*i)->GetModifier()->m_miscvalue;
+                        break;
+                    default:
+                        i_spell_param = (*i)->GetModifier()->m_amount;
+                        break;
+                }
+
+                procTriggered.push_back( ProcTriggeredData(spellProto,i_spell_param,*i, cooldown) );
+            }
         }
 
@@ -10017,31 +10098,21 @@
             }
 
-            /// this is aura triggering code call
-            Aura* triggeredByAura = i->triggeredByAura;
-
-            /// save charges existence before processing to prevent crash at access to deleted triggered aura after
-            /// used in speedup code check before check aura existance.
-            bool triggeredByAuraWithCharges =  triggeredByAura->m_procCharges > 0;
-
-            /// success in event proccesing
-            /// used in speedup code check before check aura existance.
+            // save charges existence before processing to prevent crash at access to deleted triggered aura after
+            bool triggeredByAuraWithCharges =  i->triggeredByAura->m_procCharges > 0;
+
             bool casted = false;
-
-            /// process triggered code
             switch(*aur)
             {
                 case SPELL_AURA_PROC_TRIGGER_SPELL:
                 {
-                    sLog.outDebug("ProcDamageAndSpell: casting spell (triggered by %s proc aura of spell %u)",
-                        (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-                    casted = HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, attType, i->cooldown);
+                    sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", i->spellInfo->Id,(isVictim?"a victim's":"an attacker's"),i->triggeredByAura->GetId());
+                    casted = HandleProcTriggerSpell(pTarget, damage, i->triggeredByAura, procSpell,i->spellParam,attType,i->cooldown);
                     break;
                 }
                 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
                 {
-                    uint32 triggered_damage = triggeredByAura->GetModifier()->m_amount;
-                    sLog.outDebug("ProcDamageAndSpell: doing %u damage (triggered by %s aura of spell %u)",
-                        triggered_damage, (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-                    SpellNonMeleeDamageLog(pTarget, triggeredByAura->GetId(), triggered_damage, true, true);
+                    sLog.outDebug("ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", i->spellParam, i->spellInfo->Id,(isVictim?"a victim's":"an attacker's"),i->triggeredByAura->GetId());
+                    uint32 damage = i->spellParam;
+                    SpellNonMeleeDamageLog(pTarget, i->spellInfo->Id, damage, true, true);
                     casted = true;
                     break;
@@ -10049,23 +10120,69 @@
                 case SPELL_AURA_DUMMY:
                 {
-                    uint32 effect = triggeredByAura->GetEffIndex();
-                    sLog.outDebug("ProcDamageAndSpell: casting spell (triggered by %s dummy aura of spell %u)",
-                        (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-                    casted = HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag,i->cooldown);
+                    sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", i->spellInfo->Id,(isVictim?"a victim's":"an attacker's"),i->triggeredByAura->GetId());
+                    casted = HandleDummyAuraProc(pTarget, i->spellInfo, i->spellParam, damage, i->triggeredByAura, procSpell, procFlag,i->cooldown);
                     break;
                 }
                 case SPELL_AURA_PRAYER_OF_MENDING:
                 {
-                    sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
-                        (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-
-                    casted = HandleMeandingAuraProc(triggeredByAura);
+                    sLog.outDebug("ProcDamageAndSpell(mending): casting spell id %u (triggered by %s dummy aura of spell %u)", i->spellInfo->Id,(isVictim?"a victim's":"an attacker's"),i->triggeredByAura->GetId());
+
+                    // aura can be deleted at casts
+                    int32 heal = i->triggeredByAura->GetModifier()->m_amount;
+                    uint64 caster_guid = i->triggeredByAura->GetCasterGUID();
+
+                    // jumps
+                    int32 jumps = i->triggeredByAura->m_procCharges-1;
+
+                    // current aura expire
+                    i->triggeredByAura->m_procCharges = 1;  // will removed at next charges decrease
+
+                    // next target selection
+                    if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
+                    {
+                        Aura* aura = i->triggeredByAura;
+
+                        SpellEntry const* spellProto = aura->GetSpellProto();
+                        uint32 effIdx = aura->GetEffIndex();
+
+                        float radius;
+                        if (spellProto->EffectRadiusIndex[effIdx])
+                            radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
+                        else
+                            radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
+
+                        if(Player* caster = ((Player*)aura->GetCaster()))
+                        {
+                            caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
+
+                            if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
+                            {
+                                // aura will applied from caster, but spell casted from current aura holder
+                                SpellModifier *mod = new SpellModifier;
+                                mod->op = SPELLMOD_CHARGES;
+                                mod->value = jumps-5;               // negative
+                                mod->type = SPELLMOD_FLAT;
+                                mod->spellId = spellProto->Id;
+                                mod->effectId = effIdx;
+                                mod->lastAffected = NULL;
+                                mod->mask = spellProto->SpellFamilyFlags;
+                                mod->charges = 0;
+
+                                caster->AddSpellMod(mod, true);
+                                CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,aura,caster->GetGUID());
+                                caster->AddSpellMod(mod, false);
+                            }
+                        }
+                    }
+
+                    // heal
+                    CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
+                    casted = true;
                     break;
                 }
                 case SPELL_AURA_MOD_HASTE:
                 {
-                    sLog.outDebug("ProcDamageAndSpell: casting spell (triggered by %s haste aura of spell %u)",
-                        (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-                    casted = HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag,i->cooldown);
+                    sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", i->spellInfo->Id,(isVictim?"a victim's":"an attacker's"),i->triggeredByAura->GetId());
+                    casted = HandleHasteAuraProc(pTarget, i->spellInfo, i->spellParam, damage, i->triggeredByAura, procSpell, procFlag,i->cooldown);
                     break;
                 }
@@ -10074,12 +10191,11 @@
                     // nothing do, just charges counter
                     // but count only in case appropriate school damage
-                    casted = triggeredByAura->GetModifier()->m_miscvalue & damageSchoolMask;
+                    casted = i->triggeredByAura->GetModifier()->m_miscvalue & damageSchoolMask;
                     break;
                 }
                 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
                 {
-                    sLog.outDebug("ProcDamageAndSpell: casting spell (triggered by %s class script aura of spell %u)",
-                        (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
-                    casted = HandleOverrideClassScriptAuraProc(pTarget, triggeredByAura, procSpell,i->cooldown);
+                    sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", i->spellInfo->Id,(isVictim?"a victim's":"an attacker's"),i->triggeredByAura->GetId());
+                    casted = HandleOverrideClassScriptAuraProc(pTarget, i->spellParam, damage, i->triggeredByAura, procSpell,i->cooldown);
                     break;
                 }
@@ -10092,18 +10208,18 @@
             }
 
-            /// Update charge (aura can be removed by triggers)
+            // Update charge (aura can be removed by triggers)
             if(casted && triggeredByAuraWithCharges)
             {
-                /// need re-found aura (can be dropped by triggers)
+                // need found aura (can be dropped by triggers)
                 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
                 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
                 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
                 {
-                    if(itr->second == triggeredByAura)      // pointer still valid
+                    if(itr->second == i->triggeredByAura)
                     {
-                        if(triggeredByAura->m_procCharges > 0)
-                            triggeredByAura->m_procCharges -= 1;
-
-                        triggeredByAura->UpdateAuraCharges();
+                        if(i->triggeredByAura->m_procCharges > 0)
+                            i->triggeredByAura->m_procCharges -= 1;
+
+                        i->triggeredByAura->UpdateAuraCharges();
                         break;
                     }
@@ -10112,5 +10228,5 @@
         }
 
-        /// Safely remove auras with zero charges
+        // Safely remove auras with zero charges
         for(AuraList::const_iterator i = auras.begin(), next; i != auras.end(); i = next)
         {
@@ -10225,5 +10341,5 @@
     // send explicit stop packet
     // rely on vmaps here because for example stormwind is in air
-    //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
+    float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
     //if (fabs(GetPositionZ() - z) < 2.0f)
     //    Relocate(GetPositionX(), GetPositionY(), z);
@@ -10435,5 +10551,5 @@
 }
 
-Unit* Unit::SelectNearbyTarget(float dist) const
+Unit* Unit::SelectNearbyTarget() const
 {
     CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
@@ -10445,5 +10561,5 @@
 
     {
-        Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist);
+        Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
         Trinity::UnitListSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(targets, u_check);
 
@@ -10709,7 +10825,7 @@
     }
 
-    pet->SetUInt64Value(UNIT_FIELD_SUMMONEDBY, GetGUID());
-    pet->SetUInt64Value(UNIT_FIELD_CREATEDBY, GetGUID());
-    pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE,getFaction());
+    pet->SetUInt64Value(UNIT_FIELD_SUMMONEDBY, this->GetGUID());
+    pet->SetUInt64Value(UNIT_FIELD_CREATEDBY, this->GetGUID());
+    pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE,this->getFaction());
     pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
 
@@ -10729,131 +10845,2 @@
     return pet;
 }
-
-bool Unit::IsTriggeredAtSpellProcEvent(SpellEntry const* spellProto, SpellEntry const* procSpell, uint32 procFlag, WeaponAttackType attType, bool isVictim, uint32& cooldown )
-{
-    SpellProcEventEntry const * spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
-
-    if(!spellProcEvent)
-    {
-        // used to prevent spam in log about same non-handled spells
-        static std::set<uint32> nonHandledSpellProcSet;
-
-        if(spellProto->procFlags != 0 && nonHandledSpellProcSet.find(spellProto->Id)==nonHandledSpellProcSet.end())
-        {
-            sLog.outError("ProcDamageAndSpell: spell %u (%s aura source) not have record in `spell_proc_event`)",spellProto->Id,(isVictim?"a victim's":"an attacker's"));
-            nonHandledSpellProcSet.insert(spellProto->Id);
-        }
-
-        // spell.dbc use totally different flags, that only can create problems if used.
-        return false;
-    }
-
-    // Check spellProcEvent data requirements
-    if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, procSpell,procFlag))
-        return false;
-
-    // Check if current equipment allows aura to proc
-    if(!isVictim && GetTypeId() == TYPEID_PLAYER )
-    {
-        if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
-        {
-            Item *item = ((Player*)this)->GetWeaponForAttack(attType,true);
-
-            if(!item || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
-                return false;
-        }
-        else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
-        {
-            // Check if player is wearing shield
-            Item *item = ((Player*)this)->GetShield(true);
-            if(!item || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
-                return false;
-        }
-    }
-
-    float chance = (float)spellProto->procChance;
-
-    if(Player* modOwner = GetSpellModOwner())
-        modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
-
-    if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
-    {
-        uint32 WeaponSpeed = GetAttackTime(attType);
-        chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
-    }
-
-    cooldown = spellProcEvent ? spellProcEvent->cooldown : 0;
-    return roll_chance_f(chance);
-}
-
-bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
-{
-    // aura can be deleted at casts
-    SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
-    uint32 effIdx = triggeredByAura->GetEffIndex();
-    int32 heal = triggeredByAura->GetModifier()->m_amount;
-    uint64 caster_guid = triggeredByAura->GetCasterGUID();
-
-    // jumps
-    int32 jumps = triggeredByAura->m_procCharges-1;
-
-    // current aura expire
-    triggeredByAura->m_procCharges = 1;             // will removed at next charges decrease
-
-    // next target selection
-    if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
-    {
-        float radius;
-        if (spellProto->EffectRadiusIndex[effIdx])
-            radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
-        else
-            radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
-
-        if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
-        {
-            caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
-
-            if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
-            {
-                // aura will applied from caster, but spell casted from current aura holder
-                SpellModifier *mod = new SpellModifier;
-                mod->op = SPELLMOD_CHARGES;
-                mod->value = jumps-5;               // negative
-                mod->type = SPELLMOD_FLAT;
-                mod->spellId = spellProto->Id;
-                mod->effectId = effIdx;
-                mod->lastAffected = NULL;
-                mod->mask = spellProto->SpellFamilyFlags;
-                mod->charges = 0;
-
-                caster->AddSpellMod(mod, true);
-                CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
-                caster->AddSpellMod(mod, false);
-            }
-        }
-    }
-
-    // heal
-    CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
-    return true;
-}
-
-void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
-{
-    uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
-
-    if(!IS_UNIT_GUID(target_guid))
-        return;
-
-    Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
-    if(!target)
-        return;
-
-    for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
-    {
-        if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
-            target->RemoveAura(iter);
-        else
-            ++iter;
-    }
-}
Index: trunk/src/game/ObjectMgr.h
===================================================================
--- trunk/src/game/ObjectMgr.h (revision 263)
+++ trunk/src/game/ObjectMgr.h (revision 272)
@@ -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;
-    int32  dataint;
+    std::string datatext;
     float x;
     float y;
@@ -128,11 +128,4 @@
 
 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
@@ -215,6 +208,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
 };
 
@@ -258,5 +251,5 @@
 // NPC gossip text id
 typedef UNORDERED_MAP<uint32, uint32> CacheNpcTextIdMap;
-typedef std::list<GossipOption> CacheNpcOptionList;
+
 
 typedef UNORDERED_MAP<uint32, VendorItemData> CacheVendorItemMap;
@@ -307,8 +300,7 @@
         typedef UNORDERED_MAP<uint32, Quest*> QuestMap;
 
-
         typedef UNORDERED_MAP<uint32, AreaTrigger> AreaTriggerMap;
 
-        typedef UNORDERED_MAP<uint32, uint32> AreaTriggerScriptMap;
+        typedef UNORDERED_MAP<uint32, std::string> AreaTriggerScriptMap;
 
         typedef UNORDERED_MAP<uint32, ReputationOnKillEntry> RepOnKillMap;
@@ -317,6 +309,4 @@
 
         typedef UNORDERED_MAP<uint32, PetCreateSpellEntry> PetCreateSpellMap;
-
-        typedef std::vector<std::string> ScriptNameMap;
 
         Player* GetPlayer(const char* name) const { return ObjectAccessor::Instance().FindPlayerByName(name);}
@@ -487,5 +477,5 @@
         AreaTrigger const* GetGoBackTrigger(uint32 Map) const;
 
-        uint32 GetAreaTriggerScriptId(uint32 trigger_id);
+        const char* GetAreaTriggerScriptName(uint32 id);
 
         ReputationOnKillEntry const* GetReputationOnKilEntry(uint32 id) const
@@ -533,6 +523,5 @@
 
         bool LoadTrinityStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value);
-        bool LoadTrinityStrings() { return LoadTrinityStrings(WorldDatabase,"trinity_string",MIN_TRINITY_STRING_ID,MAX_TRINITY_STRING_ID); }
-	void LoadDbScriptStrings();
+        bool LoadTrinityStrings() { return LoadTrinityStrings(WorldDatabase,"trinity_string",1,std::numeric_limits<int32>::max()); }
         void LoadPetCreateSpells();
         void LoadCreatureLocales();
@@ -604,6 +593,4 @@
         uint32 GenerateItemTextID();
         uint32 GeneratePetNumber();
-        uint32 GenerateArenaTeamId();
-        uint32 GenerateGuildId();
         
         void LoadPlayerInfoInCache();
@@ -682,4 +669,5 @@
             return &itr->second;
         }
+        
         NpcOptionLocale const* GetNpcOptionLocale(uint32 entry) const
         {
@@ -706,5 +694,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)); }
 
@@ -745,5 +733,5 @@
         LocaleConstant GetLocaleForIndex(int i);
         // guild bank tabs
-        uint32 GetGuildBankTabPrice(uint8 Index) const { return Index < GUILD_BANK_MAX_TABS ? mGuildBankTabPrice[Index] : 0; }
+        const uint32 GetGuildBankTabPrice(uint8 Index) { return Index < GUILD_BANK_MAX_TABS ? mGuildBankTabPrice[Index] : 0; }
 
         uint16 GetConditionId(ConditionType condition, uint32 value1, uint32 value2);
@@ -766,5 +754,5 @@
         bool AddGameTele(GameTele& data);
         bool DeleteGameTele(std::string name);
-
+        
         CacheNpcOptionList const& GetNpcOptions() const { return m_mCacheNpcOptionList; }
 
@@ -774,5 +762,5 @@
             if(iter == m_mCacheNpcTextIdMap.end())
                 return 0;
-
+            
             return iter->second;
         }
@@ -795,23 +783,13 @@
             return &iter->second;
         }
-        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);
+        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;
+
     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;
@@ -822,5 +800,7 @@
         uint32 m_hiCorpseGuid;
 
-        QuestMap            mQuestTemplates;
+        uint32 m_hiPetNumber;
+
+        QuestMap mQuestTemplates;
 
         typedef UNORDERED_MAP<uint32, GossipText*> GossipTextMap;
@@ -869,6 +849,4 @@
         GameTeleMap         m_GameTeleMap;
 
-        ScriptNameMap       m_scriptNames;
-
         typedef             std::vector<LocaleConstant> LocalForIndex;
         LocalForIndex        m_LocalForIndex;
@@ -878,5 +856,4 @@
     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);
@@ -931,8 +908,6 @@
 
 // scripting access functions
-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();
+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);
 
 #endif
Index: trunk/src/game/Level2.cpp
===================================================================
--- trunk/src/game/Level2.cpp (revision 263)
+++ trunk/src/game/Level2.cpp (revision 272)
@@ -2362,6 +2362,6 @@
     // Check
     // Remember: "show" must also be the name of a column!
-    if( (show != "emote") && (show != "spell") && (show != "textid1") && (show != "textid2")
-        && (show != "textid3") && (show != "textid4") && (show != "textid5")
+    if( (show != "emote") && (show != "spell") && (show != "text1") && (show != "text2")
+        && (show != "text3") && (show != "text4") && (show != "text5")
         && (show != "waittime") && (show != "del") && (show != "move") && (show != "add")
         && (show != "model1") && (show != "model2") && (show != "orientation"))
@@ -2703,11 +2703,4 @@
         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;
     }
@@ -2850,5 +2843,5 @@
 
         QueryResult *result =
-            WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, model1, model2 FROM creature_movement WHERE wpguid = %u",
+            WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, text1, text2, text3, text4, text5, model1, model2 FROM creature_movement WHERE wpguid = %u",
             target->GetGUIDLow() );
         if(!result)
@@ -2862,5 +2855,5 @@
             PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetGUID());
 
-            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 )",
+            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 )",
                 target->GetPositionX(), maxDIFF, target->GetPositionY(), maxDIFF, target->GetPositionZ(), maxDIFF);
             if(!result)
@@ -2879,7 +2872,9 @@
             uint32 emote            = fields[3].GetUInt32();
             uint32 spell            = fields[4].GetUInt32();
-            uint32 textid[MAX_WAYPOINT_TEXT];
-            for(int i = 0;  i < MAX_WAYPOINT_TEXT; ++i)
-                textid[i]           = fields[5+i].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 model1           = fields[10].GetUInt32();
             uint32 model2           = fields[11].GetUInt32();
@@ -2894,6 +2889,9 @@
             PSendSysMessage(LANG_WAYPOINT_INFO_EMOTE, emote);
             PSendSysMessage(LANG_WAYPOINT_INFO_SPELL, spell);
-            for(int i = 0;  i < MAX_WAYPOINT_TEXT; ++i)
-                PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, i+1, textid[i], (textid[i] ? GetTrinityString(textid[i]) : ""));
+            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);
 
         }while( result->NextRow() );
@@ -3216,6 +3214,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, textid1, textid2, textid3, textid4, textid5, 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, text1, text2, text3, text4, text5, id FROM creature_movement WHERE id = '%u' ORDER BY point", lowguid );
 
     if (!result)
@@ -3234,5 +3232,5 @@
 
         outfile << "INSERT INTO creature_movement ";
-        outfile << "( id, point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5 ) VALUES ";
+        outfile << "( id, point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, text1, text2, text3, text4, text5 ) VALUES ";
 
         outfile << "( ";
@@ -3259,13 +3257,63 @@
         outfile << fields[9].GetUInt32();                   // spell
         outfile << ", ";
-        outfile << fields[10].GetUInt32();                  // textid1
+        const char *tmpChar = fields[10].GetString();
+        if( !tmpChar )
+        {
+            outfile << "NULL";                              // text1
+        }
+        else
+        {
+            outfile << "'";
+            outfile << tmpChar;                             // text1
+            outfile << "'";
+        }
         outfile << ", ";
-        outfile << fields[11].GetUInt32();                  // textid2
+        tmpChar = fields[11].GetString();
+        if( !tmpChar )
+        {
+            outfile << "NULL";                              // text2
+        }
+        else
+        {
+            outfile << "'";
+            outfile << tmpChar;                             // text2
+            outfile << "'";
+        }
         outfile << ", ";
-        outfile << fields[12].GetUInt32();                  // textid3
+        tmpChar = fields[12].GetString();
+        if( !tmpChar )
+        {
+            outfile << "NULL";                              // text3
+        }
+        else
+        {
+            outfile << "'";
+            outfile << tmpChar;                             // text3
+            outfile << "'";
+        }
         outfile << ", ";
-        outfile << fields[13].GetUInt32();                  // textid4
+        tmpChar = fields[13].GetString();
+        if( !tmpChar )
+        {
+            outfile << "NULL";                              // text4
+        }
+        else
+        {
+            outfile << "'";
+            outfile << tmpChar;                             // text4
+            outfile << "'";
+        }
         outfile << ", ";
-        outfile << fields[14].GetUInt32();                  // textid5
+        tmpChar = fields[14].GetString();
+        if( !tmpChar )
+        {
+            outfile << "NULL";                              // text5
+        }
+        else
+        {
+            outfile << "'";
+            outfile << tmpChar;                             // text5
+            outfile << "'";
+        }
         outfile << ");\n ";
 
Index: trunk/src/game/ItemPrototype.h
===================================================================
--- trunk/src/game/ItemPrototype.h (revision 260)
+++ trunk/src/game/ItemPrototype.h (revision 272)
@@ -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
  */
 
@@ -79,5 +79,5 @@
     NO_BIND                                     = 0,
     BIND_WHEN_PICKED_UP                         = 1,
-    BIND_WHEN_EQUIPED                           = 2,
+    BIND_WHEN_EQUIPPED                           = 2,
     BIND_WHEN_USE                               = 3,
     BIND_QUEST_ITEM                             = 4,
@@ -100,7 +100,5 @@
     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_BOA                            = 0x08000000, // bind on account
-    ITEM_FLAGS_MILLABLE                       = 0x20000000
+    ITEM_FLAGS_SPECIALUSE                     = 0x00800000  // last used flag in 2.3.0
 };
 
@@ -109,7 +107,7 @@
     BAG_FAMILY_MASK_ARROWS                    = 0x00000001,
     BAG_FAMILY_MASK_BULLETS                   = 0x00000002,
-    BAG_FAMILY_MASK_SOUL_SHARDS               = 0x00000004,
+    BAG_FAMILY_MASK_SHARDS                    = 0x00000004,
     BAG_FAMILY_MASK_LEATHERWORKING_SUPP       = 0x00000008,
-    BAG_FAMILY_MASK_INSCRIPTION_SUPP          = 0x00000010,
+    BAG_FAMILY_MASK_UNUSED                    = 0x00000010, // not used currently
     BAG_FAMILY_MASK_HERBS                     = 0x00000020,
     BAG_FAMILY_MASK_ENCHANTING_SUPP           = 0x00000040,
@@ -119,8 +117,10 @@
     BAG_FAMILY_MASK_MINING_SUPP               = 0x00000400,
     BAG_FAMILY_MASK_SOULBOUND_EQUIPMENT       = 0x00000800,
-    BAG_FAMILY_MASK_VANITY_PETS               = 0x00001000,
-    BAG_FAMILY_MASK_CURRENCY_TOKENS           = 0x00002000,
-    BAG_FAMILY_MASK_QUEST_ITEMS               = 0x00004000
-};
+    BAG_FAMILY_MASK_VANITY_PETS               = 0x00001000
+};
+
+/* TODO: Not entirely positive on need for this??
+enum SOCKET_CONTENT ();
+*/
 
 enum SocketColor
@@ -276,5 +276,5 @@
 };
 
-#define MAX_ITEM_SUBCLASS_ARMOR                   10
+#define MAX_ITEM_SUBCLASS_ARMOR                  10
 
 enum ItemSubclassReagent
@@ -390,20 +390,4 @@
 
 #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] =
@@ -541,5 +525,5 @@
     uint32 RequiredDisenchantSkill;
     float  ArmorDamageModifier;
-    uint32 ScriptId;
+    char* ScriptName;
     uint32 DisenchantID;
     uint32 FoodType;
Index: trunk/src/game/Player.cpp
===================================================================
--- trunk/src/game/Player.cpp (revision 257)
+++ trunk/src/game/Player.cpp (revision 272)
@@ -800,5 +800,5 @@
 }
 
-void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
+void Player::EnvironmentalDamage(uint64 guid, EnvironmentalDamageType type, uint32 damage)
 {
     WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
@@ -1642,5 +1642,5 @@
     {
         // far teleport to another map
-        Map* oldmap = IsInWorld() ? GetMap() : NULL;
+        Map* oldmap = IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL;
         // check if we can enter before stopping combat / removing pet / totems / interrupting spells
 
@@ -3751,5 +3751,5 @@
 }
 
-void Player::ResurrectPlayer(float restore_percent, bool applySickness)
+void Player::ResurrectPlayer(float restore_percent, bool updateToWorld, bool applySickness)
 {
     WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4);          // remove spirit healer position
@@ -4282,5 +4282,5 @@
 }
 
-void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
+void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply, bool affectStats)
 {
     if(modGroup >= BASEMOD_END || modType >= MOD_END)
@@ -5244,5 +5244,5 @@
     }
 
-    Map *m = GetMap();
+    Map *m = MapManager::Instance().GetMap(GetMapId(), this);
 
     const float old_x = GetPositionX();
@@ -5262,5 +5262,5 @@
 
         // reread after Map::Relocation
-        m = GetMap();
+        m = MapManager::Instance().GetMap(GetMapId(), this);
         x = GetPositionX();
         y = GetPositionY();
@@ -6177,7 +6177,5 @@
         return 0;
 
-    uint32 id = (*result)[0].GetUInt32();
-    delete result;
-    return id;
+    return (*result)[0].GetUInt32();
 }
 
@@ -6710,5 +6708,5 @@
     }
 
-    if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
+    if(!IsUseEquippedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
         return;
 
@@ -8488,5 +8486,5 @@
         return item;
 
-    if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
+    if( item->IsBroken() || !IsUseEquippedWeapon(attackType==BASE_ATTACK) )
         return NULL;
 
@@ -8642,5 +8640,4 @@
     return false;
 }
-
 
 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
@@ -10159,5 +10156,5 @@
         if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
             pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
-            pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
+            pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos) )
             pItem->SetBinding( true );
 
@@ -10205,5 +10202,5 @@
         if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
             pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
-            pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
+            pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos) )
             pItem2->SetBinding( true );
 
@@ -10407,5 +10404,5 @@
 
     // check also  BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
-    if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
+    if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
         pItem->SetBinding( true );
 
@@ -10551,4 +10548,6 @@
         if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
             CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
+
+        ItemPrototype const *pProto = pItem->GetProto();
 
         RemoveEnchantmentDurations(pItem);
@@ -14209,5 +14208,5 @@
         SetUInt32Value(i, 0);
 
-    //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
+    //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
 
     if(result)
@@ -14219,9 +14218,8 @@
             uint32 spellid = fields[1].GetUInt32();
             uint32 effindex = fields[2].GetUInt32();
-            uint32 stackcount = fields[3].GetUInt32();
-            int32 damage     = (int32)fields[4].GetUInt32();
-            int32 maxduration = (int32)fields[5].GetUInt32();
-            int32 remaintime = (int32)fields[6].GetUInt32();
-            int32 remaincharges = (int32)fields[7].GetUInt32();
+            int32 damage     = (int32)fields[3].GetUInt32();
+            int32 maxduration = (int32)fields[4].GetUInt32();
+            int32 remaintime = (int32)fields[5].GetUInt32();
+            int32 remaincharges = (int32)fields[6].GetUInt32();
 
             SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
@@ -14260,13 +14258,9 @@
                 continue;
 
-            for(uint32 i=0; i<stackcount; i++)
-            {
-                Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
-                if(!damage)
-                    damage = aura->GetModifier()->m_amount;
-                aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
-                AddAura(aura);
-                sLog.outString("Added aura spellid %u, effect %u", spellproto->Id, effindex);
-            }
+            Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
+            if(!damage)
+                damage = aura->GetModifier()->m_amount;
+            aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
+            AddAura(aura);
         }
         while( result->NextRow() );
@@ -15327,52 +15321,29 @@
 
     AuraMap const& auras = GetAuras();
-
-    if (auras.empty())
-        return;
-
-    spellEffectPair lastEffectPair = auras.begin()->first;
-    uint32 stackCounter = 1;
-
-    for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
-    {
-        if(itr == auras.end() || lastEffectPair != itr->first)
-        {
-            AuraMap::const_iterator itr2 = itr;
-            // save previous spellEffectPair to db
-            itr2--;
-            SpellEntry const *spellInfo = itr2->second->GetSpellProto();
-
-            //skip all auras from spells that are passive or need a shapeshift
-            if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
-            {
-                //do not save single target auras (unless they were cast by the player)
-                if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
-                {
-                    uint8 i;
-                    // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
-                    for (i = 0; i < 3; i++)
-                        if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
-                        spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
-                            break;
-
-                    if (i == 3)
-                    {
-                        CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
-                            "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
-                            GetGUIDLow(), itr2->second->GetCasterGUID(), (uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->m_procCharges));
-                    }
-                }
-            }
-
-            if(itr == auras.end())
+    for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
+    {
+        SpellEntry const *spellInfo = itr->second->GetSpellProto();
+
+        //skip all auras from spells that are passive or need a shapeshift
+        if (itr->second->IsPassive() || itr->second->IsRemovedOnShapeLost())
+            continue;
+
+        //do not save single target auras (unless they were cast by the player)
+        if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
+            continue;
+
+        uint8 i;
+        // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
+        for (i = 0; i < 3; i++)
+            if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
+            spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
                 break;
-        }
-
-        if (lastEffectPair == itr->first)
-            stackCounter++;
-        else
-        {
-            lastEffectPair = itr->first;
-            stackCounter = 1;
+
+        if (i == 3)
+        {
+            CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u' and spell = '%u' and  effect_index= '%u'",GetGUIDLow(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex());
+            CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
+                "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%d', '%d', '%d', '%d')",
+                GetGUIDLow(), itr->second->GetCasterGUID(), (uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(), (*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
         }
     }
@@ -17940,5 +17911,5 @@
             continue;
 
-        if (sSpellStore.LookupEntry(pAbility->spellId))
+        if (SpellEntry const* spellentry = sSpellStore.LookupEntry(pAbility->spellId))
         {
             // Ok need learn spell
@@ -18353,4 +18324,5 @@
         Player* not_gray_member_with_max_level = NULL;
 
+        // gets the max member level of the group, and the max member level that still gets XP
         pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
 
@@ -18361,5 +18333,5 @@
             xp = (PvP || !not_gray_member_with_max_level) ? 0 : Trinity::XP::Gain(not_gray_member_with_max_level, pVictim);
 
-            /// skip in check PvP case (for speed, not used)
+            // skip in check PvP case (for speed, not used)
             bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
             bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
@@ -18688,16 +18660,4 @@
     UpdateBlockPercentage();
 }
-
-bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
-{
-    for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
-        if(itr->pos == pos)
-            return true;
-    return false;
-}
-
-//***********************************
-//-------------TRINITY---------------
-//***********************************
 
 void Player::HandleFallDamage(MovementInfo& movementInfo)
@@ -18937,6 +18897,6 @@
                 target->AddThreat(this, 1000000.0f);
         }
-        // Delete the assigned possessed AI
-        ((Creature*)target)->DeletePossessedAI();
+        // Disable the assigned possessed AI
+        ((Creature*)target)->DisablePossessedAI();
     }
 }
@@ -19002,4 +18962,13 @@
 }
 
+bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
+{
+    for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
+        if(itr->pos == this->pos)
+            return true;
+
+    return false;
+}
+
 bool Player::isTotalImmunity()
 {
Index: trunk/src/game/GridNotifiersImpl.h
===================================================================
--- trunk/src/game/GridNotifiersImpl.h (revision 265)
+++ trunk/src/game/GridNotifiersImpl.h (revision 272)
@@ -73,5 +73,5 @@
 
     // Creature AI reaction
-    if(c->isAggressive() && !c->hasUnitState(UNIT_STAT_CHASE | UNIT_STAT_SEARCHING | UNIT_STAT_FLEEING))
+    if(!c->hasUnitState(UNIT_STAT_CHASE | UNIT_STAT_SEARCHING | UNIT_STAT_FLEEING))
     {
         if( c->AI() && c->IsWithinSightDist(pl) /*c->AI()->IsVisible(pl)*/ && !c->IsInEvadeMode() )
@@ -82,5 +82,5 @@
 inline void CreatureCreatureRelocationWorker(Creature* c1, Creature* c2)
 {
-    if(c1->isAggressive() && !c1->hasUnitState(UNIT_STAT_CHASE | UNIT_STAT_SEARCHING | UNIT_STAT_FLEEING))
+    if(!c1->hasUnitState(UNIT_STAT_CHASE | UNIT_STAT_SEARCHING | UNIT_STAT_FLEEING))
     {
         if( c1->AI() && c1->IsWithinSightDist(c2) /*c1->AI()->IsVisible(c2)*/ && !c1->IsInEvadeMode() )
@@ -88,5 +88,5 @@
     }
 
-    if(c2->isAggressive() && !c2->hasUnitState(UNIT_STAT_CHASE | UNIT_STAT_SEARCHING | UNIT_STAT_FLEEING))
+    if(!c2->hasUnitState(UNIT_STAT_CHASE | UNIT_STAT_SEARCHING | UNIT_STAT_FLEEING))
     {
         if( c2->AI() && c1->IsWithinSightDist(c2) /*c2->AI()->IsVisible(c1)*/ && !c2->IsInEvadeMode() )
Index: trunk/src/game/NPCHandler.cpp
===================================================================
--- trunk/src/game/NPCHandler.cpp (revision 257)
+++ trunk/src/game/NPCHandler.cpp (revision 272)
@@ -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
  */
 
@@ -223,5 +223,5 @@
     TrainerSpellData const* trainer_spells = unit->GetTrainerSpells();
     if(!trainer_spells)
-        return;
+        return; 
 
     // not found, cheat?
@@ -340,11 +340,13 @@
     if(!code.empty())
     {
+
         if (!Script->GossipSelectWithCode(_player, unit, _player->PlayerTalkClass->GossipOptionSender (option), _player->PlayerTalkClass->GossipOptionAction( option ), code.c_str()))
             unit->OnGossipSelect (_player, option);
     }
     else
+
     {
         if (!Script->GossipSelect (_player, unit, _player->PlayerTalkClass->GossipOptionSender (option), _player->PlayerTalkClass->GossipOptionAction (option)))
-           unit->OnGossipSelect (_player, option);
+            unit->OnGossipSelect (_player, option);
     }
 }
@@ -376,5 +378,5 @@
 void WorldSession::SendSpiritResurrect()
 {
-    _player->ResurrectPlayer(0.5f, true);
+    _player->ResurrectPlayer(0.5f,false, true);
 
     _player->DurabilityLossAll(0.25f,true);
Index: trunk/src/game/Spell.cpp
===================================================================
--- trunk/src/game/Spell.cpp (revision 248)
+++ trunk/src/game/Spell.cpp (revision 272)
@@ -997,7 +997,4 @@
 
             unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL);
-            //TODO: find a better way to judge CC auras
-            if(m_spellInfo->Attributes & SPELL_ATTR_BREAKABLE_BY_DAMAGE)
-                unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CC);
         }
         else
Index: trunk/src/game/Pet.cpp
===================================================================
--- trunk/src/game/Pet.cpp (revision 265)
+++ trunk/src/game/Pet.cpp (revision 272)
@@ -287,9 +287,4 @@
             ++iter;
             m_charmInfo->GetActionBarEntry(index)->SpellOrAction = atol((*iter).c_str());
-
-            // patch for old data where some spells have ACT_DECIDE but should have ACT_CAST
-            // so overwrite old state 
-            SpellEntry const *spellInfo = sSpellStore.LookupEntry(m_charmInfo->GetActionBarEntry(index)->SpellOrAction);
-            if (spellInfo && spellInfo->AttributesEx & SPELL_ATTR_EX_UNAUTOCASTABLE_BY_PET) m_charmInfo->GetActionBarEntry(index)->Type = ACT_CAST;
         }
 
@@ -1328,5 +1323,5 @@
         SetUInt32Value(i, 0);
 
-    QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
+    QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM pet_aura WHERE guid = '%u'",m_charmInfo->GetPetNumber());
 
     if(result)
@@ -1338,9 +1333,8 @@
             uint32 spellid = fields[1].GetUInt32();
             uint32 effindex = fields[2].GetUInt32();
-            uint32 stackcount= fields[3].GetUInt32();
-            int32 damage     = (int32)fields[4].GetUInt32();
-            int32 maxduration = (int32)fields[5].GetUInt32();
-            int32 remaintime = (int32)fields[6].GetUInt32();
-            int32 remaincharges = (int32)fields[7].GetUInt32();
+            int32 damage     = (int32)fields[3].GetUInt32();
+            int32 maxduration = (int32)fields[4].GetUInt32();
+            int32 remaintime = (int32)fields[5].GetUInt32();
+            int32 remaincharges = (int32)fields[6].GetUInt32();
 
             SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
@@ -1379,13 +1373,10 @@
                 continue;
 
-            for(uint32 i=0; i<stackcount; i++)
-            {
-                Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
-
-                if(!damage)
-                    damage = aura->GetModifier()->m_amount;
-                aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
-                AddAura(aura);
-            }
+            Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
+
+            if(!damage)
+                damage = aura->GetModifier()->m_amount;
+            aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
+            AddAura(aura);
         }
         while( result->NextRow() );
@@ -1400,50 +1391,28 @@
 
     AuraMap const& auras = GetAuras();
-    if (auras.empty())
-        return;
-
-    spellEffectPair lastEffectPair = auras.begin()->first;
-    uint32 stackCounter = 1;
-
-    for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
-    {
-        if(itr == auras.end() || lastEffectPair != itr->first)
-        {
-            AuraMap::const_iterator itr2 = itr;
-            // save previous spellEffectPair to db
-            itr2--;
-            SpellEntry const *spellInfo = itr2->second->GetSpellProto();
-            /// do not save single target auras (unless they were cast by the player)
-            if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
-            {
-                if(!itr2->second->IsPassive())
-                {
-                    // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
-                    uint8 i;
-                    for (i = 0; i < 3; i++)
-                        if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
-                            spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
-                            spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
-                            break;
-
-                    if (i == 3)
-                    {
-                        CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
-                            "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%u', '%d', '%d', '%d', '%d')",
-                            m_charmInfo->GetPetNumber(), itr2->second->GetCasterGUID(),(uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->m_procCharges));
-                    }
-                }
-            }
-            if(itr == auras.end())
+    for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
+    {
+        // skip all auras from spell that apply at cast SPELL_AURA_MOD_SHAPESHIFT or pet area auras.
+        SpellEntry const *spellInfo = itr->second->GetSpellProto();
+        uint8 i;
+        for (i = 0; i < 3; i++)
+            if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH ||
+                spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_OWNER ||
+                spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_PET )
                 break;
-        }
-
-        if (lastEffectPair == itr->first)
-            stackCounter++;
-        else
-        {
-            lastEffectPair = itr->first;
-            stackCounter = 1;
-        }
+
+        if (i != 3)
+            continue;
+        
+        if(itr->second->IsPassive())
+            continue;
+
+        /// do not save single target auras (unless they were cast by the player)
+        if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
+            continue;
+
+        CharacterDatabase.PExecute("INSERT INTO pet_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
+            "VALUES ('%u', '" I64FMTD "', '%u', '%u', '%d', '%d', '%d', '%d')",
+            m_charmInfo->GetPetNumber(), itr->second->GetCasterGUID(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(),(*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
     }
 }
@@ -1465,8 +1434,4 @@
         return false;
     }
-
-    // same spells don't have autocast option
-    if (spellInfo->AttributesEx & SPELL_ATTR_EX_UNAUTOCASTABLE_BY_PET)
-        active = ACT_CAST;
 
     PetSpellMap::iterator itr = m_spells.find(spell_id);
@@ -1544,5 +1509,5 @@
         CastSpell(this, spell_id, true);
     else if(state == PETSPELL_NEW)
-        m_charmInfo->AddSpellToAB(oldspell_id, spell_id, (ActiveStates)active);
+        m_charmInfo->AddSpellToAB(oldspell_id, spell_id);
 
     if(newspell->active == ACT_ENABLED)
@@ -1694,8 +1659,8 @@
         return;
 
-    //if(const SpellEntry *tempSpell = GetSpellStore()->LookupEntry(spellid))
-    //    if(tempSpell->EffectImplicitTargetA[0] != TARGET_ALL_AROUND_CASTER
-    //        && tempSpell->EffectImplicitTargetA[0] != TARGET_CHAIN_DAMAGE)
-    //        return;    
+    if(const SpellEntry *tempSpell = GetSpellStore()->LookupEntry(spellid))
+        if(tempSpell->EffectImplicitTargetA[0] != TARGET_ALL_AROUND_CASTER
+            && tempSpell->EffectImplicitTargetA[0] != TARGET_CHAIN_DAMAGE)
+            return;    
 
     PetSpellMap::const_iterator itr = m_spells.find((uint16)spellid);
Index: trunk/src/game/WaypointManager.h
===================================================================
--- trunk/src/game/WaypointManager.h (revision 263)
+++ trunk/src/game/WaypointManager.h (revision 272)
@@ -26,10 +26,9 @@
 #include "Utilities/UnorderedMap.h"
 
-#define MAX_WAYPOINT_TEXT 5
 struct WaypointBehavior
 {
     uint32 emote;
     uint32 spell;
-    int32  textid[MAX_WAYPOINT_TEXT];
+    std::string text[5];
     uint32 model1;
     uint32 model2;
Index: trunk/src/game/AuctionHouse.cpp
===================================================================
--- trunk/src/game/AuctionHouse.cpp (revision 260)
+++ trunk/src/game/AuctionHouse.cpp (revision 272)
@@ -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 << (uint32) auction->Id;
-    data << (uint32) pItem->GetEntry();
+    data << auction->Id;
+    data << pItem->GetUInt32Value(OBJECT_FIELD_ENTRY);
 
     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 equiped empty bag to auction)
+    // prevent sending bag with items (cheat: can be placed in bag after adding equipped empty bag to auction)
     if(!it)
     {
@@ -717,5 +717,5 @@
                                             if (il)
                                             {
-                                                if (il->Name.size() > size_t(loc_idx) && !il->Name[loc_idx].empty())
+                                                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
                                                     name = il->Name[loc_idx];
                                             }
Index: trunk/src/game/MapInstanced.cpp
===================================================================
--- trunk/src/game/MapInstanced.cpp (revision 257)
+++ trunk/src/game/MapInstanced.cpp (revision 272)
@@ -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
  */
 
@@ -27,5 +27,5 @@
 #include "World.h"
 
-MapInstanced::MapInstanced(uint32 id, time_t expiry) : Map(id, expiry, 0, 0)
+MapInstanced::MapInstanced(uint32 id, time_t expiry, uint32 aInstanceId) : Map(id, expiry, 0, 0)
 {
     // initialize instanced maps list
@@ -262,2 +262,3 @@
     m_InstancedMaps.erase(itr++);
 }
+
Index: trunk/src/game/ObjectMgr.cpp
===================================================================
--- trunk/src/game/ObjectMgr.cpp (revision 263)
+++ trunk/src/game/ObjectMgr.cpp (revision 272)
@@ -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,5 +22,4 @@
 #include "Database/DatabaseEnv.h"
 #include "Database/SQLStorage.h"
-#include "Database/SQLStorageImpl.h"
 
 #include "Log.h"
@@ -118,10 +117,6 @@
     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);
@@ -421,5 +416,5 @@
 
         //prepare mail data... :
-        uint32 itemTextId = CreateItemText( msgAuctionWonBody.str() );
+        uint32 itemTextId = this->CreateItemText( msgAuctionWonBody.str() );
 
         // set owner to bidder (to prevent delete item with sender char deleting)
@@ -472,5 +467,5 @@
         sLog.outDebug("AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
 
-        uint32 itemTextId = CreateItemText( msgAuctionSalePendingBody.str() );
+        uint32 itemTextId = this->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);
@@ -504,5 +499,5 @@
         sLog.outDebug("AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
 
-        uint32 itemTextId = CreateItemText( auctionSuccessfulBody.str() );
+        uint32 itemTextId = this->CreateItemText( auctionSuccessfulBody.str() );
 
         uint32 profit = auction->bid + auction->deposit - auctionCut;
@@ -551,4 +546,5 @@
         // 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
@@ -568,6 +564,6 @@
 void ObjectMgr::LoadCreatureLocales()
 {
-    mCreatureLocaleMap.clear();                              // need for reload case
-
+    mCreatureLocaleMap.clear();
+    
     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");
 
@@ -628,5 +624,5 @@
     sLog.outString( ">> Loaded %u creature locale strings", mCreatureLocaleMap.size() );
 }
-   
+
 void ObjectMgr::LoadNpcOptionLocales()
 {
@@ -697,17 +693,7 @@
 }
 
-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()
 {
-    SQLCreatureLoader loader;
-    loader.Load(sCreatureStorage);
+    sCreatureStorage.Load();
 
     sLog.outString( ">> Loaded %u creature definitions", sCreatureStorage.RecordCount );
@@ -1527,5 +1513,5 @@
         aItem->location = fields[11].GetUInt8();
         //check if sold item exists
-        if ( GetAItem( aItem->item_guidlow ) )
+        if ( this->GetAItem( aItem->item_guidlow ) )
         {
             GetAuctionsMap( aItem->location )->AddAuction(aItem);
@@ -1547,6 +1533,6 @@
 void ObjectMgr::LoadItemLocales()
 {
-    mItemLocaleMap.clear();                                 // need for reload case
-
+    mItemLocaleMap.clear();
+    
     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");
 
@@ -1609,17 +1595,7 @@
 }
 
-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()
 {
-    SQLItemLoader loader;
-    loader.Load(sItemStorage);
+    sItemStorage.Load ();
     sLog.outString( ">> Loaded %u item prototypes", sItemStorage.RecordCount );
     sLog.outString();
@@ -2531,5 +2507,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)
@@ -3580,5 +3556,5 @@
 void ObjectMgr::LoadQuestLocales()
 {
-    mQuestLocaleMap.clear();                                // need for reload case
+    mQuestLocaleMap.clear();
 
     QueryResult *result = WorldDatabase.Query("SELECT entry,"
@@ -3774,5 +3750,5 @@
     scripts.clear();                                        // need for reload support
 
-    QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,dataint, x, y, z, o FROM %s", tablename );
+    QueryResult *result = WorldDatabase.PQuery( "SELECT id,delay,command,datalong,datalong2,datatext, x, y, z, o FROM %s", tablename );
 
     uint32 count = 0;
@@ -3796,14 +3772,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.dataint   = fields[5].GetInt32();
-        tmp.x         = fields[6].GetFloat();
-        tmp.y         = fields[7].GetFloat();
-        tmp.z         = fields[8].GetFloat();
-        tmp.o         = fields[9].GetFloat();
+        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();
 
         // generic command args check
@@ -3817,16 +3793,4 @@
                     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;
             }
@@ -4193,6 +4157,6 @@
 void ObjectMgr::LoadPageTextLocales()
 {
-    mPageTextLocaleMap.clear();                             // need for reload case
-
+    mPageTextLocaleMap.clear();
+    
     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");
 
@@ -4243,17 +4207,7 @@
 }
 
-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()
 {
-    SQLInstanceLoader loader;
-    loader.Load(sInstanceTemplate);
+    sInstanceTemplate.Load();
 
     for(uint32 i = 0; i < sInstanceTemplate.MaxEntry; i++)
@@ -4371,6 +4325,6 @@
 void ObjectMgr::LoadNpcTextLocales()
 {
-    mNpcTextLocaleMap.clear();                              // need for reload case
-
+    mNpcTextLocaleMap.clear();
+    
     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,"
@@ -4669,5 +4623,5 @@
 
         uint32 Trigger_ID      = fields[0].GetUInt32();
-        const char *scriptName = fields[1].GetString();
+        std::string scriptName = fields[1].GetCppString();
 
         AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
@@ -4677,5 +4631,5 @@
             continue;
         }
-        mAreaTriggerScripts[Trigger_ID] = GetScriptId(scriptName);
+        mAreaTriggerScripts[Trigger_ID] = scriptName;
     } while( result->NextRow() );
 
@@ -4685,5 +4639,4 @@
     sLog.outString( ">> Loaded %u areatrigger scripts", count );
 }
-
 uint32 ObjectMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )
 {
@@ -4744,9 +4697,9 @@
 uint16 ObjectMgr::GetTaxiMount( uint32 id, uint32 team )
 {
-    uint16 mount_entry = 0;
-    uint16 mount_id = 0;
+    uint32 mount_entry = 0;
+    uint32 mount_id = 0;
 
     TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id);
-    if(node)
+    if (node)
     {
         if (team == ALLIANCE) mount_entry = node->alliance_mount_type;
@@ -4987,4 +4940,5 @@
     }
 
+            // find now nearest graveyard at same map
     if(entryNear)
         return entryNear;
@@ -5227,4 +5181,5 @@
     {
         m_hiCharGuid = (*result)[0].GetUInt32()+1;
+
         delete result;
     }
@@ -5234,9 +5189,15 @@
     {
         m_hiCreatureGuid = (*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(id) FROM character_pet" );
+    if( result )
+    {
+        m_hiPetGuid = (*result)[0].GetUInt32()+1;
+
+        delete result;
+    }
 
     result = CharacterDatabase.Query( "SELECT MAX(guid) FROM item_instance" );
@@ -5244,4 +5205,5 @@
     {
         m_hiItemGuid = (*result)[0].GetUInt32()+1;
+
         delete result;
     }
@@ -5257,4 +5219,5 @@
     {
         m_hiGoGuid = (*result)[0].GetUInt32()+1;
+
         delete result;
     }
@@ -5264,20 +5227,31 @@
     {
         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()+1;
+        m_ItemTextId = (*result)[0].GetUInt32();
+
         delete result;
     }
+    else
+        m_ItemTextId = 0;
 
     result = CharacterDatabase.Query( "SELECT MAX(guid) FROM corpse" );
@@ -5285,70 +5259,40 @@
     {
         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()
 {
-    if(m_auctionid>=0xFFFFFFFE)
+    ++m_auctionid;
+    if(m_auctionid>=0xFFFFFFFF)
     {
         sLog.outError("Auctions ids overflow!! Can't continue, shutting down server. ");
-        World::StopNow(ERROR_EXIT_CODE);
-    }
-    return m_auctionid++;
+        sWorld.m_stopEvent = true;
+    }
+    return m_auctionid;
 }
 
 uint32 ObjectMgr::GenerateMailID()
 {
-    if(m_mailid>=0xFFFFFFFE)
+    ++m_mailid;
+    if(m_mailid>=0xFFFFFFFF)
     {
         sLog.outError("Mail ids overflow!! Can't continue, shutting down server. ");
-        World::StopNow(ERROR_EXIT_CODE);
-    }
-    return m_mailid++;
+        sWorld.m_stopEvent = true;
+    }
+    return m_mailid;
 }
 
 uint32 ObjectMgr::GenerateItemTextID()
 {
-    if(m_ItemTextId>=0xFFFFFFFE)
+    ++m_ItemTextId;
+    if(m_ItemTextId>=0xFFFFFFFF)
     {
         sLog.outError("Item text ids overflow!! Can't continue, shutting down server. ");
-        World::StopNow(ERROR_EXIT_CODE);
-    }
-    return m_ItemTextId++;
+        sWorld.m_stopEvent = true;
+    }
+    return m_ItemTextId;
 }
 
@@ -5372,52 +5316,59 @@
     {
         case HIGHGUID_ITEM:
-            if(m_hiItemGuid>=0xFFFFFFFE)
+            ++m_hiItemGuid;
+            if(m_hiItemGuid>=0xFFFFFFFF)
             {
                 sLog.outError("Item guid overflow!! Can't continue, shutting down server. ");
-                World::StopNow(ERROR_EXIT_CODE);
-            }
-            return m_hiItemGuid++;
+                sWorld.m_stopEvent = true;
+            }
+            return m_hiItemGuid;
         case HIGHGUID_UNIT:
-            if(m_hiCreatureGuid>=0x00FFFFFE)
+            ++m_hiCreatureGuid;
+            if(m_hiCreatureGuid>=0x00FFFFFF)
             {
                 sLog.outError("Creature guid overflow!! Can't continue, shutting down server. ");
-                World::StopNow(ERROR_EXIT_CODE);
-            }
-            return m_hiCreatureGuid++;
+                sWorld.m_stopEvent = true;
+            }
+            return m_hiCreatureGuid;
         case HIGHGUID_PET:
-            if(m_hiPetGuid>=0x00FFFFFE)
+            ++m_hiPetGuid;
+            if(m_hiPetGuid>=0x00FFFFFF)
             {
                 sLog.outError("Pet guid overflow!! Can't continue, shutting down server. ");
-                World::StopNow(ERROR_EXIT_CODE);
-            }
-            return m_hiPetGuid++;
+                sWorld.m_stopEvent = true;
+            }
+            return m_hiPetGuid;
         case HIGHGUID_PLAYER:
-            if(m_hiCharGuid>=0xFFFFFFFE)
+            ++m_hiCharGuid;
+            if(m_hiCharGuid>=0xFFFFFFFF)
             {
                 sLog.outError("Players guid overflow!! Can't continue, shutting down server. ");
-                World::StopNow(ERROR_EXIT_CODE);
-            }
-            return m_hiCharGuid++;
+                sWorld.m_stopEvent = true;
+            }
+            return m_hiCharGuid;
         case HIGHGUID_GAMEOBJECT:
-            if(m_hiGoGuid>=0x00FFFFFE)
+            ++m_hiGoGuid;
+            if(m_hiGoGuid>=0x00FFFFFF)
             {
                 sLog.outError("Gameobject guid overflow!! Can't continue, shutting down server. ");
-                World::StopNow(ERROR_EXIT_CODE);
-            }
-            return m_hiGoGuid++;
+                sWorld.m_stopEvent = true;
+            }
+            return m_hiGoGuid;
         case HIGHGUID_CORPSE:
-            if(m_hiCorpseGuid>=0xFFFFFFFE)
+            ++m_hiCorpseGuid;
+            if(m_hiCorpseGuid>=0xFFFFFFFF)
             {
                 sLog.outError("Corpse guid overflow!! Can't continue, shutting down server. ");
-                World::StopNow(ERROR_EXIT_CODE);
-            }
-            return m_hiCorpseGuid++;
+                sWorld.m_stopEvent = true;
+            }
+            return m_hiCorpseGuid;
         case HIGHGUID_DYNAMICOBJECT:
-            if(m_hiDoGuid>=0xFFFFFFFE)
+            ++m_hiDoGuid;
+            if(m_hiDoGuid>=0xFFFFFFFF)
             {
                 sLog.outError("DynamicObject guid overflow!! Can't continue, shutting down server. ");
-                World::StopNow(ERROR_EXIT_CODE);
-            }
-            return m_hiDoGuid++;
+                sWorld.m_stopEvent = true;
+            }
+            return m_hiDoGuid;
         default:
             ASSERT(0);
@@ -5430,6 +5381,6 @@
 void ObjectMgr::LoadGameObjectLocales()
 {
-    mGameObjectLocaleMap.clear();                           // need for reload case
-
+    mGameObjectLocaleMap.clear();
+    
     QueryResult *result = WorldDatabase.Query("SELECT entry,"
         "name_loc1,name_loc2,name_loc3,name_loc4,name_loc5,name_loc6,name_loc7,name_loc8,"
@@ -5499,17 +5450,7 @@
 }
 
-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()
 {
-    SQLGameObjectLoader loader;
-    loader.Load(sGOStorage);
+    sGOStorage.Load();
 
     // some checks
@@ -6684,10 +6625,10 @@
 }
 
-uint32 ObjectMgr::GetAreaTriggerScriptId(uint32 trigger_id)
-{
-    AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(trigger_id);
+const char* ObjectMgr::GetAreaTriggerScriptName(uint32 id)
+{
+    AreaTriggerScriptMap::const_iterator i = mAreaTriggerScripts.find(id);
     if(i!= mAreaTriggerScripts.end())
-        return i->second;
-    return 0;
+        return i->second.c_str();
+    return "";
 }
 
@@ -6734,8 +6675,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;
@@ -6858,28 +6799,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;
@@ -7011,5 +6952,5 @@
         if(itr->first > new_id)
             new_id = itr->first;
-
+    
     // use next
     ++new_id;
@@ -7051,5 +6992,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();
@@ -7142,5 +7083,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();
@@ -7249,5 +7190,4 @@
         "SELECT id,gossip_id,npcflag,icon,action,box_money,coded,option_text,box_text "
         "FROM npc_option");
-
     if( !result )
     {
@@ -7402,82 +7342,8 @@
 }
 
-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
-uint32 GetAreaTriggerScriptId(uint32 trigger_id)
-{
-    return objmgr.GetAreaTriggerScriptId(trigger_id);
+const char* GetAreaTriggerScriptNameById(uint32 id)
+{
+    return objmgr.GetAreaTriggerScriptName(id);
 }
 
@@ -7494,12 +7360,2 @@
     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();
-}
Index: trunk/src/game/SpellMgr.cpp
===================================================================
--- trunk/src/game/SpellMgr.cpp (revision 265)
+++ trunk/src/game/SpellMgr.cpp (revision 272)
@@ -100,5 +100,5 @@
 }
 
-/*bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2)
+bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2)
 {
     SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
@@ -114,5 +114,5 @@
 
     return true;
-}*/
+}
 
 int32 CompareAuraRanks(uint32 spellId_1, uint32 effIndex_1, uint32 spellId_2, uint32 effIndex_2)
@@ -245,17 +245,4 @@
         case SPELL_CURSE:
         case SPELL_ASPECT:
-        case SPELL_POSITIVE_SHOUT:
-        case SPELL_JUDGEMENT:
-        case SPELL_WARLOCK_CORRUPTION:
-            return spellSpec1==spellSpec2;
-        default:
-            return false;
-    }
-}
-
-bool IsSingleFromSpellSpecificPerTarget(uint32 spellSpec1,uint32 spellSpec2)
-{
-    switch(spellSpec1)
-    {
         case SPELL_TRACKER:
         case SPELL_WARLOCK_ARMOR:
@@ -263,4 +250,7 @@
         case SPELL_ELEMENTAL_SHIELD:
         case SPELL_MAGE_POLYMORPH:
+        case SPELL_POSITIVE_SHOUT:
+        case SPELL_JUDGEMENT:
+        case SPELL_WARLOCK_CORRUPTION:
             return spellSpec1==spellSpec2;
         case SPELL_BATTLE_ELIXIR:
@@ -1041,8 +1031,8 @@
 }
 
-bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2, bool sameCaster) const
-{
-    //if(spellId_1 == spellId_2) // auras due to the same spell
-    //    return false;
+bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) const
+{
+    if(spellId_1 == spellId_2) // auras due to the same spell
+        return false;
 
     SpellEntry const *spellInfo_1 = sSpellStore.LookupEntry(spellId_1);
@@ -1052,16 +1042,8 @@
         return false;
 
-    SpellSpecific spellId_spec_1 = GetSpellSpecific(spellId_1);
-    SpellSpecific spellId_spec_2 = GetSpellSpecific(spellId_2);
-    if (spellId_spec_1 && spellId_spec_2)
-        if (IsSingleFromSpellSpecificPerTarget(spellId_spec_1, spellId_spec_2)
-            ||(IsSingleFromSpellSpecificPerCaster(spellId_spec_1, spellId_spec_2) && sameCaster))
-            return true;
-
     if(spellInfo_1->SpellFamilyName != spellInfo_2->SpellFamilyName)
         return false;
 
-    // generic spells
-    if(!spellInfo_1->SpellFamilyName)
+    if(!spellInfo_1->SpellFamilyName) // generic spells
     {
         if(!spellInfo_1->SpellIconID 
@@ -1069,46 +1051,11 @@
             return false;
     }
-
-    // if both elixirs are not battle/guardian/potions/flasks then always stack
-    else if(spellInfo_1->SpellFamilyName == SPELLFAMILY_POTION)
-    {
-        if(spellId_spec_1 || spellId_spec_2)
+    else if (spellInfo_1->SpellFamilyFlags != spellInfo_2->SpellFamilyFlags)
+        return false;
+
+    for(uint32 i = 0; i < 3; ++i)
+        if(spellInfo_1->Effect[i] != spellInfo_2->Effect[i]
+            || spellInfo_1->EffectApplyAuraName[i] != spellInfo_2->EffectApplyAuraName[i])
             return false;
-    }
-
-    // check for class spells
-    else
-    {
-        if (spellInfo_1->SpellFamilyFlags != spellInfo_2->SpellFamilyFlags)
-            return false;
-    }
-
-    for(uint32 i = 0; i < 3; ++i)
-    {
-        if(spellInfo_1->Effect[i] != spellInfo_2->Effect[i]
-            || spellInfo_1->EffectApplyAuraName[i] != spellInfo_2->EffectApplyAuraName[i]
-            || spellInfo_1->EffectMiscValue[i] != spellInfo_2->EffectMiscValue[i]) // paladin resist aura
-            return false; // need itemtype check? need an example to add that check
-
-        if(spellInfo_1->EffectApplyAuraName[i] // both spell has the same auras
-            && !sameCaster
-            && spellInfo_1->Effect[i] != SPELL_EFFECT_APPLY_AREA_AURA_PARTY) // not area auras (shaman totem)
-            // a better check may be effect == SPELL_EFFECT_APPLY_AURA
-        {
-            switch(spellInfo_1->EffectApplyAuraName[i])
-            {
-                // DOT or HOT from different casters will stack
-                case SPELL_AURA_PERIODIC_DAMAGE:
-                case SPELL_AURA_PERIODIC_HEAL:
-                case SPELL_AURA_PERIODIC_TRIGGER_SPELL:
-                case SPELL_AURA_PERIODIC_ENERGIZE:
-                case SPELL_AURA_PERIODIC_MANA_LEECH:
-                case SPELL_AURA_PERIODIC_LEECH:
-                    return false;
-                default:
-                    break;
-            }
-        }
-    }
 
     return true;
Index: trunk/src/game/ObjectAccessor.cpp
===================================================================
--- trunk/src/game/ObjectAccessor.cpp (revision 268)
+++ trunk/src/game/ObjectAccessor.cpp (revision 272)
@@ -143,13 +143,5 @@
 {
     Creature * ret = GetObjectInWorld(guid, (Creature*)NULL);
-    if(!ret)
-        return NULL;
-
-    if(ret->GetMapId() != u.GetMapId())
-        return NULL;
-
-    if(ret->GetInstanceId() != u.GetInstanceId())
-        return NULL;
-
+    if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
     return ret;
 }
@@ -257,4 +249,30 @@
 
 void
+ObjectAccessor::_update()
+{
+    UpdateDataMapType update_players;
+    {
+        Guard guard(i_updateGuard);
+        while(!i_objects.empty())
+        {
+            Object* obj = *i_objects.begin();
+            i_objects.erase(i_objects.begin());
+            if (!obj)
+                continue;
+            _buildUpdateObject(obj, update_players);
+            obj->ClearUpdateMask(false);
+        }
+    }
+
+    WorldPacket packet;                                     // here we allocate a std::vector with a size of 0x10000
+    for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
+    {
+        iter->second.BuildPacket(&packet);
+        iter->first->GetSession()->SendPacket(&packet);
+        packet.clear();                                     // clean the string
+    }
+}
+
+void
 ObjectAccessor::UpdateObject(Object* obj, Player* exceptPlayer)
 {
@@ -344,5 +362,5 @@
     TypeContainerVisitor<WorldObjectChangeAccumulator, WorldTypeMapContainer > player_notifier(notifier);
     CellLock<GridReadGuard> cell_lock(cell, p);
-    cell_lock->Visit(cell_lock, player_notifier, *obj->GetMap());
+    cell_lock->Visit(cell_lock, player_notifier, *MapManager::Instance().GetMap(obj->GetMapId(), obj));
 }
 
@@ -488,8 +506,19 @@
 
 void
+ObjectAccessor::AddActiveObject( WorldObject * obj )
+{
+    i_activeobjects.insert(obj);
+}
+
+void
+ObjectAccessor::RemoveActiveObject( WorldObject * obj )
+{
+    i_activeobjects.erase(obj);
+}
+
+void
 ObjectAccessor::Update(uint32 diff)
 {
-/*    {
-        //Player update now in MapManager -> UpdatePlayers
+    {
         // player update might remove the player from grid, and that causes crashes. We HAVE to update players first, and then the active objects.
         HashMapHolder<Player>::MapType& playerMap = HashMapHolder<Player>::GetContainer();
@@ -502,5 +531,4 @@
         }
 
-        // TODO: move this to Map::Update
         // clone the active object list, because update might remove from it
         std::set<WorldObject *> activeobjects(i_activeobjects);
@@ -561,36 +589,31 @@
             }
         }
-    }*/
-
-    UpdateDataMapType update_players;
-    {
-        Guard guard(i_updateGuard);
-        while(!i_objects.empty())
-        {
-            Object* obj = *i_objects.begin();
-            i_objects.erase(i_objects.begin());
-            if (!obj)
-                continue;
-            _buildUpdateObject(obj, update_players);
-            obj->ClearUpdateMask(false);
-        }
-    }
-
-    WorldPacket packet;                                     // here we allocate a std::vector with a size of 0x10000
-    for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
-    {
-        iter->second.BuildPacket(&packet);
-        iter->first->GetSession()->SendPacket(&packet);
-        packet.clear();                                     // clean the string
-    }
-}
-
-void
-ObjectAccessor::UpdatePlayers(uint32 diff)
-{
-    HashMapHolder<Player>::MapType& playerMap = HashMapHolder<Player>::GetContainer();
-    for(HashMapHolder<Player>::MapType::iterator iter = playerMap.begin(); iter != playerMap.end(); ++iter)
-        if(iter->second->IsInWorld())
-            iter->second->Update(diff);
+    }
+
+    _update();
+}
+
+bool
+ObjectAccessor::ActiveObjectsNearGrid(uint32 x, uint32 y, uint32 m_id, uint32 i_id) const
+{
+    CellPair cell_min(x*MAX_NUMBER_OF_CELLS, y*MAX_NUMBER_OF_CELLS);
+    CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
+    cell_min << 2;
+    cell_min -= 2;
+    cell_max >> 2;
+    cell_max += 2;
+
+    for(std::set<WorldObject*>::const_iterator itr = i_activeobjects.begin(); itr != i_activeobjects.end(); ++itr)
+    {
+        if( m_id != (*itr)->GetMapId() || i_id != (*itr)->GetInstanceId() )
+            continue;
+
+        CellPair p = Trinity::ComputeCellPair((*itr)->GetPositionX(), (*itr)->GetPositionY());
+        if( (cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
+            (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord) )
+            return true;
+    }
+
+    return false;
 }
 
@@ -655,5 +678,5 @@
     Cell cell(p);
 
-    obj->GetMap()->UpdateObjectVisibility(obj,cell,p);
+    MapManager::Instance().GetMap(obj->GetMapId(), obj)->UpdateObjectVisibility(obj,cell,p);
 }
 
@@ -662,5 +685,5 @@
     CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
     Cell cell(p);
-    Map* m = player->GetMap();
+    Map* m = MapManager::Instance().GetMap(player->GetMapId(),player);
 
     m->UpdatePlayerVisibility(player,cell,p);
