Index: /trunk/src/shared/Common.h
===================================================================
--- /trunk/src/shared/Common.h (revision 255)
+++ /trunk/src/shared/Common.h (revision 257)
@@ -147,5 +147,5 @@
 #define strnicmp strncasecmp
 #define I64FMT "%016llX"
-#define I64FMTD "%llu"
+#define I64FMTD "%I64u"
 #define SI64FMTD "%lld"
 #endif
Index: /trunk/src/game/SpellEffects.cpp
===================================================================
--- /trunk/src/game/SpellEffects.cpp (revision 246)
+++ /trunk/src/game/SpellEffects.cpp (revision 257)
@@ -1172,5 +1172,5 @@
                     m_caster->CastSpell(m_caster, 45009, true);
                     return;
-                }                
+                }
                 case 45030:                                 // Impale Emissary
                 {
@@ -1275,5 +1275,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 +2251,5 @@
         m_caster->ModifyPower(POWER_MANA,gain);
         //send log
-        m_caster->SendEnergizeSpellLog(m_caster, m_spellInfo->Id,gain,POWER_MANA,false);
+        m_caster->SendEnergizeSpellLog(m_caster, m_spellInfo->Id,gain,POWER_MANA);
     }
 }
@@ -2267,5 +2267,5 @@
                     /*do not uncomment .
                     if(bg->GetTypeID()==BATTLEGROUND_WS)
-                        bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
+                        bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
                     sLog.outDebug("Send Event Horde Flag Picked Up");
                     break;
@@ -2280,5 +2280,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, this->gameObjTarget);
+                        bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
                     sLog.outDebug("Send Event Alliance Flag Picked Up");
                     break;
@@ -2291,10 +2291,10 @@
                     case 23385:                                 // Alliance Flag Returns
                         if(bg->GetTypeID()==BATTLEGROUND_WS)
-                            bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
+                            bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
                         sLog.outDebug("Alliance Flag Returned");
                         break;
                     case 23386:                                   // Horde Flag Returns
                         if(bg->GetTypeID()==BATTLEGROUND_WS)
-                            bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
+                            bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
                         sLog.outDebug("Horde Flag Returned");
                         break;*/
@@ -2302,5 +2302,5 @@
                     /*
                     if(bg->GetTypeID()==BATTLEGROUND_EY)
-                        bg->EventPlayerClickedOnFlag((Player*)m_caster, this->gameObjTarget);
+                        bg->EventPlayerClickedOnFlag((Player*)m_caster, gameObjTarget);
                     */
                     break;
@@ -2681,5 +2681,5 @@
 
     // Some level depends spells
-    int multiplier  = 0;
+    int multiplier = 0;
     int level_diff = 0;
     switch (m_spellInfo->Id)
@@ -2688,15 +2688,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 +3760,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
-        MapManager::Instance().GetMap(mapid, m_caster)->CreatureRelocation((Creature*)m_caster, fx, fy, fz, -m_caster->GetOrientation());
+        m_caster->GetMap()->CreatureRelocation((Creature*)m_caster, fx, fy, fz, -m_caster->GetOrientation());
 }
 
@@ -3781,5 +3781,5 @@
         return;
 
-    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());
+    sLog.outDebug("SpellEffect::AddHonor called for spell_id %u , that rewards %d honor points to player: %u", m_spellInfo->Id, damage, ((Player*)unitTarget)->GetGUIDLow());
 
     // TODO: find formula for honor reward based on player's level!
@@ -3787,5 +3787,5 @@
     // now fixed only for level 70 players:
     if (((Player*)unitTarget)->getLevel() == 70)
-        ((Player*)unitTarget)->RewardHonor(NULL, 1, this->damage);
+        ((Player*)unitTarget)->RewardHonor(NULL, 1, damage);
 }
 
@@ -4002,5 +4002,5 @@
 
     // add to world
-    MapManager::Instance().GetMap(pet->GetMapId(), pet)->Add((Creature*)pet);
+    pet->GetMap()->Add((Creature*)pet);
 
     // visual effect for levelup
@@ -4032,5 +4032,5 @@
                 return;
 
-            MapManager::Instance().GetMap(OldSummon->GetMapId(), OldSummon)->Remove((Creature*)OldSummon,false);
+            OldSummon->GetMap()->Remove((Creature*)OldSummon,false);
             OldSummon->SetMapId(m_caster->GetMapId());
 
@@ -4039,5 +4039,5 @@
 
             OldSummon->Relocate(px, py, pz, OldSummon->GetOrientation());
-            MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster)->Add((Creature*)OldSummon);
+            m_caster->GetMap()->Add((Creature*)OldSummon);
 
             if(m_caster->GetTypeId() == TYPEID_PLAYER && OldSummon->isControlled() )
@@ -4122,8 +4122,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,4 +4447,5 @@
             ((Player*)m_caster)->AddComboPoints(unitTarget, 1);
     }
+
     // Mangle (Cat): CP
     if(m_spellInfo->SpellFamilyName==SPELLFAMILY_DRUID && (m_spellInfo->SpellFamilyFlags==0x0000040000000000LL))
@@ -4453,5 +4454,4 @@
             ((Player*)m_caster)->AddComboPoints(unitTarget,1);
     }
-
 
     // take ammo
@@ -5449,5 +5449,5 @@
 }
 
-void Spell::EffectResurrect(uint32 i)
+void Spell::EffectResurrect(uint32 /*effIndex*/)
 {
     if(!unitTarget)
@@ -5670,5 +5670,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 +5697,5 @@
 
     if(m_caster->GetTypeId() != TYPEID_PLAYER)
-        MapManager::Instance().GetMap(m_caster->GetMapId(), m_caster)->CreatureRelocation((Creature*)m_caster,x,y,z,m_caster->GetOrientation());
+        m_caster->GetMap()->CreatureRelocation((Creature*)m_caster,x,y,z,m_caster->GetOrientation());
 
     // not all charge effects used in negative spells
@@ -6133,5 +6133,5 @@
             linkedGO->SetOwnerGUID(m_caster->GetGUID() );
 
-            MapManager::Instance().GetMap(linkedGO->GetMapId(), linkedGO)->Add(linkedGO);
+            linkedGO->GetMap()->Add(linkedGO);
         }
         else
Index: /trunk/src/game/MapReference.h
===================================================================
--- /trunk/src/game/MapReference.h (revision 257)
+++ /trunk/src/game/MapReference.h (revision 257)
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * 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
+ * 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
+ */
+
+#ifndef _MAPREFERENCE_H
+#define _MAPREFERENCE_H
+
+#include "Utilities/LinkedReference/Reference.h"
+#include "Map.h"
+
+class TRINITY_DLL_SPEC MapReference : public Reference<Map, Player>
+{
+    protected:
+        void targetObjectBuildLink()
+        {
+            // called from link()
+            getTarget()->m_mapRefManager.insertFirst(this);
+            getTarget()->m_mapRefManager.incSize();
+        }
+        void targetObjectDestroyLink()
+        {
+            // called from unlink()
+            if(isValid()) getTarget()->m_mapRefManager.decSize();
+        }
+        void sourceObjectDestroyLink()
+        {
+            // called from invalidate()
+            getTarget()->m_mapRefManager.decSize();
+        }
+    public:
+        MapReference() : Reference<Map, Player>() {}
+        ~MapReference() { unlink(); }
+        MapReference *next() { return (MapReference*)Reference<Map, Player>::next(); }
+        MapReference const *next() const { return (MapReference const*)Reference<Map, Player>::next(); }
+};
+#endif
Index: /trunk/src/game/MapRefManager.h
===================================================================
--- /trunk/src/game/MapRefManager.h (revision 257)
+++ /trunk/src/game/MapRefManager.h (revision 257)
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * 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
+ * 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
+ */
+
+#ifndef _MAPREFMANAGER
+#define _MAPREFMANAGER
+
+#include "Utilities/LinkedReference/RefManager.h"
+
+class MapReference;
+
+class MapRefManager : public RefManager<Map, Player>
+{
+    public:
+        typedef LinkedListHead::Iterator< MapReference > iterator;
+        typedef LinkedListHead::Iterator< MapReference const > const_iterator;
+
+        MapReference* getFirst() { return (MapReference*)RefManager<Map, Player>::getFirst(); }
+        MapReference const* getFirst() const { return (MapReference const*)RefManager<Map, Player>::getFirst(); }
+        MapReference* getLast() { return (MapReference*)RefManager<Map, Player>::getLast(); }
+        MapReference const* getLast() const { return (MapReference const*)RefManager<Map, Player>::getLast(); }
+
+        iterator begin() { return iterator(getFirst()); }
+        iterator end() { return iterator(NULL); }
+        iterator rbegin() { return iterator(getLast()); }
+        iterator rend() { return iterator(NULL); }
+        const_iterator begin() const { return const_iterator(getFirst()); }
+        const_iterator end() const  { return const_iterator(getLast()); }
+};
+#endif
Index: /trunk/src/game/Map.h
===================================================================
--- /trunk/src/game/Map.h (revision 206)
+++ /trunk/src/game/Map.h (revision 257)
@@ -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,4 +34,5 @@
 #include "SharedDefines.h"
 #include "GameSystem/GridRefManager.h"
+#include "MapRefManager.h"
 
 #include <bitset>
@@ -127,4 +128,5 @@
 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);
@@ -238,4 +240,12 @@
         GameObject* GetGameObjectInMap(uint64 guid);
 
+        bool HavePlayers() const { return !m_mapRefManager.isEmpty(); }
+        uint32 GetPlayersCountExceptGMs() const;
+        bool PlayersNearGrid(uint32 x,uint32 y) const;
+
+        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:
@@ -287,4 +297,5 @@
         uint32 m_unloadTimer;
 
+        MapRefManager m_mapRefManager;
     private:
         typedef GridReadGuard ReadGuard;
@@ -326,6 +337,4 @@
 {
     public:
-        typedef std::list<Player *> PlayerList;                 // online players only
-
         InstanceMap(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode);
         ~InstanceMap();
@@ -338,12 +347,8 @@
         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);
-        uint32 GetPlayersCountExceptGMs() const;
-        uint32 HavePlayers() const { return !i_Players.empty(); }
-        void SendResetWarnings(uint32 timeLeft);
+        void SendResetWarnings(uint32 timeLeft) const;
         void SetResetSchedule(bool on);
     private:
@@ -360,6 +365,4 @@
 {
     public:
-        typedef std::list<Player *> PlayerList;                 // online players only
-
         BattleGroundMap(uint32 id, time_t, uint32 InstanceId);
         ~BattleGroundMap();
@@ -370,6 +373,4 @@
         void SetUnload();
         void UnloadAll(bool pForce);
-    private:
-        PlayerList i_Players;
 };
 
Index: /trunk/src/game/ObjectAccessor.h
===================================================================
--- /trunk/src/game/ObjectAccessor.h (revision 233)
+++ /trunk/src/game/ObjectAccessor.h (revision 257)
@@ -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,4 +187,5 @@
 
         void Update(uint32 diff);
+        void UpdatePlayers(uint32 diff);
 
         Corpse* GetCorpseForPlayerGUID(uint64 guid);
Index: /trunk/src/game/StatSystem.cpp
===================================================================
--- /trunk/src/game/StatSystem.cpp (revision 229)
+++ /trunk/src/game/StatSystem.cpp (revision 257)
@@ -385,5 +385,5 @@
         weapon_maxdamage = lvl*1.25*att_speed;
     }
-    else if(!IsUseEquippedWeapon(attType==BASE_ATTACK))      //check if player not in form but still can't use weapon (broken/etc)
+    else if(!IsUseEquipedWeapon(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/Unit.h
===================================================================
--- /trunk/src/game/Unit.h (revision 252)
+++ /trunk/src/game/Unit.h (revision 257)
@@ -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
  */
 
@@ -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, bool critical = false);
+        void SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage,Powers powertype);
         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,4 +1040,5 @@
         void RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer);
         void RemoveAurasDueToSpellByCancel(uint32 spellId);
+        void RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo);
         void RemoveNotOwnSingleTargetAuras();
 
@@ -1371,8 +1372,10 @@
 
         void ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, AuraTypeSet const& procAuraTypes, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage, SpellSchoolMask damageSchoolMask );
-        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);
+        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);
 
         uint32 m_state;                                     // Even derived shouldn't modify
Index: /trunk/src/game/SpellAuras.h
===================================================================
--- /trunk/src/game/SpellAuras.h (revision 236)
+++ /trunk/src/game/SpellAuras.h (revision 257)
@@ -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,13 +186,10 @@
         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);
@@ -254,5 +251,5 @@
             uint8 slot = GetAuraSlot();
 
-            // only aura inslot with charges and without stack limitation
+            // only aura in slot 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/BattleGround.h
===================================================================
--- /trunk/src/game/BattleGround.h (revision 102)
+++ /trunk/src/game/BattleGround.h (revision 257)
@@ -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,5 +96,6 @@
     RESPAWN_ONE_DAY                 = 86400,                // secs
     RESPAWN_IMMEDIATELY             = 0,                    // secs
-    BUFF_RESPAWN_TIME               = 180                  // secs
+    BUFF_RESPAWN_TIME               = 180,                  // secs
+    BG_HONOR_SCORE_TICKS            = 330                   // points
 };
 
@@ -434,5 +435,4 @@
 
         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/SpellAuras.cpp
===================================================================
--- /trunk/src/game/SpellAuras.cpp (revision 252)
+++ /trunk/src/game/SpellAuras.cpp (revision 257)
@@ -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::HandleAuraHealing,                               //115 SPELL_AURA_MOD_HEALING
+    &Aura::HandleNoImmediateEffect,                         //115 SPELL_AURA_MOD_HEALING                 implemented in Unit::SpellBaseHealingBonusForVictim
     &Aura::HandleNoImmediateEffect,                         //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT
     &Aura::HandleNoImmediateEffect,                         //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE     implemented in Unit::MagicSpellHitResult
-    &Aura::HandleAuraHealingPct,                            //118 SPELL_AURA_MOD_HEALING_PCT
+    &Aura::HandleNoImmediateEffect,                         //118 SPELL_AURA_MOD_HEALING_PCT             implemented in Unit::SpellHealingBonus
     &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::HandleAuraHealingPct,                            //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT   implemented in Unit::SpellHealingBonus
+    &Aura::HandleNoImmediateEffect,                         //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::HandleAuraAttackPowerAttacker,                   //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS implemented in Unit::MeleeDamageBonus
+    &Aura::HandleNoImmediateEffect,                         //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,4 +2000,14 @@
         }
 
+        // 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)
@@ -2295,4 +2305,8 @@
 void Aura::HandleAuraMounted(bool apply, bool Real)
 {
+    // only at real add/remove aura
+    if(!Real)
+        return;
+
     if(apply)
     {
@@ -2694,5 +2708,7 @@
             else
             {
-                if (uint32 modelid = ci->GetRandomValidModelId()) m_target->SetDisplayId(modelid);
+                                                            // Will use the default model here
+                if (uint32 modelid = ci->GetRandomValidModelId())
+                    m_target->SetDisplayId(modelid);
 
                 // Dragonmaw Illusion (set mount model also)
@@ -3590,5 +3606,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
@@ -3599,5 +3615,5 @@
 }
 
-void Aura::HandleAuraModIncreaseMountedSpeed(bool apply, bool Real)
+void Aura::HandleAuraModIncreaseMountedSpeed(bool /*apply*/, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -3638,5 +3654,5 @@
 }
 
-void Aura::HandleAuraModIncreaseSwimSpeed(bool apply, bool Real)
+void Aura::HandleAuraModIncreaseSwimSpeed(bool /*apply*/, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -3647,5 +3663,5 @@
 }
 
-void Aura::HandleAuraModDecreaseSpeed(bool apply, bool Real)
+void Aura::HandleAuraModDecreaseSpeed(bool /*apply*/, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -3658,5 +3674,5 @@
 }
 
-void Aura::HandleAuraModUseNormalSpeed(bool apply, bool Real)
+void Aura::HandleAuraModUseNormalSpeed(bool /*apply*/, bool Real)
 {
     // all applied/removed only at real aura add/remove
@@ -4343,5 +4359,5 @@
 }
 
-void Aura::HandleModSpellDamagePercentFromStat(bool apply, bool Real)
+void Aura::HandleModSpellDamagePercentFromStat(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4354,5 +4370,5 @@
 }
 
-void Aura::HandleModSpellHealingPercentFromStat(bool apply, bool Real)
+void Aura::HandleModSpellHealingPercentFromStat(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4372,5 +4388,5 @@
 }
 
-void Aura::HandleModSpellDamagePercentFromAttackPower(bool apply, bool Real)
+void Aura::HandleModSpellDamagePercentFromAttackPower(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4383,5 +4399,5 @@
 }
 
-void Aura::HandleModSpellHealingPercentFromAttackPower(bool apply, bool Real)
+void Aura::HandleModSpellHealingPercentFromAttackPower(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4392,5 +4408,5 @@
 }
 
-void Aura::HandleModHealingDone(bool apply, bool Real)
+void Aura::HandleModHealingDone(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4432,5 +4448,5 @@
 }
 
-void Aura::HandleAuraModResistenceOfStatPercent(bool apply, bool Real)
+void Aura::HandleAuraModResistenceOfStatPercent(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -4567,5 +4583,5 @@
 }
 
-void Aura::HandleModPowerRegenPCT(bool apply, bool Real)
+void Aura::HandleModPowerRegenPCT(bool /*apply*/, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4581,5 +4597,5 @@
 }
 
-void Aura::HandleModManaRegen(bool apply, bool Real)
+void Aura::HandleModManaRegen(bool /*apply*/, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4668,5 +4684,5 @@
 /********************************/
 
-void Aura::HandleAuraModParryPercent(bool apply, bool Real)
+void Aura::HandleAuraModParryPercent(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId()!=TYPEID_PLAYER)
@@ -4676,5 +4692,5 @@
 }
 
-void Aura::HandleAuraModDodgePercent(bool apply, bool Real)
+void Aura::HandleAuraModDodgePercent(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId()!=TYPEID_PLAYER)
@@ -4685,5 +4701,5 @@
 }
 
-void Aura::HandleAuraModBlockPercent(bool apply, bool Real)
+void Aura::HandleAuraModBlockPercent(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId()!=TYPEID_PLAYER)
@@ -4694,5 +4710,5 @@
 }
 
-void Aura::HandleAuraModRegenInterrupt(bool apply, bool Real)
+void Aura::HandleAuraModRegenInterrupt(bool /*apply*/, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4762,5 +4778,5 @@
 }
 
-void Aura::HandleModSpellCritChanceShool(bool apply, bool Real)
+void Aura::HandleModSpellCritChanceShool(bool /*apply*/, bool Real)
 {
     // spells required only Real aura add/remove
@@ -4842,37 +4858,4 @@
 
     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;
-    }
 }
 
@@ -5324,5 +5307,5 @@
 }
 
-void Aura::HandleAuraModExpertise(bool apply, bool Real)
+void Aura::HandleAuraModExpertise(bool /*apply*/, bool Real)
 {
     if(m_target->GetTypeId() != TYPEID_PLAYER)
@@ -5347,15 +5330,4 @@
     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/Map.cpp
===================================================================
--- /trunk/src/game/Map.cpp (revision 233)
+++ /trunk/src/game/Map.cpp (revision 257)
@@ -36,4 +36,5 @@
 #include "ScriptCalls.h"
 #include "Group.h"
+#include "MapRefManager.h"
 
 #include "MapInstanced.h"
@@ -450,4 +451,6 @@
 bool Map::Add(Player *player)
 {
+    player->GetMapRef().link(this, player);
+
     player->SetInstanceId(GetInstanceId());
 
@@ -594,4 +597,53 @@
 void Map::Update(const uint32 &t_diff)
 {
+    resetMarkedCells();
+
+    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);
+
+    for(MapRefManager::iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
+    {
+        Player* plr = iter->getSource();
+        if(!plr->IsInWorld())
+            continue;
+
+        CellPair standing_cell(Trinity::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()));
+
+        // 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)
+            continue;
+
+        // 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);
+                }
+            }
+        }
+    }
+
+
     // 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
@@ -611,4 +663,5 @@
 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)
@@ -910,5 +963,5 @@
 
     {
-        if(!pForce && ObjectAccessor::Instance().ActiveObjectsNearGrid(x, y, i_id, i_InstanceId) )
+        if(!pForce && PlayersNearGrid(x, y) )
             return false;
 
@@ -1419,4 +1472,41 @@
 }
 
+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;
+}
+
 template void Map::Add(Corpse *);
 template void Map::Add(Creature *);
@@ -1454,5 +1544,5 @@
 bool InstanceMap::CanEnter(Player *player)
 {
-    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
+    if(player->GetMapRef().getTarget() == this)
     {
         sLog.outError("InstanceMap::CanEnter - player %s(%u) already in map %d,%d,%d!", player->GetName(), player->GetGUIDLow(), GetId(), GetInstanceId(), GetSpawnMode());
@@ -1571,5 +1661,4 @@
         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());
@@ -1596,7 +1685,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(!m_unloadTimer && i_Players.empty())
+    //if last player set unload timer
+    if(!m_unloadTimer && m_mapRefManager.getSize() == 1)
         m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld.getConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
     Map::Remove(player, remove);
@@ -1663,11 +1752,11 @@
     // the instance must be deleted from the DB by InstanceSaveManager
 
-    if(!i_Players.empty())
+    if(HavePlayers())
     {
         if(method == INSTANCE_RESET_ALL)
         {
             // notify the players to leave the instance so it can be reset
-            for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
-                (*itr)->SendResetFailedNotify(GetId());
+            for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+                itr->getSource()->SendResetFailedNotify(GetId());
         }
         else
@@ -1676,6 +1765,6 @@
             {
                 // set the homebind timer for players inside (1 minute)
-                for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
-                    (*itr)->m_InstanceValid = false;
+                for(MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+                    itr->getSource()->m_InstanceValid = false;
             }
 
@@ -1693,14 +1782,5 @@
     }
 
-    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;
+    return m_mapRefManager.isEmpty();
 }
 
@@ -1716,23 +1796,21 @@
     Group *group = player->GetGroup();
     // group members outside the instance group don't get bound
-    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);
-        }
+    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);
     }
 }
@@ -1746,9 +1824,12 @@
 void InstanceMap::UnloadAll(bool pForce)
 {
-    if(!i_Players.empty())
+    if(HavePlayers())
     {
         sLog.outError("InstanceMap::UnloadAll: there are still players in the instance at unload, should not happen!");
-        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());
+        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());
+        }
     }
 
@@ -1759,8 +1840,8 @@
 }
 
-void InstanceMap::SendResetWarnings(uint32 timeLeft)
-{
-    for(PlayerList::iterator itr = i_Players.begin(); itr != i_Players.end(); ++itr)
-        (*itr)->SendInstanceResetWarning(GetId(), timeLeft);
+void InstanceMap::SendResetWarnings(uint32 timeLeft) const
+{
+    for(MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
+        itr->getSource()->SendInstanceResetWarning(GetId(), timeLeft);
 }
 
@@ -1770,5 +1851,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(i_Players.empty() && !IsRaid() && !IsHeroic())
+    if(!HavePlayers() && !IsRaid() && !IsHeroic())
     {
         InstanceSave *save = sInstanceSaveManager.GetInstanceSave(GetInstanceId());
@@ -1778,10 +1859,4 @@
 }
 
-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 ******* */
 
@@ -1797,5 +1872,5 @@
 bool BattleGroundMap::CanEnter(Player * player)
 {
-    if(std::find(i_Players.begin(),i_Players.end(),player)!=i_Players.end())
+    if(player->GetMapRef().getTarget() == this)
     {
         sLog.outError("BGMap::CanEnter - player %u already in map!", player->GetGUIDLow());
@@ -1818,5 +1893,4 @@
         if(!CanEnter(player))
             return false;
-        i_Players.push_back(player);
         // reset instance validity, battleground maps do not homebind
         player->m_InstanceValid = true;
@@ -1828,5 +1902,4 @@
 {
     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);
 }
@@ -1839,13 +1912,12 @@
 void BattleGroundMap::UnloadAll(bool pForce)
 {
-    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());
+    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());
         // 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
-        i_Players.remove(plr);
+        plr->GetMapRef().unlink();
     }
 
Index: /trunk/src/game/MapInstanced.h
===================================================================
--- /trunk/src/game/MapInstanced.h (revision 206)
+++ /trunk/src/game/MapInstanced.h (revision 257)
@@ -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, uint32 aInstanceId);
+        MapInstanced(uint32 id, time_t expiry);
         ~MapInstanced() {}
 
Index: /trunk/src/game/Player.h
===================================================================
--- /trunk/src/game/Player.h (revision 233)
+++ /trunk/src/game/Player.h (revision 257)
@@ -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,4 +34,5 @@
 #include "WorldSession.h"
 #include "Pet.h"
+#include "MapReference.h"
 #include "Util.h"                                           // for Tokens typedef
 
@@ -780,5 +781,5 @@
 
 /// Type of environmental damages
-enum EnvironmentalDamageType
+enum EnviromentalDamage
 {
     DAMAGE_EXHAUSTED = 0,
@@ -1125,5 +1126,5 @@
         uint32 GetArmorProficiency() const { return m_ArmorProficiency; }
         bool IsInFeralForm() const { return m_form == FORM_CAT || m_form == FORM_BEAR || m_form == FORM_DIREBEAR; }
-        bool IsUseEquippedWeapon( bool mainhand ) const
+        bool IsUseEquipedWeapon( bool mainhand ) const
         {
             // disarm applied only to mainhand weapon
@@ -1307,5 +1308,5 @@
                 SetMoney (GetMoney() > uint32(-d) ? GetMoney() + d : 0);
             else
-                SetMoney (GetMoney() < MAX_MONEY_AMOUNT - d ? GetMoney() + d : MAX_MONEY_AMOUNT);
+                SetMoney (GetMoney() < uint32(MAX_MONEY_AMOUNT - d) ? GetMoney() + d : MAX_MONEY_AMOUNT);
 
             // "At Gold Limit"
@@ -1429,5 +1430,4 @@
         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);
@@ -1519,6 +1519,6 @@
         void SendUpdateToOutOfRangeGroupMembers();
 
-        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 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 SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; }
         uint32 GetGuildId() { return GetUInt32Value(PLAYER_GUILDID);  }
@@ -1533,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, this->GetGUID());
+            SetUInt32ValueInDB(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * 6), ArenaTeamId, GetGUID());
         }
         uint32 GetArenaTeamId(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * 6)); }
@@ -1609,5 +1609,5 @@
         void SendLogXPGain(uint32 GivenXP,Unit* victim,uint32 RestXP);
 
-		//Low Level Packets
+        //Low Level Packets
         void PlaySound(uint32 Sound, bool OnlySelf);
         //notifiers
@@ -1641,5 +1641,5 @@
         void KillPlayer();
         uint32 GetResurrectionSpellId();
-        void ResurrectPlayer(float restore_percent, bool updateToWorld = true, bool applySickness = false);
+        void ResurrectPlayer(float restore_percent, bool applySickness = false);
         void BuildPlayerRepop();
         void RepopAtGraveyard();
@@ -1763,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, bool affectStats = true);
+        void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply);
         float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const;
         float GetTotalBaseModValue(BaseModGroup modGroup) const;
@@ -1770,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);
@@ -1935,8 +1935,8 @@
 
         /*********************************************************/
-        /***              ENVIRONMENTAL SYSTEM                  ***/
-        /*********************************************************/
-
-        void EnvironmentalDamage(uint64 guid, EnvironmentalDamageType type, uint32 damage);
+        /***              ENVIROMENTAL SYSTEM                  ***/
+        /*********************************************************/
+
+        void EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage);
 
         /*********************************************************/
@@ -2063,4 +2063,6 @@
 
         GridReference<Player> &GetGridRef() { return m_gridRef; }
+        MapReference &GetMapRef() { return m_mapRef; }
+
         bool isAllowedToLoot(Creature* creature);
 
@@ -2308,4 +2310,5 @@
 
         GridReference<Player> m_gridRef;
+        MapReference m_mapRef;
 };
 
Index: /trunk/src/game/MapManager.cpp
===================================================================
--- /trunk/src/game/MapManager.cpp (revision 132)
+++ /trunk/src/game/MapManager.cpp (revision 257)
@@ -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, 0);
+            m = new MapInstanced(id, i_gridCleanUpDelay);
         }
         else
@@ -247,4 +247,6 @@
         return;
 
+    ObjectAccessor::Instance().UpdatePlayers(i_timer.GetCurrent());
+
     for(MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter)
     {
@@ -337,5 +339,5 @@
         for(MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr)
             if(mitr->second->IsDungeon())
-                ret += ((InstanceMap*)mitr->second)->GetPlayers().size();
+                ret += ((InstanceMap*)mitr->second)->GetPlayers().getSize();
     }
     return ret;
Index: /trunk/src/game/Unit.cpp
===================================================================
--- /trunk/src/game/Unit.cpp (revision 253)
+++ /trunk/src/game/Unit.cpp (revision 257)
@@ -1149,6 +1149,4 @@
             if ( GetSpellSchoolMask(spellInfo) & SPELL_SCHOOL_MASK_NORMAL )
             {
-                uint32 modDamage=*damage;
-
                 // apply spellmod to Done damage
                 if(Player* modOwner = GetSpellModOwner())
@@ -1435,5 +1433,5 @@
     if(!this || !pVictim)
         return 0;
-    if(!this->isAlive() || !pVictim->isAlive())
+    if(!isAlive() || !pVictim->isAlive())
         return 0;
 
@@ -4128,10 +4126,15 @@
 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
 {
-    if (IsSingleTargetSpell((*i).second->GetSpellProto()))
-    {
-        if(Unit* caster = (*i).second->GetCaster())
+    Aura* Aur = i->second;
+    SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
+
+    Unit* caster = NULL;
+    if (IsSingleTargetSpell(AurSpellInfo))
+    {
+        caster = Aur->GetCaster();
+        if(caster)
         {
             AuraList& scAuras = caster->GetSingleCastAuras();
-            scAuras.remove((*i).second);
+            scAuras.remove(Aur);
         }
         else
@@ -4142,5 +4145,6 @@
     }
 
-    if ((*i).second->GetModifier()->m_auraname < TOTAL_AURAS)
+    // 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)
     {
         m_modAuras[(*i).second->GetModifier()->m_auraname].remove((*i).second);
@@ -4154,6 +4158,4 @@
     }
 
-    // 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);
@@ -4163,11 +4165,20 @@
     ++m_removedAuras;                                       // internal count used by unit update
 
-    // Status unsummoned at aura remove
+    // Statue unsummoned at aura remove
     Totem* statue = NULL;
-    if(IsChanneledSpell(Aur->GetSpellProto()))
-        if(Unit* caster = Aur->GetCaster())
+    bool caster_channeled = false;
+    if(IsChanneledSpell(AurSpellInfo))
+    {
+        if(!caster)                                         // can be already located for IsSingleTargetSpell case
+            caster = Aur->GetCaster();
+
+        if(caster)
+        {
             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))
@@ -4186,4 +4197,7 @@
     Aur->_RemoveAura();
     delete Aur;
+
+    if(caster_channeled)
+        RemoveAurasAtChanneledTarget (AurSpellInfo);
 
     if(statue)
@@ -4612,6 +4626,8 @@
 }
 
-bool Unit::HandleHasteAuraProc(Unit *pVictim, SpellEntry const *hasteSpell, uint32 /*effIndex*/, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 cooldown)
-{
+bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 cooldown)
+{
+    SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
+
     Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
         ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
@@ -4673,6 +4689,9 @@
 }
 
-bool Unit::HandleDummyAuraProc(Unit *pVictim, SpellEntry const *dummySpell, uint32 effIndex, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 cooldown)
-{
+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 ();
+
     Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
         ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
@@ -6262,5 +6281,4 @@
                             return false;
 
-                        uint32 spell = 0;
                         switch(triggeredByAura->GetSpellProto()->Id)
                         {
@@ -6292,5 +6310,4 @@
 
                         // overwrite non existing triggered spell call in spell.dbc
-                        uint32 spell = 0;
                         switch(triggeredByAura->GetSpellProto()->Id)
                         {
@@ -6492,6 +6509,8 @@
 }
 
-bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, int32 scriptId, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
-{
+bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
+{
+    int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
+
     if(!pVictim || !pVictim->isAlive())
         return false;
@@ -7259,5 +7278,5 @@
 }
 
-void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype, bool critical)
+void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
 {
     WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
@@ -7359,5 +7378,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;
 
@@ -8207,5 +8226,5 @@
 
     // ..done (for creature type by mask) in taken
-    AuraList const& mDamageDoneCreature = this->GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
+    AuraList const& mDamageDoneCreature = 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))
@@ -8275,5 +8294,5 @@
     // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT  included in weapon damage
 
-    AuraList const& mDamageDoneVersus = this->GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
+    AuraList const& mDamageDoneVersus = 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))
@@ -8730,5 +8749,5 @@
     if(IsInWorld())
     {
-        Map *m = MapManager::Instance().GetMap(GetMapId(), this);
+        Map *m = GetMap();
 
         if(GetTypeId()==TYPEID_PLAYER)
@@ -9792,6 +9811,4 @@
 }
 
-
-
 CharmInfo* Unit::InitCharmInfo(Unit *charm)
 {
@@ -9957,15 +9974,13 @@
 struct ProcTriggeredData
 {
-    ProcTriggeredData(SpellEntry const * _spellInfo, uint32 _spellParam, Aura* _triggeredByAura, uint32 _cooldown)
-        : spellInfo(_spellInfo), spellParam(_spellParam), triggeredByAura(_triggeredByAura),
+    ProcTriggeredData(Aura* _triggeredByAura, uint32 _cooldown)
+        : triggeredByAura(_triggeredByAura),
         triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex())),
         cooldown(_cooldown)
-        {}
-
-    SpellEntry const * spellInfo;
-    uint32 spellParam;
-    Aura* triggeredByAura;
-    Unit::spellEffectPair triggeredByAura_SpellPair;
-    uint32 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
 };
 
@@ -9984,85 +9999,11 @@
             next = i; ++next;
 
-            SpellEntry const *spellProto = (*i)->GetSpellProto();
-            if(!spellProto)
+            Aura* i_aura = *i;
+
+            uint32 cooldown;                                // returned at next line
+            if(!IsTriggeredAtSpellProcEvent(i_aura->GetSpellProto(), procSpell, procFlag,attType,isVictim,cooldown))
                 continue;
 
-            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) );
-            }
+            procTriggered.push_back( ProcTriggeredData(i_aura, cooldown) );
         }
 
@@ -10097,21 +10038,31 @@
             }
 
-            // save charges existence before processing to prevent crash at access to deleted triggered aura after
-            bool triggeredByAuraWithCharges =  i->triggeredByAura->m_procCharges > 0;
-
+            /// 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.
             bool casted = false;
+
+            /// process triggered code
             switch(*aur)
             {
                 case SPELL_AURA_PROC_TRIGGER_SPELL:
                 {
-                    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);
+                    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);
                     break;
                 }
                 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
                 {
-                    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);
+                    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);
                     casted = true;
                     break;
@@ -10119,69 +10070,23 @@
                 case SPELL_AURA_DUMMY:
                 {
-                    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);
+                    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);
                     break;
                 }
                 case SPELL_AURA_PRAYER_OF_MENDING:
                 {
-                    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;
+                    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);
                     break;
                 }
                 case SPELL_AURA_MOD_HASTE:
                 {
-                    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);
+                    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);
                     break;
                 }
@@ -10190,11 +10095,12 @@
                     // nothing do, just charges counter
                     // but count only in case appropriate school damage
-                    casted = i->triggeredByAura->GetModifier()->m_miscvalue & damageSchoolMask;
+                    casted = triggeredByAura->GetModifier()->m_miscvalue & damageSchoolMask;
                     break;
                 }
                 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
                 {
-                    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);
+                    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);
                     break;
                 }
@@ -10207,18 +10113,18 @@
             }
 
-            // Update charge (aura can be removed by triggers)
+            /// Update charge (aura can be removed by triggers)
             if(casted && triggeredByAuraWithCharges)
             {
-                // need found aura (can be dropped by triggers)
+                /// need re-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 == i->triggeredByAura)
+                    if(itr->second == triggeredByAura)      // pointer still valid
                     {
-                        if(i->triggeredByAura->m_procCharges > 0)
-                            i->triggeredByAura->m_procCharges -= 1;
-
-                        i->triggeredByAura->UpdateAuraCharges();
+                        if(triggeredByAura->m_procCharges > 0)
+                            triggeredByAura->m_procCharges -= 1;
+
+                        triggeredByAura->UpdateAuraCharges();
                         break;
                     }
@@ -10227,5 +10133,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)
         {
@@ -10340,5 +10246,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);
@@ -10824,7 +10730,7 @@
     }
 
-    pet->SetUInt64Value(UNIT_FIELD_SUMMONEDBY, this->GetGUID());
-    pet->SetUInt64Value(UNIT_FIELD_CREATEDBY, this->GetGUID());
-    pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE,this->getFaction());
+    pet->SetUInt64Value(UNIT_FIELD_SUMMONEDBY, GetGUID());
+    pet->SetUInt64Value(UNIT_FIELD_CREATEDBY, GetGUID());
+    pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE,getFaction());
     pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
 
@@ -10844,2 +10750,131 @@
     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/ItemPrototype.h
===================================================================
--- /trunk/src/game/ItemPrototype.h (revision 230)
+++ /trunk/src/game/ItemPrototype.h (revision 257)
@@ -79,5 +79,5 @@
     NO_BIND                                     = 0,
     BIND_WHEN_PICKED_UP                         = 1,
-    BIND_WHEN_EQUIPPED                           = 2,
+    BIND_WHEN_EQUIPED                           = 2,
     BIND_WHEN_USE                               = 3,
     BIND_QUEST_ITEM                             = 4,
Index: /trunk/src/game/Player.cpp
===================================================================
--- /trunk/src/game/Player.cpp (revision 233)
+++ /trunk/src/game/Player.cpp (revision 257)
@@ -800,5 +800,5 @@
 }
 
-void Player::EnvironmentalDamage(uint64 guid, EnvironmentalDamageType type, uint32 damage)
+void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
 {
     WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
@@ -1642,5 +1642,5 @@
     {
         // far teleport to another map
-        Map* oldmap = IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL;
+        Map* oldmap = IsInWorld() ? GetMap() : 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 updateToWorld, bool applySickness)
+void Player::ResurrectPlayer(float restore_percent, 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, bool affectStats)
+void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
 {
     if(modGroup >= BASEMOD_END || modType >= MOD_END)
@@ -5244,5 +5244,5 @@
     }
 
-    Map *m = MapManager::Instance().GetMap(GetMapId(), this);
+    Map *m = GetMap();
 
     const float old_x = GetPositionX();
@@ -5262,5 +5262,5 @@
 
         // reread after Map::Relocation
-        m = MapManager::Instance().GetMap(GetMapId(), this);
+        m = GetMap();
         x = GetPositionX();
         y = GetPositionY();
@@ -6177,5 +6177,7 @@
         return 0;
 
-    return (*result)[0].GetUInt32();
+    uint32 id = (*result)[0].GetUInt32();
+    delete result;
+    return id;
 }
 
@@ -6708,5 +6710,5 @@
     }
 
-    if(!IsUseEquippedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
+    if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
         return;
 
@@ -8486,5 +8488,5 @@
         return item;
 
-    if( item->IsBroken() || !IsUseEquippedWeapon(attackType==BASE_ATTACK) )
+    if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
         return NULL;
 
@@ -8640,4 +8642,5 @@
     return false;
 }
+
 
 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
@@ -10156,5 +10159,5 @@
         if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
             pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
-            pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos) )
+            pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
             pItem->SetBinding( true );
 
@@ -10202,5 +10205,5 @@
         if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
             pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
-            pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos) )
+            pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
             pItem2->SetBinding( true );
 
@@ -10404,5 +10407,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_EQUIPPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
+    if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
         pItem->SetBinding( true );
 
@@ -10548,6 +10551,4 @@
         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);
@@ -14208,5 +14209,5 @@
         SetUInt32Value(i, 0);
 
-    //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
+    //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
 
     if(result)
@@ -14218,8 +14219,9 @@
             uint32 spellid = fields[1].GetUInt32();
             uint32 effindex = fields[2].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();
+            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();
 
             SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
@@ -14258,9 +14260,13 @@
                 continue;
 
-            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);
+            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);
+            }
         }
         while( result->NextRow() );
@@ -15321,29 +15327,52 @@
 
     AuraMap const& auras = GetAuras();
-    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)
+
+    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())
                 break;
-
-        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));
+        }
+
+        if (lastEffectPair == itr->first)
+            stackCounter++;
+        else
+        {
+            lastEffectPair = itr->first;
+            stackCounter = 1;
         }
     }
@@ -17911,5 +17940,5 @@
             continue;
 
-        if (SpellEntry const* spellentry = sSpellStore.LookupEntry(pAbility->spellId))
+        if (sSpellStore.LookupEntry(pAbility->spellId))
         {
             // Ok need learn spell
@@ -18324,5 +18353,4 @@
         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);
 
@@ -18333,5 +18361,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();
@@ -18660,4 +18688,16 @@
     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)
@@ -18962,13 +19002,4 @@
 }
 
-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/NPCHandler.cpp
===================================================================
--- /trunk/src/game/NPCHandler.cpp (revision 230)
+++ /trunk/src/game/NPCHandler.cpp (revision 257)
@@ -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,13 +340,11 @@
     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);
     }
 }
@@ -378,5 +376,5 @@
 void WorldSession::SendSpiritResurrect()
 {
-    _player->ResurrectPlayer(0.5f,false, true);
+    _player->ResurrectPlayer(0.5f, true);
 
     _player->DurabilityLossAll(0.25f,true);
Index: /trunk/src/game/MapInstanced.cpp
===================================================================
--- /trunk/src/game/MapInstanced.cpp (revision 102)
+++ /trunk/src/game/MapInstanced.cpp (revision 257)
@@ -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, uint32 aInstanceId) : Map(id, expiry, 0, 0)
+MapInstanced::MapInstanced(uint32 id, time_t expiry) : Map(id, expiry, 0, 0)
 {
     // initialize instanced maps list
@@ -262,3 +262,2 @@
     m_InstancedMaps.erase(itr++);
 }
-
Index: /trunk/src/game/ObjectAccessor.cpp
===================================================================
--- /trunk/src/game/ObjectAccessor.cpp (revision 237)
+++ /trunk/src/game/ObjectAccessor.cpp (revision 257)
@@ -143,5 +143,13 @@
 {
     Creature * ret = GetObjectInWorld(guid, (Creature*)NULL);
-    if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
+    if(!ret)
+        return NULL;
+
+    if(ret->GetMapId() != u.GetMapId())
+        return NULL;
+
+    if(ret->GetInstanceId() != u.GetInstanceId())
+        return NULL;
+
     return ret;
 }
@@ -249,30 +257,4 @@
 
 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)
 {
@@ -362,5 +344,5 @@
     TypeContainerVisitor<WorldObjectChangeAccumulator, WorldTypeMapContainer > player_notifier(notifier);
     CellLock<GridReadGuard> cell_lock(cell, p);
-    cell_lock->Visit(cell_lock, player_notifier, *MapManager::Instance().GetMap(obj->GetMapId(), obj));
+    cell_lock->Visit(cell_lock, player_notifier, *obj->GetMap());
 }
 
@@ -520,4 +502,5 @@
 ObjectAccessor::Update(uint32 diff)
 {
+
     {
         // player update might remove the player from grid, and that causes crashes. We HAVE to update players first, and then the active objects.
@@ -590,6 +573,13 @@
         }
     }
-
-    _update();
+}
+
+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);
 }
 
@@ -678,5 +668,5 @@
     Cell cell(p);
 
-    MapManager::Instance().GetMap(obj->GetMapId(), obj)->UpdateObjectVisibility(obj,cell,p);
+    obj->GetMap()->UpdateObjectVisibility(obj,cell,p);
 }
 
@@ -685,5 +675,5 @@
     CellPair p = Trinity::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
     Cell cell(p);
-    Map* m = MapManager::Instance().GetMap(player->GetMapId(),player);
+    Map* m = player->GetMap();
 
     m->UpdatePlayerVisibility(player,cell,p);
Index: /trunk/src/bindings/scripts/include/sc_creature.cpp
===================================================================
--- /trunk/src/bindings/scripts/include/sc_creature.cpp (revision 229)
+++ /trunk/src/bindings/scripts/include/sc_creature.cpp (revision 257)
@@ -680,11 +680,9 @@
     }
 
-    InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-    InstanceMap::PlayerList::const_iterator i;
-    for (i = PlayerList.begin(); i != PlayerList.end(); ++i)
-    {
-        if((*i)->isAlive())
-            pUnit->AddThreat(*i, 0.0f);
-    }
+    Map::PlayerList const &PlayerList = map->GetPlayers();
+    for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
+        if (Player* i_pl = i->getSource())
+            if (!i_pl->isAlive())
+                pUnit->AddThreat(i_pl, 0.0f);
 }
 
@@ -721,4 +719,18 @@
     ((Player*)pUnit)->TeleportTo(pUnit->GetMapId(), x, y, z, o, TELE_TO_NOT_LEAVE_COMBAT);
 }
+
+void ScriptedAI::DoTeleportAll(float x, float y, float z, float o)
+{
+    Map *map = m_creature->GetMap();
+    if (!map->IsDungeon())
+        return;
+
+    Map::PlayerList const &PlayerList = map->GetPlayers();
+    for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
+        if (Player* i_pl = i->getSource())
+            if (!i_pl->isAlive())
+                i_pl->TeleportTo(m_creature->GetMapId(), x, y, z, o, TELE_TO_NOT_LEAVE_COMBAT);
+}
+
 
 Unit* ScriptedAI::DoSelectLowestHpFriendly(float range, uint32 MinHPDiff)
Index: /trunk/src/bindings/scripts/include/sc_creature.h
===================================================================
--- /trunk/src/bindings/scripts/include/sc_creature.h (revision 203)
+++ /trunk/src/bindings/scripts/include/sc_creature.h (revision 257)
@@ -147,4 +147,5 @@
     //Teleports a player without dropping threat (only teleports to same map)
     void DoTeleportPlayer(Unit* pUnit, float x, float y, float z, float o);
+    void DoTeleportAll(float x, float y, float z, float o);
 
     //Returns friendly unit with the most amount of hp missing from max hp
Index: /trunk/src/bindings/scripts/scripts/zone/hellfire_citadel/magtheridons_lair/instance_magtheridons_lair.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/hellfire_citadel/magtheridons_lair/instance_magtheridons_lair.cpp (revision 141)
+++ /trunk/src/bindings/scripts/scripts/zone/hellfire_citadel/magtheridons_lair/instance_magtheridons_lair.cpp (revision 257)
@@ -119,7 +119,4 @@
     void SetData(uint32 type, uint32 data)
     {
-        Player *player = GetPlayer();
-        if(!player) return;
-
         switch(type)
         {
@@ -130,5 +127,5 @@
             if(data != IN_PROGRESS)
             {
-                if(GameObject *Door = GameObject::GetGameObject(*player, DoorGUID))
+                if(GameObject *Door = instance->GetGameObjectInMap(DoorGUID))
                     Door->SetGoState(0);
             }
@@ -143,5 +140,5 @@
                     for(std::set<uint64>::iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
                     {
-                        if(Creature *Channeler = (Creature*)Unit::GetUnit(*player, *i))
+                        if(Creature *Channeler = instance->GetCreatureInMap(*i))
                         {
                             if(Channeler->isAlive())
@@ -152,5 +149,5 @@
                     }
                     CageTimer = 0;
-                    if(GameObject *Door = GameObject::GetGameObject(*player, DoorGUID))
+                    if(GameObject *Door = instance->GetGameObjectInMap(DoorGUID))
                         Door->SetGoState(0);
                 }break;
@@ -162,5 +159,5 @@
                     for(std::set<uint64>::iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
                     {
-                        Creature *Channeler = (Creature*)Unit::GetUnit(*player, *i);
+                        Creature *Channeler = instance->GetCreatureInMap(*i);
                         if(Channeler && Channeler->isAlive())
                         {
@@ -171,5 +168,5 @@
                     }
                     // Release Magtheridon after two minutes.
-                    Creature *Magtheridon = (Creature*)Unit::GetUnit(*player, MagtheridonGUID);
+                    Creature *Magtheridon = instance->GetCreatureInMap(MagtheridonGUID);
                     if(Magtheridon && Magtheridon->isAlive())
                     {
@@ -177,5 +174,5 @@
                         CageTimer = 120000;
                     }
-                    if(GameObject *Door = GameObject::GetGameObject(*player, DoorGUID))
+                    if(GameObject *Door = instance->GetGameObjectInMap(DoorGUID))
                         Door->SetGoState(1);
                 }break;
@@ -183,5 +180,5 @@
                 for(std::set<uint64>::iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
                 {
-                    Unit *Channeler = Unit::GetUnit(*player, *i);
+                    Creature *Channeler = instance->GetCreatureInMap(*i);
                     if(Channeler && Channeler->isAlive())
                     {
@@ -198,5 +195,5 @@
             for(std::set<uint64>::iterator i = ColumnGUID.begin(); i != ColumnGUID.end(); ++i)
             {
-                if(GameObject *Column = GameObject::GetGameObject(*player, *i))
+                if(GameObject *Column = instance->GetGameObjectInMap(*i))
                     Column->SetGoState(!data);
             }
@@ -214,11 +211,4 @@
     }
 
-    Player* GetPlayer()
-    {
-        if(((InstanceMap*)instance)->GetPlayers().size())
-            return ((InstanceMap*)instance)->GetPlayers().front();
-        return NULL;
-    }
-
     void AttackNearestTarget(Creature *creature)
     {
@@ -226,16 +216,19 @@
         float range;
         Player* target = NULL;
-        InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)instance)->GetPlayers();
-        InstanceMap::PlayerList::const_iterator i;
+        Map::PlayerList const &PlayerList = instance->GetPlayers();
+        Map::PlayerList::const_iterator i;
         for(i = PlayerList.begin(); i != PlayerList.end(); ++i)
         {
-            if((*i)->isTargetableForAttack())
-            {
-                range = (*i)->GetDistance(creature);
-                if(range < minRange)
-                {
-                    minRange = range;
-                    target = *i;
-                }                
+            if(Player* i_pl = i->getSource())
+            {
+                if(i_pl->isTargetableForAttack())
+                {
+                    range = i_pl->GetDistance(creature);
+                    if(range < minRange)
+                    {
+                        minRange = range;
+                        target = i_pl;
+                    }                
+                }
             }
         }
@@ -249,12 +242,9 @@
             if(CageTimer <= diff)
             {
-                if(Player *player = GetPlayer())
-                {
-                    Creature *Magtheridon = (Creature*)Unit::GetUnit(*player, MagtheridonGUID);
-                    if(Magtheridon && Magtheridon->isAlive())
-                    {
-                        Magtheridon->clearUnitState(UNIT_STAT_STUNNED);
-                        AttackNearestTarget(Magtheridon);
-                    }
+                Creature *Magtheridon = instance->GetCreatureInMap(MagtheridonGUID);
+                if(Magtheridon && Magtheridon->isAlive())
+                {
+                    Magtheridon->clearUnitState(UNIT_STAT_STUNNED);
+                    AttackNearestTarget(Magtheridon);
                 }
                 CageTimer = 0;
@@ -266,15 +256,12 @@
             if(RespawnTimer <= diff)
             {
-                if(Player *player = GetPlayer())
-                {
-                    for(std::set<uint64>::iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
-                    {
-                        if(Creature *Channeler = (Creature*)Unit::GetUnit(*player, *i))
-                        {
-                            if(Channeler->isAlive())
-                                Channeler->AI()->EnterEvadeMode();
-                            else
-                                Channeler->Respawn();
-                        }
+                for(std::set<uint64>::iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i)
+                {
+                    if(Creature *Channeler = instance->GetCreatureInMap(*i))
+                    {
+                        if(Channeler->isAlive())
+                            Channeler->AI()->EnterEvadeMode();
+                        else
+                            Channeler->Respawn();
                     }
                 }
Index: /trunk/src/bindings/scripts/scripts/zone/temple_of_ahnqiraj/boss_cthun.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/temple_of_ahnqiraj/boss_cthun.cpp (revision 206)
+++ /trunk/src/bindings/scripts/scripts/zone/temple_of_ahnqiraj/boss_cthun.cpp (revision 257)
@@ -578,18 +578,21 @@
                 if(!map->IsDungeon()) return;
 
-                InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-                for (InstanceMap::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
-                {
-                    //Play random sound to the zone
-                    switch (rand()%8)
+                Map::PlayerList const &PlayerList = map->GetPlayers();
+                for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
+                {
+                    if (Player* i_pl = i->getSource())
                     {
-                        case 0: (*i)->SendPlaySound(RND_WISPER_1, true); break;
-                        case 1: (*i)->SendPlaySound(RND_WISPER_2, true); break;
-                        case 2: (*i)->SendPlaySound(RND_WISPER_3, true); break;
-                        case 3: (*i)->SendPlaySound(RND_WISPER_4, true); break;
-                        case 4: (*i)->SendPlaySound(RND_WISPER_5, true); break;
-                        case 5: (*i)->SendPlaySound(RND_WISPER_6, true); break;
-                        case 6: (*i)->SendPlaySound(RND_WISPER_7, true); break;
-                        case 7: (*i)->SendPlaySound(RND_WISPER_8, true); break;
+                        //Play random sound to the zone
+                        switch (rand()%8)
+                        {
+                            case 0: i_pl->SendPlaySound(RND_WISPER_1, true); break;
+                            case 1: i_pl->SendPlaySound(RND_WISPER_2, true); break;
+                            case 2: i_pl->SendPlaySound(RND_WISPER_3, true); break;
+                            case 3: i_pl->SendPlaySound(RND_WISPER_4, true); break;
+                            case 4: i_pl->SendPlaySound(RND_WISPER_5, true); break;
+                            case 5: i_pl->SendPlaySound(RND_WISPER_6, true); break;
+                            case 6: i_pl->SendPlaySound(RND_WISPER_7, true); break;
+                            case 7: i_pl->SendPlaySound(RND_WISPER_8, true); break;
+                        }
                     }
                 }
Index: /trunk/src/bindings/scripts/scripts/zone/sunwell_plateau/boss_kalecgos.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/sunwell_plateau/boss_kalecgos.cpp (revision 239)
+++ /trunk/src/bindings/scripts/scripts/zone/sunwell_plateau/boss_kalecgos.cpp (revision 257)
@@ -369,11 +369,10 @@
         Map *map = m_creature->GetMap();
         if(!map->IsDungeon()) return;
-        InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-        InstanceMap::PlayerList::const_iterator i;
-        for (i = PlayerList.begin(); i != PlayerList.end(); ++i)
-        {
-            if((*i)->HasAura(AURA_SPECTRAL_REALM,0))
-                (*i)->RemoveAurasDueToSpell(AURA_SPECTRAL_REALM);
-        }
+        Map::PlayerList const &PlayerList = map->GetPlayers();
+        Map::PlayerList::const_iterator i;
+        for(i = PlayerList.begin(); i != PlayerList.end(); ++i)
+            if(Player* i_pl = i->getSource())
+                if(i_pl->HasAura(AURA_SPECTRAL_REALM,0))
+                    i_pl->RemoveAurasDueToSpell(AURA_SPECTRAL_REALM);
     }
 
Index: /trunk/src/bindings/scripts/scripts/zone/sunwell_plateau/boss_felmyst.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/sunwell_plateau/boss_felmyst.cpp (revision 122)
+++ /trunk/src/bindings/scripts/scripts/zone/sunwell_plateau/boss_felmyst.cpp (revision 257)
@@ -296,5 +296,5 @@
             break;
         case 2:
-            if(Player* target = SelectRandomPlayer(150))
+            if(Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0, 150, true))
             {
                 Creature* Vapor = m_creature->SummonCreature(MOB_VAPOR, target->GetPositionX()-5+rand()%10, target->GetPositionY()-5+rand()%10, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 9000);
@@ -312,5 +312,5 @@
             DespawnSummons(MOB_VAPOR_TRAIL);
             //m_creature->CastSpell(m_creature, SPELL_VAPOR_SELECT); need core support
-            if(Player* target = SelectRandomPlayer(150))
+            if(Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0, 150, true))
             {
                 //target->CastSpell(target, SPELL_VAPOR_SUMMON, true); need core support
@@ -331,5 +331,5 @@
             break;
         case 5:
-            if(Player* target = SelectRandomPlayer(150))
+            if(Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0, 150, true))
             {
                 BreathX = target->GetPositionX();
@@ -434,5 +434,5 @@
                 break;
             case EVENT_ENCAPSULATE:
-                if(Unit* target = SelectRandomPlayer(150))
+                if(Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0, 150, true))
                 {
                     m_creature->CastSpell(target, SPELL_ENCAPSULATE_CHANNEL, false);
@@ -516,24 +516,4 @@
         }
     }
-
-    Player* SelectRandomPlayer(float range = 0.0f)
-    {
-        Map *map = m_creature->GetMap();
-        if (!map->IsDungeon()) return NULL;
-
-        InstanceMap::PlayerList PlayerList = ((InstanceMap*)map)->GetPlayers();
-        InstanceMap::PlayerList::iterator i;
-        while(PlayerList.size())
-        {
-            i = PlayerList.begin();
-            advance(i, rand()%PlayerList.size());
-            if((range == 0.0f || m_creature->IsWithinDistInMap(*i, range))
-                && (*i)->isTargetableForAttack())
-                return *i;
-            else
-                PlayerList.erase(i);
-        }
-        return NULL;
-    }
 };
 
Index: /trunk/src/bindings/scripts/scripts/zone/aunchindoun/shadow_labyrinth/boss_grandmaster_vorpil.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/aunchindoun/shadow_labyrinth/boss_grandmaster_vorpil.cpp (revision 229)
+++ /trunk/src/bindings/scripts/scripts/zone/aunchindoun/shadow_labyrinth/boss_grandmaster_vorpil.cpp (revision 257)
@@ -221,16 +221,5 @@
         if ( DrawnShadows_Timer < diff)
         {
-            Map *map = m_creature->GetMap();
-            if(map->IsDungeon())
-            {
-                InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-                for (InstanceMap::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
-                {
-                    if((*i)->isAlive())
-                    {
-                        (*i)->TeleportTo(555,VorpilPosition[0][0],VorpilPosition[0][1],VorpilPosition[0][2],0);
-                    }
-                }
-            }
+            DoTeleportAll(VorpilPosition[0][0],VorpilPosition[0][1],VorpilPosition[0][2],0);
             m_creature->Relocate(VorpilPosition[0][0],VorpilPosition[0][1],VorpilPosition[0][2],0);
             DoCast(m_creature,SPELL_DRAWN_SHADOWS,true);
Index: /trunk/src/bindings/scripts/scripts/zone/coilfang_resevoir/serpent_shrine/boss_leotheras_the_blind.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/coilfang_resevoir/serpent_shrine/boss_leotheras_the_blind.cpp (revision 229)
+++ /trunk/src/bindings/scripts/scripts/zone/coilfang_resevoir/serpent_shrine/boss_leotheras_the_blind.cpp (revision 257)
@@ -755,17 +755,20 @@
 		{
 			Map *map = m_creature->GetMap();
-			InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-			for(InstanceMap::PlayerList::const_iterator itr = PlayerList.begin();itr != PlayerList.end(); ++itr)
+			Map::PlayerList const &PlayerList = map->GetPlayers();
+			for(Map::PlayerList::const_iterator itr = PlayerList.begin();itr != PlayerList.end(); ++itr)
             {
-				bool isCasting = false;
-				for(uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
-					if((*itr)->m_currentSpells[i])
-						isCasting = true;
-				
-				if(isCasting)
-				{
-					DoCast((*itr), SPELL_EARTHSHOCK);
-					break;
-				}
+                if (Player* i_pl = itr->getSource())
+                {
+				    bool isCasting = false;
+				    for(uint8 i = 0; i < CURRENT_MAX_SPELL; ++i)
+					    if(i_pl->m_currentSpells[i])
+						    isCasting = true;
+    				
+				    if(isCasting)
+				    {
+					    DoCast(i_pl, SPELL_EARTHSHOCK);
+					    break;
+				    }
+                }
 			}
 			Earthshock_Timer = 8000 + rand()%7000;
Index: /trunk/src/bindings/scripts/scripts/zone/coilfang_resevoir/serpent_shrine/boss_lady_vashj.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/coilfang_resevoir/serpent_shrine/boss_lady_vashj.cpp (revision 229)
+++ /trunk/src/bindings/scripts/scripts/zone/coilfang_resevoir/serpent_shrine/boss_lady_vashj.cpp (revision 257)
@@ -251,10 +251,10 @@
 			//remove old tainted cores to prevent cheating in phase 2
 			Map *map = m_creature->GetMap();
-			InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-			for(InstanceMap::PlayerList::const_iterator i = PlayerList.begin();i != PlayerList.end(); ++i)
-            {
-                if((*i))
+			Map::PlayerList const &PlayerList = map->GetPlayers();
+			for(Map::PlayerList::const_iterator i = PlayerList.begin();i != PlayerList.end(); ++i)
+            {
+                if(Player* i_pl = i->getSource())
                 {
-                    (*i)->DestroyItemCount(31088, 1, true);
+                    i_pl->DestroyItemCount(31088, 1, true);
                 }
             }
Index: /trunk/src/bindings/scripts/scripts/zone/karazhan/karazhan.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/karazhan/karazhan.cpp (revision 90)
+++ /trunk/src/bindings/scripts/scripts/zone/karazhan/karazhan.cpp (revision 257)
@@ -286,12 +286,12 @@
                     if(!map->IsDungeon()) return;
 
-                    InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-                    if(PlayerList.empty())
+                    Map::PlayerList const &PlayerList = map->GetPlayers();
+                    if(PlayerList.isEmpty())
                         return;
 
                     RaidWiped = true;
-                    for(InstanceMap::PlayerList::const_iterator i = PlayerList.begin();i != PlayerList.end(); ++i)
+                    for(Map::PlayerList::const_iterator i = PlayerList.begin();i != PlayerList.end(); ++i)
                     {
-                        if((*i)->isAlive() && !(*i)->isGameMaster())
+                        if (i->getSource()->isAlive() && !i->getSource()->isGameMaster())
                         {
                             RaidWiped = false;
Index: /trunk/src/bindings/scripts/scripts/zone/zulaman/boss_janalai.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/zulaman/boss_janalai.cpp (revision 90)
+++ /trunk/src/bindings/scripts/scripts/zone/zulaman/boss_janalai.cpp (revision 257)
@@ -398,9 +398,10 @@
             Map *map = m_creature->GetMap();
             if(!map->IsDungeon()) return;
-            InstanceMap::PlayerList const &PlayerList =((InstanceMap*)map)->GetPlayers();
-            for(InstanceMap::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
-            {
-                if((*i)->isAlive())
-                    DoTeleportPlayer(*i, JanalainPos[0][0]-5+rand()%10, JanalainPos[0][1]-5+rand()%10, JanalainPos[0][2], 0);
+            Map::PlayerList const &PlayerList = map->GetPlayers();
+            for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
+            {
+                if (Player* i_pl = i->getSource())
+                    if(i_pl->isAlive())
+                        DoTeleportPlayer(i_pl, JanalainPos[0][0]-5+rand()%10, JanalainPos[0][1]-5+rand()%10, JanalainPos[0][2], 0);
             }
             //m_creature->CastSpell(Temp, SPELL_SUMMON_PLAYERS, true); // core bug, spell does not work if too far
Index: /trunk/src/bindings/scripts/scripts/zone/zulaman/boss_hexlord.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/zulaman/boss_hexlord.cpp (revision 202)
+++ /trunk/src/bindings/scripts/scripts/zone/zulaman/boss_hexlord.cpp (revision 257)
@@ -372,5 +372,5 @@
         if(SiphonSoul_Timer < diff)
         {
-            Player* target = SelectRandomPlayer(50);
+            Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0, 70, true);
             Unit *trigger = DoSpawnCreature(MOB_TEMP_TRIGGER, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 30000);
             if(!target || !trigger) EnterEvadeMode();
@@ -436,24 +436,4 @@
         m_creature->CastSpell(target, PlayerAbility[PlayerClass][random].spell, false);
     }
-
-    Player* SelectRandomPlayer(float range = 0.0f, bool alive = true)
-    {
-        Map *map = m_creature->GetMap();
-        if (!map->IsDungeon()) return NULL;
-
-        InstanceMap::PlayerList PlayerList = ((InstanceMap*)map)->GetPlayers();
-        InstanceMap::PlayerList::iterator i;
-        while(PlayerList.size())
-        {
-            i = PlayerList.begin();
-            advance(i, rand()%PlayerList.size());
-            if((range == 0.0f || m_creature->IsWithinDistInMap(*i, range))
-                && (!alive || (*i)->isAlive()))
-                return *i;
-            else
-                PlayerList.erase(i);
-        }
-        return NULL;
-    }
 };
 
Index: /trunk/src/bindings/scripts/scripts/zone/zulaman/instance_zulaman.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/zulaman/instance_zulaman.cpp (revision 90)
+++ /trunk/src/bindings/scripts/scripts/zone/zulaman/instance_zulaman.cpp (revision 257)
@@ -140,19 +140,26 @@
     void OpenDoor(uint64 DoorGUID, bool open)
     {
-        if(((InstanceMap*)instance)->GetPlayers().size())
-            if(Player* first = ((InstanceMap*)instance)->GetPlayers().front())
-                if(GameObject *Door = GameObject::GetGameObject(*first, DoorGUID))
-                    Door->SetUInt32Value(GAMEOBJECT_STATE, open ? 0 : 1);
+        if(GameObject *Door = instance->GetGameObjectInMap(DoorGUID))
+            Door->SetUInt32Value(GAMEOBJECT_STATE, open ? 0 : 1);
     }
 
     void SummonHostage(uint8 num)
     {
-        if(QuestMinute && ((InstanceMap*)instance)->GetPlayers().size())
-            if(Player* first = ((InstanceMap*)instance)->GetPlayers().front())
-                if(Unit* Hostage = first->SummonCreature(HostageInfo[num].npc, HostageInfo[num].x, HostageInfo[num].y, HostageInfo[num].z, HostageInfo[num].o, TEMPSUMMON_DEAD_DESPAWN, 0))
-                {
-                    Hostage->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
-                    Hostage->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
-                }
+        if(!QuestMinute)
+            return;
+
+        Map::PlayerList const &PlayerList = instance->GetPlayers();
+        if (PlayerList.isEmpty())
+            return;
+
+        Map::PlayerList::const_iterator i = PlayerList.begin();
+        if(Player* i_pl = i->getSource())
+        {
+            if(Unit* Hostage = i_pl->SummonCreature(HostageInfo[num].npc, HostageInfo[num].x, HostageInfo[num].y, HostageInfo[num].z, HostageInfo[num].o, TEMPSUMMON_DEAD_DESPAWN, 0))
+            {
+                Hostage->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
+                Hostage->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
+            }
+        }
     }
 
Index: /trunk/src/bindings/scripts/scripts/zone/magisters_terrace/boss_felblood_kaelthas.cpp
===================================================================
--- /trunk/src/bindings/scripts/scripts/zone/magisters_terrace/boss_felblood_kaelthas.cpp (revision 137)
+++ /trunk/src/bindings/scripts/scripts/zone/magisters_terrace/boss_felblood_kaelthas.cpp (revision 257)
@@ -232,15 +232,15 @@
         m_creature->Relocate(KaelLocations[0][0], KaelLocations[0][1], LOCATION_Z, 0);
 		Map *map = m_creature->GetMap();
-        InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-		InstanceMap::PlayerList::const_iterator i;
+        Map::PlayerList const &PlayerList = map->GetPlayers();
+		Map::PlayerList::const_iterator i;
 		for (i = PlayerList.begin(); i != PlayerList.end(); ++i)
 		{
-			//if(!(*i)->isGameMaster())
-			if((*i) && (*i)->isAlive())
-			{
-				(*i)->CastSpell((*i), SPELL_TELEPORT_CENTER, true);
-				m_creature->GetNearPoint(m_creature,x,y,z,5,5,0);
-				(*i)->TeleportTo(m_creature->GetMapId(),x,y,LOCATION_Z,(*i)->GetOrientation());
-			}
+			if (Player* i_pl = i->getSource())
+			    if(i_pl->isAlive())
+			    {
+				    i_pl->CastSpell(i_pl, SPELL_TELEPORT_CENTER, true);
+				    m_creature->GetNearPoint(m_creature,x,y,z,5,5,0);
+				    i_pl->TeleportTo(m_creature->GetMapId(),x,y,LOCATION_Z,i_pl->GetOrientation());
+			    }
         }
         DoCast(m_creature, SPELL_TELEPORT_CENTER, true);
@@ -250,11 +250,12 @@
     {
 		Map *map = m_creature->GetMap();
-        InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-		InstanceMap::PlayerList::const_iterator i;
+        Map::PlayerList const &PlayerList = map->GetPlayers();
+		Map::PlayerList::const_iterator i;
 		for (i = PlayerList.begin(); i != PlayerList.end(); ++i)
-		{            
-			if((*i) && (*i)->isAlive())
+		{
+            if (Player* i_pl = i->getSource())
+			    if(i_pl->isAlive())
                 // Knockback into the air
-                (*i)->CastSpell((*i), SPELL_GRAVITY_LAPSE_DOT, true, 0, 0, m_creature->GetGUID());
+                    i_pl->CastSpell(i_pl, SPELL_GRAVITY_LAPSE_DOT, true, 0, 0, m_creature->GetGUID());
         }
     }
@@ -263,39 +264,42 @@
     {
 		Map *map = m_creature->GetMap();
-		InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-		InstanceMap::PlayerList::const_iterator i;
+		Map::PlayerList const &PlayerList = map->GetPlayers();
+		Map::PlayerList::const_iterator i;
+		for (i = PlayerList.begin(); i != PlayerList.end(); ++i)
+		{
+            if (Player* i_pl = i->getSource())
+            {
+			    if(i_pl->isAlive())
+                {
+                    // Also needs an exception in spell system.
+                    i_pl->CastSpell(i_pl, SPELL_GRAVITY_LAPSE_FLY, true, 0, 0, m_creature->GetGUID());
+                    // Use packet hack
+                    WorldPacket data(12);
+                    data.SetOpcode(SMSG_MOVE_SET_CAN_FLY);
+                    data.append(i_pl->GetPackGUID());
+                    data << uint32(0);
+                    i_pl->SendMessageToSet(&data, true);
+				    i_pl->SetSpeed(MOVE_FLY, 2.0f);
+                }
+            }
+        }
+    }
+
+    void RemoveGravityLapse()
+    {
+		Map *map = m_creature->GetMap();
+        Map::PlayerList const &PlayerList = map->GetPlayers();
+		Map::PlayerList::const_iterator i;
 		for (i = PlayerList.begin(); i != PlayerList.end(); ++i)
 		{ 
-			if((*i) && (*i)->isAlive())
+            if(Player* i_pl = i->getSource())
             {
-                // Also needs an exception in spell system.
-                (*i)->CastSpell((*i), SPELL_GRAVITY_LAPSE_FLY, true, 0, 0, m_creature->GetGUID());
-                // Use packet hack
-                WorldPacket data(12);
-                data.SetOpcode(SMSG_MOVE_SET_CAN_FLY);
-                data.append((*i)->GetPackGUID());
-                data << uint32(0);
-                (*i)->SendMessageToSet(&data, true);
-				(*i)->SetSpeed(MOVE_FLY, 2.0f);
-            }
-        }
-    }
-
-    void RemoveGravityLapse()
-    {
-		Map *map = m_creature->GetMap();
-        InstanceMap::PlayerList const &PlayerList = ((InstanceMap*)map)->GetPlayers();
-		InstanceMap::PlayerList::const_iterator i;
-		for (i = PlayerList.begin(); i != PlayerList.end(); ++i)
-		{ 
-            if((*i))
-            {
-                (*i)->RemoveAurasDueToSpell(SPELL_GRAVITY_LAPSE_FLY);
-                (*i)->RemoveAurasDueToSpell(SPELL_GRAVITY_LAPSE_DOT);
+                i_pl->RemoveAurasDueToSpell(SPELL_GRAVITY_LAPSE_FLY);
+                i_pl->RemoveAurasDueToSpell(SPELL_GRAVITY_LAPSE_DOT);
                 WorldPacket data(12);
                 data.SetOpcode(SMSG_MOVE_UNSET_CAN_FLY);
-                data.append((*i)->GetPackGUID());
+                data.append(i_pl->GetPackGUID());
                 data << uint32(0);
-                (*i)->SendMessageToSet(&data, true);
+                i_pl->SendMessageToSet(&data, true);
             }
         }
Index: /trunk/src/framework/Utilities/LinkedReference/Reference.h
===================================================================
--- /trunk/src/framework/Utilities/LinkedReference/Reference.h (revision 102)
+++ /trunk/src/framework/Utilities/LinkedReference/Reference.h (revision 257)
@@ -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
  */
 
@@ -75,4 +75,5 @@
 
         Reference<TO,FROM>* next() { return((Reference<TO,FROM>*)LinkedListElement::next()); }
+        Reference<TO,FROM>const* next() const { return((Reference<TO,FROM> const*)LinkedListElement::next()); }
         Reference<TO,FROM>* prev() { return((Reference<TO,FROM>*)LinkedListElement::prev()); }
 
Index: /trunk/src/framework/Utilities/LinkedReference/RefManager.h
===================================================================
--- /trunk/src/framework/Utilities/LinkedReference/RefManager.h (revision 102)
+++ /trunk/src/framework/Utilities/LinkedReference/RefManager.h (revision 257)
@@ -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,7 @@
 
         Reference<TO, FROM>* getFirst() { return ((Reference<TO, FROM>*) LinkedListHead::getFirst()); }
+        Reference<TO, FROM> const* getFirst() const { return ((Reference<TO, FROM> const*) LinkedListHead::getFirst()); }
         Reference<TO, FROM>* getLast() { return ((Reference<TO, FROM>*) LinkedListHead::getLast()); }
+        Reference<TO, FROM> const* getLast() const { return ((Reference<TO, FROM> const*) LinkedListHead::getLast()); }
 
         iterator begin() { return iterator(getFirst()); }
Index: /trunk/win/VC71/game.vcproj
===================================================================
--- /trunk/win/VC71/game.vcproj (revision 208)
+++ /trunk/win/VC71/game.vcproj (revision 257)
@@ -338,4 +338,10 @@
 			</File>
 			<File
+				RelativePath="..\..\src\game\MapReference.h">
+			</File>
+			<File
+				RelativePath="..\..\src\game\MapRefManager.h">
+			</File>				
+			<File
 				RelativePath="..\..\src\game\MiscHandler.cpp">
 			</File>
Index: /trunk/win/VC80/game.vcproj
===================================================================
--- /trunk/win/VC80/game.vcproj (revision 208)
+++ /trunk/win/VC80/game.vcproj (revision 257)
@@ -628,4 +628,12 @@
 			</File>
 			<File
+				RelativePath="..\..\src\game\MapReference.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\game\MapRefManager.h"
+				>
+			</File>				
+			<File
 				RelativePath="..\..\src\game\MiscHandler.cpp"
 				>
Index: /trunk/win/VC90/game.vcproj
===================================================================
--- /trunk/win/VC90/game.vcproj (revision 208)
+++ /trunk/win/VC90/game.vcproj (revision 257)
@@ -633,4 +633,12 @@
 			</File>
 			<File
+				RelativePath="..\..\src\game\MapReference.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\game\MapRefManager.h"
+				>
+			</File>			
+			<File
 				RelativePath="..\..\src\game\MiscHandler.cpp"
 				>
