changeset 2139:f9b55be70c1b

Слияние
author Ritor1
date Thu, 02 Jan 2014 09:11:28 +0600
parents 7cc14d9d966d (current diff) d145d0e93a16 (diff)
children 4c0c475917dd
files mm7_3.cpp
diffstat 159 files changed, 32112 insertions(+), 7975 deletions(-) [+]
line wrap: on
line diff
--- a/.hgignore	Thu Jan 02 09:11:01 2014 +0600
+++ b/.hgignore	Thu Jan 02 09:11:28 2014 +0600
@@ -3,4 +3,5 @@
 Release/
 *.orig
 .git/*
-Build/
+Build/*
+Build/Visual Studio 2010 Mine/
--- a/Actor.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Actor.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -1669,7 +1669,7 @@
     v3->vVelocity.z = 0;
     v3->vVelocity.y = 0;
     v3->vVelocity.x = 0;
-    if ( _42FB5C_check_spell(v16) )
+    if ( _42FB5C_check_spell(v3->pMonsterInfo.uSpell1ID) )
     {
       v3->uCurrentActionLength = 64;
       v3->uCurrentActionTime = 0;
@@ -3899,8 +3899,8 @@
 void Actor::_4BBF61_summon_actor( int a1, __int16 x, int y, int z )
 {
   Actor *v7; // esi@5
-  MonsterInfo *v9; // edi@5
-  MonsterDesc *v10; // ebx@5
+  //MonsterInfo *v9; // edi@5
+  //MonsterDesc *v10; // ebx@5
   int v12; // ebx@7
   int v13; // eax@8
   __int16 v16; // [sp+10h] [bp-4h]@3
@@ -3909,20 +3909,18 @@
   {
     v16 = 0;
     if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
-    {
       v16 = pIndoor->GetSector(x, y, z);
-    }
     v7 = &pActors[uNumActors];
     v7->Reset();
-    v9 = &pMonsterStats->pInfos[a1];
-    v10 = &pMonsterList->pMonsters[a1 - 1];
-    strcpy(v7->pActorName, v9->pName);
-    v7->sCurrentHP = LOWORD(v9->uHP);
-    memcpy(&v7->pMonsterInfo, v9, 0x58u);
+    //v9 = &pMonsterStats->pInfos[a1];
+    //v10 = &pMonsterList->pMonsters[a1 - 1];
+    strcpy(v7->pActorName, pMonsterStats->pInfos[a1].pName);
+    v7->sCurrentHP = LOWORD(pMonsterStats->pInfos[a1].uHP);
+    memcpy(&v7->pMonsterInfo, &pMonsterStats->pInfos[a1], 0x58u);
     v7->word_000086_some_monster_id = a1;
-    v7->uActorRadius = v10->uMonsterRadius;
-    v7->uActorHeight = v10->uMonsterHeight;
-    v7->uMovementSpeed = v10->uMovementSpeed;
+    v7->uActorRadius = pMonsterList->pMonsters[a1 - 1].uMonsterRadius;
+    v7->uActorHeight = pMonsterList->pMonsters[a1 - 1].uMonsterHeight;
+    v7->uMovementSpeed = pMonsterList->pMonsters[a1 - 1].uMovementSpeed;
     v7->vInitialPosition.x = x;
     v7->vPosition.x = x;
     v7->uAttributes |= 80000;
@@ -3941,16 +3939,14 @@
     v7->pMonsterInfo.uHostilityType = MonsterInfo::Hostility_Long;
     v7->PrepareSprites(0);
     for ( int i = 0; i < 4; i++)
-    {
-      pSoundList->LoadSound(v10->pSoundSampleIDs[i], 0);
-    }
-    v12 = 0;
-    do
-    {
-      LOWORD(v13) = pSoundList->LoadSound(v12 + word_4EE088_sound_ids[v9->uSpell1ID], 1u);
-      v12++;
-    }
-    while ( v13 );
+      pSoundList->LoadSound(pMonsterList->pMonsters[a1 - 1].pSoundSampleIDs[i], 0);
+    //v12 = 0;
+    //do// 
+    //{
+      //LOWORD(v13) = pSoundList->LoadSound(v12 + word_4EE088_sound_ids[pMonsterStats->pInfos[a1].uSpell1ID], 1);
+      //v12++;
+    //}
+    //while ( v13 );
     ++uNumActors;
   }
 }
@@ -4404,4 +4400,45 @@
     this->pActorBuffs[ACTOR_BUFF_FATE].Reset();
   }
   return rand() % (armorSum + 2 * this->pMonsterInfo.uLevel + 10) + a2a + 1 > armorSum + 5;
+}
+
+//----- (00448A98) --------------------------------------------------------
+void __fastcall ToggleActorGroupFlag(unsigned int uGroupID, unsigned int uFlag, unsigned int bToggle)
+{
+  if ( uGroupID )
+  {
+    if ( bToggle )
+    {
+      for ( uint i = 0; i < (unsigned int)uNumActors; ++i )
+      {
+        if ( pActors[i].uGroup == uGroupID )
+        {
+          pActors[i].uAttributes |= uFlag;
+          if ( uFlag == 0x10000 )
+          {
+            pActors[i].uAIState = Disabled;
+            pActors[i].UpdateAnimation();
+          }
+        }
+      }
+    }
+    else
+    {
+      for ( uint i = 0; i < (unsigned int)uNumActors; ++i )
+      {
+        if ( pActors[i].uGroup == uGroupID )
+        {
+          if ( uFlag == 0x10000 )
+          {
+            if ( pActors[i].uAIState != Dead )
+            {
+              if ( pActors[i].uAIState != 4 && pActors[i].uAIState != 11 )
+                pActors[i].uAIState = Standing;
+            }
+          }
+          LODWORD(pActors[i].uAttributes) &= ~uFlag;
+        }
+      }
+    }
+  }
 }
\ No newline at end of file
--- a/Arcomage.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Arcomage.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -70,7 +70,7 @@
 //----- (0040DEDB) --------------------------------------------------------
 unsigned int R8G8B8_to_TargetFormat(int uColor)
 {
-  return TargetColor(LOBYTE(uColor), BYTE1(uColor), BYTE2(uColor));
+  return Color16(LOBYTE(uColor), BYTE1(uColor), BYTE2(uColor));
 }
 
 /*  388 */
@@ -624,7 +624,7 @@
 {
 
 unsigned __int16 *pSrc; // eax@2
-unsigned __int16 *dest_surf_pos; // edi@3
+//unsigned __int16 *dest_surf_pos; // edi@3
 int uSrcTotalWidth; // ecx@4
 unsigned int v10; // esi@9
 int v21; // [sp+Ch] [bp-18h]@8
@@ -639,7 +639,7 @@
 if ( !pArcomageGame->pBlit_Copy_pixels )
     return;
 
-dest_surf_pos = &pRenderer->pTargetSurface[pTargetPoint->x + pTargetPoint->y * pRenderer->uTargetSurfacePitch];
+//dest_surf_pos = &pRenderer->pTargetSurface[pTargetPoint->x + pTargetPoint->y * pRenderer->uTargetSurfacePitch];
 src_width = pSrcRect->right - pSrcRect->left;
 src_height = pSrcRect->bottom - pSrcRect->top;
 
@@ -671,12 +671,13 @@
             for (int j=0; j< src_width; ++j)
                 {
                 if ( *src_surf_pos != v10 )
-                    *dest_surf_pos = *src_surf_pos;
-                ++dest_surf_pos;
+                  pRenderer->WritePixel16(pTargetPoint->x + j, pTargetPoint->y + i, *src_surf_pos);
+                    //*dest_surf_pos = *src_surf_pos;
+                //++dest_surf_pos;
                 ++src_surf_pos;
                 }
             src_surf_pos+=uSrcPitch;
-            dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
+            //dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
             }
     }
 else 
@@ -687,12 +688,13 @@
         for (int j=0; j< src_width; ++j)
             {
             if ( *src_surf_pos != v10 )
-                *dest_surf_pos = (v21 & (*dest_surf_pos >> 1)) + (v21 & (*src_surf_pos >> 1));
-            ++dest_surf_pos;
+              pRenderer->WritePixel16(pTargetPoint->x + j, pTargetPoint->y + i, (v21 & (pRenderer->ReadPixel16(pTargetPoint->x + j, pTargetPoint->y + i) >> 1)) + (v21 & (*src_surf_pos >> 1)));
+                //*dest_surf_pos = (v21 & (*dest_surf_pos >> 1)) + (v21 & (*src_surf_pos >> 1));
+            //++dest_surf_pos;
             ++src_surf_pos;
             }
         src_surf_pos+=uSrcPitch;
-        dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
+        //dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
         }
     }
 
@@ -703,7 +705,7 @@
     {
 
     unsigned __int16 *pSrc; // eax@2
-    unsigned __int16 *dest_surf_pos; // edi@3
+    //unsigned __int16 *dest_surf_pos; // edi@3
     int uSrcTotalWidth; // ecx@4
     int v21; // [sp+Ch] [bp-18h]@8
     unsigned __int16 *src_surf_pos; // [sp+10h] [bp-14h]@9
@@ -716,7 +718,7 @@
     if ( !pArcomageGame->pBlit_Copy_pixels )
         return;
 
-    dest_surf_pos = &pRenderer->pTargetSurface[pTargetPoint->x + pTargetPoint->y * pRenderer->uTargetSurfacePitch];
+    //dest_surf_pos = &pRenderer->pTargetSurface[pTargetPoint->x + pTargetPoint->y * pRenderer->uTargetSurfacePitch];
     src_width = pSrcRect->right - pSrcRect->left;
     src_height = pSrcRect->bottom - pSrcRect->top;
 
@@ -744,13 +746,14 @@
         for (int i=0; i< src_height; ++i)
             {
             for (int j=0; j< src_width; ++j)
-                {    
-                *dest_surf_pos = *src_surf_pos;
-                ++dest_surf_pos;
+                { 
+                  pRenderer->WritePixel16(pTargetPoint->x + j, pTargetPoint->y + i, *src_surf_pos);
+                //*dest_surf_pos = *src_surf_pos;
+                //++dest_surf_pos;
                 ++src_surf_pos;
                 }
             src_surf_pos+=uSrcPitch;
-            dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
+            //dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
             }
         }
     else 
@@ -760,12 +763,13 @@
             {
             for (int j=0; j< src_width; ++j)
                 {
-                 *dest_surf_pos = (v21 & (*dest_surf_pos >> 1)) + (v21 & (*src_surf_pos >> 1));
-                ++dest_surf_pos;
+                 //*dest_surf_pos = (v21 & (*dest_surf_pos >> 1)) + (v21 & (*src_surf_pos >> 1));
+                //++dest_surf_pos;
+                  pRenderer->WritePixel16(pTargetPoint->x + j, pTargetPoint->y + i, (v21 & (pRenderer->ReadPixel16(pTargetPoint->x + j, pTargetPoint->y + i) >> 1)) + (v21 & (*src_surf_pos >> 1)));
                 ++src_surf_pos;
                 }
             src_surf_pos+=uSrcPitch;
-            dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
+            //dest_surf_pos += pRenderer->uTargetSurfacePitch - src_width;
             }
         }
 }
@@ -4085,11 +4089,15 @@
     }
 
 void DrawSquare( POINT *pTargetXY, unsigned __int16 uColor )
-    {
+{
     pRenderer->BeginScene();
     if ( pRenderer->uNumSceneBegins )
-        {
-        int xVal = pTargetXY->x;
+    {
+      pRenderer->WritePixel16(pTargetXY->x,     pTargetXY->y, uColor);
+      pRenderer->WritePixel16(pTargetXY->x + 1, pTargetXY->y, uColor);
+      pRenderer->WritePixel16(pTargetXY->x,     pTargetXY->y + 1, uColor);
+      pRenderer->WritePixel16(pTargetXY->x + 1, pTargetXY->y + 1, uColor);
+        /*int xVal = pTargetXY->x;
         int yVal = pTargetXY->y;
         if ( xVal >= 0 && xVal <= 639 && yVal >= 0 && yVal <= 479)
             {
@@ -4097,26 +4105,27 @@
             pRenderer->pTargetSurface[xVal+1 + pRenderer->uTargetSurfacePitch * yVal] = uColor;
             pRenderer->pTargetSurface[xVal + pRenderer->uTargetSurfacePitch * (yVal+1)] = uColor;
             pRenderer->pTargetSurface[xVal+1 + pRenderer->uTargetSurfacePitch * (yVal+1)] = uColor;
-            }
+            }*/
         pRenderer->EndScene();
         }
-    }
+}
 
 //----- (0040DBD3) --------------------------------------------------------
 void DrawPixel( POINT *pTargetXY, unsigned __int16 uColor )
-    {
+{
     pRenderer->BeginScene();
     if ( pRenderer->uNumSceneBegins )
         {
-        int xVal = pTargetXY->x;
+          pRenderer->WritePixel16(pTargetXY->x, pTargetXY->y, uColor);
+        /*int xVal = pTargetXY->x;
         int yVal = pTargetXY->y;
         if ( xVal >= 0 && xVal <= 639 && yVal >= 0 && yVal <= 479)
             {
             pRenderer->pTargetSurface[xVal + pRenderer->uTargetSurfacePitch * yVal] = uColor;
-            }
+            }*/
         pRenderer->EndScene();
         }
-    }
+}
 
 
 //----- (0040DDB1) --------------------------------------------------------
--- a/AudioPlayer.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/AudioPlayer.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -45,15 +45,17 @@
 
 
 
-unsigned __int8 uSoundVolumeMultiplier = 4;
-unsigned __int8 uVoicesVolumeMultiplier = 4;
-unsigned __int8 uMusicVolimeMultiplier = 4;
+unsigned __int8 uSoundVolumeMultiplier;// = 4;
+unsigned __int8 uVoicesVolumeMultiplier;// = 4;
+unsigned __int8 uMusicVolimeMultiplier;// = 4;
 int bWalkSound; // idb
 
 std::array<float, 10> pSoundVolumeLevels = 
 {
   0.0000000f, 0.1099999f, 0.2199999f, 0.3300000f, 0.4399999f,
- 0.5500000f, 0.6600000f, 0.7699999f, 0.8799999f, 0.9700000f     //changed 0.9900000f to 0.9700000f. for some reason it only works for values below this
+ 0.5500000f, 0.6600000f, 0.7699999f, 0.8799999f, 0.9700000f  
+//  0.0000000f, 0.4900000f, 0.5500000f, 0.6100000f, 0.6700000f,  //for 128.0f
+// 0.7000000f, 0.7600000f, 0.8200000f, 0.8800000f, 0.9700000f     //changed 0.9900000f to 0.9700000f. for some reason it only works for values below this
 };
 
 
@@ -81,13 +83,16 @@
   {
     for ( uint i = 1; i < pSoundList->sNumSounds; ++i )
     {
-      sprintf(pSoundName, "%s", pSounds[i].pSoundName);
-      pSoundDesc = &pSoundList->pSounds[i];
-      if ( pSoundList->pSounds[i].eType != SOUND_DESC_SYSTEM || (sprintf(pSoundName, "%s", pSounds[i].pSoundName),
-            pSoundList->pSounds[i].pSoundData[0] = ::LoadSound(pSoundName, (SoundData *)-1, pSounds[i].uSoundID),
-            !pAudioPlayer->b3DSoundInitialized)
-        || (pSoundDesc = &pSoundList->pSounds[i], !(pSoundDesc->uFlags & SOUND_DESC_SWAP))
-        || !pSoundDesc->pSoundData[0] )
+      sprintf(pSoundName, "%s", pSL_Sounds[i].pSoundName);
+      pSoundDesc = &pSoundList->pSL_Sounds[i];
+      if ( pSoundList->pSL_Sounds[i].eType != SOUND_DESC_SYSTEM )
+        continue;
+      sprintf(pSoundName, "%s", pSL_Sounds[i].pSoundName);
+      pSoundList->pSL_Sounds[i].pSoundData[0] = ::LoadSound(pSoundName, (SoundData *)-1, pSL_Sounds[i].uSoundID);
+      if ( !pAudioPlayer->b3DSoundInitialized )
+        continue;
+      pSoundDesc = &pSoundList->pSL_Sounds[i];
+      if ( !(pSoundDesc->uFlags & SOUND_DESC_SWAP) || !pSoundDesc->pSoundData[0] )
         continue;
       pSoundData = pSoundDesc->pSoundData[0];
       uSoundSize = *(int *)pSoundData;
@@ -95,7 +100,7 @@
       pType = AIL_file_type(pSoundBytes, uSoundSize);
       if ( !pType )
       {
-        pSoundList->pSounds[i].bDecompressed = false;
+        pSoundList->pSL_Sounds[i].bDecompressed = false;
         pSoundList->UnloadSound(i, 1);
         continue;
       }
@@ -106,20 +111,20 @@
         {
           if ( AIL_WAV_info(pSoundBytes, &pInfo) && pInfo.uChannels != 2 )
           {
-            if ( !AIL_decompress_ADPCM(&pInfo, &pSoundList->pSounds[i].p3DSound, &v12) )
+            if ( !AIL_decompress_ADPCM(&pInfo, &pSoundList->pSL_Sounds[i].p3DSound, &v12) )
             {
-              pSoundList->pSounds[i].p3DSound = 0;
-              pSoundList->pSounds[i].bDecompressed = true;
+              pSoundList->pSL_Sounds[i].p3DSound = 0;
+              pSoundList->pSL_Sounds[i].bDecompressed = true;
             }
           }
           pSoundList->UnloadSound(i, 1);
           continue;
         }
-        pSoundList->pSounds[i].bDecompressed = false;
+        pSoundList->pSL_Sounds[i].bDecompressed = false;
         pSoundList->UnloadSound(i, 1);
         continue;
       }
-      pSoundList->pSounds[i].p3DSound = pSoundList->pSounds[i].pSoundData[0];
+      pSoundList->pSL_Sounds[i].p3DSound = pSoundList->pSL_Sounds[i].pSoundData[0];
       pSoundList->UnloadSound(i, 1);
     }
   }
@@ -136,10 +141,10 @@
   uint       uSoundIdx = 0;
   SoundDesc *pSound = nullptr;
   for (uint i = 1; i < sNumSounds; ++i)
-    if (pSounds[i].uSoundID == a1)
+    if (pSL_Sounds[i].uSoundID == a1)
     {
       uSoundIdx = i;
-      pSound = &pSounds[i];
+      pSound = &pSL_Sounds[i];
       break;
     }
   if (!pSound)
@@ -230,7 +235,7 @@
     v25 = 44;
     while ( 1 )
     {
-      v10 = pSounds;
+      v10 = pSL_Sounds;
       v11 = &v10[v24 / 0x78];
       Args = &v10[v24 / 0x78];
       if ( a2 == v10[v24 / 0x78].uSoundID )
@@ -288,7 +293,7 @@
       v16 = a2;
     }
     result = v26;
-    pSounds->pSoundData[a6 + 30 * v26] = (SoundData *)lpBuffer;
+    pSL_Sounds->pSoundData[a6 + 30 * v26] = (SoundData *)lpBuffer;
     *pOutSoundSize = v16;
 
   return result;
@@ -304,13 +309,13 @@
   {
     for ( uint i = 0; i < (signed int)this->sNumSounds; ++i )
     {
-      result = this->pSounds;
+      result = this->pSL_Sounds;
       v5 = result[i].pSoundData[0];
       if ( v5 )
       {
         ReleaseSoundData(v5);
-        this->pSounds[i].pSoundData[0] = 0;
-        result = (SoundDesc *)((char *)&this->pSounds[i] + 40);
+        this->pSL_Sounds[i].pSoundData[0] = 0;
+        result = (SoundDesc *)((char *)&this->pSL_Sounds[i] + 40);
         *(int *)&result->pSoundName[0] &= 0xFFFFFFFEu;
       }
     }
@@ -323,14 +328,14 @@
 {
   for ( int i = 0; i < (signed int)this->sNumSounds; ++i )
   {
-    if ( this->pSounds[i].eType != SOUND_DESC_SYSTEM && (a2 || this->pSounds[i].eType != SOUND_DESC_LOCK) )
+    if ( this->pSL_Sounds[i].eType != SOUND_DESC_SYSTEM && (a2 || this->pSL_Sounds[i].eType != SOUND_DESC_LOCK) )
     {
-      if ( this->pSounds[i].pSoundData[0] )
+      if ( this->pSL_Sounds[i].pSoundData[0] )
       {
-        ReleaseSoundData(this->pSounds[i].pSoundData[0]);
-        this->pSounds[i].pSoundData[0] = 0;
+        ReleaseSoundData(this->pSL_Sounds[i].pSoundData[0]);
+        this->pSL_Sounds[i].pSoundData[0] = 0;
       }
-      this->pSounds[i].uFlags &= ~SOUND_DESC_SYSTEM;
+      this->pSL_Sounds[i].uFlags &= ~SOUND_DESC_SYSTEM;
     }
   }
 }
@@ -338,20 +343,20 @@
 //----- (004A9DCD) --------------------------------------------------------
 void SoundList::UnloadSound(unsigned int uSoundID, char a3)
 {
-  if ( pSounds[uSoundID].eType != SOUND_DESC_SYSTEM )
+  if ( pSL_Sounds[uSoundID].eType != SOUND_DESC_SYSTEM )
   {
-    if ( (pSounds[uSoundID].uFlags & SOUND_DESC_SWAP) && pSounds[uSoundID].p3DSound && a3 )
+    if ( (pSL_Sounds[uSoundID].uFlags & SOUND_DESC_SWAP) && pSL_Sounds[uSoundID].p3DSound && a3 )
     {
-      if ( pSounds[uSoundID].bDecompressed)
-        AIL_mem_free_lock(pSounds[uSoundID].p3DSound);
-      pSounds[uSoundID].p3DSound = 0;
-      pSounds[uSoundID].uFlags &= ~SOUND_DESC_SYSTEM;
+      if ( pSL_Sounds[uSoundID].bDecompressed)
+        AIL_mem_free_lock(pSL_Sounds[uSoundID].p3DSound);
+      pSL_Sounds[uSoundID].p3DSound = 0;
+      pSL_Sounds[uSoundID].uFlags &= ~SOUND_DESC_SYSTEM;
     }
-    if ( pSounds[uSoundID].pSoundData[0] )
+    if ( pSL_Sounds[uSoundID].pSoundData[0] )
     {
-      ReleaseSoundData(pSounds[uSoundID].pSoundData[0]);
-      pSounds[uSoundID].pSoundData[0] = NULL;
-      pSounds[uSoundID].uFlags &= ~SOUND_DESC_SYSTEM;
+      ReleaseSoundData(pSL_Sounds[uSoundID].pSoundData[0]);
+      pSL_Sounds[uSoundID].pSoundData[0] = NULL;
+      pSL_Sounds[uSoundID].uFlags &= ~SOUND_DESC_SYSTEM;
     }
   }
 }
@@ -367,7 +372,7 @@
     Error("Unable to save dsounds.bin!");
 
   fwrite(this, 4, 1, v2);
-  fwrite(this->pSounds, 0x78u, this->sNumSounds, v2);
+  fwrite(this->pSL_Sounds, 0x78u, this->sNumSounds, v2);
   fclose(v2);
 }
 
@@ -382,12 +387,12 @@
   assert(sNumSounds);
   assert(!num_mm8_sounds);
 
-  pSounds = (SoundDesc *)malloc(sNumSounds * sizeof(SoundDesc));
-  memcpy(pSounds, (char *)data_mm7 + 4, num_mm7_sounds * sizeof(SoundDesc));
+  pSL_Sounds = (SoundDesc *)malloc(sNumSounds * sizeof(SoundDesc));
+  memcpy(pSL_Sounds, (char *)data_mm7 + 4, num_mm7_sounds * sizeof(SoundDesc));
   for (uint i = 0; i < num_mm6_sounds; ++i)
   {
     auto src = (SoundDesc_mm6 *)((char *)data_mm6 + 4) + i;
-    SoundDesc* dst = &pSounds[num_mm7_sounds + i];
+    SoundDesc* dst = &pSL_Sounds[num_mm7_sounds + i];
 
     memcpy(dst, src, sizeof(SoundDesc_mm6));
     dst->p3DSound = nullptr;
@@ -417,9 +422,9 @@
   FILE *File; // [sp+2F8h] [bp-4h]@1
   unsigned int Argsa; // [sp+304h] [bp+8h]@3
 
-  free(this->pSounds);
+  free(this->pSL_Sounds);
   v3 = 0;
-  this->pSounds = 0;
+  this->pSL_Sounds = 0;
   this->sNumSounds = 0;
   v4 = fopen(Args, "r");
   File = v4;
@@ -443,7 +448,7 @@
   }
   this->sNumSounds = v5;
   v6 = malloc(120 * v5);
-  this->pSounds = (SoundDesc *)v6;
+  this->pSL_Sounds = (SoundDesc *)v6;
   if ( v6 == (void *)v3 )
     Error("SoundListClass::load - Out of Memory!");
 
@@ -457,16 +462,16 @@
     memcpy(&v19, txt_file_frametable_parser(&Buf, &v18), sizeof(v19));
     if ( v19.uPropCount && *v19.pProperties[0] != 47 )
     {
-      sprintf(this->pSounds[this->sNumSounds].pSoundName, "%s", v19.pProperties[0]);
+      sprintf(this->pSL_Sounds[this->sNumSounds].pSoundName, "%s", v19.pProperties[0]);
       v9 = atoi(v19.pProperties[1]);
       v10 = v19.pProperties[2];
-      this->pSounds[this->sNumSounds].uSoundID = v9;
+      this->pSL_Sounds[this->sNumSounds].uSoundID = v9;
       if ( _stricmp(v10, "system") )
       {
         if ( _stricmp(v19.pProperties[2], "swap") )
         {
           v11 = _stricmp(v19.pProperties[2], "lock");
-          v12 = this->pSounds;
+          v12 = this->pSL_Sounds;
           v13 = v11 == 0;
           v14 = this->sNumSounds;
           if ( v13 )
@@ -475,13 +480,13 @@
             v12[v14].eType = SOUND_DESC_LEVEL;
         }
         else
-          this->pSounds[this->sNumSounds].eType = SOUND_DESC_SWAP;
+          this->pSL_Sounds[this->sNumSounds].eType = SOUND_DESC_SWAP;
       }
       else
-        this->pSounds[this->sNumSounds].eType = SOUND_DESC_SYSTEM;
+        this->pSL_Sounds[this->sNumSounds].eType = SOUND_DESC_SYSTEM;
       if ( v19.uPropCount >= 4 && !_stricmp(v19.pProperties[3], "3D") )
       {
-        v15 = (int)&this->pSounds[this->sNumSounds].uFlags;
+        v15 = (int)&this->pSL_Sounds[this->sNumSounds].uFlags;
         *(int *)v15 |= SOUND_DESC_SWAP;
       }
       ++this->sNumSounds;
@@ -535,44 +540,30 @@
   if (!bPlayerReady)
     return;
 
-    if ( this->b3DSoundInitialized && a2 && this->uNum3DSamples > 0 )
+  if ( this->b3DSoundInitialized && a2 )
+  {
+    for ( uint i = 0; i < this->uNum3DSamples; ++i )
     {
-      for ( uint i = 0; i < this->uNum3DSamples; ++i )
-      {
-        if ( this->p3DSamples[i].field_4 == a2 && AIL_3D_sample_status(this->p3DSamples[i].hSample) == 4 )
-          AIL_end_3D_sample(this->p3DSamples[i].hSample);
-      }
-      goto LABEL_9;
+      if ( this->p3DSamples[i].field_4 == a2 && AIL_3D_sample_status(this->p3DSamples[i].hSample) == AIL::Sample::Playing )
+        AIL_end_3D_sample(this->p3DSamples[i].hSample);
     }
-    else
+  }
+  if ( this->hDigDriver && a2 )
+  {
+    for ( uint i = 0; i < this->uMixerChannels; ++i )
     {
-LABEL_9:
-      if ( this->hDigDriver )
+      if ( this->pMixerChannels[i].source_pid == a2 && AIL_sample_status(this->pMixerChannels[i].hSample) == AIL::Sample::Playing)
       {
-        if ( a2 && this->uMixerChannels > 0 )
-        {
-          for ( uint i = 0; i < this->uMixerChannels; ++i )
-          {
-            if ( this->pMixerChannels[i].source_pid == a2 )
-            {
-              if ( AIL_sample_status(this->pMixerChannels[i].hSample) == AIL::Sample::Playing)
-              {
-                AIL_end_sample(this->pMixerChannels[i].hSample);
-                FreeChannel(&this->pMixerChannels[i]);
-              }
-            }
-          }
-        }
+        AIL_end_sample(this->pMixerChannels[i].hSample);
+        FreeChannel(&this->pMixerChannels[i]);
       }
     }
+  }
 }
 
 //----- (004AA306) --------------------------------------------------------
-void AudioPlayer::PlaySound(SoundID eSoundID, signed int a3, unsigned int uNumRepeats, signed int PartyX, signed int PartyY, int a7, unsigned int uVolume, int sPlaybackRate)
+void AudioPlayer::PlaySound(SoundID eSoundID, signed int a3, unsigned int uNumRepeats, signed int source_x, signed int source_y, int a7, float uVolume, int sPlaybackRate)
 {
-  //AudioPlayer *pAudioPlayer1; // esi@1
-  //signed int pNum; // edx@5
-  //int *pSoundID; // ecx@6
   int v12; // edi@13
   signed int v13; // ecx@17
   signed int v14; // eax@20
@@ -598,9 +589,7 @@
   int v34; // eax@70
   char v35; // zf@70
   signed int v36; // ebx@74
-  //AudioPlayer *pAudioPlayer2; // edi@79
   AudioPlayer_3DSample *pAudioPlayer_3DSample3; // esi@79
-  //unsigned int v39; // ebx@80
   int v40; // eax@81
   char *v41; // edi@82
   int v42; // esi@82
@@ -616,47 +605,16 @@
   int v52; // eax@104
   float v53; // ST0C_4@106
   float v54; // ST04_4@106
-  //AudioPlayer *pAudioPlayer3; // edx@106
   SoundDesc *pSoundDesc; // edx@107
   SpriteObject *pLayingItem3; // eax@114
-  //int v58; // edx@115
-  //int v59; // ecx@115
-  //Actor *pActor2; // eax@118
-  //MixerChannel *pMixerChannel; // esi@126
   signed int v62; // esi@133
-  //AudioPlayer *pAudioPlayer4; // ebx@133
-  //MixerChannel *pMixerChannel2; // edi@134
-  //int v65; // ebx@141
-  //AudioPlayer *pAudioPlayer5; // ecx@142
-  //MixerChannel *pMixerChannel3; // edi@142
   int v68; // eax@143
-  //MixerChannel *pMixerChannel4; // edi@149
-  //int v70; // ecx@152
-  //SoundDesc *pSoundDesc2; // eax@153
-  //int v72; // edi@156
-  //MixerChannel *pMixerChannel5; // esi@157
-  //unsigned int pVolume; // eax@157
-  //int pPartyX; // ebx@159
-  //int v76; // ebx@160
-  //SpriteObject *pLayingItem4; // edi@164
-  //unsigned int pPosY; // edx@166
-  //unsigned int pPosX; // ecx@166
-  //int v80; // eax@167
-  //Actor *pActor3; // edi@168
-  //BLVDoor *pBLVDoor2; // edi@173
-  //int v83; // eax@183
-  //int v84; // eax@183
-  //_SAMPLE *v85; // ST18_4@186
   unsigned int v86; // [sp+14h] [bp-60h]@84
-  //int v87; // [sp+14h] [bp-60h]@115
   RenderVertexSoft pRenderVertexSoft; // [sp+24h] [bp-50h]@1
-  //unsigned int v89; // [sp+54h] [bp-20h]@12
   int v90; // [sp+58h] [bp-1Ch]@68
   float v91; // [sp+5Ch] [bp-18h]@68
-  //unsigned int v92; // [sp+60h] [bp-14h]@10
   float v93; // [sp+64h] [bp-10h]@1
   signed int varC; // [sp+68h] [bp-Ch]@68
-  //AudioPlayer *pAudioPlayer; // [sp+6Ch] [bp-8h]@1
   int v96; // [sp+70h] [bp-4h]@19
   signed int uNumRepeatsb; // [sp+84h] [bp+10h]@93
   float uNumRepeatsa; // [sp+84h] [bp+10h]@104
@@ -666,25 +624,14 @@
   int v102; // [sp+90h] [bp+1Ch]@60
   int v103; // [sp+90h] [bp+1Ch]@68
 
-  if (!bPlayerReady)
-    return;
-  if (!uSoundVolumeMultiplier)
-    return;
-  if (!hDigDriver)
-    return;
-  if (eSoundID == SOUND_Invalid)
+  if ( !bPlayerReady || !uSoundVolumeMultiplier || !hDigDriver || eSoundID == SOUND_Invalid )
     return;
 
-  //pAudioPlayer = this;
-  //v35 = this->bPlayerReady == 0;
-  //pAudioPlayer = this;
-  //LODWORD(v93) = 10000;
   int sample_volume = 10000;
 
-
   int sound_id = 0;
   for (uint i = 0; i < pSoundList->sNumSounds; ++i)
-    if (pSoundList->pSounds[i].uSoundID == eSoundID)
+    if (pSoundList->pSL_Sounds[i].uSoundID == eSoundID)
     {
       sound_id = i;
       break;
@@ -695,345 +642,501 @@
     Log::Warning(L"SoundID = %u not found", eSoundID);
     return;
   }
+  assert(sound_id < pSoundList->sNumSounds);
+  if ( !a7 )
+  {
+    if ( !pSoundList->pSL_Sounds[sound_id].pSoundData[0] )
+    {
+      if ( pSoundList->pSL_Sounds[sound_id].eType == SOUND_DESC_SWAP )
+        pSoundList->LoadSound(eSoundID, 0);
+    }
+  }
+  if ( !pSoundList->pSL_Sounds[sound_id].pSoundData[a7] )
+    return;
 
   int start_channel = 0,
       end_channel = 0;
-v62 = start_channel;
-  assert(sound_id < pSoundList->sNumSounds);
-  SoundDesc* sound_desc = &pSoundList->pSounds[sound_id];
-  if (!b3DSoundInitialized || sound_desc->Is3D())
+  v62 = start_channel;
+
+  if (!b3DSoundInitialized || pSoundList->pSL_Sounds[sound_id].Is3D())
   {
-    if (!a3)  // generic sound like from UI
+    if (a3 == 0)  // generic sound like from UI
     {
       start_channel = 10;
       end_channel = 12;
-      for (v62 = start_channel; v62 <= end_channel; ++v62)
+      for (uint i = start_channel; i <= end_channel; ++i)
       {
-        MixerChannel* channel = pMixerChannels + v62;
-        if (AIL_sample_status(channel->hSample) == AIL::Sample::Done)
+        if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )
         {
-          AIL_end_sample(channel->hSample);
-          if (channel->uSourceTrackIdx)
-            FreeChannel(channel);
-          break;
+          if ( pMixerChannels[i].uSourceTrackIdx == sound_id )
+            return;                          // already playing the same sound from the same source - return
+          AIL_end_sample(pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+          FreeChannel(&pMixerChannels[i]);
         }
       }
+      for ( uint j = start_channel; j <= end_channel; j++ )
+      {
+        if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
+        {
+          AIL_init_sample(pMixerChannels[j].hSample);
+          char *p = (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7];
+          if (a7 == 0)  p = p + 4;//for RIFF
+		  if ( eSoundID == 75 )// Ritor1: include +7 for pSounds[20]
+			  p = p + 7;
+          AIL_set_sample_file(pMixerChannels[j].hSample, p, -1);
+          if ( sample_volume == 10000 )
+            sample_volume = uMasterVolume;
+          if (uVolume)
+            sample_volume = uVolume;
+          int object_type = PID_TYPE(a3),
+              object_id = PID_ID(a3);
+          if (source_x != -1)//        
+          {
+            //if (!source_x)
+              //source_x = pParty->vPosition.x;
+            //if (!source_y)
+              //source_y = pParty->vPosition.y;
+           if ( source_x )//Ritor1: for pedestals
+           {
+              AIL_set_sample_pan(pMixerChannels[j].hSample, sub_4AB66C(source_x, source_y));
+              int vol = GetSoundStrengthByDistanceFromParty(source_x, source_y, pParty->vPosition.z);
+              AIL_set_sample_volume(pMixerChannels[j].hSample, vol);
+           }
+          }
+          if (uNumRepeats)
+            AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+          pMixerChannels[j].uSourceTrackIdx = sound_id;
+          pMixerChannels[j].source_pid = a3;
+          pMixerChannels[j].uSourceTrackID = eSoundID;
+          int rval = AIL_start_sample(pMixerChannels[j].hSample);
+          if ( sPlaybackRate )
+            AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+          if (object_type == OBJECT_Player)
+            AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+          return;
+        }
+      }
+      return;
     }
     else if (a3 == -1)  // exclusive sounds - can override
     {
-      start_channel = 13;
-      end_channel = 13;
-      for (v62 = start_channel; v62 <= end_channel; ++v62)
+      /*if ( AIL_sample_status(pMixerChannels[13].hSample) == AIL::Sample::Done )
       {
-        MixerChannel* channel = pMixerChannels + v62;
-        if (AIL_sample_status(channel->hSample) == AIL::Sample::Done)
+          AIL_end_sample(pMixerChannels[13].hSample);
+          if ( pMixerChannels[13].uSourceTrackIdx )
+            FreeChannel(&pMixerChannels[13]);
+      }*/
+      AIL_init_sample(pMixerChannels[13].hSample);
+      char *p = (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7];
+      if (a7 == 0)
+        p = p + 4;//for RIFF
+	  if ( eSoundID == 75 )//  Ritor1: include +7 for pSounds[20]
+		  p = p + 7;
+       AIL_set_sample_file(pMixerChannels[13].hSample, p, -1);
+       if ( sample_volume == 10000 )
+         sample_volume = uMasterVolume;
+       if (uVolume)
+         sample_volume = uVolume;
+       AIL_set_sample_volume(pMixerChannels[13].hSample, sample_volume);
+       int object_type = PID_TYPE(a3),
+           object_id = PID_ID(a3);
+       if (uNumRepeats)
+         AIL_set_sample_loop_count(pMixerChannels[13].hSample, uNumRepeats - 1);
+       pMixerChannels[13].uSourceTrackIdx = sound_id;
+       pMixerChannels[13].source_pid = a3;
+       pMixerChannels[13].uSourceTrackID = eSoundID;
+       int rval = AIL_start_sample(pMixerChannels[13].hSample);//no sound chest close 
+       if ( sPlaybackRate )
+         AIL_set_sample_playback_rate(pMixerChannels[13].hSample, sPlaybackRate);
+       if (object_type == OBJECT_Player)
+         AIL_sample_ms_position(pMixerChannels[13].hSample, &sLastTrackLengthMS, 0);
+       return;
+    }
+    else if (a3 < 0)    // exclusive sounds - no override (close chest)
+    {
+      start_channel = 14;
+      end_channel = 14;
+      for (uint i = start_channel; i <= end_channel; ++i)
+      {
+        if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )
         {
-          AIL_end_sample(channel->hSample);
-          if (channel->uSourceTrackIdx)
-            FreeChannel(channel);
-          break;
+          if ( pMixerChannels[i].uSourceTrackIdx == sound_id )
+            return;                          // already playing the same sound from the same source - return
+          AIL_end_sample(pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+          FreeChannel(&pMixerChannels[i]);
         }
       }
+      for ( uint j = start_channel; j <= end_channel; j++ )
+      {
+        if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
+        {
+          AIL_init_sample(pMixerChannels[j].hSample);
+          char *p = (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7];
+          if (a7 == 0)  p = p + 4;//for RIFF
+		  if ( eSoundID == 75 )//  Ritor1: include +7 for pSounds[20]
+			  p = p + 7;
+          AIL_set_sample_file(pMixerChannels[j].hSample, p, -1);
+          if ( sample_volume == 10000 )
+            sample_volume = uMasterVolume;
+          if (uVolume)
+            sample_volume = uVolume;
+          int object_type = PID_TYPE(a3),
+              object_id = PID_ID(a3);
+          if (uNumRepeats)
+            AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+          pMixerChannels[j].uSourceTrackIdx = sound_id;
+          pMixerChannels[j].source_pid = a3;
+          pMixerChannels[j].uSourceTrackID = eSoundID;
+          int rval = AIL_start_sample(pMixerChannels[j].hSample);//no sound chest close 
+          if ( sPlaybackRate )
+            AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+          if (object_type == OBJECT_Player)
+            AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+          return;
+        }
+      }
+      return;
     }
     else
     {
-      if (a3 < 0)    // exclusive sounds - no override
-      {
-        start_channel = 14;
-        end_channel = 14;
-        for (uint i = 0; i < uMixerChannels; ++i)
-        {
-          MixerChannel* channel = &pMixerChannels[i];
-          if (channel->source_pid == a3 && AIL_sample_status(channel->hSample) == AIL::Sample::Playing)
-          {
-            if (channel->uSourceTrackIdx == sound_id)
-              return;                          // already playing the same sound from the same source - return
-            AIL_end_sample(channel->hSample);  // requested new sound from the same source - end & switch
-            FreeChannel(channel);
-          }
-        }
-      }
-      else
-      {
         int object_type = PID_TYPE(a3),
             object_id = PID_ID(a3);
         switch (object_type)
         {
           case OBJECT_BLVDoor:
+          {
+            assert(uCurrentlyLoadedLevelType == LEVEL_Indoor);
+            assert(object_id < pIndoor->uNumDoors);
+            if ( !pIndoor->pDoors[object_id].uDoorID )
+              return;
+
+            start_channel = 10;
+            end_channel = 12;
+            for (uint i = start_channel; i <= end_channel; ++i)
+            {
+              if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )
+              {
+                if ( pMixerChannels[i].uSourceTrackIdx == sound_id )
+                  return;                          // already playing the same sound from the same source - return
+                AIL_end_sample( pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+                FreeChannel(&pMixerChannels[i]);
+              }
+            }
+            for ( uint j = start_channel; j <= end_channel; j++ )
+            {
+              if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
+              {
+                AIL_init_sample(pMixerChannels[j].hSample);
+                AIL_set_sample_file(pMixerChannels[j].hSample, (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
+                if (uVolume)
+                  sample_volume = uVolume;
+                AIL_set_sample_volume(pMixerChannels[j].hSample, sample_volume);
+                /*if (!GetSoundStrengthByDistanceFromParty(pIndoor->pDoors[object_id].pXOffsets[0], pIndoor->pDoors[object_id].pYOffsets[0], pIndoor->pDoors[object_id].pZOffsets[0]))
+                {
+                  AIL_end_sample(pMixerChannels[j].hSample);
+                  FreeChannel(&pMixerChannels[j]);
+                  return;
+                } */
+                AIL_set_sample_pan(pMixerChannels[j].hSample, sub_4AB66C(pIndoor->pDoors[object_id].pXOffsets[0], pIndoor->pDoors[object_id].pYOffsets[0]));
+                if (uNumRepeats)
+                  AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+                pMixerChannels[j].uSourceTrackIdx = sound_id;
+                pMixerChannels[j].source_pid = a3;
+                pMixerChannels[j].uSourceTrackID = eSoundID;
+                int rval = AIL_start_sample(pMixerChannels[j].hSample);
+                if ( sPlaybackRate )
+                  AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+                if (object_type == OBJECT_Player)
+                  AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+                return;
+              }
+            }
+          }
+          return;
+
           case OBJECT_Player:
           {
             start_channel = 10;
             end_channel = 12;
-            for (v62 = start_channel; v62 <= end_channel; ++v62)
+            for (uint i = start_channel; i <= end_channel; ++i)
             {
-              MixerChannel* channel = pMixerChannels + v62;
-              if (AIL_sample_status(channel->hSample) == AIL::Sample::Done)
+              if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )
+              {
+                if ( pMixerChannels[i].uSourceTrackIdx == sound_id )
+                  return;                          // already playing the same sound from the same source - return
+                AIL_end_sample( pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+                FreeChannel(&pMixerChannels[i]);
+              }
+            }
+            for ( uint j = start_channel; j <= end_channel; j++ )
+            {
+              if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
               {
-                AIL_end_sample(channel->hSample);
-                if (channel->uSourceTrackIdx)
-                  FreeChannel(channel);
-                break;
+                AIL_init_sample(pMixerChannels[j].hSample);
+                AIL_set_sample_file(pMixerChannels[j].hSample, (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
+                if (uVolume)
+                  sample_volume = uVolume;
+                AIL_set_sample_volume(pMixerChannels[j].hSample, sample_volume);
+                if (uNumRepeats)
+                  AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+                pMixerChannels[j].uSourceTrackIdx = sound_id;
+                pMixerChannels[j].source_pid = a3;
+                pMixerChannels[j].uSourceTrackID = eSoundID;
+                int rval = AIL_start_sample(pMixerChannels[j].hSample);
+                if ( sPlaybackRate )
+                  AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+                if (object_type == OBJECT_Player)
+                  AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+                return;
               }
             }
           }
-          break;
+          return;
 
           case OBJECT_Actor:
           {
             start_channel = 0;
             end_channel = 3;
-
             assert(object_id < uNumActors);
-            Actor* actor = &pActors[object_id];
-
-            sample_volume = GetSoundStrengthByDistanceFromParty(actor->vPosition.x, actor->vPosition.y, actor->vPosition.z);
+            sample_volume = GetSoundStrengthByDistanceFromParty(pActors[object_id].vPosition.x, pActors[object_id].vPosition.y, pActors[object_id].vPosition.z);
             if (!sample_volume)
               return;
-            for (uint i = 0; i < uMixerChannels; ++i)
+            for (uint i = start_channel; i <= end_channel; ++i)
             {
-              MixerChannel* channel = &pMixerChannels[i];
-              if (channel->source_pid == a3 && AIL_sample_status(channel->hSample) == AIL::Sample::Playing)
+              if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )
+              {
+                if ( pMixerChannels[i].uSourceTrackIdx == sound_id )
+                  return;                          // already playing the same sound from the same source - return
+                AIL_end_sample( pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+                FreeChannel(&pMixerChannels[i]);
+              }
+            }
+            for ( uint j = start_channel; j <= end_channel; j++ )
+            {
+              if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
               {
-                if (channel->uSourceTrackIdx == sound_id)
-                  return;                          // already playing the same sound from the same source - return
-                AIL_end_sample(channel->hSample);  // requested new sound from the same source - end & switch
-                FreeChannel(channel);
+                AIL_init_sample(pMixerChannels[j].hSample);
+                AIL_set_sample_file(pMixerChannels[j].hSample, (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
+                if (uVolume)
+                  sample_volume = uVolume;
+                AIL_set_sample_volume(pMixerChannels[j].hSample, sample_volume);
+                if (!GetSoundStrengthByDistanceFromParty(pActors[object_id].vPosition.x, pActors[object_id].vPosition.y, pActors[object_id].vPosition.z))
+                  return;
+                AIL_set_sample_pan(pMixerChannels[j].hSample, sub_4AB66C(pActors[object_id].vPosition.x, pActors[object_id].vPosition.y));
+                if (uNumRepeats)
+                  AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+                pMixerChannels[j].uSourceTrackIdx = sound_id;
+                pMixerChannels[j].source_pid = a3;
+                pMixerChannels[j].uSourceTrackID = eSoundID;
+                int rval = AIL_start_sample(pMixerChannels[j].hSample);
+                if ( sPlaybackRate )
+                  AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+                if (object_type == OBJECT_Player)
+                  AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+                return;
               }
             }
           }
-          break;
+          return;
 
           case OBJECT_Decoration:
           {
             start_channel = 4;
             end_channel = 4;
-
             assert(object_id < uNumLevelDecorations);
-            LevelDecoration* decor = &pLevelDecorations[object_id];
-
-            sample_volume = GetSoundStrengthByDistanceFromParty(decor->vPosition.x, decor->vPosition.y, decor->vPosition.z);
+            sample_volume = GetSoundStrengthByDistanceFromParty(pLevelDecorations[object_id].vPosition.x, pLevelDecorations[object_id].vPosition.y, pLevelDecorations[object_id].vPosition.z);
             if (!sample_volume)
               return;
-            for (uint i = 0; i < uMixerChannels; ++i)
+            for (uint i = start_channel; i <= end_channel; ++i)
             {
-              MixerChannel* channel = &pMixerChannels[i];
-              if (channel->source_pid == a3 && AIL_sample_status(channel->hSample) == AIL::Sample::Playing)
+              if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )//        
+              {
+                if ( pMixerChannels[i].uSourceTrackIdx == sound_id )
+                  return;                          // already playing the same sound from the same source - return
+                AIL_end_sample(pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+                FreeChannel(&pMixerChannels[i]);
+              }
+            }
+            for ( uint j = start_channel; j <= end_channel; j++ )
+            {
+              if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
               {
-                if (channel->uSourceTrackIdx == sound_id)
-                  return;                          // already playing the same sound from the same source - return
-                AIL_end_sample(channel->hSample);  // requested new sound from the same source - end & switch
-                FreeChannel(channel);
+                AIL_init_sample(pMixerChannels[j].hSample);
+                AIL_set_sample_file(pMixerChannels[j].hSample, (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
+                if (uVolume)
+                  sample_volume = uVolume;
+                AIL_set_sample_volume(pMixerChannels[j].hSample, sample_volume);
+                if (!GetSoundStrengthByDistanceFromParty(pLevelDecorations[object_id].vPosition.x, pLevelDecorations[object_id].vPosition.y, pLevelDecorations[object_id].vPosition.z))
+                  return;
+                AIL_set_sample_pan(pMixerChannels[j].hSample, sub_4AB66C(pLevelDecorations[object_id].vPosition.x, pLevelDecorations[object_id].vPosition.y));
+                if (uNumRepeats)
+                  AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+                pMixerChannels[j].uSourceTrackIdx = sound_id;
+                pMixerChannels[j].source_pid = a3;
+                pMixerChannels[j].uSourceTrackID = eSoundID;
+                int rval = AIL_start_sample(pMixerChannels[j].hSample);
+                if ( sPlaybackRate )
+                  AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+                if (object_type == OBJECT_Player)
+                  AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+                return;
               }
             }
           }
-          break;
+          return;
 
           case OBJECT_Item:
           {
             start_channel = 5;
             end_channel = 7;
-
             assert(object_id < uNumSpriteObjects);
-            SpriteObject* object = &pSpriteObjects[object_id];
-
-            sample_volume = GetSoundStrengthByDistanceFromParty(object->vPosition.x, object->vPosition.y, object->vPosition.z);
+            sample_volume = GetSoundStrengthByDistanceFromParty(pSpriteObjects[object_id].vPosition.x, pSpriteObjects[object_id].vPosition.y, pSpriteObjects[object_id].vPosition.z);
             if (!sample_volume)
               return;
-            for (uint i = 0; i < uMixerChannels; ++i)
+            for (uint i = start_channel; i <= end_channel; ++i)
             {
-              MixerChannel* channel = &pMixerChannels[i];
-              if (channel->source_pid == a3 && AIL_sample_status(channel->hSample) == AIL::Sample::Playing)
+              if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )
+              {
+                if (pMixerChannels[i].uSourceTrackIdx == sound_id)
+                  return;                          // already playing the same sound from the same source - return
+                AIL_end_sample(pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+                FreeChannel(&pMixerChannels[i]);
+              }
+            }
+            for ( uint j = start_channel; j <= end_channel; j++ )
+            {
+              if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
               {
-                if (channel->uSourceTrackIdx == sound_id)
-                  return;                          // already playing the same sound from the same source - return
-                AIL_end_sample(channel->hSample);  // requested new sound from the same source - end & switch
-                FreeChannel(channel);
+                AIL_init_sample(pMixerChannels[j].hSample);
+                AIL_set_sample_file(pMixerChannels[j].hSample, (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
+                if (uVolume)
+                  sample_volume = uVolume;
+                AIL_set_sample_volume(pMixerChannels[j].hSample, sample_volume);
+                if (!GetSoundStrengthByDistanceFromParty(pSpriteObjects[object_id].vPosition.x, pSpriteObjects[object_id].vPosition.y, pSpriteObjects[object_id].vPosition.z) )
+                  return;
+                AIL_set_sample_pan(pMixerChannels[v62].hSample, sub_4AB66C(pSpriteObjects[object_id].vPosition.x, pSpriteObjects[object_id].vPosition.y));
+                if (uNumRepeats)
+                  AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+                pMixerChannels[j].uSourceTrackIdx = sound_id;
+                pMixerChannels[j].source_pid = a3;
+                pMixerChannels[j].uSourceTrackID = eSoundID;
+                int rval = AIL_start_sample(pMixerChannels[j].hSample);
+                if ( sPlaybackRate )
+                  AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+                if (object_type == OBJECT_Player)
+                  AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+                return;
               }
             }
           }
-          break;
+          return;
 
           case OBJECT_BModel:
           {
             start_channel = 8;
             end_channel = 9;
-            for (uint i = 0; i < uMixerChannels; ++i)
+            for (uint i = start_channel; i <= end_channel; ++i)
             {
-              MixerChannel* channel = &pMixerChannels[i];
-              if (channel->source_pid == a3 && AIL_sample_status(channel->hSample) == AIL::Sample::Playing)
+              if ( pMixerChannels[i].source_pid == a3 && AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Playing )
+              {
+                if ( pMixerChannels[i].uSourceTrackIdx == sound_id )
+                  return;                          // already playing the same sound from the same source - return
+                AIL_end_sample(pMixerChannels[i].hSample);  // requested new sound from the same source - end & switch
+                FreeChannel(&pMixerChannels[i]);
+              }
+            }
+            for ( uint j = start_channel; j <= end_channel; j++ )
+            {
+              if ( AIL_sample_status(pMixerChannels[j].hSample) == AIL::Sample::Done )
               {
-                if (channel->uSourceTrackIdx == sound_id)
-                  return;                          // already playing the same sound from the same source - return
-                AIL_end_sample(channel->hSample);  // requested new sound from the same source - end & switch
-                FreeChannel(channel);
+                AIL_init_sample(pMixerChannels[j].hSample);
+                AIL_set_sample_file(pMixerChannels[j].hSample, (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
+                if (uVolume)
+                  sample_volume = uVolume;
+                AIL_set_sample_volume(pMixerChannels[j].hSample, sample_volume);
+                if (uNumRepeats)
+                  AIL_set_sample_loop_count(pMixerChannels[j].hSample, uNumRepeats - 1);
+                pMixerChannels[j].uSourceTrackIdx = sound_id;
+                pMixerChannels[j].source_pid = a3;
+                pMixerChannels[j].uSourceTrackID = eSoundID;
+                int rval = AIL_start_sample(pMixerChannels[j].hSample);
+                if ( sPlaybackRate )
+                  AIL_set_sample_playback_rate(pMixerChannels[j].hSample, sPlaybackRate);
+                if (object_type == OBJECT_Player)
+                  AIL_sample_ms_position(pMixerChannels[j].hSample, &sLastTrackLengthMS, 0);
+                return;
               }
             }
           }
-          break;
+          return;
 
           default:
             assert(false);
         }
       }
-    }
-      /*if ( start_channel <= end_channel)
-      {
-        pMixerChannel2 = &pAudioPlayer->pMixerChannels[start_channel];
-        while ( AIL_sample_status(pMixerChannel2->hSample) != AIL::Sample::Done)
-        {
-          ++v62;
-          ++pMixerChannel2;
-          if ( v62 > end_channel )
-            goto LABEL_140;
-        }
-        AIL_end_sample(pMixerChannel2->hSample);
-        if ( pMixerChannel2->uSourceTrackIdx )
-          _4ABE55(pMixerChannel2);
-      }
-LABEL_140:*/
 
+	  __debugbreak();//Ritor1
       if (start_channel > end_channel)  // no free channel - occupy the quitest one
       {
         start_channel = -1;
-
         int min_volume = sample_volume;
         for (uint i = start_channel; i <= end_channel; ++i)
         {
-          MixerChannel* channel = &pMixerChannels[i];
-
-          int volume = AIL_sample_volume(channel->hSample);
+          int volume = AIL_sample_volume(pMixerChannels[i].hSample);
           if (volume < min_volume)
           {
             min_volume = volume;
             start_channel = i;
           }
         }
-        /*v65 = start_channel;
-        v91 = v93;
-      if (start_channel <= end_channel)
-      {
-        //pAudioPlayer5 = pAudioPlayer;
-        pMixerChannel3 = &pAudioPlayer->pMixerChannels[start_channel];
-        do
-        {
-          v68 = AIL_sample_volume(pMixerChannel3->hSample);
-          if ( v68 < SLODWORD(v91) )
-          {
-            LODWORD(v91) = v68;
-            v62 = v65;
-          }
-          ++v65;
-          ++pMixerChannel3;
-        }
-        while ( v65 <= end_channel );*/
-
         if (v62 == -1)   // no free channels at all - only channel 13 allows override (a3 == -1)
         {
           if (start_channel != 13)
             return;
           v62 = 13;
         }
-
-        MixerChannel* channel = &pMixerChannels[v62];
-        AIL_end_sample(channel->hSample);
-        FreeChannel(channel);
+        AIL_end_sample(pMixerChannels[v62].hSample);
+        FreeChannel(&pMixerChannels[v62]);
       }
 
       if (v62 > end_channel)//10!=13
         return;
 
-//LABEL_150:
-      if (sample_volume == 10000)
+      if ( sample_volume == 10000 )
         sample_volume = uMasterVolume;
 
-        //v70 = 0;
-      if ( !a7 )
-      {
-          //pSoundDesc = pSoundList->pSounds;
-          //pSoundDesc2 = &pSoundList->pSounds[sound_id];
-        if (!sound_desc->pSoundData[0])
-        {
-          if (sound_desc->eType == SOUND_DESC_SWAP)
-            pSoundList->LoadSound(eSoundID, 0);
-        }
-      }
-        //v72 = 4 * (a7 + 30 * sound_id) + 44;
-      if (!pSoundList->pSounds[sound_id].pSoundData[a7])
-        return;
-
-        //pMixerChannel5 = &pAudioPlayer->pMixerChannels[v62];
-      MixerChannel* channel = &pMixerChannels[v62];
-      AIL_init_sample(channel->hSample);
-      AIL_set_sample_file(channel->hSample, (char *)pSoundList->pSounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
+      AIL_init_sample(pMixerChannels[v62].hSample);
+      AIL_set_sample_file(pMixerChannels[v62].hSample, (char *)pSoundList->pSL_Sounds[sound_id].pSoundData[a7] + 4 * (a7 == 0), -1);
       if (uVolume)
         sample_volume = uVolume;
-      AIL_set_sample_volume(channel->hSample, sample_volume);
+      AIL_set_sample_volume(pMixerChannels[v62].hSample, sample_volume);
 
       int object_type = PID_TYPE(a3),
           object_id = PID_ID(a3);
-      if (PartyX != -1)
-      {
-        if (!PartyX) PartyX = pParty->vPosition.x;
-        if (!PartyY) PartyY = pParty->vPosition.y;
-        AIL_set_sample_pan(channel->hSample, sub_4AB66C(PartyX, PartyY));
-        AIL_set_sample_volume(channel->hSample, GetSoundStrengthByDistanceFromParty(PartyX, PartyY, pParty->vPosition.z));
-      }
-      else if (object_type == OBJECT_BLVDoor)
+      if (source_x != -1)
       {
-        assert(uCurrentlyLoadedLevelType == LEVEL_Indoor);
-
-        assert(object_id < pIndoor->uNumDoors);
-        BLVDoor* door = &pIndoor->pDoors[object_id];
-        if (!door->uDoorID)
-          return;
-
-        if (!GetSoundStrengthByDistanceFromParty(door->pXOffsets[0], door->pYOffsets[0], door->pZOffsets[0]))
-        {
-          AIL_end_sample(channel->hSample);
-          FreeChannel(channel);
-          return;
-        }
-        AIL_set_sample_pan(channel->hSample, sub_4AB66C(door->pXOffsets[0], door->pYOffsets[0]));
-      }
-      else if (object_type == OBJECT_Item)
-      {
-        assert(object_id < uNumSpriteObjects);
-        SpriteObject* object = &pSpriteObjects[object_id];
-        if (!GetSoundStrengthByDistanceFromParty(object->vPosition.x, object->vPosition.y, object->vPosition.z) )
-            return;
-        AIL_set_sample_pan(channel->hSample, sub_4AB66C(object->vPosition.x, object->vPosition.y));
-      }
-      else if (object_type == OBJECT_Actor)
-      {
-        assert(object_id < uNumActors);
-        Actor* actor = &pActors[object_id];
-        if (!GetSoundStrengthByDistanceFromParty(actor->vPosition.x, actor->vPosition.y, actor->vPosition.z))
-          return;
-        AIL_set_sample_pan(channel->hSample, sub_4AB66C(actor->vPosition.x, actor->vPosition.y));
-      }
-      else if (object_type == OBJECT_Decoration)
-      {
-        assert(object_id < uNumLevelDecorations);
-        LevelDecoration* decor = &pLevelDecorations[object_id];
-        if (!GetSoundStrengthByDistanceFromParty(decor->vPosition.x, decor->vPosition.y, decor->vPosition.z))
-          return;
-        AIL_set_sample_pan(channel->hSample, sub_4AB66C(decor->vPosition.x, decor->vPosition.y));
+        if (!source_x)
+          source_x = pParty->vPosition.x;
+        if (!source_y)
+          source_y = pParty->vPosition.y;
+        AIL_set_sample_pan(pMixerChannels[v62].hSample, sub_4AB66C(source_x, source_y));
+        AIL_set_sample_volume(pMixerChannels[v62].hSample, GetSoundStrengthByDistanceFromParty(source_x, source_y, pParty->vPosition.z));
       }
 
-//LABEL_184:
       if (uNumRepeats)
-        AIL_set_sample_loop_count(channel->hSample, uNumRepeats - 1);
-      channel->uSourceTrackIdx = sound_id;
-      channel->source_pid = a3;
-      channel->uSourceTrackID = eSoundID;
-      int rval = AIL_start_sample(channel->hSample);
+        AIL_set_sample_loop_count(pMixerChannels[v62].hSample, uNumRepeats - 1);
+      pMixerChannels[v62].uSourceTrackIdx = sound_id;
+      pMixerChannels[v62].source_pid = a3;
+      pMixerChannels[v62].uSourceTrackID = eSoundID;
+      int rval = AIL_start_sample(pMixerChannels[v62].hSample);
       if ( sPlaybackRate )
-        AIL_set_sample_playback_rate(channel->hSample, sPlaybackRate);
+        AIL_set_sample_playback_rate(pMixerChannels[v62].hSample, sPlaybackRate);
       if (object_type == OBJECT_Player)
-        AIL_sample_ms_position(channel->hSample, &sLastTrackLengthMS, 0);
-      return;
+        AIL_sample_ms_position(pMixerChannels[v62].hSample, &sLastTrackLengthMS, 0);
+      return; 
   }
-
+  else
+  {
   __debugbreak(); // 3d sound stuff, refactor
   v12 = 13;
   if ( a3 < 0 )
@@ -1255,18 +1358,18 @@
     v102 = v36;
   }
   //v39 = v89;
-  if ( pSoundList->pSounds[sound_id].p3DSound || (LOWORD(v40) = pSoundList->LoadSound(eSoundID, 0), v40) )
+  if ( pSoundList->pSL_Sounds[sound_id].p3DSound || (LOWORD(v40) = pSoundList->LoadSound(eSoundID, 0), v40) )
   {
     v41 = (char *)pAudioPlayer + 16 * v102;
     v42 = (int)(v41 + 20);
-    if ( AIL_set_3D_sample_file(*((int *)v41 + 5), *(void **)((char *)&pSoundList->pSounds->p3DSound + sound_id * sizeof(SoundDesc))) )
+    if ( AIL_set_3D_sample_file(*((int *)v41 + 5), *(void **)((char *)&pSoundList->pSL_Sounds->p3DSound + sound_id * sizeof(SoundDesc))) )
     {
       if ( uNumRepeats )
         v86 = uNumRepeats - 1;
       else
         v86 = 1;
       AIL_set_3D_sample_loop_count(*(int *)v42, v86);
-      if ( PartyX == -1 )
+      if ( source_x == -1 )
       {
         if ( PID_TYPE(a3) == 1 )
         {
@@ -1349,13 +1452,14 @@
         v47 = (double)pLayingItem2->vPosition.z;
         goto LABEL_101;
       }
-      pRenderVertexSoft.vWorldPosition.x = (double)PartyX;
-      v43 = (double)PartyY;
+      pRenderVertexSoft.vWorldPosition.x = (double)source_x;
+      v43 = (double)source_y;
       pRenderVertexSoft.vWorldPosition.y = v43;
       v47 = (double)pParty->sEyelevel + (double)pParty->vPosition.z;
       goto LABEL_101;
     }
   }
+  }
 }
 
 //----- (0040DEA5) --------------------------------------------------------
@@ -1373,7 +1477,7 @@
   //unsigned __int8 v3; // zf@1
   //int *v4; // eax@2
   //unsigned __int8 v5; // sf@4
-  AudioPlayer_3DSample *v6; // esi@5
+  //AudioPlayer_3DSample *v6; // esi@5
   int v7; // ebx@6
   int v8; // ebx@9
   int v9; // ebx@10
@@ -1437,164 +1541,360 @@
   if (!bPlayerReady)
     return;
   
-  if (field_2D0_time_left <= pEventTimer->uTimeElapsed)
-    field_2D0_time_left = 32;
-  else
+  //if (field_2D0_time_left <= pEventTimer->uTimeElapsed)
+    //field_2D0_time_left = 32;
+  //else
+  //{
+    //field_2D0_time_left -= pEventTimer->uTimeElapsed;
+    //return;
+  //}
+  field_2D0_time_left -= pEventTimer->uTimeElapsed;
+  if ( field_2D0_time_left <= 0 )
   {
-    field_2D0_time_left -= pEventTimer->uTimeElapsed;
-    return;
-  }
-
-  //v3 = this->b3DSoundInitialized == 0;
-  if ( b3DSoundInitialized )
+  field_2D0_time_left = 32;
+  if ( b3DSoundInitialized )//for 3D sound
   {
     __debugbreak(); // refactor refactor
-    //v3 = this->uNum3DSamples == 0;
-    //v5 = this->uNum3DSamples < 0;
-    v59 = 0;
-    if (uNum3DSamples > 0)
+    v2 = 0;
+    for ( v59 = 0; v59 < pAudioPlayer->uNum3DSamples; ++v59 )
     {
-      v6 = this->p3DSamples;
-      while ( 1 )
+      v7 = PID_TYPE(this->p3DSamples[v59].field_4);
+      if ( AIL_3D_sample_status(this->p3DSamples[v59].hSample) == AIL::Sample::Done )
       {
-        v7 = PID_TYPE(v6->field_4);
-        if ( AIL_3D_sample_status(v6->hSample) == 2 )
-        {
-          AIL_end_3D_sample(v6->hSample);
-          pAudioPlayer->_4ABF23(v6);
-        }
-        if ( AIL_3D_sample_status(v6->hSample) != 4 )
-          goto LABEL_35;
-        v8 = v7 - 1;//
-        if ( v8 )//> 1
-          break;
-        if ( uCurrentlyLoadedLevelType != LEVEL_Indoor )//==1
-          goto LABEL_31;
-        pDoor = &pIndoor->pDoors[PID_ID(v6->field_4)];
-        if ( pDoor->uDoorID )
-        {
-          uNumRepeats = *pDoor->pXOffsets;
-          a1.vWorldPosition.x = (double)uNumRepeats;
-          uNumRepeats = *pDoor->pYOffsets;
-          a1.vWorldPosition.y = (double)uNumRepeats;
-          uNumRepeats = *pDoor->pZOffsets;
-          v11 = (double)uNumRepeats;
-          goto LABEL_21;
-        }
-LABEL_35:
-        ++v59;
-        ++v6;
-        if ( v59 >= pAudioPlayer->uNum3DSamples )
-        {
-          v2 = 0;
-          goto LABEL_37;
-        }
+        AIL_end_3D_sample(this->p3DSamples[v59].hSample);
+        pAudioPlayer->_4ABF23(&this->p3DSamples[v59]);
       }
-
-      v9 = v8 - 1;//
-      if ( v9 )//> 2
+      if ( AIL_3D_sample_status(this->p3DSamples[v59].hSample) != AIL::Sample::Playing )
+        continue;
+      v8 = v7 - 1;//
+      if ( v8 )//> 1
       {
-        v10 = v9 - 1;//
-        if ( !v10 )//3
-        {
-          v13 = &pActors[PID_ID(v6->field_4)];
-          uNumRepeats = v13->vPosition.x;
-          v14 = v13->vPosition.y;
-          a1.vWorldPosition.x = (double)uNumRepeats;
-          uNumRepeats = v13->vPosition.z;
-          a1.vWorldPosition.y = (double)v14;
-          v11 = (double)uNumRepeats;
-          goto LABEL_21;
-        }
-        if ( v10 != 2 )//4
+        v9 = v8 - 1;//
+        if ( v9 )//> 2
         {
-          a1.vWorldPosition.x = (double)pParty->vPosition.x;
-          a1.vWorldPosition.y = (double)pParty->vPosition.y;
-          v11 = (double)pParty->sEyelevel + (double)pParty->vPosition.z;
-          goto LABEL_21;
-        }//5
-        v12 = (SpriteObject *)&pLevelDecorations[PID_ID(v6->field_4)];
-      }
-      else//2
-      {
-        v12 = &pSpriteObjects[PID_ID(v6->field_4)];
-      }
-      a1.vWorldPosition.x = (double)v12->vPosition.x;
-      a1.vWorldPosition.y = (double)v12->vPosition.y;
-      v11 = (double)v12->vPosition.z;
-LABEL_21:
-      a1.vWorldPosition.z = v11;
-      if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
-      {
-        v16 = pGame->pIndoorCameraD3D->fRotationXCosine;
-        v17 = pGame->pIndoorCameraD3D->fRotationXSine;
-        v55 = pGame->pIndoorCameraD3D->fRotationYCosine;
-        v56 = pGame->pIndoorCameraD3D->fRotationYSine;
-        if (pGame->pIndoorCameraD3D->sRotationX)
+          v10 = v9 - 1;//
+          if ( !v10 )//3
+          {
+            v13 = &pActors[PID_ID(this->p3DSamples[v59].field_4)];
+            //uNumRepeats = v13->vPosition.x;
+            //v14 = v13->vPosition.y;
+            a1.vWorldPosition.x = (double)v13->vPosition.x;
+            //uNumRepeats = v13->vPosition.z;
+            a1.vWorldPosition.y = (double)v13->vPosition.y;
+            //v11 = (double)uNumRepeats;
+            a1.vWorldPosition.z = v13->vPosition.z;
+            if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
+            {
+              v16 = pGame->pIndoorCameraD3D->fRotationXCosine;
+              v17 = pGame->pIndoorCameraD3D->fRotationXSine;
+              v55 = pGame->pIndoorCameraD3D->fRotationYCosine;
+              v56 = pGame->pIndoorCameraD3D->fRotationYSine;
+              if (pGame->pIndoorCameraD3D->sRotationX)
+              {
+                v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+                *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+                v18 = a1.vWorldPosition.z - (double)pParty->vPosition.z;
+                if ( pRenderer->pRenderD3D )
+                {
+                  v19 = *(float *)&uNumRepeats * v56 + v58 * v55;
+                  v20 = v58 * v56 - *(float *)&uNumRepeats * v55;
+                }
+                else
+                {
+                  v19 = v58 * v55 - *(float *)&uNumRepeats * v56;
+                  v20 = v58 * v56 + *(float *)&uNumRepeats * v55;
+                }
+                a1.vWorldViewPosition.x = v19 * v16 - v18 * v17;
+                a1.vWorldViewPosition.y = v20;
+                a1.vWorldViewPosition.z = v19 * v17 + v18 * v16;
+              }
+              else
+              {
+                v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+                *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+                if ( pRenderer->pRenderD3D )
+                {
+                  a1.vWorldViewPosition.x = *(float *)&uNumRepeats * v56 + v58 * v55;
+                  v21 = v58 * v56 - *(float *)&uNumRepeats * v55;
+                }
+                else
+                {
+                  a1.vWorldViewPosition.x = v58 * v55 - *(float *)&uNumRepeats * v56;
+                  v21 = v58 * v56 + *(float *)&uNumRepeats * v55;
+                }
+                a1.vWorldViewPosition.y = v21;
+                a1.vWorldViewPosition.z = a1.vWorldPosition.z - (double)pParty->vPosition.z;
+              }
+            }
+            else
+              pGame->pIndoorCameraD3D->ViewTransform(&a1, 1);
+            v58 = a1.vWorldViewPosition.y * -0.012207031;
+            v22 = a1.vWorldViewPosition.x * 0.012207031;
+            *(float *)&uNumRepeats = v22;
+            v23 = abs((signed __int64)v22);
+            v24 = abs(0);
+            v25 = abs((signed __int64)v58);
+            if ( int_get_vector_length(v25, v24, v23) <= 100 )
+            {
+              AIL_set_3D_position(this->p3DSamples[v59].hSample, LODWORD(v58), 0.0, uNumRepeats);
+              v26 = -*(float *)&uNumRepeats;
+              v27 = -v58;
+              AIL_set_3D_orientation(this->p3DSamples[v59].hSample, LODWORD(v27), 0.0, LODWORD(v26), 0.0, 1.0, 0.0);
+            }
+            else
+            {
+              AIL_end_3D_sample(this->p3DSamples[v59].hSample);
+              pAudioPlayer->_4ABF23(&this->p3DSamples[v59]);
+            }
+            continue;
+          }
+          if ( v10 != 2 )//4
+          {
+            a1.vWorldPosition.x = (double)pParty->vPosition.x;
+            a1.vWorldPosition.y = (double)pParty->vPosition.y;
+            v11 = (double)pParty->sEyelevel + (double)pParty->vPosition.z;
+            a1.vWorldPosition.z = v11;
+            if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
+            {
+              v16 = pGame->pIndoorCameraD3D->fRotationXCosine;
+              v17 = pGame->pIndoorCameraD3D->fRotationXSine;
+              v55 = pGame->pIndoorCameraD3D->fRotationYCosine;
+              v56 = pGame->pIndoorCameraD3D->fRotationYSine;
+              if (pGame->pIndoorCameraD3D->sRotationX)
+              {
+                v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+                *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+                v18 = a1.vWorldPosition.z - (double)pParty->vPosition.z;
+                if ( pRenderer->pRenderD3D )
+                {
+                  v19 = *(float *)&uNumRepeats * v56 + v58 * v55;
+                  v20 = v58 * v56 - *(float *)&uNumRepeats * v55;
+                }
+                else
+                {
+                  v19 = v58 * v55 - *(float *)&uNumRepeats * v56;
+                  v20 = v58 * v56 + *(float *)&uNumRepeats * v55;
+                }
+                a1.vWorldViewPosition.x = v19 * v16 - v18 * v17;
+                a1.vWorldViewPosition.y = v20;
+                a1.vWorldViewPosition.z = v19 * v17 + v18 * v16;
+              }
+              else
+              {
+                v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+                *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+                if ( pRenderer->pRenderD3D )
+                {
+                  a1.vWorldViewPosition.x = *(float *)&uNumRepeats * v56 + v58 * v55;
+                  v21 = v58 * v56 - *(float *)&uNumRepeats * v55;
+                }
+                else
+                {
+                  a1.vWorldViewPosition.x = v58 * v55 - *(float *)&uNumRepeats * v56;
+                  v21 = v58 * v56 + *(float *)&uNumRepeats * v55;
+                }
+                a1.vWorldViewPosition.y = v21;
+                a1.vWorldViewPosition.z = a1.vWorldPosition.z - (double)pParty->vPosition.z;
+              }
+            }
+            else
+              pGame->pIndoorCameraD3D->ViewTransform(&a1, 1);
+            v58 = a1.vWorldViewPosition.y * -0.012207031;
+            v22 = a1.vWorldViewPosition.x * 0.012207031;
+            *(float *)&uNumRepeats = v22;
+            v23 = abs((signed __int64)v22);
+            v24 = abs(0);
+            v25 = abs((signed __int64)v58);
+            if ( int_get_vector_length(v25, v24, v23) <= 100 )
+            {
+              AIL_set_3D_position(this->p3DSamples[v59].hSample, LODWORD(v58), 0.0, uNumRepeats);
+              v26 = -*(float *)&uNumRepeats;
+              v27 = -v58;
+              AIL_set_3D_orientation(this->p3DSamples[v59].hSample, LODWORD(v27), 0.0, LODWORD(v26), 0.0, 1.0, 0.0);
+            }
+            else
+            {
+              AIL_end_3D_sample(this->p3DSamples[v59].hSample);
+              pAudioPlayer->_4ABF23(&this->p3DSamples[v59]);
+            }
+            continue;
+          }//5
+          v12 = (SpriteObject *)&pLevelDecorations[PID_ID(this->p3DSamples[v59].field_4)];
+        }
+        else//2
+          v12 = &pSpriteObjects[PID_ID(this->p3DSamples[v59].field_4)];
+        a1.vWorldPosition.x = (double)v12->vPosition.x;
+        a1.vWorldPosition.y = (double)v12->vPosition.y;
+        v11 = (double)v12->vPosition.z;
+//LABEL_21:
+        a1.vWorldPosition.z = v11;
+        if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
         {
-          v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
-          *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
-          v18 = a1.vWorldPosition.z - (double)pParty->vPosition.z;
-          if ( pRenderer->pRenderD3D )
+          v16 = pGame->pIndoorCameraD3D->fRotationXCosine;
+          v17 = pGame->pIndoorCameraD3D->fRotationXSine;
+          v55 = pGame->pIndoorCameraD3D->fRotationYCosine;
+          v56 = pGame->pIndoorCameraD3D->fRotationYSine;
+          if (pGame->pIndoorCameraD3D->sRotationX)
           {
-            v19 = *(float *)&uNumRepeats * v56 + v58 * v55;
-            v20 = v58 * v56 - *(float *)&uNumRepeats * v55;
+            v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+            *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+            v18 = a1.vWorldPosition.z - (double)pParty->vPosition.z;
+            if ( pRenderer->pRenderD3D )
+            {
+              v19 = *(float *)&uNumRepeats * v56 + v58 * v55;
+              v20 = v58 * v56 - *(float *)&uNumRepeats * v55;
+            }
+            else
+            {
+              v19 = v58 * v55 - *(float *)&uNumRepeats * v56;
+              v20 = v58 * v56 + *(float *)&uNumRepeats * v55;
+            }
+            a1.vWorldViewPosition.x = v19 * v16 - v18 * v17;
+            a1.vWorldViewPosition.y = v20;
+            a1.vWorldViewPosition.z = v19 * v17 + v18 * v16;
           }
           else
           {
-            v19 = v58 * v55 - *(float *)&uNumRepeats * v56;
-            v20 = v58 * v56 + *(float *)&uNumRepeats * v55;
+            v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+            *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+            if ( pRenderer->pRenderD3D )
+            {
+              a1.vWorldViewPosition.x = *(float *)&uNumRepeats * v56 + v58 * v55;
+              v21 = v58 * v56 - *(float *)&uNumRepeats * v55;
+            }
+            else
+            {
+              a1.vWorldViewPosition.x = v58 * v55 - *(float *)&uNumRepeats * v56;
+              v21 = v58 * v56 + *(float *)&uNumRepeats * v55;
+            }
+            a1.vWorldViewPosition.y = v21;
+            a1.vWorldViewPosition.z = a1.vWorldPosition.z - (double)pParty->vPosition.z;
           }
-          a1.vWorldViewPosition.x = v19 * v16 - v18 * v17;
-          a1.vWorldViewPosition.y = v20;
-          a1.vWorldViewPosition.z = v19 * v17 + v18 * v16;
+        }
+        else
+          pGame->pIndoorCameraD3D->ViewTransform(&a1, 1);
+        v58 = a1.vWorldViewPosition.y * -0.012207031;
+        v22 = a1.vWorldViewPosition.x * 0.012207031;
+        *(float *)&uNumRepeats = v22;
+        v23 = abs((signed __int64)v22);
+        v24 = abs(0);
+        v25 = abs((signed __int64)v58);
+        if ( int_get_vector_length(v25, v24, v23) <= 100 )
+        {
+          AIL_set_3D_position(this->p3DSamples[v59].hSample, LODWORD(v58), 0.0, uNumRepeats);
+          v26 = -*(float *)&uNumRepeats;
+          v27 = -v58;
+          AIL_set_3D_orientation(this->p3DSamples[v59].hSample, LODWORD(v27), 0.0, LODWORD(v26), 0.0, 1.0, 0.0);
         }
         else
         {
-          v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
-          *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
-          if ( pRenderer->pRenderD3D )
+          AIL_end_3D_sample(this->p3DSamples[v59].hSample);
+          pAudioPlayer->_4ABF23(&this->p3DSamples[v59]);
+        }
+        continue;
+      }
+      if ( uCurrentlyLoadedLevelType != LEVEL_Indoor )//==1
+      {
+        pGame->pIndoorCameraD3D->ViewTransform(&a1, 1);
+        v58 = a1.vWorldViewPosition.y * -0.012207031;
+        v22 = a1.vWorldViewPosition.x * 0.012207031;
+        *(float *)&uNumRepeats = v22;
+        v23 = abs((signed __int64)v22);
+        v24 = abs(0);
+        v25 = abs((signed __int64)v58);
+        if ( int_get_vector_length(v25, v24, v23) <= 100 )
+        {
+          AIL_set_3D_position(this->p3DSamples[v59].hSample, LODWORD(v58), 0.0, uNumRepeats);
+          v26 = -*(float *)&uNumRepeats;
+          v27 = -v58;
+          AIL_set_3D_orientation(this->p3DSamples[v59].hSample, LODWORD(v27), 0.0, LODWORD(v26), 0.0, 1.0, 0.0);
+        }
+        else
+        {
+          AIL_end_3D_sample(this->p3DSamples[v59].hSample);
+          pAudioPlayer->_4ABF23(&this->p3DSamples[v59]);
+        }
+        continue;
+      }
+      pDoor = &pIndoor->pDoors[PID_ID(this->p3DSamples[v59].field_4)];
+      if ( pDoor->uDoorID )
+      {
+        uNumRepeats = *pDoor->pXOffsets;
+        a1.vWorldPosition.x = (double)uNumRepeats;
+        uNumRepeats = *pDoor->pYOffsets;
+        a1.vWorldPosition.y = (double)uNumRepeats;
+        uNumRepeats = *pDoor->pZOffsets;
+        v11 = (double)uNumRepeats;
+        a1.vWorldPosition.z = v11;
+        if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
+        {
+          v16 = pGame->pIndoorCameraD3D->fRotationXCosine;
+          v17 = pGame->pIndoorCameraD3D->fRotationXSine;
+          v55 = pGame->pIndoorCameraD3D->fRotationYCosine;
+          v56 = pGame->pIndoorCameraD3D->fRotationYSine;
+          if (pGame->pIndoorCameraD3D->sRotationX)
           {
-            a1.vWorldViewPosition.x = *(float *)&uNumRepeats * v56 + v58 * v55;
-            v21 = v58 * v56 - *(float *)&uNumRepeats * v55;
+            v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+            *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+            v18 = a1.vWorldPosition.z - (double)pParty->vPosition.z;
+            if ( pRenderer->pRenderD3D )
+            {
+              v19 = *(float *)&uNumRepeats * v56 + v58 * v55;
+              v20 = v58 * v56 - *(float *)&uNumRepeats * v55;
+            }
+            else
+            {
+              v19 = v58 * v55 - *(float *)&uNumRepeats * v56;
+              v20 = v58 * v56 + *(float *)&uNumRepeats * v55;
+            }
+            a1.vWorldViewPosition.x = v19 * v16 - v18 * v17;
+            a1.vWorldViewPosition.y = v20;
+            a1.vWorldViewPosition.z = v19 * v17 + v18 * v16;
           }
           else
           {
-            a1.vWorldViewPosition.x = v58 * v55 - *(float *)&uNumRepeats * v56;
-            v21 = v58 * v56 + *(float *)&uNumRepeats * v55;
+            v58 = a1.vWorldPosition.x - (double)pParty->vPosition.x;
+            *(float *)&uNumRepeats = a1.vWorldPosition.y - (double)pParty->vPosition.y;
+            if ( pRenderer->pRenderD3D )
+            {
+              a1.vWorldViewPosition.x = *(float *)&uNumRepeats * v56 + v58 * v55;
+              v21 = v58 * v56 - *(float *)&uNumRepeats * v55;
+            }
+            else
+            {
+              a1.vWorldViewPosition.x = v58 * v55 - *(float *)&uNumRepeats * v56;
+              v21 = v58 * v56 + *(float *)&uNumRepeats * v55;
+            }
+            a1.vWorldViewPosition.y = v21;
+            a1.vWorldViewPosition.z = a1.vWorldPosition.z - (double)pParty->vPosition.z;
           }
-          a1.vWorldViewPosition.y = v21;
-          a1.vWorldViewPosition.z = a1.vWorldPosition.z - (double)pParty->vPosition.z;
+        }
+        else
+          pGame->pIndoorCameraD3D->ViewTransform(&a1, 1);
+        v58 = a1.vWorldViewPosition.y * -0.012207031;
+        v22 = a1.vWorldViewPosition.x * 0.012207031;
+        *(float *)&uNumRepeats = v22;
+        v23 = abs((signed __int64)v22);
+        v24 = abs(0);
+        v25 = abs((signed __int64)v58);
+        if ( int_get_vector_length(v25, v24, v23) <= 100 )
+        {
+          AIL_set_3D_position(this->p3DSamples[v59].hSample, LODWORD(v58), 0.0, uNumRepeats);
+          v26 = -*(float *)&uNumRepeats;
+          v27 = -v58;
+          AIL_set_3D_orientation(this->p3DSamples[v59].hSample, LODWORD(v27), 0.0, LODWORD(v26), 0.0, 1.0, 0.0);
+        }
+        else
+        {
+          AIL_end_3D_sample(this->p3DSamples[v59].hSample);
+          pAudioPlayer->_4ABF23(&this->p3DSamples[v59]);
         }
       }
-      else
-      {
-LABEL_31:
-        pGame->pIndoorCameraD3D->ViewTransform(&a1, 1u);
-      }
-      v58 = a1.vWorldViewPosition.y * -0.012207031;
-      v22 = a1.vWorldViewPosition.x * 0.012207031;
-      *(float *)&uNumRepeats = v22;
-      v23 = abs((signed __int64)v22);
-      v24 = abs(0);
-      v25 = abs((signed __int64)v58);
-      if ( int_get_vector_length(v25, v24, v23) <= 100 )
-      {
-        AIL_set_3D_position(v6->hSample, LODWORD(v58), 0.0, uNumRepeats);
-        v26 = -*(float *)&uNumRepeats;
-        v27 = -v58;
-        AIL_set_3D_orientation(v6->hSample, LODWORD(v27), 0.0, LODWORD(v26), 0.0, 1.0, 0.0);
-      }
-      else
-      {
-        AIL_end_3D_sample(v6->hSample);
-        pAudioPlayer->_4ABF23(v6);
-      }
-      goto LABEL_35;
     }
+    //}
   }
 
-LABEL_37:
+//LABEL_37:
   for (uint i = 0; i < uMixerChannels; ++i)
   {
     if (AIL_sample_status(pMixerChannels[i].hSample) == AIL::Sample::Done)
@@ -1630,48 +1930,104 @@
         if (!pIndoor->pDoors[source_id].uDoorID)
           continue;
 
-        source_x = pIndoor->pDoors[source_id].pXOffsets[0];
-        source_y = pIndoor->pDoors[source_id].pYOffsets[0];
-        source_z = pIndoor->pDoors[source_id].pZOffsets[0];
+        //source_x = pIndoor->pDoors[source_id].pXOffsets[0];
+        //source_y = pIndoor->pDoors[source_id].pYOffsets[0];
+        //source_z = pIndoor->pDoors[source_id].pZOffsets[0];
+        int sound_strength = GetSoundStrengthByDistanceFromParty(pIndoor->pDoors[source_id].pXOffsets[0],
+                                                                 pIndoor->pDoors[source_id].pYOffsets[0],
+                                                                 pIndoor->pDoors[source_id].pZOffsets[0]);
+        if ( sound_strength )
+        {
+          AIL_set_sample_volume(pMixerChannels[i].hSample, sound_strength);
+          AIL_set_sample_pan(pMixerChannels[i].hSample, sub_4AB66C(pIndoor->pDoors[source_id].pXOffsets[0],
+                                                                 pIndoor->pDoors[source_id].pYOffsets[0]));
+        }
+        else
+        {
+          AIL_end_sample(pMixerChannels[i].hSample);
+          FreeChannel(&pMixerChannels[i]);
+        }
       }
-      break;
+      continue;
 
       case OBJECT_Item:
       {
         assert(source_id < uNumSpriteObjects);
 
-        source_x = pSpriteObjects[source_id].vPosition.x;
-        source_y = pSpriteObjects[source_id].vPosition.y;
-        source_z = pSpriteObjects[source_id].vPosition.z;
+        //source_x = pSpriteObjects[source_id].vPosition.x;
+        //source_y = pSpriteObjects[source_id].vPosition.y;
+        //source_z = pSpriteObjects[source_id].vPosition.z;
+        int sound_strength = GetSoundStrengthByDistanceFromParty(pSpriteObjects[source_id].vPosition.x,
+                                                                 pSpriteObjects[source_id].vPosition.y,
+                                                                 pSpriteObjects[source_id].vPosition.z);
+        if ( sound_strength )
+        {
+          AIL_set_sample_volume(pMixerChannels[i].hSample, sound_strength);
+          AIL_set_sample_pan(pMixerChannels[i].hSample, sub_4AB66C(pSpriteObjects[source_id].vPosition.x,
+                                                                   pSpriteObjects[source_id].vPosition.y));
+        }
+        else
+        {
+          AIL_end_sample(pMixerChannels[i].hSample);
+          FreeChannel(&pMixerChannels[i]);
+        }
       }
-      break;
+      continue;
 
       case OBJECT_Decoration:
       {
         assert(source_id < uNumLevelDecorations);
 
-        source_x = pLevelDecorations[source_id].vPosition.x;
-        source_y = pLevelDecorations[source_id].vPosition.y;
-        source_z = pLevelDecorations[source_id].vPosition.z;
+        //source_x = pLevelDecorations[source_id].vPosition.x;
+        //source_y = pLevelDecorations[source_id].vPosition.y;
+        //source_z = pLevelDecorations[source_id].vPosition.z;
+        int sound_strength = GetSoundStrengthByDistanceFromParty(pLevelDecorations[source_id].vPosition.x,
+                                                                 pLevelDecorations[source_id].vPosition.y,
+                                                                 pLevelDecorations[source_id].vPosition.z);
+        if ( sound_strength )
+        {
+          AIL_set_sample_volume(pMixerChannels[i].hSample, sound_strength);
+          AIL_set_sample_pan(pMixerChannels[i].hSample, sub_4AB66C(pLevelDecorations[source_id].vPosition.x,
+                                                                   pLevelDecorations[source_id].vPosition.y));
+        }
+        else
+        {
+          AIL_end_sample(pMixerChannels[i].hSample);
+          FreeChannel(&pMixerChannels[i]);
+        }
       }
-      break;
+      continue;
 
       case OBJECT_Actor:
       {
         assert(source_id < uNumActors);
 
-        source_x = pActors[source_id].vPosition.x;
-        source_y = pActors[source_id].vPosition.y;
-        source_z = pActors[source_id].vPosition.z;
+        //source_x = pActors[source_id].vPosition.x;
+        //source_y = pActors[source_id].vPosition.y;
+        //source_z = pActors[source_id].vPosition.z;
+        int sound_strength = GetSoundStrengthByDistanceFromParty(pActors[source_id].vPosition.x,
+                                                                 pActors[source_id].vPosition.y,
+                                                                 pActors[source_id].vPosition.z);
+        if ( sound_strength )
+        {
+          AIL_set_sample_volume(pMixerChannels[i].hSample, sound_strength);
+          AIL_set_sample_pan(pMixerChannels[i].hSample, sub_4AB66C(pActors[source_id].vPosition.x,
+                                                                   pActors[source_id].vPosition.y));
+        }
+        else
+        {
+          AIL_end_sample(pMixerChannels[i].hSample);
+          FreeChannel(&pMixerChannels[i]);
+        }
       }
-      break;
+      continue;
 
       default:
         assert(false);
         continue;
     }
 
-    if (int sound_strength = GetSoundStrengthByDistanceFromParty(source_x, source_y, source_z))
+    /*if (int sound_strength = GetSoundStrengthByDistanceFromParty(source_x, source_y, source_z))
     {
       AIL_set_sample_volume(pMixerChannels[i].hSample, sound_strength);
       AIL_set_sample_pan(pMixerChannels[i].hSample, sub_4AB66C(source_x, source_y));
@@ -1680,16 +2036,13 @@
     {
       AIL_end_sample(pMixerChannels[i].hSample);
       FreeChannel(&pMixerChannels[i]);
-    }
+    } */
   }
 
-
-
-  if (pCurrentScreen != SCREEN_GAME)
+  if (pCurrentScreen != SCREEN_GAME) //     
   {
-    MixerChannel* channel = &pMixerChannels[4];
-    if (AIL_sample_status(channel->hSample) == AIL::Sample::Playing)
-      AIL_end_sample(channel->hSample);
+    if (AIL_sample_status(pMixerChannels[4].hSample) == AIL::Sample::Playing)
+      AIL_end_sample(pMixerChannels[4].hSample);
     return;
   }
   if (!_6807E0_num_decorations_with_sounds_6807B8)
@@ -1699,8 +2052,6 @@
       //v59 = 0;
   for (uint i = 0; i < _6807E0_num_decorations_with_sounds_6807B8; ++i)
   {
-      //while ( 1 )
-      //{
         LODWORD(v56) = 1;
         //v43 = _6807B8_level_decorations_ids[v59];
         //v44 = &pLevelDecorations[_6807B8_level_decorations_ids[v59]];
@@ -1725,9 +2076,9 @@
         uNumRepeats = 2;
         if (decor->field_1A)
         {
-          v51 = decor->field_1A - 32;
-          decor->field_1A = v51;
-          if ( v51 < 0 )
+          //v51 = decor->field_1A - 32;
+          decor->field_1A = decor->field_1A - 32;
+          if ( decor->field_1A < 0 )
             decor->field_1A = 0;
         }
     }
@@ -1743,7 +2094,7 @@
           {
             v53 = 8 * _6807B8_level_decorations_ids[i];
             LOBYTE(v53) = v53 | OBJECT_Decoration;
-            PlaySound((SoundID)decor_desc->uSoundID, v53, uNumRepeats, -1, 0, 0, 0, 0);
+            PlaySound((SoundID)decor_desc->uSoundID, v53, uNumRepeats, -1, 0, 0, 0, 0);// ,  
           }
           continue;
         }
@@ -1799,6 +2150,7 @@
     }
     continue;
   }
+  }
 }
 
 //----- (004AB66C) --------------------------------------------------------
@@ -1835,37 +2187,27 @@
 //----- (004AB71F) --------------------------------------------------------
 void AudioPlayer::StopChannels(int uStartChannel, int uEndChannel)
 {
-  int v4; // ecx@1
-  int v9; // [sp+4h] [bp-4h]@3
-
   if ( bPlayerReady )
   {
     if ( b3DSoundInitialized )
     {
-      v9 = 0;
-      if ( uNum3DSamples > 0 )
+      for ( uint i = 0; i < uNum3DSamples; ++i )
       {
-        for ( v4 = 0; v4 < uNum3DSamples; ++v4 )
+        if ( (uStartChannel == -1 || i < uStartChannel || i > uEndChannel)
+            && p3DSamples[i].field_8 && pSoundList->pSL_Sounds[p3DSamples[i].field_8].eType != SOUND_DESC_SYSTEM)
         {
-          if ( (uStartChannel == -1 || v4 < uStartChannel || v4 > uEndChannel)
-              && p3DSamples[v4].field_8
-              && pSoundList->pSounds[p3DSamples[v4].field_8].eType != SOUND_DESC_SYSTEM)
-          {
-            AIL_end_3D_sample(p3DSamples[v4].hSample);
-            _4ABF23(&p3DSamples[v4]);
-            p3DSamples[v4].field_4 = 0;
-            v4 = v9;
-          }
-          v9 = v4;
+          AIL_end_3D_sample(p3DSamples[i].hSample);
+          _4ABF23(&p3DSamples[i]);
+          p3DSamples[i].field_4 = 0;
         }
       }
     }
-    if ( hDigDriver && uMixerChannels > 0 )
+    if ( hDigDriver )
     {
       for ( int i = 0; i < uMixerChannels; ++i )
       {
         if ( (uStartChannel == -1 || i < uStartChannel || i > uEndChannel)
-          && pSoundList->pSounds[pMixerChannels[i].uSourceTrackIdx].eType != SOUND_DESC_SYSTEM)
+          && pSoundList->pSL_Sounds[pMixerChannels[i].uSourceTrackIdx].eType != SOUND_DESC_SYSTEM)//,   , 
         {
           AIL_end_sample(pMixerChannels[i].hSample);
           FreeChannel(&pMixerChannels[i]);
@@ -1892,7 +2234,7 @@
     return;
   }
 
-  ReadFile(hAudioSnd, &uNumSoundHeaders, 4u, &NumberOfBytesRead, 0);
+  ReadFile(hAudioSnd, &uNumSoundHeaders, 4, &NumberOfBytesRead, 0);
   pSoundHeaders = nullptr;
   pSoundHeaders = (SoundHeader *)malloc(52 * uNumSoundHeaders + 2);
   ReadFile(hAudioSnd, pSoundHeaders, 52 * uNumSoundHeaders, &NumberOfBytesRead, 0);
@@ -2184,14 +2526,14 @@
   int num_playing_channels; // [sp+4Ch] [bp-8h]@5
   //int v16; // [sp+50h] [bp-4h]@5
 
-  if (!pSoundList->pSounds)
+  if (!pSoundList->pSL_Sounds)
     return;
  
     //v4 = &pSoundList->pSounds[pChannel->uSourceTrackIdx];
-    if ( pSoundList->pSounds[pChannel->uSourceTrackIdx].eType == SOUND_DESC_SWAP)
+    if ( pSoundList->pSL_Sounds[pChannel->uSourceTrackIdx].eType == SOUND_DESC_SWAP)
     {
-      if ( pSoundList->pSounds[pChannel->uSourceTrackIdx].pSoundData[0] && 
-          !(pSoundList->pSounds[pChannel->uSourceTrackIdx].uFlags & SOUND_DESC_SYSTEM) )
+      if ( pSoundList->pSL_Sounds[pChannel->uSourceTrackIdx].pSoundData[0] && 
+          !(pSoundList->pSL_Sounds[pChannel->uSourceTrackIdx].uFlags & SOUND_DESC_SYSTEM) )
       {
         num_playing_channels = 0;
         num_same_sound_on_channels = 0;
@@ -2226,7 +2568,7 @@
 {
   int v2; // ebx@1
   //AudioPlayer *v3; // esi@1
-  SoundDesc *v4; // eax@2
+  //SoundDesc *v4; // eax@2
   unsigned __int8 v5; // zf@5
   unsigned __int8 v6; // sf@5
   char *v7; // edi@6
@@ -2239,14 +2581,12 @@
   int v14; // [sp+4Ch] [bp-8h]@5
   int v15; // [sp+50h] [bp-4h]@5
 
-  v2 = 0;
-  //v3 = this;
-  if ( pSoundList->pSounds )
+  if ( pSoundList->pSL_Sounds )
   {
-    v4 = &pSoundList->pSounds[a2->field_8];
-    if ( v4->eType == SOUND_DESC_SWAP)
+    //v4 = &pSoundList->pSounds[a2->field_8];
+    if ( pSoundList->pSL_Sounds[a2->field_8].eType == SOUND_DESC_SWAP)
     {
-      if ( v4->p3DSound && !(v4->uFlags & SOUND_DESC_SYSTEM) )
+      if ( pSoundList->pSL_Sounds[a2->field_8].p3DSound && !(pSoundList->pSL_Sounds[a2->field_8].uFlags & SOUND_DESC_SYSTEM) )
       {
         v5 = this->uNum3DSamples == 0;
         v6 = this->uNum3DSamples < 0;
@@ -2255,37 +2595,29 @@
         if ( v6 | v5 )
           goto LABEL_16;
         v7 = (char *)this->p3DSamples;
-        do
+        __debugbreak();//Ritor1
+        for ( v2 = 0; v2 < uNum3DSamples; ++v2 )
         {
           if ( a2->field_C == *((int *)v7 + 3) )
           {
             v8 = v15;
-            v9 = *(int *)v7;
+            //v9 = this->p3DSamples[v2];
             ++v15;
             v13[v8] = v2;
-            if ( AIL_3D_sample_status((void *)v9) == 4 )
+            if ( AIL_3D_sample_status(&this->p3DSamples[v2]) == 4 )
               ++v14;
           }
-          ++v2;
           v7 += 16;
         }
-        while ( v2 < uNum3DSamples );
         if ( !v14 )
         {
 LABEL_16:
           pSoundList->UnloadSound(a2->field_8, 1);
-          v10 = 0;
-          if ( v15 > 0 )
+          for ( v10 = 0; v10 < v15; v10++ )
           {
-            do
-            {
-              v11 = v13[v10++];
-              *(&bEAXSupported + 4 * (v11 + 2)) = 0;
-              v12 = __OFSUB__(v10, v15);
-              v6 = v10 - v15 < 0;
-              p3DSamples[v11].field_8 = 0;
-            }
-            while ( v6 ^ v12 );
+            v11 = v13[v10];
+            *(&bEAXSupported + 4 * (v11 + 2)) = 0;
+            p3DSamples[v11].field_8 = 0;
           }
         }
       }
@@ -2345,71 +2677,61 @@
 //----- (004AC0A2) --------------------------------------------------------
 int AudioPlayer::_4AC0A2()
 {
-  AudioPlayer *v1; // esi@1
-  unsigned int v2; // eax@1
-  char v3; // zf@1
-  int v4; // ebx@1
-  int *v5; // edi@2
-  int v6; // eax@4
-  AudioPlayer_3DSample *v8; // ebx@7
+  unsigned int map_id; // eax@1
+  //int v4; // ebx@1
+  //int *v5; // edi@2
+  //int v6; // eax@4
+  //AudioPlayer_3DSample *v8; // ebx@7
   void *v9; // eax@8
-  int v10; // ebx@14
-  unsigned int v11; // eax@14
+  //int v10; // ebx@14
+  //unsigned int v11; // eax@14
   int v12; // [sp+1Ch] [bp-8h]@1
-  int v13; // [sp+20h] [bp-4h]@6
+  //int v13; // [sp+20h] [bp-4h]@6
 
-  v1 = this;
-  v2 = pMapStats->GetMapInfo(pCurrentMapName);
-  v3 = v1->b3DSoundInitialized == 0;
-  v4 = v2;
-  v12 = v2;
-  if ( !v3 )
+  __debugbreak();//Ritor1
+  map_id = pMapStats->GetMapInfo(pCurrentMapName);
+  if ( this->b3DSoundInitialized )
   {
-    v5 = &v1->uNum3DSamples;
-    AIL_3D_provider_attribute(v1->h3DSoundProvider, "Maximum supported samples", &v1->uNum3DSamples);
-    if ( v1->uNum3DSamples > 32 )
-      *v5 = 32;
-    v6 = *v5;
-    if ( !*v5 )
+    //v5 = &this->uNum3DSamples;
+    AIL_3D_provider_attribute(this->h3DSoundProvider, "Maximum supported samples", &this->uNum3DSamples);
+    if ( this->uNum3DSamples > 32 )
+      this->uNum3DSamples = 32;
+    //v6 = this->uNum3DSamples;
+    if ( !this->uNum3DSamples )
     {
-      v1->b3DSoundInitialized = 0;
+      this->b3DSoundInitialized = 0;
       return -1;
     }
-    v13 = 0;
-    if ( v6 > 0 )
-    {
-      v8 = v1->p3DSamples;
-      while ( 1 )
+    //v13 = 0;
+    //if ( this->uNum3DSamples > 0 )
+    //{
+      //v8 = this->p3DSamples;
+      //while ( 1 )
+      for ( uint i = 0; i < this->uNum3DSamples; ++i )
       {
-        v9 = (void *)AIL_allocate_3D_sample_handle(v1->h3DSoundProvider);
-        v8->hSample = v9;
+        v9 = (void *)AIL_allocate_3D_sample_handle(this->h3DSoundProvider);
+        this->p3DSamples[i].hSample = v9;
         if ( !v9 )
-          break;
+          this->uNum3DSamples = i;
         AIL_set_3D_sample_float_distances(v9, 4096.0, 256.0, 4096.0, 256.0);
-        AIL_set_3D_sample_volume(v8->hSample, v1->s3DSoundVolume);
-        ++v13;
-        ++v8;
-        if ( v13 >= *v5 )
-          goto LABEL_12;
+        AIL_set_3D_sample_volume(this->p3DSamples[i].hSample, this->s3DSoundVolume);
+        //++v8;
       }
-      *v5 = v13;
-LABEL_12:
-      v4 = v12;
-    }
-    if ( v1->bEAXSupported )
+    //}
+    if ( this->bEAXSupported )
     {
-      v10 = v4;
-      v11 = pMapStats->pInfos[v10].uEAXEnv;
-      v12 = pMapStats->pInfos[v10].uEAXEnv;
-      if ( v11 >= 0x1A )
+      //v10 = v4;
+      //v11 = pMapStats->pInfos[map_id].uEAXEnv;
+      v12 = pMapStats->pInfos[map_id].uEAXEnv;
+      if ( pMapStats->pInfos[map_id].uEAXEnv >= 0x1A )
       {
         pAudioPlayer->SetEAXPreferences();
-        v1->field_214 = -1;
+        this->field_214 = -1;
       }
       else
       {
-        AIL_set_3D_provider_preference(v1->h3DSoundProvider, "EAX environment selection", &v12);
-        v1->field_214 = v12;
+        AIL_set_3D_provider_preference(this->h3DSoundProvider, "EAX environment selection", &v12);
+        this->field_214 = v12;
       }
     }
   }
@@ -2419,7 +2741,8 @@
 //----- (004A96BE) --------------------------------------------------------
 void ReleaseSoundData(void *_this)
 {
-  for ( uint i = 0; (void *)&pSounds[i].pSoundData < (void *)&pSounds[2999].pSoundData; i++ )
+  //for ( uint i = 0; (void *)&pSounds[i].pSoundData < (void *)&pSounds[2999].pSoundData; i++ )
+  for ( uint i = 0; i < 2999; i++ )
   {
     if ( pSounds[i].pSoundData == _this )
     {
@@ -2519,7 +2842,7 @@
     pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uCompressedSize = pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize;
     if ( pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize )
     {
-      ReadFile(pAudioPlayer->hAudioSnd, (char *)pOutBuff + 4, pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize, &NumberOfBytesRead, 0);
+      ReadFile(pAudioPlayer->hAudioSnd, pOutBuff->pData, pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize + 7, &NumberOfBytesRead, 0);// Ritor1: include +7 for pSounds[20]
     }
     else
     {
@@ -2530,12 +2853,12 @@
   {
     uID = (unsigned int)malloc(pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uCompressedSize);
     ReadFile(pAudioPlayer->hAudioSnd, (LPVOID)uID, pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uCompressedSize, &NumberOfBytesRead, 0);
-    zlib::MemUnzip((char *)pOutBuff + 4, &pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize, (const void *)uID, pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uCompressedSize);
+    zlib::MemUnzip(pOutBuff->pData, &pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize, (const void *)uID, pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uCompressedSize);
     free((void *)uID);
   }
   if ( pOutBuff )
   {
-    *(int *)pOutBuff = pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize;
+    pOutBuff->uDataSize = pAudioPlayer->pSoundHeaders[uFindSound_BinSearch_ResultID].uDecompressedSize;
     uLastLoadedSoundID = 0;
     if ( pSounds[0].pSoundData )
     {
--- a/AudioPlayer.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/AudioPlayer.h	Thu Jan 02 09:11:28 2014 +0600
@@ -165,7 +165,7 @@
   void SetMusicVolume(int vol);
   void SetMasterVolume(float fVolume);
   void _4AA258(int a2);
-  void PlaySound(SoundID eSoundID, signed int a3, unsigned int uNumRepeats, signed int a5, signed int a6, int a7, unsigned int uVolume, int sPlaybackRate);
+  void PlaySound(SoundID eSoundID, signed int a3, unsigned int uNumRepeats, signed int a5, signed int a6, int a7, float uVolume, int sPlaybackRate);
   void UpdateSounds();
   void StopChannels(int uStartChannel, int uEndChannel);
   void LoadAudioSnd();
@@ -281,7 +281,7 @@
 struct SoundList
 {
   inline SoundList():
-    sNumSounds(0), pSounds(nullptr), uTotalLoadedSoundSize(0)
+    sNumSounds(0), pSL_Sounds(nullptr), uTotalLoadedSoundSize(0)
   {}
 
   void Initialize();
@@ -295,7 +295,7 @@
   int FromFileTxt(const char *Args);
 
   signed int sNumSounds;
-  SoundDesc *pSounds;
+  SoundDesc *pSL_Sounds;
   unsigned int uTotalLoadedSoundSize;
 };
 #pragma pack(pop)
--- a/Bink_Smacker.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Bink_Smacker.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -24,34 +24,46 @@
 int  (__stdcall *smackw32_SmackBlitClear)(HSMACKBLIT, unsigned short *, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, int) = 0;
 int  (__stdcall *smackw32_SmackGoto)(_SMACK *, long) = 0;
 int  (__stdcall *smackw32_SmackBufferOpen)(HWND a1, long a2, long a3, long a4, long a5, long a6) = nullptr;
+void(__stdcall *smackw32_SmackBufferNewPalette)(HSMACKBUF, void *, unsigned int) = nullptr;
+void(__stdcall *smackw32_SmackColorRemapWithTrans)(_SMACK *, void *, unsigned int, unsigned int, unsigned int) = nullptr;
 void SMACKW32_DLL_Initialize()
 {
- HMODULE pDll = LoadLibraryW(L"SmackW32.dll");
-
- smackw32_SmackSoundUseMSS = (int (__stdcall *)(HDIGDRIVER))GetProcAddress(pDll, "_SmackSoundUseMSS@4");
- smackw32_SmackUseMMX = (unsigned int (__stdcall *)(unsigned int))GetProcAddress(pDll, "_SmackUseMMX@4");
- smackw32_SmackOpen = (HSMACK (__stdcall *)(HANDLE, unsigned int, unsigned int))GetProcAddress(pDll, "_SmackOpen@12");
- smackw32_SmackBlitOpen = (HSMACKBLIT (__stdcall *)(unsigned int))GetProcAddress(pDll, "_SmackBlitOpen@4");
- smackw32_SmackToBuffer = (void (__stdcall *)(HSMACK, unsigned int, unsigned int, unsigned int, unsigned int, void *, unsigned int))GetProcAddress(pDll, "_SmackToBuffer@28");
- smackw32_SmackBlitSetPalette = (void (__stdcall *)(HSMACKBLIT, void *, unsigned int))GetProcAddress(pDll, "_SmackBlitSetPalette@12");
- smackw32_SmackDoFrame = (unsigned int (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackDoFrame@4");
- smackw32_SmackToBufferRect = (unsigned int (__stdcall *)(HSMACK, unsigned int))GetProcAddress(pDll, "_SmackToBufferRect@8");
- smackw32_SmackBlit = (void (__stdcall *)(HSMACKBLIT, void *, unsigned int, unsigned int, unsigned int, void *, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int))GetProcAddress(pDll, "_SmackBlit@44");
- smackw32_SmackNextFrame = (void (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackNextFrame@4");
- smackw32_SmackWait = (unsigned int (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackWait@4");
- smackw32_SmackSoundOnOff = (unsigned int (__stdcall *)(HSMACK, unsigned int))GetProcAddress(pDll, "_SmackSoundOnOff@8");
- smackw32_SmackClose = (void (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackClose@4");
- smackw32_SmackBufferClose = (void (__stdcall *)(HSMACKBUF))GetProcAddress(pDll, "_SmackBufferClose@4");
- smackw32_SmackBlitClose = (void (__stdcall *)(HSMACKBLIT))GetProcAddress(pDll, "_SmackBlitClose@4");
- smackw32_SmackBlitClear = (int (__stdcall *)(HSMACKBLIT, unsigned short *, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, int))GetProcAddress(pDll, "_SmackBlitClear@32");
- smackw32_SmackGoto = (int  (__stdcall *)(_SMACK *, long))GetProcAddress(pDll, "_SmackGoto@8");
- smackw32_SmackBufferOpen = (int  (__stdcall *)(HWND, long, long, long, long, long))GetProcAddress(pDll, "_SmackBufferOpen@24");
+  HMODULE pDll = LoadLibraryW(L"SmackW32.dll");
+  
+  #define LOAD(x) smackw32_##x = (decltype(smackw32_##x))GetProcAddress(pDll, #x)
+  {
+    smackw32_SmackSoundUseMSS = (int (__stdcall *)(HDIGDRIVER))GetProcAddress(pDll, "_SmackSoundUseMSS@4");
+    smackw32_SmackUseMMX = (unsigned int (__stdcall *)(unsigned int))GetProcAddress(pDll, "_SmackUseMMX@4");
+    smackw32_SmackOpen = (HSMACK (__stdcall *)(HANDLE, unsigned int, unsigned int))GetProcAddress(pDll, "_SmackOpen@12");
+    smackw32_SmackBlitOpen = (HSMACKBLIT (__stdcall *)(unsigned int))GetProcAddress(pDll, "_SmackBlitOpen@4");
+    smackw32_SmackToBuffer = (void (__stdcall *)(HSMACK, unsigned int, unsigned int, unsigned int, unsigned int, void *, unsigned int))GetProcAddress(pDll, "_SmackToBuffer@28");
+    smackw32_SmackBlitSetPalette = (void (__stdcall *)(HSMACKBLIT, void *, unsigned int))GetProcAddress(pDll, "_SmackBlitSetPalette@12");
+    smackw32_SmackDoFrame = (unsigned int (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackDoFrame@4");
+    smackw32_SmackToBufferRect = (unsigned int (__stdcall *)(HSMACK, unsigned int))GetProcAddress(pDll, "_SmackToBufferRect@8");
+    smackw32_SmackBlit = (void (__stdcall *)(HSMACKBLIT, void *, unsigned int, unsigned int, unsigned int, void *, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int))GetProcAddress(pDll, "_SmackBlit@44");
+    smackw32_SmackNextFrame = (void (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackNextFrame@4");
+    smackw32_SmackWait = (unsigned int (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackWait@4");
+    smackw32_SmackSoundOnOff = (unsigned int (__stdcall *)(HSMACK, unsigned int))GetProcAddress(pDll, "_SmackSoundOnOff@8");
+    smackw32_SmackClose = (void (__stdcall *)(HSMACK))GetProcAddress(pDll, "_SmackClose@4");
+    smackw32_SmackBufferClose = (void (__stdcall *)(HSMACKBUF))GetProcAddress(pDll, "_SmackBufferClose@4");
+    smackw32_SmackBlitClose = (void (__stdcall *)(HSMACKBLIT))GetProcAddress(pDll, "_SmackBlitClose@4");
+    smackw32_SmackBlitClear = (int (__stdcall *)(HSMACKBLIT, unsigned short *, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, int))GetProcAddress(pDll, "_SmackBlitClear@32");
+    smackw32_SmackGoto = (int  (__stdcall *)(_SMACK *, long))GetProcAddress(pDll, "_SmackGoto@8");
+    smackw32_SmackBufferOpen = (int  (__stdcall *)(HWND, long, long, long, long, long))GetProcAddress(pDll, "_SmackBufferOpen@24");
+	smackw32_SmackBufferNewPalette = (void(__stdcall *)(HSMACKBUF, void *, unsigned int))GetProcAddress(pDll, "_SmackBufferNewPalette@12");
+	smackw32_SmackColorRemapWithTrans = (void(__stdcall *)(_SMACK *, void *, unsigned int, unsigned int, unsigned int))GetProcAddress(pDll, "_SmackColorRemapWithTrans@20");
+    //LOAD(SmackBufferNewPalette);
+    //LOAD(SmackColorRemapWithTrans);
+  }
 }
 
 
 
 
-
+void __stdcall SmackColorRemapWithTrans(_SMACK *a1, void *a2, unsigned int a3, unsigned int a4, unsigned int a5)
+{
+  return (smackw32_SmackColorRemapWithTrans)(a1, a2, a3, a4, a5);
+}
 
 void __stdcall SmackBlitClose(HSMACKBLIT hBlit)
 {
@@ -152,21 +164,11 @@
 
 
 // sub_4D83D0: using guessed type int __stdcall SmackBufferNewPalette(_DWORD, _DWORD, _DWORD);
-int __stdcall SmackBufferNewPalette(long a1, long a2, long a3)
+void __stdcall SmackBufferNewPalette(HSMACKBUF a1, void *a2, unsigned int a3)
 {
- //__asm int 3
- return 0;
+ (smackw32_SmackBufferNewPalette)(a1, a2, a3);
 }
 
-// sub_4D83D4: using guessed type int __stdcall SmackColorRemapWithTrans(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
-int __stdcall SmackColorRemapWithTrans(long a1, long a2, long a3, long a4, long a5)
-{
- //__asm int 3
- return 0;
-}
-
-
-
 
 
 
--- a/Bink_Smacker.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Bink_Smacker.h	Thu Jan 02 09:11:28 2014 +0600
@@ -143,6 +143,52 @@
         int numrects;
         HDC lastdc;
 };
+#define BINKFRAMERATE            0x00001000L // Override fr (call BinkFrameRate first)
+#define BINKPRELOADALL            0x00002000L // Preload the entire animation
+#define BINKSNDTRACK            0x00004000L // Set the track number to play
+#define BINKOLDFRAMEFORMAT        0x00008000L // using the old Bink frame format (internal use only)
+#define BINKRBINVERT            0x00010000L // use reversed R and B planes (internal use only)
+#define BINKGRAYSCALE            0x00020000L // Force Bink to use grayscale
+#define BINKNOMMX                0x00040000L // Don't use MMX
+#define BINKNOSKIP                0x00080000L // Don't skip frames if falling behind
+#define BINKALPHA                0x00100000L // Decompress alpha plane (if present)
+#define BINKNOFILLIOBUF            0x00200000L // Fill the IO buffer in SmackOpen
+#define BINKSIMULATE            0x00400000L // Simulate the speed (call BinkSim first)
+#define BINKFILEHANDLE            0x00800000L // Use when passing in a file handle
+#define BINKIOSIZE                0x01000000L // Set an io size (call BinkIOSize first)
+#define BINKIOPROCESSOR            0x02000000L // Set an io processor (call BinkIO first)
+#define BINKFROMMEMORY            0x04000000L // Use when passing in a pointer to the file
+#define BINKNOTHREADEDIO        0x08000000L // Don't use a background thread for IO
+
+#define BINKSURFACEFAST            0x00000000L
+#define BINKSURFACESLOW            0x08000000L
+#define BINKSURFACEDIRECT        0x04000000L
+
+#define BINKCOPYALL                0x80000000L // copy all pixels (not just changed)
+#define BINKCOPY2XH                0x10000000L // Force doubling height scaling
+#define BINKCOPY2XHI            0x20000000L // Force interleaving height scaling
+#define BINKCOPY2XW                0x30000000L // copy the width zoomed by two
+#define BINKCOPY2XWH            0x40000000L // copy the width and height zoomed by two
+#define BINKCOPY2XWHI            0x50000000L // copy the width and height zoomed by two
+#define BINKCOPY1XI                0x60000000L // copy the width and height zoomed by two
+#define BINKCOPYNOSCALING        0x70000000L // Force scaling off
+
+#define SMACKNEEDPAN    0x00020L // Will be setting the pan
+#define SMACKNEEDVOLUME 0x00040L // Will be setting the volume
+#define SMACKFRAMERATE  0x00080L // Override fr (call SmackFrameRate first)
+#define SMACKLOADEXTRA  0x00100L // Load the extra buffer during SmackOpen
+#define SMACKPRELOADALL 0x00200L // Preload the entire animation
+#define SMACKNOSKIP     0x00400L // Don't skip frames if falling behind
+#define SMACKSIMULATE   0x00800L // Simulate the speed (call SmackSim first)
+#define SMACKFILEHANDLE 0x01000L // Use when passing in a file handle
+#define SMACKTRACK1     0x02000L // Play audio track 1
+#define SMACKTRACK2     0x04000L // Play audio track 2
+#define SMACKTRACK3     0x08000L // Play audio track 3
+#define SMACKTRACK4     0x10000L // Play audio track 4
+#define SMACKTRACK5     0x20000L // Play audio track 5
+#define SMACKTRACK6     0x40000L // Play audio track 6
+#define SMACKTRACK7     0x80000L // Play audio track 7
+
 
 #define SMACKBUFFER555      0x80000000
 #define SMACKBUFFER565      0xC0000000
@@ -180,10 +226,10 @@
 int __stdcall SmackGoto(_SMACK *a1, long a2);
 
 // sub_4D83D0: using guessed type int __stdcall SmackBufferNewPalette(_DWORD, _DWORD, _DWORD);
-int __stdcall SmackBufferNewPalette(long a1, long a2, long a3);
+void __stdcall SmackBufferNewPalette(HSMACKBUF a1, void *a2, unsigned int a3);
 
 // sub_4D83D4: using guessed type int __stdcall SmackColorRemapWithTrans(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD);
-int __stdcall SmackColorRemapWithTrans(long a1, long a2, long a3, long a4, long a5);
+void __stdcall SmackColorRemapWithTrans(_SMACK *a1, void *a2, unsigned int a3, unsigned int a4, unsigned int a5);
 
 
 
--- a/Build/Visual Studio 2012/World of Might and Magic.vcxproj	Thu Jan 02 09:11:01 2014 +0600
+++ b/Build/Visual Studio 2012/World of Might and Magic.vcxproj	Thu Jan 02 09:11:28 2014 +0600
@@ -286,6 +286,72 @@
     <ClInclude Include="..\..\lib\legacy_dx\rmxfguid.h" />
     <ClInclude Include="..\..\lib\legacy_dx\rmxftmpl.h" />
     <ClInclude Include="..\..\lib\legacy_dx\strsafe.h" />
+    <ClInclude Include="..\..\lib\libavcodec\avcodec.h" />
+    <ClInclude Include="..\..\lib\libavcodec\avfft.h" />
+    <ClInclude Include="..\..\lib\libavcodec\dxva2.h" />
+    <ClInclude Include="..\..\lib\libavcodec\old_codec_ids.h" />
+    <ClInclude Include="..\..\lib\libavcodec\vaapi.h" />
+    <ClInclude Include="..\..\lib\libavcodec\vda.h" />
+    <ClInclude Include="..\..\lib\libavcodec\vdpau.h" />
+    <ClInclude Include="..\..\lib\libavcodec\version.h" />
+    <ClInclude Include="..\..\lib\libavcodec\xvmc.h" />
+    <ClInclude Include="..\..\lib\libavformat\avformat.h" />
+    <ClInclude Include="..\..\lib\libavformat\avio.h" />
+    <ClInclude Include="..\..\lib\libavformat\version.h" />
+    <ClInclude Include="..\..\lib\libavutil\adler32.h" />
+    <ClInclude Include="..\..\lib\libavutil\aes.h" />
+    <ClInclude Include="..\..\lib\libavutil\attributes.h" />
+    <ClInclude Include="..\..\lib\libavutil\audioconvert.h" />
+    <ClInclude Include="..\..\lib\libavutil\audio_fifo.h" />
+    <ClInclude Include="..\..\lib\libavutil\avassert.h" />
+    <ClInclude Include="..\..\lib\libavutil\avconfig.h" />
+    <ClInclude Include="..\..\lib\libavutil\avstring.h" />
+    <ClInclude Include="..\..\lib\libavutil\avutil.h" />
+    <ClInclude Include="..\..\lib\libavutil\base64.h" />
+    <ClInclude Include="..\..\lib\libavutil\blowfish.h" />
+    <ClInclude Include="..\..\lib\libavutil\bprint.h" />
+    <ClInclude Include="..\..\lib\libavutil\bswap.h" />
+    <ClInclude Include="..\..\lib\libavutil\buffer.h" />
+    <ClInclude Include="..\..\lib\libavutil\channel_layout.h" />
+    <ClInclude Include="..\..\lib\libavutil\common.h" />
+    <ClInclude Include="..\..\lib\libavutil\cpu.h" />
+    <ClInclude Include="..\..\lib\libavutil\crc.h" />
+    <ClInclude Include="..\..\lib\libavutil\dict.h" />
+    <ClInclude Include="..\..\lib\libavutil\error.h" />
+    <ClInclude Include="..\..\lib\libavutil\eval.h" />
+    <ClInclude Include="..\..\lib\libavutil\fifo.h" />
+    <ClInclude Include="..\..\lib\libavutil\file.h" />
+    <ClInclude Include="..\..\lib\libavutil\frame.h" />
+    <ClInclude Include="..\..\lib\libavutil\hmac.h" />
+    <ClInclude Include="..\..\lib\libavutil\imgutils.h" />
+    <ClInclude Include="..\..\lib\libavutil\intfloat.h" />
+    <ClInclude Include="..\..\lib\libavutil\intfloat_readwrite.h" />
+    <ClInclude Include="..\..\lib\libavutil\intreadwrite.h" />
+    <ClInclude Include="..\..\lib\libavutil\lfg.h" />
+    <ClInclude Include="..\..\lib\libavutil\log.h" />
+    <ClInclude Include="..\..\lib\libavutil\lzo.h" />
+    <ClInclude Include="..\..\lib\libavutil\mathematics.h" />
+    <ClInclude Include="..\..\lib\libavutil\md5.h" />
+    <ClInclude Include="..\..\lib\libavutil\mem.h" />
+    <ClInclude Include="..\..\lib\libavutil\murmur3.h" />
+    <ClInclude Include="..\..\lib\libavutil\old_pix_fmts.h" />
+    <ClInclude Include="..\..\lib\libavutil\opt.h" />
+    <ClInclude Include="..\..\lib\libavutil\parseutils.h" />
+    <ClInclude Include="..\..\lib\libavutil\pixdesc.h" />
+    <ClInclude Include="..\..\lib\libavutil\pixfmt.h" />
+    <ClInclude Include="..\..\lib\libavutil\random_seed.h" />
+    <ClInclude Include="..\..\lib\libavutil\rational.h" />
+    <ClInclude Include="..\..\lib\libavutil\samplefmt.h" />
+    <ClInclude Include="..\..\lib\libavutil\sha.h" />
+    <ClInclude Include="..\..\lib\libavutil\time.h" />
+    <ClInclude Include="..\..\lib\libavutil\timecode.h" />
+    <ClInclude Include="..\..\lib\libavutil\timestamp.h" />
+    <ClInclude Include="..\..\lib\libavutil\version.h" />
+    <ClInclude Include="..\..\lib\libavutil\xtea.h" />
+    <ClInclude Include="..\..\lib\libswresample\swresample.h" />
+    <ClInclude Include="..\..\lib\libswresample\version.h" />
+    <ClInclude Include="..\..\lib\libswscale\swscale.h" />
+    <ClInclude Include="..\..\lib\libswscale\version.h" />
     <ClInclude Include="..\..\lib\lua\lua-5.2.2\lapi.h" />
     <ClInclude Include="..\..\lib\lua\lua-5.2.2\lauxlib.h" />
     <ClInclude Include="..\..\lib\lua\lua-5.2.2\lcode.h" />
@@ -311,6 +377,12 @@
     <ClInclude Include="..\..\lib\lua\lua-5.2.2\lvm.h" />
     <ClInclude Include="..\..\lib\lua\lua-5.2.2\lzio.h" />
     <ClInclude Include="..\..\lib\lua\lua.h" />
+    <ClInclude Include="..\..\lib\OpenAL\al.h" />
+    <ClInclude Include="..\..\lib\OpenAL\alc.h" />
+    <ClInclude Include="..\..\lib\OpenAL\efx-creative.h" />
+    <ClInclude Include="..\..\lib\OpenAL\EFX-Util.h" />
+    <ClInclude Include="..\..\lib\OpenAL\efx.h" />
+    <ClInclude Include="..\..\lib\OpenAL\xram.h" />
     <ClInclude Include="..\..\lib\zlib\deflate.h" />
     <ClInclude Include="..\..\lib\zlib\infblock.h" />
     <ClInclude Include="..\..\lib\zlib\infcodes.h" />
@@ -388,6 +460,14 @@
       <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename)_wrap.cxx</Outputs>
       <Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).swig</Message>
     </CustomBuild>
+    <None Include="..\..\lib\OpenAL\lib\x86\avcodec-55.def" />
+    <None Include="..\..\lib\OpenAL\lib\x86\avdevice-55.def" />
+    <None Include="..\..\lib\OpenAL\lib\x86\avfilter-3.def" />
+    <None Include="..\..\lib\OpenAL\lib\x86\avformat-55.def" />
+    <None Include="..\..\lib\OpenAL\lib\x86\avutil-52.def" />
+    <None Include="..\..\lib\OpenAL\lib\x86\postproc-52.def" />
+    <None Include="..\..\lib\OpenAL\lib\x86\swresample-0.def" />
+    <None Include="..\..\lib\OpenAL\lib\x86\swscale-2.def" />
     <None Include="..\..\lib\swig.bat" />
     <None Include="..\..\Player.swig">
       <Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">call "../../lib/swig" "%(FileName)" %(RelativeDir) "%(FileName)%(Extension)" "%(FullPath)" "$(SolutionDir)" %(Filename)_wrap.cxx</Command>
@@ -395,6 +475,17 @@
       <Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).swig</Message>
     </None>
   </ItemGroup>
+  <ItemGroup>
+    <Library Include="..\..\lib\OpenAL\lib\OpenAL\OpenAL32.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\avcodec.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\avdevice.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\avfilter.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\avformat.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\avutil.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\postproc.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\swresample.lib" />
+    <Library Include="..\..\lib\OpenAL\lib\x86\swscale.lib" />
+  </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
--- a/Build/Visual Studio 2012/World of Might and Magic.vcxproj.filters	Thu Jan 02 09:11:01 2014 +0600
+++ b/Build/Visual Studio 2012/World of Might and Magic.vcxproj.filters	Thu Jan 02 09:11:28 2014 +0600
@@ -37,203 +37,101 @@
     <Filter Include="lib\swig\swigwin-2.0.11">
       <UniqueIdentifier>{8c52b1ac-9e41-4a16-be04-bdac9a244ac1}</UniqueIdentifier>
     </Filter>
+    <Filter Include="lib\OpenAL">
+      <UniqueIdentifier>{ee28ca77-318b-4477-8c10-1fc75d47b5b3}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\OpenAL\lib">
+      <UniqueIdentifier>{9e09d25e-db72-4f51-b0f6-b5def5d61409}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\OpenAL\lib\OpenAL">
+      <UniqueIdentifier>{ccc1aed6-a901-4d62-9a78-319835aecfc4}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\OpenAL\lib\x86">
+      <UniqueIdentifier>{23bc5e63-c1ce-4fc8-acb4-ccbdfe47483f}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\libavcodec">
+      <UniqueIdentifier>{fe2f566e-4b3a-42e1-a216-30fbd39489a9}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\libavformat">
+      <UniqueIdentifier>{4f270f5a-17cd-430b-985b-8384cc0655cb}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\libavutil">
+      <UniqueIdentifier>{c972bce6-7e57-47ad-aea8-f5cf33c8bac2}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\libswresample">
+      <UniqueIdentifier>{27d1b44b-0562-467b-abad-cb2f4ae78541}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="lib\libswscale">
+      <UniqueIdentifier>{293e30b6-9ded-426f-a0be-425b0a877e93}</UniqueIdentifier>
+    </Filter>
   </ItemGroup>
   <ItemGroup>
-    <ClCompile Include="..\..\Level\Decoration.cpp">
-      <Filter>Level</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\adler32.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\compress.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\crc32.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\deflate.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\infblock.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\infcodes.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\inffast.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\inflate.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\inftrees.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\infutil.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\trees.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\uncompr.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\zlib\zutil.c">
-      <Filter>lib\zlib</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lapi.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lauxlib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lbaselib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lbitlib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lcode.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lcorolib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lctype.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldblib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldebug.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldo.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldump.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lfunc.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lgc.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\linit.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\liolib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\llex.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lmathlib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lmem.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\loadlib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lobject.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lopcodes.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\loslib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lparser.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lstate.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lstring.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lstrlib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ltable.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ltablib.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ltm.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lua.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lundump.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lvm.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lzio.c">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\NewUI\MainMenu.cpp">
-      <Filter>NewUI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIBooks.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UICharacter.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UiGame.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIGuilds.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIHouses.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIMainMenu.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIMsgProc.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIOptions.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIPartyCreation.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIPopup.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIRest.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UISaveLoad.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UIShops.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\UITransition.cpp">
-      <Filter>UI</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\Books\UIMapBook.cpp">
-      <Filter>UI\Books</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\Books\UINotesBooks.cpp">
-      <Filter>UI\Books</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\UI\Books\UISpellBook.cpp">
-      <Filter>UI\Books</Filter>
-    </ClCompile>
+    <ClCompile Include="..\..\Level\Decoration.cpp" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lapi.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lauxlib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lbaselib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lbitlib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lcode.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lcorolib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lctype.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldblib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldebug.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldo.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ldump.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lfunc.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lgc.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\linit.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\liolib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\llex.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lmathlib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lmem.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\loadlib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lobject.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lopcodes.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\loslib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lparser.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lstate.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lstring.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lstrlib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ltable.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ltablib.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\ltm.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lua.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lundump.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lvm.c" />
+    <ClCompile Include="..\..\lib\lua\lua-5.2.2\lzio.c" />
+    <ClCompile Include="..\..\lib\zlib\adler32.c" />
+    <ClCompile Include="..\..\lib\zlib\compress.c" />
+    <ClCompile Include="..\..\lib\zlib\crc32.c" />
+    <ClCompile Include="..\..\lib\zlib\deflate.c" />
+    <ClCompile Include="..\..\lib\zlib\infblock.c" />
+    <ClCompile Include="..\..\lib\zlib\infcodes.c" />
+    <ClCompile Include="..\..\lib\zlib\inffast.c" />
+    <ClCompile Include="..\..\lib\zlib\inflate.c" />
+    <ClCompile Include="..\..\lib\zlib\inftrees.c" />
+    <ClCompile Include="..\..\lib\zlib\infutil.c" />
+    <ClCompile Include="..\..\lib\zlib\trees.c" />
+    <ClCompile Include="..\..\lib\zlib\uncompr.c" />
+    <ClCompile Include="..\..\lib\zlib\zutil.c" />
+    <ClCompile Include="..\..\NewUI\Core\UIControlModule_wrap.cxx" />
+    <ClCompile Include="..\..\NewUI\MainMenu.cpp" />
+    <ClCompile Include="..\..\UI\Books\UIMapBook.cpp" />
+    <ClCompile Include="..\..\UI\Books\UINotesBooks.cpp" />
+    <ClCompile Include="..\..\UI\Books\UISpellBook.cpp" />
+    <ClCompile Include="..\..\UI\UIBooks.cpp" />
+    <ClCompile Include="..\..\UI\UICharacter.cpp" />
+    <ClCompile Include="..\..\UI\UiGame.cpp" />
+    <ClCompile Include="..\..\UI\UIGuilds.cpp" />
+    <ClCompile Include="..\..\UI\UIHouses.cpp" />
+    <ClCompile Include="..\..\UI\UIMainMenu.cpp" />
+    <ClCompile Include="..\..\UI\UIMsgProc.cpp" />
+    <ClCompile Include="..\..\UI\UIOptions.cpp" />
+    <ClCompile Include="..\..\UI\UIPartyCreation.cpp" />
+    <ClCompile Include="..\..\UI\UIPopup.cpp" />
+    <ClCompile Include="..\..\UI\UIRest.cpp" />
+    <ClCompile Include="..\..\UI\UISaveLoad.cpp" />
+    <ClCompile Include="..\..\UI\UIShops.cpp" />
+    <ClCompile Include="..\..\UI\UITransition.cpp" />
     <ClCompile Include="..\..\_deleted.cpp" />
     <ClCompile Include="..\..\Actor.cpp" />
     <ClCompile Include="..\..\AIL.cpp" />
@@ -265,11 +163,13 @@
     <ClCompile Include="..\..\LightsStack.cpp" />
     <ClCompile Include="..\..\LOD.cpp" />
     <ClCompile Include="..\..\Log.cpp" />
+    <ClCompile Include="..\..\LuaVM.cpp" />
     <ClCompile Include="..\..\mm7_2.cpp" />
     <ClCompile Include="..\..\mm7_3.cpp" />
     <ClCompile Include="..\..\mm7_4.cpp" />
     <ClCompile Include="..\..\mm7_5.cpp" />
     <ClCompile Include="..\..\mm7_6.cpp" />
+    <ClCompile Include="..\..\mm7_7.cpp" />
     <ClCompile Include="..\..\mm7_data.cpp" />
     <ClCompile Include="..\..\mm7text_ru.cpp" />
     <ClCompile Include="..\..\Monsters.cpp" />
@@ -291,227 +191,88 @@
     <ClCompile Include="..\..\SpriteObject.cpp" />
     <ClCompile Include="..\..\Sprites.cpp" />
     <ClCompile Include="..\..\StorylineTextTable.cpp" />
+    <ClCompile Include="..\..\stru10.cpp" />
     <ClCompile Include="..\..\stru6.cpp" />
     <ClCompile Include="..\..\stru9.cpp" />
-    <ClCompile Include="..\..\stru10.cpp" />
     <ClCompile Include="..\..\texts.cpp" />
     <ClCompile Include="..\..\Texture.cpp" />
     <ClCompile Include="..\..\TileTable.cpp" />
+    <ClCompile Include="..\..\Timer.cpp" />
     <ClCompile Include="..\..\TurnEngine.cpp" />
     <ClCompile Include="..\..\VectorTypes.cpp" />
     <ClCompile Include="..\..\VideoPlayer.cpp" />
     <ClCompile Include="..\..\Viewport.cpp" />
     <ClCompile Include="..\..\Vis.cpp" />
     <ClCompile Include="..\..\Weather.cpp" />
-    <ClCompile Include="..\..\mm7_7.cpp" />
-    <ClCompile Include="..\..\NewUI\Core\UIControlModule_wrap.cxx">
-      <Filter>NewUI\Core</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\Timer.cpp" />
-    <ClCompile Include="..\..\LuaVM.cpp" />
   </ItemGroup>
   <ItemGroup>
-    <ClInclude Include="..\..\Level\Decoration.h">
-      <Filter>Level</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\d3d.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\d3dcaps.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\d3drm.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\d3drmdef.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\d3drmobj.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\d3drmwin.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\d3dtypes.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\ddraw.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dinput.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dinputd.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmdls.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmerror.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmksctrl.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmplugin.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmusbuff.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmusicc.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmusicf.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmusici.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dmusics.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dsconf.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dsound.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\dvoice.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\multimon.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\rmxfguid.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\rmxftmpl.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\legacy_dx\strsafe.h">
-      <Filter>lib\legacy_dx</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\deflate.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\infblock.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\infcodes.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\inffast.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\inffixed.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\inftrees.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\infutil.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\trees.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\zconf.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\zlib.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\zlib\zutil.h">
-      <Filter>lib\zlib</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua.h">
-      <Filter>lib\lua</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lapi.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lauxlib.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lcode.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lctype.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ldebug.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ldo.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lfunc.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lgc.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\llex.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\llimits.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lmem.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lobject.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lopcodes.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lparser.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lstate.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lstring.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ltable.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ltm.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lua.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\luaconf.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lualib.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lundump.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lvm.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lzio.h">
-      <Filter>lib\lua\lua-5.2.2</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\NewUI\MainMenu.h">
-      <Filter>NewUI</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\NewUI\Core\UIControl.h">
-      <Filter>NewUI\Core</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\UI\UIBooks.h">
-      <Filter>UI</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\UI\UIHouses.h">
-      <Filter>UI</Filter>
-    </ClInclude>
+    <ClInclude Include="..\..\Level\Decoration.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\d3d.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\d3dcaps.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\d3drm.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\d3drmdef.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\d3drmobj.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\d3drmwin.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\d3dtypes.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\ddraw.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dinput.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dinputd.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmdls.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmerror.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmksctrl.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmplugin.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmusbuff.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmusicc.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmusicf.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmusici.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dmusics.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dsconf.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dsound.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\dvoice.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\multimon.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\rmxfguid.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\rmxftmpl.h" />
+    <ClInclude Include="..\..\lib\legacy_dx\strsafe.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lapi.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lauxlib.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lcode.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lctype.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ldebug.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ldo.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lfunc.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lgc.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\llex.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\llimits.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lmem.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lobject.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lopcodes.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lparser.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lstate.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lstring.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ltable.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\ltm.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lua.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\luaconf.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lualib.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lundump.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lvm.h" />
+    <ClInclude Include="..\..\lib\lua\lua-5.2.2\lzio.h" />
+    <ClInclude Include="..\..\lib\lua\lua.h" />
+    <ClInclude Include="..\..\lib\zlib\deflate.h" />
+    <ClInclude Include="..\..\lib\zlib\infblock.h" />
+    <ClInclude Include="..\..\lib\zlib\infcodes.h" />
+    <ClInclude Include="..\..\lib\zlib\inffast.h" />
+    <ClInclude Include="..\..\lib\zlib\inffixed.h" />
+    <ClInclude Include="..\..\lib\zlib\inftrees.h" />
+    <ClInclude Include="..\..\lib\zlib\infutil.h" />
+    <ClInclude Include="..\..\lib\zlib\trees.h" />
+    <ClInclude Include="..\..\lib\zlib\zconf.h" />
+    <ClInclude Include="..\..\lib\zlib\zlib.h" />
+    <ClInclude Include="..\..\lib\zlib\zutil.h" />
+    <ClInclude Include="..\..\NewUI\Core\UIControl.h" />
+    <ClInclude Include="..\..\NewUI\MainMenu.h" />
+    <ClInclude Include="..\..\UI\UIBooks.h" />
+    <ClInclude Include="..\..\UI\UIHouses.h" />
     <ClInclude Include="..\..\Actor.h" />
     <ClInclude Include="..\..\AIL.h" />
     <ClInclude Include="..\..\Arcomage.h" />
@@ -546,6 +307,7 @@
     <ClInclude Include="..\..\Lights.h" />
     <ClInclude Include="..\..\LOD.h" />
     <ClInclude Include="..\..\Log.h" />
+    <ClInclude Include="..\..\LuaVM.h" />
     <ClInclude Include="..\..\MapInfo.h" />
     <ClInclude Include="..\..\MM7.h" />
     <ClInclude Include="..\..\mm7_data.h" />
@@ -557,6 +319,7 @@
     <ClInclude Include="..\..\OSAPI.h" />
     <ClInclude Include="..\..\OSInfo.h" />
     <ClInclude Include="..\..\OSWindow.h" />
+    <ClInclude Include="..\..\OurMath.h" />
     <ClInclude Include="..\..\Outdoor.h" />
     <ClInclude Include="..\..\Outdoor_stuff.h" />
     <ClInclude Include="..\..\Overlays.h" />
@@ -572,8 +335,6 @@
     <ClInclude Include="..\..\SpriteObject.h" />
     <ClInclude Include="..\..\Sprites.h" />
     <ClInclude Include="..\..\StorylineTextTable.h" />
-    <ClInclude Include="..\..\stru6.h" />
-    <ClInclude Include="..\..\stru9.h" />
     <ClInclude Include="..\..\stru10.h" />
     <ClInclude Include="..\..\stru123.h" />
     <ClInclude Include="..\..\stru159.h" />
@@ -582,33 +343,295 @@
     <ClInclude Include="..\..\stru298.h" />
     <ClInclude Include="..\..\stru314.h" />
     <ClInclude Include="..\..\stru367.h" />
+    <ClInclude Include="..\..\stru6.h" />
+    <ClInclude Include="..\..\stru9.h" />
+    <ClInclude Include="..\..\TestClass.h" />
     <ClInclude Include="..\..\texts.h" />
     <ClInclude Include="..\..\Texture.h" />
     <ClInclude Include="..\..\TileFrameTable.h" />
+    <ClInclude Include="..\..\Timer.h" />
     <ClInclude Include="..\..\TurnEngine.h" />
     <ClInclude Include="..\..\VectorTypes.h" />
     <ClInclude Include="..\..\VideoPlayer.h" />
     <ClInclude Include="..\..\Viewport.h" />
     <ClInclude Include="..\..\Vis.h" />
     <ClInclude Include="..\..\Weather.h" />
-    <ClInclude Include="..\..\TestClass.h" />
-    <ClInclude Include="..\..\OurMath.h" />
-    <ClInclude Include="..\..\Timer.h" />
-    <ClInclude Include="..\..\LuaVM.h" />
+    <ClInclude Include="..\..\lib\libavcodec\avcodec.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\avfft.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\dxva2.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\old_codec_ids.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\vaapi.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\vda.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\vdpau.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\version.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavcodec\xvmc.h">
+      <Filter>lib\libavcodec</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavformat\avformat.h">
+      <Filter>lib\libavformat</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavformat\avio.h">
+      <Filter>lib\libavformat</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavformat\version.h">
+      <Filter>lib\libavformat</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\adler32.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\aes.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\attributes.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\audioconvert.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\audio_fifo.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\avassert.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\avconfig.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\avstring.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\avutil.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\base64.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\blowfish.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\bprint.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\bswap.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\buffer.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\channel_layout.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\common.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\cpu.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\crc.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\dict.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\error.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\eval.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\fifo.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\file.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\frame.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\hmac.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\imgutils.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\intfloat.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\intfloat_readwrite.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\intreadwrite.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\lfg.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\log.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\lzo.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\mathematics.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\md5.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\mem.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\murmur3.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\old_pix_fmts.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\opt.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\parseutils.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\pixdesc.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\pixfmt.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\random_seed.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\rational.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\samplefmt.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\sha.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\time.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\timecode.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\timestamp.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\version.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libavutil\xtea.h">
+      <Filter>lib\libavutil</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libswresample\swresample.h">
+      <Filter>lib\libswresample</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libswresample\version.h">
+      <Filter>lib\libswresample</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libswscale\swscale.h">
+      <Filter>lib\libswscale</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\libswscale\version.h">
+      <Filter>lib\libswscale</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\OpenAL\al.h">
+      <Filter>lib\OpenAL</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\OpenAL\alc.h">
+      <Filter>lib\OpenAL</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\OpenAL\efx.h">
+      <Filter>lib\OpenAL</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\OpenAL\efx-creative.h">
+      <Filter>lib\OpenAL</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\OpenAL\EFX-Util.h">
+      <Filter>lib\OpenAL</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\lib\OpenAL\xram.h">
+      <Filter>lib\OpenAL</Filter>
+    </ClInclude>
   </ItemGroup>
   <ItemGroup>
-    <None Include="..\..\lib\legacy_dx\d3dvec.inl">
-      <Filter>lib\legacy_dx</Filter>
+    <None Include="..\..\lib\legacy_dx\d3dvec.inl" />
+    <None Include="..\..\Player.swig" />
+    <None Include="..\..\lib\swig.bat" />
+    <None Include="..\..\lib\OpenAL\lib\x86\avcodec-55.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </None>
+    <None Include="..\..\lib\OpenAL\lib\x86\avdevice-55.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </None>
+    <None Include="..\..\lib\OpenAL\lib\x86\avfilter-3.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
     </None>
-    <None Include="..\..\lib\swig.bat">
-      <Filter>lib</Filter>
+    <None Include="..\..\lib\OpenAL\lib\x86\avformat-55.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </None>
+    <None Include="..\..\lib\OpenAL\lib\x86\avutil-52.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
     </None>
-    <None Include="..\..\Player.swig" />
+    <None Include="..\..\lib\OpenAL\lib\x86\postproc-52.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </None>
+    <None Include="..\..\lib\OpenAL\lib\x86\swresample-0.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </None>
+    <None Include="..\..\lib\OpenAL\lib\x86\swscale-2.def">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </None>
   </ItemGroup>
   <ItemGroup>
-    <CustomBuild Include="..\..\NewUI\Core\UIControlModule.swig">
-      <Filter>NewUI\Core</Filter>
-    </CustomBuild>
-    <CustomBuild Include="..\..\PlayerModule.swig" />
+    <CustomBuild Include="..\..\NewUI\Core\UIControlModule.swig" />
+  </ItemGroup>
+  <ItemGroup>
+    <Library Include="..\..\lib\OpenAL\lib\OpenAL\OpenAL32.lib">
+      <Filter>lib\OpenAL\lib\OpenAL</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\avcodec.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\avdevice.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\avfilter.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\avformat.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\avutil.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\postproc.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\swresample.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
+    <Library Include="..\..\lib\OpenAL\lib\x86\swscale.lib">
+      <Filter>lib\OpenAL\lib\x86</Filter>
+    </Library>
   </ItemGroup>
 </Project>
\ No newline at end of file
--- a/CastSpellInfo.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/CastSpellInfo.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -1959,7 +1959,7 @@
 				{
 					v730 = 0;
 				}
-
+ 
                 __debugbreak(); // castspellinfo.cpp(1962): warning C4700: uninitialized local variable 'v271' used
 				if ( rand() % 100 < 10 * v2 || 
 					(rand() % 100 < 80 && (v731 == 3 || v731 == 4 )) ||
--- a/DecalBuilder.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/DecalBuilder.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -456,9 +456,7 @@
   
   BLVFace* pFace = &pIndoor->pFaces[uFaceID];
 
-  if (pFace->uAttributes & 0x400000)
-    return true;
-  if (pFace->Fluid())
+  if ( pFace->Indoor_sky() || pFace->Fluid() )
     return true;
   for (uint i = 0; i < pBloodsplatContainer->std__vector_pBloodsplats_size; ++i)
   {
@@ -495,7 +493,7 @@
 
 	this->uNumDecals = 0;
 	v10 = pBloodsplatContainer->std__vector_pBloodsplats_size;
-	if ( !(pFace->uAttributes & 0x400000) && !(pFace->uAttributes & 0x10) )
+	if ( !pFace->Indoor_sky() && !pFace->Fluid() )
 	{
 		for(int i = 0; i < pBloodsplatContainer->std__vector_pBloodsplats_size; i++ )
 		{
@@ -508,9 +506,9 @@
 				(double)pFace->pBoundingBox.z2 + pBloodsplat->radius > pBloodsplat->z )
 			{
 				v8 = (double)((pFace->pFacePlane.dist
-							+ round(pBloodsplat->x) * pFace->pFacePlane.vNormal.x
-							+ round(pBloodsplat->y) * pFace->pFacePlane.vNormal.y
-							+ round(pBloodsplat->z) * pFace->pFacePlane.vNormal.z) >> 16);
+							+ round_to_int(pBloodsplat->x) * pFace->pFacePlane.vNormal.x
+							+ round_to_int(pBloodsplat->y) * pFace->pFacePlane.vNormal.y
+							+ round_to_int(pBloodsplat->z) * pFace->pFacePlane.vNormal.z) >> 16);
 				if ( v8 <= pBloodsplat->radius )
 				{
 					pBloodsplat->dot_dist = v8;
--- a/Events.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Events.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -1420,11 +1420,11 @@
         else
           {
           pGameLoadingUI_ProgressBar->uType = (GUIProgressBar::Type)((activeLevelDecoration == NULL) + 1);
-          sub_44987B(v99, MapStartPoint_Party);
+          Transition_StopSound_Autosave(v99, MapStartPoint_Party);
           v133 = 1;
           if ( pCurrentScreen == SCREEN_HOUSE )
             {
-            if ( uGameState == GAME_STATE_2 )
+            if ( uGameState == GAME_STATE_CHANGE_LOCATION )
               {
               pAudioPlayer->StopChannels(-1, -1);
               dialog_menu_id = HOUSE_DIALOGUE_NULL;
--- a/GUIFont.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/GUIFont.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -192,7 +192,7 @@
             if ( char_pxl )
                 {
                 if ( char_pxl == 1 )
-                    *draw_buff = pFontPalette[1];         
+                    *draw_buff = pFontPalette[1];     
                 else         
                     *draw_buff = draw_color;         
                 }
@@ -646,11 +646,11 @@
 //----- (00414162) --------------------------------------------------------
 void uGameUIFontMain_initialize()
 {
-  uGameUIFontMain = TargetColor(0xAu, 0, 0);
+  uGameUIFontMain = Color16(0xAu, 0, 0);
 }
 
 //----- (00414174) --------------------------------------------------------
 void uGameUIFontShadow_initialize()
 {
-  uGameUIFontShadow = TargetColor(0xE6u, 214u, 193u);
+  uGameUIFontShadow = Color16(0xE6u, 214u, 193u);
 }
\ No newline at end of file
--- a/GUIProgressBar.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/GUIProgressBar.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -177,10 +177,6 @@
 //----- (00443670) --------------------------------------------------------
 void GUIProgressBar::Draw()
 {
-  IconFrame *v3; // eax@10
-  float v4; // ST2C_4@10
-
-  //v1 = this;
   pRenderer->BeginScene();
   if (uType != TYPE_Fullscreen)
   {
@@ -191,19 +187,15 @@
         if (!pRenderer->bWindowMode)
           pRenderer->_49FD3A();
       }
-      pRenderer->DrawTextureIndexed(0x50u, 0x7Au, &pBardata);
-      v3 = pIconsFrameTable->GetFrame(uIconID_TurnHour, 0);
-      pRenderer->DrawTextureTransparent(0x64u, 0x92u, &pIcons_LOD->pTextures[v3->uTextureID]);
-      v4 = (double)(113 * uProgressCurrent) / (double)uProgressMax;
-      pRenderer->FillRectFast(
-        174,
-        164,
-        floorf(v4 + 0.5f),//COERCE_UNSIGNED_INT64(v4 + 6.7553994e15),
-        16,
-        pRenderer->uTargetRMask);
-        pRenderer->EndScene();
-		pRenderer->Present();
-		return;
+      pRenderer->DrawTextureIndexed(80, 122, &pBardata);//  
+      pRenderer->DrawTextureTransparent(100, 146, &pIcons_LOD->pTextures[pIconsFrameTable->GetFrame(uIconID_TurnHour, 0)->uTextureID]);
+      //pRenderer->FillRectFast(174, 164, floorf(((double)(113 * uProgressCurrent) / (double)uProgressMax) + 0.5f),//COERCE_UNSIGNED_INT64(v4 + 6.7553994e15),
+        //16, pRenderer->uTargetRMask);
+      pRenderer->FillRectFast(174, 164, floorf(((double)(113 * uProgressCurrent) / (double)uProgressMax) + 0.5f),//COERCE_UNSIGNED_INT64(v4 + 6.7553994e15),
+        16, 0xF800);
+      pRenderer->EndScene();
+      pRenderer->Present();
+      return;
     }
     pRenderer->EndScene();
     return;
@@ -211,16 +203,14 @@
 
   if (!pLoadingBg.pPixels)
   {
-	pRenderer->EndScene();
+    pRenderer->EndScene();
     return;
   }
 
   pRenderer->DrawTextureRGB(0, 0, &pLoadingBg);
-  pRenderer->SetRasterClipRect(0, 0, 0x27Fu, 0x1DFu);
-  pRenderer->SetTextureClipRect(0xACu, 0x1CBu,
-    15 * (signed int)(signed __int64)((double)(300 * uProgressCurrent) / (double)uProgressMax) / 15 + 172,
-    0x1D7u);
-  pRenderer->DrawTextureTransparent(0xACu, 0x1CBu, &pLoadingProgress);
+  pRenderer->SetRasterClipRect(0, 0, 639, 479);
+  pRenderer->SetTextureClipRect(172, 459, 15 * (signed int)(signed __int64)((double)(300 * uProgressCurrent) / (double)uProgressMax) / 15 + 172, 471);
+  pRenderer->DrawTextureTransparent(172, 459, &pLoadingProgress);
   pRenderer->ResetTextureClipRect();
   pRenderer->EndScene();
   pRenderer->Present();
--- a/GUIWindow.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/GUIWindow.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -229,7 +229,7 @@
     {
       remaing_time = pParty->pPartyBuffs[i].uExpireTime- pParty->uTimePlayed;//!!!
       Y_pos = string_count * pFontComic->uFontHeight + 40; 
-      text_color = TargetColor(spell_tooltip_colors[i].R, spell_tooltip_colors[i].G, spell_tooltip_colors[i].B);
+      text_color = Color16(spell_tooltip_colors[i].R, spell_tooltip_colors[i].G, spell_tooltip_colors[i].B);
       DrawText(pFontComic, 52, Y_pos, text_color, aSpellNames[i], 0, 0, 0);
       DrawBuff_remaining_time_string(Y_pos, this, remaing_time, pFontComic); 
       ++string_count;
@@ -871,8 +871,8 @@
   memcpy(&pWindow, this, sizeof(pWindow));
   pWindow.uFrameWidth -= 18;
   pWindow.uFrameZ -= 18;
-  pWhiteColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
-  pColor2 = TargetColor(0x15u, 0x99u, 0xE9u);
+  pWhiteColor = Color16(0xFFu, 0xFFu, 0xFFu);
+  pColor2 = Color16(0x15u, 0x99u, 0xE9u);
   pRenderer->DrawTextureIndexed(0x1DDu, 0, pTexture_Dialogue_Background);
   pRenderer->DrawTextureTransparent(0x1D4u, 0, &pIcons_LOD->pTextures[uTextureID_right_panel_loop]);
   if ( pDialogueNPCCount != uNumDialogueNPCPortraits || !uHouse_ExitPic )
@@ -1117,7 +1117,7 @@
     sprintfex(pTmpBuf2.data(), "%d %s ", (int)seconds, text);
     strcat(pTmpBuf.data(), pTmpBuf2.data());
   }
-  this->DrawTitleText(pFontArrus, 0, (212 - pFontArrus->CalcTextHeight(pTmpBuf.data(), this, 0, 0)) / 2 + 101, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+  this->DrawTitleText(pFontArrus, 0, (212 - pFontArrus->CalcTextHeight(pTmpBuf.data(), this, 0, 0)) / 2 + 101, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
 }
 
 
@@ -1965,7 +1965,7 @@
       }
       case WINDOW_50:
       {
-        v27 = TargetColor(255, 255, 255);
+        v27 = Color16(255, 255, 255);
         if ( ptr_507BD0->receives_keyboard_input_2 == WINDOW_INPUT_IN_PROGRESS)
         {
           ptr_507BD0->DrawMessageBox(0);
@@ -2332,7 +2332,7 @@
   a1.uFrameZ = a1.uFrameWidth + a1.uFrameX - 1;
   a1.uFrameW = a1.uFrameHeight + a1.uFrameY - 1;
   v1 = pItemsTable->pItems[(unsigned int)pGUIWindow_ScrollWindow->ptr_1C + 700].pName;
-  v2 = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+  v2 = Color16(0xFFu, 0xFFu, 0x9Bu);
   sprintf(pTmpBuf.data(), format_4E2D80, v2, v1);
   a1.DrawTitleText(pFontCreate, 0, 0, 0, pTmpBuf.data(), 3u);
   a1.DrawText(
@@ -2458,8 +2458,8 @@
       pUIAnum_Torchlight->uIconID = pIconsFrameTable->FindIcon("torchC");
       pIconsFrameTable->InitializeAnimation((signed __int16)pUIAnum_Torchlight->uIconID);
     }
-    uGameUIFontMain = TargetColor(0xC8u, 0, 0);
-    uGameUIFontShadow = TargetColor(10, 0, 0);
+    uGameUIFontMain = Color16(0xC8u, 0, 0);
+    uGameUIFontShadow = Color16(10, 0, 0);
   }
   else if (align == PartyAlignment_Neutral)
   {
@@ -2551,8 +2551,8 @@
       uTextureID_507698 = pIcons_LOD->LoadTexture("edge_top", TEXTURE_16BIT_PALETTE);
       pTexture_591428 = pIcons_LOD->LoadTexturePtr("endcap", TEXTURE_16BIT_PALETTE);
     }
-    uGameUIFontMain = TargetColor(0xAu, 0, 0);
-    uGameUIFontShadow = TargetColor(230, 214, 193);
+    uGameUIFontMain = Color16(0xAu, 0, 0);
+    uGameUIFontShadow = Color16(230, 214, 193);
   }
   else if (align == PartyAlignment_Good)
   {
@@ -2600,8 +2600,8 @@
       pIcons_LOD->ReloadTexture(&pIcons_LOD->pTextures[uTextureID_507698], "edge_top-b", 2);
       pIcons_LOD->ReloadTexture(pTexture_591428, "endcap-b", 2);
     }
-    uGameUIFontMain = TargetColor(0, 0, 0xC8u);
-    uGameUIFontShadow = TargetColor(255, 255, 255);
+    uGameUIFontMain = Color16(0, 0, 0xC8u);
+    uGameUIFontShadow = Color16(255, 255, 255);
   }
   else Error("Invalid alignment type: %u", align);
 }
--- a/GUIWindow.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/GUIWindow.h	Thu Jan 02 09:11:28 2014 +0600
@@ -231,16 +231,21 @@
   DIALOGUE_USE_NPC_ABILITY = 9,
   DIALOGUE_13 = 0xD,
   DIALOGUE_18 = 0x12,
-  DIALOGUE_19 = 19,
-  DIALOGUE_20 = 20,
-  DIALOGUE_21 = 21,
-  DIALOGUE_22 = 22,
-  DIALOGUE_23 = 23,
-  DIALOGUE_24 = 0x18,
+  DIALOGUE_EVT_A = 19,
+  DIALOGUE_EVT_B = 20,
+  DIALOGUE_EVT_C = 21,
+  DIALOGUE_EVT_D = 22,
+  DIALOGUE_EVT_E = 23,
+  DIALOGUE_EVT_F = 0x18,
   DIALOGUE_76 = 76,
   DIALOGUE_PROFESSION_DETAILS = 77,
-  DIALOGUE_ARENA_WELCOME = 0x59,
-  DIALOGUE_ARENA_FIGHT_NOT_OVER_YET = 0x5A,
+  DIALOGUE_84 = 84,
+  DIALOGUE_ARENA_SELECT_PAGE = 85,
+  DIALOGUE_ARENA_SELECT_SQUIRE = 86,
+  DIALOGUE_ARENA_SELECT_KNIGHT = 87,
+  DIALOGUE_ARENA_SELECT_CHAMPION = 88,
+  DIALOGUE_ARENA_WELCOME = 89,
+  DIALOGUE_ARENA_FIGHT_NOT_OVER_YET = 90,
   DIALOGUE_ARENA_REWARD = 0x5B,
   DIALOGUE_ARENA_ALREADY_WON = 0x5C,
 };
--- a/Game.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Game.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -3,7 +3,7 @@
 #endif
 
 #include "Vis.h"
-
+#include "Weather.h"
 #include "LightmapBuilder.h"
 #include "DecalBuilder.h"
 #include "ParticleEngine.h"
@@ -170,7 +170,7 @@
   }
   if (!pVideoPlayer->pSmackerMovie)
   {
-    GameUI_DrawMinimap(488, 16, 625, 133, viewparams->uMinimapZoom, pParty->uFlags & 2);
+    GameUI_DrawMinimap(488, 16, 625, 133, viewparams->uMinimapZoom, true);//redraw = pParty->uFlags & 2);
     if (v4)
     {
       if ( !PauseGameDrawing() && pRenderer->pRenderD3D) // clear game viewport with transparent color
@@ -205,6 +205,8 @@
   static uint frames_this_second = 0;
   static uint last_frame_time = GetTickCount();
   static uint framerate_time_elapsed = 0;
+  if ( pCurrentScreen == SCREEN_GAME && uCurrentlyLoadedLevelType == LEVEL_Outdoor)
+    pWeather->Draw();//Ritor1: my include
 
   uint frame_dt = GetTickCount() - last_frame_time;
   last_frame_time = GetTickCount();
@@ -227,17 +229,17 @@
     if (render_framerate)
     {
       sprintf(pTmpBuf.data(), "FPS: % .4f", framerate);
-      pPrimaryWindow->DrawText(pFontArrus, 494, 0, TargetColor(0, 0, 0), pTmpBuf.data(), 0, 0, 0);
+      pPrimaryWindow->DrawText(pFontArrus, 494, 0, Color16(0, 0, 0), pTmpBuf.data(), 0, 0, 0);
     }
 
     if (uCurrentlyLoadedLevelType == LEVEL_Indoor)
     {
       int sector_id = pIndoor->GetSector(pParty->vPosition.x, pParty->vPosition.y, pParty->vPosition.z);
       sprintf(pTmpBuf.data(), "Party Sector ID:        %u/%u\n", sector_id, pIndoor->uNumSectors);
-      pPrimaryWindow->DrawText(pFontArrus, 16, 16, TargetColor(255, 255, 255), pTmpBuf.data(), 0, 0, -1);
+      pPrimaryWindow->DrawText(pFontArrus, 16, 16, Color16(255, 255, 255), pTmpBuf.data(), 0, 0, -1);
     }
     sprintf(pTmpBuf.data(), "Party Position:         % d % d % d", pParty->vPosition.x, pParty->vPosition.y, pParty->vPosition.z);
-    pPrimaryWindow->DrawText(pFontArrus, 16, 16 + 16, TargetColor(255, 255, 255), pTmpBuf.data(), 0, 0, -1);
+    pPrimaryWindow->DrawText(pFontArrus, 16, 16 + 16, Color16(255, 255, 255), pTmpBuf.data(), 0, 0, -1);
   
     if (uCurrentlyLoadedLevelType == LEVEL_Indoor)
     {
@@ -252,7 +254,7 @@
       int floor_level = ODM_GetFloorLevel(pParty->vPosition.x, pParty->vPosition.y, pParty->vPosition.z, 0, &on_water, &_a6, false);
       sprintf(pTmpBuf.data(), "ODM_GetFloorLevel: %d   on_water: %s    a6 = %d\n", floor_level, on_water ? "true" : "false", _a6);
     }
-    pPrimaryWindow->DrawText(pFontArrus, 16, 16 + 16 + 16, TargetColor(255, 255, 255), pTmpBuf.data(), 0, 0, -1);
+    pPrimaryWindow->DrawText(pFontArrus, 16, 16 + 16 + 16, Color16(255, 255, 255), pTmpBuf.data(), 0, 0, -1);
   }
 
   GUI_UpdateWindows();
@@ -278,24 +280,9 @@
 //----- (00463149) --------------------------------------------------------
 void Game::Loop()
 {
-  //signed int v0; // ebp@3
-  //signed int v1; // esi@4
-  //Render *v2; // edi@7
-  //signed int v3; // esi@7
-  signed int pNewNPCsCount; // ecx@58
-  NPCData *pNPC; // eax@59
-  Player *pPlayer; // esi@65
-  //OtherOverlay *pOtherOverlay; // esi@67
-  //signed int v8; // edi@67
-  //int pPlayerNum; // edi@69
-  int *pHealth; // esi@71
-  //signed int v11; // esi@78
-  //int v12; // eax@83
   const char *pLocationName; // [sp-4h] [bp-68h]@74
   bool bLoading; // [sp+10h] [bp-54h]@1
-  //signed int bLoadinga; // [sp+10h] [bp-54h]@19
   signed int v16; // [sp+14h] [bp-50h]@8
-  //int v17[4]; // [sp+18h] [bp-4Ch]@80
   MSG Msg; // [sp+28h] [bp-3Ch]@20
   char Source[64]; // [sp+44h] [bp-20h]@76
 
@@ -395,152 +382,129 @@
         viewparams->bRedrawGameUI = true;
       }
       pAudioPlayer->UpdateSounds();
+      if ( (signed int)uGameState == GAME_STATE_PLAYING )
+      {
+        pGame->Draw();
+        continue;
+      }
       if (uGameState == GAME_FINISHED)
-        //goto LABEL_96;
       {
         game_finished = true;
         continue;
       }
-      if (uGameState == GAME_STATE_2)
+      if (uGameState == GAME_STATE_CHANGE_LOCATION)//  
       {
         pAudioPlayer->StopChannels(-1, -1);
         PrepareWorld(0);
         uGameState = GAME_STATE_PLAYING;
         continue;
       }
-      if ( (signed int)uGameState <= GAME_STATE_2 )
-        //goto LABEL_85;
+      if ( (signed int)uGameState <= GAME_STATE_5 || uGameState == GAME_STATE_GAME_QUITTING_TO_MAIN_MENU )//GAME_STATE_NEWGAME_OUT_GAMEMENU, GAME_STATE_LOADING_GAME
       {
-        pGame->Draw();
+        game_finished = true;
         continue;
       }
-      if ( (signed int)uGameState <= GAME_STATE_5 || uGameState == GAME_STATE_GAME_QUITTING_TO_MAIN_MENU )
+      if ( uGameState == GAME_STATE_FINAL_WINDOW )
       {
-//LABEL_96:
-        game_finished = true;
+        pRenderer->BeginScene();
+        GUI_UpdateWindows();
+        pRenderer->EndScene();
+        pRenderer->Present();
         continue;
       }
       if ( uGameState != GAME_STATE_PARTY_DIED )
       {
-        if ( uGameState != GAME_STATE_FINAL_WINDOW )
+        pGame->Draw();
+        continue;
+      }
+      if ( uGameState == GAME_STATE_PARTY_DIED )
+      {
+        pAudioPlayer->StopChannels(-1, -1);
+        memset(&pParty->pHirelings[0], 0, 0x4Cu);
+        memset(&pParty->pHirelings[1], 0, 0x4Cu);
+        for ( int i = 0; i < (signed int)pNPCStats->uNumNewNPCs; ++i )
         {
-//LABEL_85:
-          pGame->Draw();
+          if ( pNPCStats->pNewNPCData[i].field_24 )
+            pNPCStats->pNewNPCData[i].uFlags &= 0xFFFFFF7Fu;
+        }
+        pVideoPlayer->PlayDeathMovie();
+        if ( pVideoPlayer->AnyMovieLoaded() )
+          pVideoPlayer->Unload();
+        SaveGame(0, 0);
+        ++pParty->uNumDeaths;
+        for ( uint i = 0; i < 4; ++i )
+          pParty->pPlayers[i].SetVariable(VAR_Award, 85);
+        pParty->days_played_without_rest = 0;
+        pParty->uTimePlayed += 0x276000ui64;
+        LOWORD(pParty->uFlags) &= ~0x204;
+        pParty->SetGold(0);
+        pOtherOverlayList->Reset();
+        memset(pParty->pPartyBuffs.data(), 0, 0x140u);
+
+        if ( pParty->bTurnBasedModeOn == 1 )
+        {
+          pTurnEngine->End(true);
+          pParty->bTurnBasedModeOn = 0;
+        }
+        for( int i = 0; i < 4; ++i)
+        {
+          memset(pParty->pPlayers[i].pConditions.data(), 0, 0xA0u);//(pConditions, 0, 160)
+          memset(pParty->pPlayers[i].pPlayerBuffs.data(), 0, 0x180u);//(pPlayerBuffs[0], 0, 384)
+          pParty->pPlayers[i].sHealth = 1;
+          uActiveCharacter = 1;
+        }
+        if (_449B57_test_bit(pParty->_quest_bits, PARTY_QUEST_FINISHED_EMERALD_ISLE))
+        {
+          pParty->vPosition.x = -17331;            // respawn in harmondale
+          pParty->vPosition.y = 12547;
+          pParty->vPosition.z = 465;
+          pParty->sRotationY = 0;
+          pLocationName = "out02.odm";
         }
         else
         {
-          pRenderer->BeginScene();
-          GUI_UpdateWindows();
-          pRenderer->EndScene();
-          //goto LABEL_89;
-          pRenderer->Present();
-        }
-        continue;
-      }
-      pAudioPlayer->StopChannels(-1, -1);//    
-      memset(&pParty->pHirelings[0], 0, 0x4Cu);
-      memset(&pParty->pHirelings[1], 0, 0x4Cu);
-      pNewNPCsCount = 0;
-      if ( (signed int)pNPCStats->uNumNewNPCs > 0 )
-      {
-        pNPC = pNPCStats->pNewNPCData;
-        do
-        {
-		  if ( pNPC->field_24 )
-			  pNPC->uFlags &= 0xFFFFFF7Fu;
-          ++pNewNPCsCount;
-          ++pNPC;
+          pParty->vPosition.x = 12552;             // respawn on emerald isle
+          pParty->vPosition.y = 1816;
+          pParty->vPosition.z = 0;
+          pParty->sRotationY = 512;
+          pLocationName = "out01.odm";
         }
-        while ( pNewNPCsCount < (signed int)pNPCStats->uNumNewNPCs );
-      }
-      pVideoPlayer->PlayDeathMovie();
-      if ( pVideoPlayer->AnyMovieLoaded() )
-        pVideoPlayer->Unload();
-      SaveGame(0, 0);
-      ++pParty->uNumDeaths;
-      pPlayer = pParty->pPlayers.data();
-      do
-      {
-        pPlayer->SetVariable(VAR_Award, 85);
-        ++pPlayer;
-      }
-      while ( (signed int)pPlayer < (signed int)pParty->pHirelings.data() );
-      pParty->days_played_without_rest = 0;
-      pParty->uTimePlayed += 0x276000ui64;
-      LOWORD(pParty->uFlags) &= ~0x204;
-      pParty->SetGold(0);
-      pOtherOverlayList->Reset();
-      memset(pParty->pPartyBuffs.data(), 0, 0x140u);
+        strcpy(Source, pLocationName);
+        pParty->uFallStartY = pParty->vPosition.z;
+        pParty->sRotationX = 0;
+        pParty->uFallSpeed = 0;
+        pParty->field_6E4 = 0;
+        pParty->field_6E0 = 0;
+        if ( _stricmp(Source, pCurrentMapName) )
+        {
+          strcpy(pCurrentMapName, Source);
+          _5B65A8_npcdata_uflags_or_other = pParty->vPosition.x;
+          _5B65AC_npcdata_fame_or_other = pParty->vPosition.y;
+          _5B65B0_npcdata_rep_or_other = pParty->vPosition.z;
+          _5B65B4_npcdata_loword_house_or_other = pParty->sRotationY;
+          _5B65B8_npcdata_hiword_house_or_other = pParty->sRotationX;
+          dword_5B65C0 = 1;
+          PrepareWorld(1);
+        }
+        InitializeActors();
 
-      if ( pParty->bTurnBasedModeOn == 1 )
-      {
-        pTurnEngine->End(true);
-        pParty->bTurnBasedModeOn = 0;
+        int num_conscious_players = 0;
+        int conscious_players_ids[4] = {-1, -1, -1, -1};
+        for (int i = 0; i < 4; ++i)
+        {
+          if (pParty->pPlayers[i].CanAct())
+            conscious_players_ids[num_conscious_players++] = i;
+        }
+        if (num_conscious_players)
+        {
+          int idx = conscious_players_ids[rand() % num_conscious_players];
+          Assert(idx >= 0);
+          pParty->pPlayers[idx].PlaySound(SPEECH_99, 0);
+        }
+
+        ShowStatusBarString(pGlobalTXT_LocalizationStrings[524], 2);// "Once again you've cheated death!.." "   ! "
+        uGameState = GAME_STATE_PLAYING;
       }
-      //pHealth = &pParty->pPlayers[0].sHealth;//193C
-      //do
-	  for(int i=0; i<4; ++i)
-      {
-        memset(pParty->pPlayers[i].pConditions.data(), 0, 0xA0u);//(pConditions, 0, 160)
-        memset(pParty->pPlayers[i].pPlayerBuffs.data(), 0, 0x180u);//(pPlayerBuffs[0], 0, 384)
-        //*pHealth = 1;
-		pParty->pPlayers[i].sHealth=1;
-        //pHealth += 1743; //6CF
-        uActiveCharacter = 1;
-      }
-    //  while ( (signed int)pHealth < (signed int)&pParty->field_871C[567] );
-      if (_449B57_test_bit(pParty->_quest_bits, PARTY_QUEST_FINISHED_EMERALD_ISLE))
-      {
-        pParty->vPosition.x = -17331;            // respawn in harmondale
-        pParty->vPosition.y = 12547;
-        pParty->vPosition.z = 465;
-        pParty->sRotationY = 0;
-        pLocationName = "out02.odm";
-      }
-      else
-      {
-        pParty->vPosition.x = 12552;             // respawn on emerald isle
-        pParty->vPosition.y = 1816;
-        pParty->vPosition.z = 0;
-        pParty->sRotationY = 512;
-        pLocationName = "out01.odm";
-      }
-      strcpy(Source, pLocationName);
-      pParty->uFallStartY = pParty->vPosition.z;
-      pParty->sRotationX = 0;
-      pParty->uFallSpeed = 0;
-      pParty->field_6E4 = 0;
-      pParty->field_6E0 = 0;
-      if ( _stricmp(Source, pCurrentMapName) )
-      {
-        strcpy(pCurrentMapName, Source);
-        _5B65A8_npcdata_uflags_or_other = pParty->vPosition.x;
-        _5B65AC_npcdata_fame_or_other = pParty->vPosition.y;
-        _5B65B0_npcdata_rep_or_other = pParty->vPosition.z;
-        _5B65B4_npcdata_loword_house_or_other = pParty->sRotationY;
-        _5B65B8_npcdata_hiword_house_or_other = pParty->sRotationX;
-        dword_5B65C0 = 1;
-        PrepareWorld(1);
-      }
-      InitializeActors();
-
-
-      int num_conscious_players = 0;
-      int conscious_players_ids[4] = {-1, -1, -1, -1};
-      for (int v11 = 0; v11 < 4; ++v11)
-      {
-        if (pPlayers[v11 + 1]->CanAct())
-          conscious_players_ids[num_conscious_players++] = v11;
-      }
-      if (num_conscious_players)
-      {
-        int idx = conscious_players_ids[rand() % num_conscious_players];
-        Assert(idx >= 0);
-        pPlayers[idx + 1]->PlaySound(SPEECH_99, 0);
-      }
-
-      ShowStatusBarString(pGlobalTXT_LocalizationStrings[524], 2u);// "Once again you've cheated death!.." "   ! "
-      uGameState = GAME_STATE_PLAYING;
     }
     while (!game_finished);
 
@@ -1396,6 +1360,7 @@
   char a1[64]; // [sp+1F8h] [bp-404h]@467
   char Str2[128]; // [sp+238h] [bp-3C4h]@527
   Actor actor; // [sp+2B8h] [bp-344h]@4
+  unsigned short* screenshot;
 
   dword_50CDC8 = 0;
   if ( !pEventTimer->bPaused )
@@ -1888,30 +1853,30 @@
         case UIMSG_ToggleTint:
           pRenderer->bTinting = pRenderer->bTinting == 0;
           continue;
-        case UIMSG_ChangeMusicVolume:
-          if ( uMessageParam == 4 )
+        case UIMSG_ChangeMusicVolume:  // 
+          if ( uMessageParam == 4 )// 
           {
             --uMusicVolimeMultiplier;
             if ( (char)uMusicVolimeMultiplier < 1 )
               uMusicVolimeMultiplier = 0;
-            GUIWindow::Create(243, 0xD8u, 0, 0, WINDOW_PressedButton2, (int)pBtn_SliderLeft, (char *)1);
+            GUIWindow::Create(243, 216, 0, 0, WINDOW_PressedButton2, (int)pBtn_SliderLeft, (char *)1);
             if ( uMusicVolimeMultiplier )
-              pAudioPlayer->PlaySound(SOUND_Bell, -1, 0, -1, 0, 0, pSoundVolumeLevels[(char)uMusicVolimeMultiplier] * 64.0f, 0);
-            pAudioPlayer->SetMusicVolume(pSoundVolumeLevels[(char)uMusicVolimeMultiplier] * 64.0f);
+              pAudioPlayer->PlaySound(SOUND_Bell, -1, 0, -1, 0, 0, pSoundVolumeLevels[uMusicVolimeMultiplier] * 64.0f, 0);
+            pAudioPlayer->SetMusicVolume(pSoundVolumeLevels[uMusicVolimeMultiplier] * 64.0f);
             continue;
           }
-          if ( uMessageParam == 5 )
+          if ( uMessageParam == 5 )// 
           {
             ++uMusicVolimeMultiplier;
             if ( (char)uMusicVolimeMultiplier > 9 )
               uMusicVolimeMultiplier = 9;
-            GUIWindow::Create(435, 0xD8u, 0, 0, WINDOW_PressedButton2, (int)pBtn_SliderRight, (char *)1);
+            GUIWindow::Create(435, 216, 0, 0, WINDOW_PressedButton2, (int)pBtn_SliderRight, (char *)1);
             if ( uMusicVolimeMultiplier )
-              pAudioPlayer->PlaySound(SOUND_Bell, -1, 0, -1, 0, 0, pSoundVolumeLevels[(char)uMusicVolimeMultiplier] * 64.0f, 0);
-            pAudioPlayer->SetMusicVolume(pSoundVolumeLevels[(char)uMusicVolimeMultiplier] * 64.0f);
+              pAudioPlayer->PlaySound(SOUND_Bell, -1, 0, -1, 0, 0, pSoundVolumeLevels[uMusicVolimeMultiplier] * 64.0f, 0);
+            pAudioPlayer->SetMusicVolume(pSoundVolumeLevels[uMusicVolimeMultiplier] * 64.0f);
             continue;
           }
-          uMusicVolimeMultiplier = (pMouse->GetCursorPos(&v202)->x - 263) / 17;
+          uMusicVolimeMultiplier = (pMouse->GetCursorPos(&v202)->x - 263) / 17;//   
           if ( (char)uMusicVolimeMultiplier > 9 )
             uMusicVolimeMultiplier = 9;
           if ( uMusicVolimeMultiplier )
@@ -2428,7 +2393,7 @@
                     case SCREEN_HOUSE:
                       if ( uDialogueType )
                         uDialogueType = 0;
-                      if ( uGameState == GAME_STATE_2 )
+                      if ( uGameState == GAME_STATE_CHANGE_LOCATION )
                       {
                         while ( HouseDialogPressCloseBtn() )
                           ;
@@ -2683,10 +2648,10 @@
               pGUIWindow_CurrentMenu->_41D08F_set_keyboard_control_group(6, 1, 0, 0);
               viewparams->field_48 = 1;
               stru_506E40.Release();
-              uNumSeconds = (unsigned int)MakeScreenshot(155, 117);
-              pRenderer->SavePCXImage("gamma.pcx", (char *)uNumSeconds, 155, 117);
-              free((void *)uNumSeconds);
-              stru_506E40._40E55E("gamma.pcx", 0);
+              screenshot = MakeScreenshot(155, 117);
+              pRenderer->SavePCXImage("gamma.pcx", screenshot, 155, 117);
+              free(screenshot);
+              stru_506E40.LoadPCXFile("gamma.pcx", 0);
               continue;
             }
             pGUIWindow_Settings->Release();
@@ -2731,7 +2696,7 @@
           PlayHouseSound(uCurrentHouse_Animation, HouseSound_NotEnoughMoney_TrainingSuccessful);
           pVideoPlayer->Unload();
           DialogueEnding();
-          viewparams->bRedrawGameUI = 1;
+          viewparams->bRedrawGameUI = true;
           if ( dword_59117C_teleportx | dword_591178_teleporty | dword_591174_teleportz | dword_591170_teleport_directiony | dword_59116C_teleport_directionx | dword_591168_teleport_speedz )
           {
             if ( dword_59117C_teleportx )
@@ -2764,21 +2729,17 @@
               dword_5B65BC = dword_591168_teleport_speedz;
             }
             else
-            {
               v38 = dword_5B65BC;
-            }
             if ( *dword_591164_teleport_map_name != 48 )
             {
               pGameLoadingUI_ProgressBar->uType = (GUIProgressBar::Type)2;
               dword_5B65C0 = _5B65A8_npcdata_uflags_or_other | _5B65AC_npcdata_fame_or_other | _5B65B0_npcdata_rep_or_other | _5B65B4_npcdata_loword_house_or_other | _5B65B8_npcdata_hiword_house_or_other | v38;
               OnMapLeave();
-              sub_44987B(dword_591164_teleport_map_name, MapStartPoint_Party);
+              Transition_StopSound_Autosave(dword_591164_teleport_map_name, MapStartPoint_Party);
             }
           }
           else
-          {
             EventProcessor(dword_5C3418, 0, 1, dword_5C341C);
-          }
           if ( !_stricmp(byte_6BE3B0.data(), "d05.blv") )
             pParty->uTimePlayed += 1474560i64;
           continue;
@@ -2965,7 +2926,7 @@
             if ( uCurrentlyLoadedLevelType != 1 )
             {
               pODMFace = &pOutdoor->pBModels[v44 >> 9].pFaces[v46 & 0x3F];
-              if ( !(pODMFace->uAttributes & 0x02000000) || !pODMFace->sCogTriggeredID )
+              if ( !pODMFace->Clickable() || !pODMFace->sCogTriggeredID )
                 continue;
               v44 = uNumSeconds;
               pSpellInfo = (CastSpellInfo *)pGUIWindow_Settings->ptr_1C;
@@ -2982,7 +2943,7 @@
               continue;
             }
             pBLVFace = &pIndoor->pFaces[v46];
-            if ( !(BYTE3(pBLVFace->uAttributes) & 2) )
+            if ( !pBLVFace->Clickable() )
               continue;
             v48 = pIndoor->pFaceExtras[pBLVFace->uFaceExtraID].uEventID == 0;
           }
@@ -3045,7 +3006,7 @@
           SaveGame(1, 0);
           strcpy(pCurrentMapName, pMapStats->pInfos[uHouse_ExitPic].pFilename);
           dword_6BE364_game_settings_1 |= GAME_SETTINGS_0001;
-          uGameState = GAME_STATE_2;
+          uGameState = GAME_STATE_CHANGE_LOCATION;
           //v53 = p2DEvents_minus1_::30[26 * (unsigned int)ptr_507BC0->ptr_1C];
           v53 = p2DEvents[(unsigned int)window_SpeakInHouse->ptr_1C - 1]._quest_related;
           if ( v53 < 0 )
@@ -3153,7 +3114,7 @@
               OnMapLeave();
               strcpy(pCurrentMapName, (const char *)&pGames_LOD->pSubIndices[pPlayer9->pInstalledBeacons[uMessageParam].SaveFileID]);
               dword_6BE364_game_settings_1 |= GAME_SETTINGS_0001;
-              uGameState = GAME_STATE_2;
+              uGameState = GAME_STATE_CHANGE_LOCATION;
               _5B65A8_npcdata_uflags_or_other = pPlayer9->pInstalledBeacons[uMessageParam].PartyPos_X;
               _5B65AC_npcdata_fame_or_other = pPlayer9->pInstalledBeacons[uMessageParam].PartyPos_Y;
               _5B65B0_npcdata_rep_or_other = pPlayer9->pInstalledBeacons[uMessageParam].PartyPos_Z;
@@ -3234,7 +3195,7 @@
                     SaveGame(1, 0);
                     OnMapLeave();
                     dword_6BE364_game_settings_1 |= GAME_SETTINGS_0001;
-                    uGameState = GAME_STATE_2;
+                    uGameState = GAME_STATE_CHANGE_LOCATION;
                     strcpy(pCurrentMapName, pMapStats->pInfos[TownPortalList[uMessageParam].uMapInfoID].pFilename);
                     dword_5B65C0 = 1;
                     _5B65A8_npcdata_uflags_or_other = TownPortalList[uMessageParam].pos.x;
@@ -3417,7 +3378,7 @@
               {
                 strcpy(pCurrentMapName, (const char *)&pGames_LOD->pSubIndices[(int)pNPCData3]);
                 dword_6BE364_game_settings_1 |= GAME_SETTINGS_0001;
-                uGameState = GAME_STATE_2;
+                uGameState = GAME_STATE_CHANGE_LOCATION;
                 OnMapLeave();
                 continue;
               }
@@ -3959,10 +3920,10 @@
             viewparams->bRedrawGameUI = 1;
           }
           stru_506E40.Release();
-          uNumSeconds = (unsigned int)MakeScreenshot(155, 117);
-          pRenderer->SavePCXImage("gamma.pcx", (char *)uNumSeconds, 155, 117);
-          free((void *)uNumSeconds);
-          stru_506E40._40E55E("gamma.pcx", 0);
+          screenshot = MakeScreenshot(155, 117);
+          pRenderer->SavePCXImage("gamma.pcx", screenshot, 155, 117);
+          free(screenshot);
+          stru_506E40.LoadPCXFile("gamma.pcx", 0);
           GUIWindow::Create(0x25Au, 0x1C2u, 0, 0, WINDOW_PressedButton, (int)pBtn_GameSettings, 0);
 //LABEL_453:
           /*if ( (signed int)pMessageQueue_50CBD0->uNumMessages >= 40 )
@@ -4515,12 +4476,14 @@
         case UIMSG_PlayerCreationRemoveUpSkill:
           v4 = pGUIWindow_CurrentMenu->pCurrentPosActiveItem - pGUIWindow_CurrentMenu->pStartingPosActiveItem;
           pGUIWindow_CurrentMenu->pCurrentPosActiveItem = v4 % 7 + pGUIWindow_CurrentMenu->pStartingPosActiveItem + 7 * pParam;
-          pParty->pPlayers[pParam].pActiveSkills[pPlayer[pParam].GetSkillIdxByOrder(2)] = 0;
+          if ( pPlayer[pParam].GetSkillIdxByOrder(2) != 37 )//37 - None()
+            pParty->pPlayers[pParam].pActiveSkills[pPlayer[pParam].GetSkillIdxByOrder(2)] = 0;
           break;
         case UIMSG_PlayerCreationRemoveDownSkill:
           v4 = pGUIWindow_CurrentMenu->pCurrentPosActiveItem - pGUIWindow_CurrentMenu->pStartingPosActiveItem;
           pGUIWindow_CurrentMenu->pCurrentPosActiveItem = v4 % 7 + pGUIWindow_CurrentMenu->pStartingPosActiveItem + 7 * pParam;
-          pParty->pPlayers[pParam].pActiveSkills[pPlayer[pParam].GetSkillIdxByOrder(3)] = 0;
+          if ( pPlayer[pParam].GetSkillIdxByOrder(3) != 37 )//37 - None()
+            pParty->pPlayers[pParam].pActiveSkills[pPlayer[pParam].GetSkillIdxByOrder(3)] = 0;
           break;
         case UIMSG_PlayerCreationChangeName:
           pAudioPlayer->PlaySound((SoundID)24, 0, 0, -1, 0, 0, 0, 0);
--- a/Game.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Game.h	Thu Jan 02 09:11:28 2014 +0600
@@ -16,7 +16,7 @@
 {
   GAME_STATE_PLAYING = 0,
   GAME_FINISHED = 1,
-  GAME_STATE_2 = 2,
+  GAME_STATE_CHANGE_LOCATION = 2,
   GAME_STATE_LOADING_GAME = 3,
   GAME_STATE_NEWGAME_OUT_GAMEMENU = 4,
   GAME_STATE_5 = 5,
--- a/IconFrameTable.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/IconFrameTable.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -36,34 +36,32 @@
 //----- (00494F70) --------------------------------------------------------
 IconFrame *IconFrameTable::GetFrame(unsigned int uIconID, unsigned int uFrameID)
 {
-  IconFrame *v3; // edi@1
+  //IconFrame *v3; // edi@1
   IconFrame *v4; // ecx@1
-  __int16 v5; // dx@2
+  //__int16 v5; // dx@2
   int v6; // edx@3
-  unsigned int v7; // eax@3
+  //unsigned int v7; // eax@3
   char *i; // ecx@3
   int v9; // esi@5
   IconFrame *result; // eax@6
 
-  v3 = this->pIcons;
-  v4 = &v3[uIconID];
-  if ( v4->uFlags & 1 && (v5 = v4->uAnimLength) != 0 )
+  v4 = &this->pIcons[uIconID];
+  if ( v4->uFlags & 1 && v4->uAnimLength != 0 )
   {
-    v6 = ((signed int)uFrameID >> 3) % (unsigned __int16)v5;
-    v7 = uIconID;
+    v6 = ((signed int)uFrameID >> 3) % (unsigned __int16)v4->uAnimLength;
     for ( i = (char *)&v4->uAnimTime; ; i += 32 )
     {
       v9 = *(short *)i;
       if ( v6 <= v9 )
         break;
       v6 -= v9;
-      ++v7;
+      ++uIconID;
     }
-    result = &v3[v7];
+    result = &this->pIcons[uIconID];
   }
   else
   {
-    result = &v3[uIconID];
+    result = &this->pIcons[uIconID];
   }
   return result;
 }
--- a/Indoor.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Indoor.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -554,7 +554,7 @@
           stru_F7B60C.face_plane.dist = pFace->pFacePlane.dist;
         }
 
-        if (stru_F8AD28.uNumLightsApplied > 0 && !(pFace->uAttributes & FACE_INDOOR_SKY))
+        if (stru_F8AD28.uNumLightsApplied > 0 && !pFace->Indoor_sky())
           pGame->pLightmapBuilder->ApplyLights(&stru_F8AD28, &stru_F7B60C, uNumVerticesa, array_507D30, pVertices, 0);
 
         if (pDecalBuilder->uNumDecals > 0)
@@ -578,7 +578,7 @@
             v27 = pBitmaps_LOD->pHardwareTextures[pFace->uBitmapID];
           }
         }
-        else if (pFace->uAttributes & 0x4000)
+        else if (pFace->uAttributes & FACE_TEXTURE_FRAME)
           v27 = pBitmaps_LOD->pHardwareTextures[pTextureFrameTable->GetFrameTexture(pFace->uBitmapID, pBLVRenderParams->field_0_timer_)];
         else
         {
@@ -586,7 +586,7 @@
           v27 = pBitmaps_LOD->pHardwareTextures[pFace->uBitmapID];
         }
 
-        if (pFace->uAttributes & FACE_INDOOR_SKY)
+        if (pFace->Indoor_sky())
           pRenderer->DrawIndoorSky(uNumVerticesa, uFaceID);
         else
           pRenderer->DrawIndoorPolygon(uNumVerticesa, pFace, v27, pFace->GetTexture(), PID(OBJECT_BModel, uFaceID), v17, 0);
@@ -619,7 +619,7 @@
   }
   else
   {
-    if ( pIndoor->pFaces[uFaceID].uAttributes & 0x40 )
+    if ( pIndoor->pFaces[uFaceID].uAttributes & FACE_DONT_CACHE_TEXTURE )
       stru_F8AD28.pDeltaUV[0] += result & pBitmaps_LOD->GetTexture(pIndoor->pFaces[uFaceID].uBitmapID)->uWidthMinus1;
   }
   return result;
@@ -937,61 +937,12 @@
   }
 }
 
-//----- (004B0967) --------------------------------------------------------
-void BspRenderer::DrawFaceOutlines()
-{
-  signed int i; // edi@1
-  int v1; // esi@2
-  unsigned int v2; // ecx@4
-  int v3; // eax@4
-  int v4; // eax@6
-  unsigned __int16 *v5; // edx@6
-  int v6; // ecx@7
-  int v7; // esi@8
-
-  for ( i = 0; i < (signed int)pBspRenderer->num_faces; ++i )
-  {
-    v1 = pBspRenderer->faces[i].uFaceID;
-    if ( v1 >= 0 )
-    {
-      if ( v1 < (signed int)pIndoor->uNumFaces )
-      {
-        v2 = pBspRenderer->faces[i].uFaceID;
-        pBLVRenderParams->field_7C = &pBspRenderer->nodes[pBspRenderer->faces[i].uNodeID].PortalScreenData;
-        v3 = GetPortalScreenCoord(v2);
-        if ( v3 )
-        {
-          if ( PortalFrustrum(v3, &stru_F8A590, pBLVRenderParams->field_7C, v1) )
-          {
-            v4 = stru_F8A590._viewport_space_y;
-            v5 = pBLVRenderParams->pRenderTarget;
-            if ( stru_F8A590._viewport_space_y <= stru_F8A590._viewport_space_w )
-            {
-              v6 = 640 * stru_F8A590._viewport_space_y;
-              do
-              {
-                v5[v6 + stru_F8A590.viewport_left_side[v4]] = -1;
-                v7 = v6 + stru_F8A590.viewport_right_side[v4];
-                v6 += 640;
-                v5[v7] = -1;
-                ++v4;
-              }
-              while ( v4 <= stru_F8A590._viewport_space_w );
-            }
-          }
-        }
-      }
-    }
-  }
-}
-
-
 //----- (004AE5BA) --------------------------------------------------------
 Texture *BLVFace::GetTexture()
 {
   unsigned int v1; // ecx@2
 
-  if ( uAttributes & 0x4000 )
+  if ( uAttributes & FACE_TEXTURE_FRAME )
     v1 = pTextureFrameTable->GetFrameTexture(this->uBitmapID, pBLVRenderParams->field_0_timer_);
   else
     v1 = uBitmapID;
@@ -1875,7 +1826,7 @@
     strncpy(pTexName, pData, 10);
     pData += 10;
 
-    if (pFace->uAttributes & 0x4000)
+    if (pFace->uAttributes & FACE_TEXTURE_FRAME)
     {
       pFace->uBitmapID = pTextureFrameTable->FindTextureByName(pTexName);
       if (pFace->uBitmapID)
@@ -1883,7 +1834,7 @@
       else
       {
         pFace->uBitmapID = pBitmaps_LOD->LoadTexture(pTexName);
-        pFace->uAttributes &= ~0x4000;
+        pFace->uAttributes &= ~FACE_TEXTURE_FRAME;
       }
     }
     else
@@ -2628,70 +2579,77 @@
 
 
 //----- (00498A41) --------------------------------------------------------
-char BLVFace::_get_normals(Vec3_int_ *a2, Vec3_int_ *a3)
+void BLVFace::_get_normals(Vec3_int_ *a2, Vec3_int_ *a3)
 {
-  BLVFace *v3; // ebx@1
-  int v4; // eax@1
-  signed __int64 v5; // qax@2
-  double v6; // st7@8
   Vec3_float_ a1; // [sp+Ch] [bp-Ch]@8
 
-  v3 = this;
-  LOBYTE(v4) = this->uPolygonType;
-  if ( (char)v4 == POLYGON_VerticalWall )
+  if ( this->uPolygonType == POLYGON_VerticalWall )
   {
     a2->x = -this->pFacePlane_old.vNormal.y;
-    LODWORD(v5) = this->pFacePlane_old.vNormal.x;
-LABEL_9:
-    a2->y = v5;
-    v4 = 0;
+    a2->y = this->pFacePlane_old.vNormal.x;
     a2->z = 0;
+
+    a3->x = 0;
     a3->y = 0;
     a3->z = 0xFFFF0000u;
-LABEL_11:
-    a3->x = v4;
+
     goto LABEL_12;
   }
-  if ( (char)v4 == POLYGON_Floor || (char)v4 == POLYGON_Ceiling )
-  {
-LABEL_10:
-    v4 = 0;
+  if ( this->uPolygonType == POLYGON_Floor || this->uPolygonType == POLYGON_Ceiling )
+  {
     a2->x = 0x10000u;
+    a2->y = 0;
     a2->z = 0;
-    a2->y = 0;
+
+    a3->x = 0;
     a3->y = 0xFFFF0000u;
     a3->z = 0;
-    goto LABEL_11;
-  }
-  if ( (char)v4 == POLYGON_InBetweenFloorAndWall || (char)v4 == POLYGON_InBetweenCeilingAndWall )
+
+    goto LABEL_12;
+  }
+  if ( this->uPolygonType == POLYGON_InBetweenFloorAndWall || this->uPolygonType == POLYGON_InBetweenCeilingAndWall )
   {
     if ( abs(this->pFacePlane_old.vNormal.z) < 46441 )
     {
-      a1.x = (double)-v3->pFacePlane_old.vNormal.y;
-      a1.y = (double)v3->pFacePlane_old.vNormal.x;
+      a1.x = (double)-this->pFacePlane_old.vNormal.y;
+      a1.y = (double)this->pFacePlane_old.vNormal.x;
       a1.z = 0.0;
       a1.Normalize();
-      v6 = a1.y * 65536.0;
+
       a2->x = (signed __int64)(a1.x * 65536.0);
-      v5 = (signed __int64)v6;
-      goto LABEL_9;
+      a2->y = (signed __int64)(a1.y * 65536.0);
+      a2->z = 0;
+
+      a3->y = 0;
+      a3->z = 0xFFFF0000u;
+      a3->x = 0;
+
+      goto LABEL_12;
     }
-    goto LABEL_10;
+    a2->x = 0x10000u;
+    a2->y = 0;
+    a2->z = 0;
+
+    a3->x = 0;
+    a3->y = 0xFFFF0000u;
+    a3->z = 0;
+
+    goto LABEL_12;
   }
 LABEL_12:
-  if ( BYTE2(v3->uAttributes) & 0x80 )
+  if ( BYTE2(this->uAttributes) & 0x80 )
   {
     a2->x = -a2->x;
     a2->y = -a2->y;
     a2->z = -a2->z;
   }
-  if ( BYTE3(v3->uAttributes) & 1 )
+  if ( BYTE3(this->uAttributes) & 1 )
   {
     a3->x = -a3->x;
     a3->y = -a3->y;
     a3->z = -a3->z;
   }
-  return v4;
+  return;
 }
 
 //----- (0044C23B) --------------------------------------------------------
@@ -2718,46 +2676,22 @@
     return true;
 }
 
-
-
-
 //----- (0046F228) --------------------------------------------------------
 void  BLV_UpdateDoors()
 {
-  //int v0; // ebx@1
-  //int v1; // edi@1
-  //BLVDoor *v2; // esi@3
-  //unsigned __int16 v3; // ax@3
-  //unsigned int v4; // ecx@5
-  //int v5; // eax@8
-  //int v6; // ecx@8
-  //int v7; // eax@12
-  //int v8; // eax@16
-  //unsigned __int8 v9; // zf@18
-  //char v10; // sf@18
-  //unsigned __int8 v11; // of@18
-  //int v12; // edi@19
-  //int v13; // ecx@19
-  //__int16 v14; // ax@19
-  BLVFace *v15; // ebx@24
-  //unsigned __int16 *v16; // ecx@24
+  BLVFace *face; // ebx@24
   Vec3_short_ *v17; // esi@24
   int v18; // eax@24
   int v19; // edx@24
   signed int v20; // eax@24
-  //Vec3_short_ *v21; // ecx@24
-  //double v22; // st7@24
-  //double v23; // st6@24
   int v24; // esi@25
   int v25; // eax@25
-  //BLVDoor *v26; // edi@25
   signed __int64 v27; // qtt@27
   BLVFaceExtra *v28; // esi@32
   int v29; // ecx@34
   int v30; // edx@34
   unsigned __int64 v31; // qax@34
   int v32; // eax@34
-  //unsigned __int16 *v33; // eax@35
   Vec3_short_ *v34; // eax@35
   int v35; // ecx@35
   int v36; // edx@35
@@ -2765,381 +2699,187 @@
   signed int v38; // edx@35
   int v39; // eax@35
   int v40; // edx@35
-  //unsigned __int8 v41; // cf@35
-  //unsigned __int16 *v42; // edi@36
   Vec3_short_ *v43; // edi@36
-  //int v44; // ecx@36
-  //int v45; // edi@36
-  //int v46; // ecx@36
-  //__int16 *v47; // edx@44
-  //int v48; // ecx@44
   unsigned int v49; // ecx@46
   unsigned __int16 v50; // ax@48
   unsigned int v51; // eax@51
   unsigned __int16 v52; // ax@54
   int v53; // ecx@57
-  //int v54; // edx@57
   unsigned __int64 v55; // qax@57
   int v56; // ecx@58
   int v57; // eax@58
-  //int v58; // eax@59
-  //SoundID v59; // [sp-24h] [bp-88h]@12
-  //signed int v60; // [sp-20h] [bp-84h]@12
-  //unsigned int v61; // [sp-1Ch] [bp-80h]@12
-  //signed int v62; // [sp-18h] [bp-7Ch]@12
-  //signed int v63; // [sp-14h] [bp-78h]@12
-  //int v64; // [sp-10h] [bp-74h]@12
-  //unsigned int v65; // [sp-Ch] [bp-70h]@12
-  //int v66; // [sp-8h] [bp-6Ch]@12
   Vec3_int_ v67;
-  //int v67; // [sp+8h] [bp-5Ch]@31
-  //int v68; // [sp+Ch] [bp-58h]@34
-  //int v69; // [sp+10h] [bp-54h]@34
   Vec3_int_ v70;
-  //int v70; // [sp+14h] [bp-50h]@31
-  //int v71; // [sp+18h] [bp-4Ch]@34
-  //int v72; // [sp+1Ch] [bp-48h]@34
   int v73; // [sp+20h] [bp-44h]@24
-  //__int16 v74; // [sp+24h] [bp-40h]@24
   int v75; // [sp+28h] [bp-3Ch]@36
   int v76; // [sp+2Ch] [bp-38h]@36
   int v77; // [sp+30h] [bp-34h]@36
-  //int v78; // [sp+34h] [bp-30h]@36
-  //int v79; // [sp+38h] [bp-2Ch]@19
-  //unsigned int v80; // [sp+3Ch] [bp-28h]@2
-  //int v81; // [sp+40h] [bp-24h]@1
   int v82; // [sp+44h] [bp-20h]@35
   int v83; // [sp+48h] [bp-1Ch]@34
   int v84; // [sp+4Ch] [bp-18h]@34
   int v85; // [sp+50h] [bp-14h]@19
   SoundID eDoorSoundID; // [sp+54h] [bp-10h]@1
-  //BLVDoor *v87; // [sp+58h] [bp-Ch]@3
   int v88; // [sp+5Ch] [bp-8h]@18
   int v89; // [sp+60h] [bp-4h]@6
 
-  //v0 = 0;
-  //v1 = 0;
   eDoorSoundID = (SoundID)pDoorSoundIDsByLocationID[dword_6BE13C_uCurrentlyLoadedLocationID];
-  //v81 = 0;
-  //if ( pIndoor->uNumDoors > 0 )
   for (uint i = 0; i < pIndoor->uNumDoors; ++i)
   {
     BLVDoor* door = &pIndoor->pDoors[i];
-    //v80 = 0;
-    //do
-    //{
-      //v2 = &pIndoor->pDoors[v80 / 0x50];
-      //v87 = &pIndoor->pDoors[v80 / 0x50];
-      //v3 = door->uState;
-      if (door->uState == BLVDoor::Closed || door->uState == BLVDoor::Open)
+    if (door->uState == BLVDoor::Closed || door->uState == BLVDoor::Open)
+    {
+      door->uAttributes &= 0xFFFFFFFDu;
+      continue;
+    }
+    door->uTimeSinceTriggered += pEventTimer->uTimeElapsed;
+    if (door->uState == BLVDoor::Opening)
+    {
+      v89 = (signed int)(door->uTimeSinceTriggered * door->uCloseSpeed) / 128;
+      if ( v89 >= door->uMoveLength )
+      {
+        v89 = door->uMoveLength;
+        door->uState = BLVDoor::Open;
+        if ( !(door->uAttributes & 6) && door->uNumVertices != 0)
+          pAudioPlayer->PlaySound((SoundID)((int)eDoorSoundID + 1), PID(OBJECT_BLVDoor,i), 0, -1, 0, 0, 0, 0);
+        goto LABEL_18;
+      }
+    }
+    else
+    {
+      signed int v5 = (signed int)(door->uTimeSinceTriggered * door->uOpenSpeed) / 128;
+      if ( v5 >= door->uMoveLength)
       {
-        door->uAttributes &= 0xFFFFFFFDu;
-        goto LABEL_62;
+        v89 = 0;
+        door->uState = BLVDoor::Closed;
+        if ( !(door->uAttributes & 6) && door->uNumVertices != 0)
+          pAudioPlayer->PlaySound((SoundID)((int)eDoorSoundID + 1), PID(OBJECT_BLVDoor,i), 0, -1, 0, 0, 0, 0);
+        goto LABEL_18;
       }
-      door->uTimeSinceTriggered += pEventTimer->uTimeElapsed;
-      //v4 = door->uTimeSinceTriggered;
-      if (door->uState == BLVDoor::Opening)
+      v89 = door->uMoveLength - v5;
+    }
+    if ( !(door->uAttributes & 6) && door->uNumVertices)
+      pAudioPlayer->PlaySound(eDoorSoundID, PID(OBJECT_BLVDoor,i), 1, -1, 0, 0, 0, 0);
+LABEL_18:
+    for (uint j = 0; j < door->uNumVertices; ++j)
+    {
+      pIndoor->pVertices[door->pVertexIDs[j]].x = ((unsigned int)(door->vDirection.x * v89) >> 16) + door->pXOffsets[j];
+      pIndoor->pVertices[door->pVertexIDs[j]].y = ((unsigned int)(door->vDirection.y * v89) >> 16) + door->pYOffsets[j];
+      pIndoor->pVertices[door->pVertexIDs[j]].z = ((unsigned int)(door->vDirection.z * v89) >> 16) + door->pZOffsets[j];
+    }
+    for ( v88 = 0; v88 < door->uNumFaces; ++v88 )
+    {
+      face = &pIndoor->pFaces[door->pFaceIDs[v88]];
+      v17 = &pIndoor->pVertices[face->pVertexIDs[0]];
+      v18 = face->pFacePlane_old.vNormal.y;
+      v73 = *(int *)&v17->x;
+      v19 = face->pFacePlane_old.vNormal.z;
+      v20 = -(v19 * (int)v17->z + (signed __int16)v73 * face->pFacePlane_old.vNormal.x + SHIWORD(v73) * v18);
+      face->pFacePlane_old.dist = v20;
+      face->pFacePlane.dist = -((double)v17->z * face->pFacePlane.vNormal.z
+                             + (double)v17->y * face->pFacePlane.vNormal.y
+                             + (double)v17->x * face->pFacePlane.vNormal.x);
+      if ( v19 )
       {
-        v89 = (signed int)(door->uTimeSinceTriggered * door->uCloseSpeed) / 128;
-        if ( v89 >= door->uMoveLength )
-        {
-          v89 = door->uMoveLength;
-          door->uState = BLVDoor::Open;
-LABEL_10:
-          if ( !(door->uAttributes & 6) && door->uNumVertices != 0)
-          {
-            //v66 = 0;
-            //v65 = 0;
-            //v64 = 0;
-            //v7 = PID(OBJECT_BLVDoor,i);
-            //v63 = 0;
-            //v62 = -1;
-            //LOBYTE(v7) = PID(OBJECT_BLVDoor,i);
-            //v61 = 0;
-            //v60 = PID(OBJECT_BLVDoor,i);
-            //v59 = (SoundID)((int)eDoorSoundID + 1);
-//LABEL_17:
-            pAudioPlayer->PlaySound((SoundID)((int)eDoorSoundID + 1), PID(OBJECT_BLVDoor,i), 0, -1, 0, 0, 0, 0);
-            //goto LABEL_18;
-          }
-          goto LABEL_18;
-        }
+        v24 = abs(v20 >> 15);
+        v25 = abs(face->pFacePlane_old.vNormal.z);
+        if ( v24 > v25 )
+          Error("Door Error\ndoor id: %i\nfacet no: %i\n\nOverflow dividing facet->d [%i] by facet->nz [%i]",
+            door->uDoorID, door->pFaceIDs[v88], face->pFacePlane_old.dist, face->pFacePlane_old.vNormal.z);
+        LODWORD(v27) = face->pFacePlane_old.dist << 16;
+        HIDWORD(v27) = face->pFacePlane_old.dist >> 16;
+        face->zCalc3 = -v27 / face->pFacePlane_old.vNormal.z;
+      }
+      if ( face->uAttributes & FACE_TEXTURE_FLOW || pRenderer->pRenderD3D )
+        face->_get_normals(&v70, &v67);
+      v28 = &pIndoor->pFaceExtras[face->uFaceExtraID];
+      if ( !pRenderer->pRenderD3D )
+      {
+        if ( !(face->uAttributes & FACE_TEXTURE_FLOW) )
+          continue;
+        v83 = (unsigned __int64)(door->vDirection.x * (signed __int64)v70.x) >> 16;
+        v85 = (unsigned __int64)(door->vDirection.y * (signed __int64)v70.y) >> 16;
+        v84 = (unsigned __int64)(door->vDirection.z * (signed __int64)v70.z) >> 16;
+        v29 = v89;
+        v28->sTextureDeltaU = -((v83 + v85 + v84) * (signed __int64)v89) >> 16;
+        v85 = (unsigned __int64)(door->vDirection.x * (signed __int64)v67.x) >> 16;
+        v83 = (unsigned __int64)(door->vDirection.y * (signed __int64)v67.y) >> 16;
+        v84 = (unsigned __int64)(door->vDirection.z * (signed __int64)v67.z) >> 16;
+        v31 = (v85 + v83 + v84) * (signed __int64)v29;
+        v32 = v31 >> 16;
+        goto LABEL_58;
       }
+      v28->sTextureDeltaU = 0;
+      v28->sTextureDeltaV = 0;
+      v34 = &pIndoor->pVertices[face->pVertexIDs[0]];
+      v35 = v34->z;
+      v36 = v34->y;
+      v82 = v34->x;
+      v37 = v70.x * v82 + v70.y * v36 + v70.z * v35;
+      v38 = v67.x * v82 + v67.y * v36 + v67.z * v35;
+      v39 = v37 >> 16;
+      *face->pVertexUIDs = v39;
+      v40 = v38 >> 16;
+      *face->pVertexVIDs = v40;
+      v84 = v39;
+      v82 = v40;
+      for (uint j = 1; j < face->uNumVertices; ++j)
+      {
+        v43 = &pIndoor->pVertices[face->pVertexIDs[j]];
+        v76 = ((__int64)v70.z * v43->z + (__int64)v70.x * v43->x + (__int64)v70.y * v43->y) >> 16;
+        v77 = ((__int64)v67.x * v43->x + (__int64)v67.y * v43->y + (__int64)v43->z * v67.z) >> 16;
+        if ( v76 < v39 )
+          v39 = v76;
+        if ( v77 < v40 )
+          v40 = v77;
+        if ( v76 > v84 )
+          v84 = v76;
+        if ( v77 > v82 )
+          v82 = v77;
+        face->pVertexUIDs[j] = v76;
+        face->pVertexVIDs[j] = v77;
+      }
+      if ( face->uAttributes & FACE_UNKNOW3 )
+        v28->sTextureDeltaU -= v39;
       else
       {
-        signed int v5 = (signed int)(door->uTimeSinceTriggered * door->uOpenSpeed) / 128;
-        //v6 = door->uMoveLength;
-        if ( v5 >= door->uMoveLength)
+        if ( SBYTE1(face->uAttributes) < 0 )
         {
-          v89 = 0;
-          door->uState = BLVDoor::Closed;
-          goto LABEL_10;
+          if ( face->uBitmapID != -1 )
+            v28->sTextureDeltaU -= v84 + pBitmaps_LOD->pTextures[face->uBitmapID].uTextureWidth;
         }
-        v89 = door->uMoveLength - v5;
-      }
-      if ( !(door->uAttributes & 6) && door->uNumVertices)
-      {
-        //v66 = 0;
-        //v65 = 0;
-        //v64 = 0;
-        //v8 = PID(OBJECT_BLVDoor,i);
-        //v63 = 0;
-        //v62 = -1;
-        //LOBYTE(v8) = 8 * v1 | 1;
-        //v61 = 1;
-        //v60 = PID(OBJECT_BLVDoor,i);
-        //v59 = eDoorSoundID;
-        pAudioPlayer->PlaySound(eDoorSoundID, PID(OBJECT_BLVDoor,i), 1, -1, 0, 0, 0, 0);
-        //goto LABEL_18;
       }
-LABEL_18:
-      //v11 = __OFSUB__(v2->uNumVertices, 0);
-      //v9 = v2->uNumVertices == 0;
-      //v10 = (signed __int16)(v2->uNumVertices - 0) < 0;
-      //v88 = 0;
-      //if (door->uNumVertices > 0)
-      for (uint j = 0; j < door->uNumVertices; ++j)
+      if ( face->uAttributes & 8 )
+        v28->sTextureDeltaV -= v40;
+      else
       {
-        //do
-        //{
-          //v12 = v88;
-          //v13 = door->pVertexIDs[v88];
-          //v85 = v89;
-          //v79 = door->vDirection.x;
-          //v85 = (unsigned __int64)(v79 * (signed __int64)v89) >> 16;
-          //v13 *= 6;
-          pIndoor->pVertices[door->pVertexIDs[j]].x = ((unsigned int)(door->vDirection.x * v89) >> 16) + door->pXOffsets[j];
-          //v85 = v89;
-          //v79 = door->vDirection.y;
-          //v85 = (unsigned __int64)(v79 * (signed __int64)v89) >> 16;
-          pIndoor->pVertices[door->pVertexIDs[j]].y = ((unsigned int)(door->vDirection.y * v89) >> 16) + door->pYOffsets[j];
-          //v85 = v89;
-          //v79 = door->vDirection.z;
-          //v85 = (unsigned __int64)(v79 * (signed __int64)v89) >> 16;
-          //v14 = ((unsigned int)(door->vDirection.z * v89) >> 16) + door->pZOffsets[j];
-          pIndoor->pVertices[door->pVertexIDs[j]].z = ((unsigned int)(door->vDirection.z * v89) >> 16) + door->pZOffsets[j];
-          //++v88;
-        //}
-        //while ( v88 < door->uNumVertices );
-        //v1 = v81;
-      }
-      //v11 = __OFSUB__(v2->uNumFaces, 0);
-      //v9 = v2->uNumFaces == 0;
-      //v10 = (signed __int16)(v2->uNumFaces - 0) < 0;
-      v88 = 0;
-      if (door->uNumFaces > 0)
-      {
-        while ( 1 )
+        if ( face->uAttributes & 0x20000 )
         {
-          v15 = &pIndoor->pFaces[door->pFaceIDs[v88]];
-          //v16 = v15->pVertexIDs;
-          v17 = &pIndoor->pVertices[v15->pVertexIDs[0]];
-          v18 = v15->pFacePlane_old.vNormal.y;
-          v73 = *(int *)&v17->x;
-          //v74 = v17->z;
-          v19 = v15->pFacePlane_old.vNormal.z;
-          v20 = -(v19 * (int)v17->z + (signed __int16)v73 * v15->pFacePlane_old.vNormal.x + SHIWORD(v73) * v18);
-          v15->pFacePlane_old.dist = v20;
-          //v21 = &pIndoor->pVertices[v15->pVertexIDs[0]];
-          //v79 = v21->x;
-          //v22 = (double)v21->x;
-          //v23 = (double)v21->y;
-          //v79 = v21->z;
-          v15->pFacePlane.dist = -((double)v17->z * v15->pFacePlane.vNormal.z
-                                 + (double)v17->y * v15->pFacePlane.vNormal.y
-                                 + (double)v17->x * v15->pFacePlane.vNormal.x);
-          if ( v19 )
-          {
-            v24 = abs(v20 >> 15);
-            v25 = abs(v15->pFacePlane_old.vNormal.z);
-            //v26 = v87;
-            if ( v24 > v25 )
-              Error("Door Error\ndoor id: %i\nfacet no: %i\n\nOverflow dividing facet->d [%i] by facet->nz [%i]",
-                door->uDoorID,
-                door->pFaceIDs[v88],
-                v15->pFacePlane_old.dist,
-                v15->pFacePlane_old.vNormal.z);
-            //v79 = v15->pFacePlane_old.vNormal.z;
-            //v85 = v15->pFacePlane_old.dist;
-            LODWORD(v27) = v15->pFacePlane_old.dist << 16;
-            HIDWORD(v27) = v15->pFacePlane_old.dist >> 16;
-            //v85 = v27 / v15->pFacePlane_old.vNormal.z;
-            v15->zCalc3 = -v27 / v15->pFacePlane_old.vNormal.z;
-          }
-          /*else
-          {
-            v26 = v87;
-          }*/
-          if ( BYTE2(v15->uAttributes) & 4 || pRenderer->pRenderD3D )
-            v15->_get_normals(&v70, &v67);
-          v28 = &pIndoor->pFaceExtras[v15->uFaceExtraID];
-          if ( !pRenderer->pRenderD3D )
-          {
-            if ( !(BYTE2(v15->uAttributes) & 4) )
-              goto LABEL_59;
-            //v79 = door->vDirection.x;
-            v83 = (unsigned __int64)(door->vDirection.x * (signed __int64)v70.x) >> 16;
-            //v85 = v71;
-            //v79 = door->vDirection.y;
-            v85 = (unsigned __int64)(door->vDirection.y * (signed __int64)v70.y) >> 16;
-            //v84 = v72;
-            //v79 = door->vDirection.z;
-            v84 = (unsigned __int64)(door->vDirection.z * (signed __int64)v70.z) >> 16;
-            //v79 = v83 + v85 + v84;
-            v29 = v89;
-            //v83 = (unsigned __int64)(v79 * (signed __int64)v89) >> 16;
-            v28->sTextureDeltaU = -((v83 + v85 + v84) * (signed __int64)v89) >> 16;
-            //v79 = door->vDirection.x;
-            v85 = (unsigned __int64)(door->vDirection.x * (signed __int64)v67.x) >> 16;
-            //v83 = v68;
-            //v79 = door->vDirection.y;
-            v83 = (unsigned __int64)(door->vDirection.y * (signed __int64)v67.y) >> 16;
-            //v84 = v69;
-            //v79 = door->vDirection.z;
-            v84 = (unsigned __int64)(door->vDirection.z * (signed __int64)v67.z) >> 16;
-            //v30 = v83 + v84;
-            //v79 = v85 + v30;
-            v31 = (v85 + v83 + v84) * (signed __int64)v29;
-            //v83 = v31 >> 16;
-            v32 = v31 >> 16;
-            goto LABEL_58;
-          }
-          v28->sTextureDeltaU = 0;
-          v28->sTextureDeltaV = 0;
-          //v33 = v15->pVertexIDs;
-          //v85 = 1;
-          v34 = &pIndoor->pVertices[v15->pVertexIDs[0]];
-          v35 = v34->z;
-          v36 = v34->y;
-          v82 = v34->x;
-          //v79 = v36;
-          v37 = v70.x * v82 + v70.y * v36 + v70.z * v35;
-          v38 = v67.x * v82 + v67.y * v36 + v67.z * v35;
-          v39 = v37 >> 16;
-          *v15->pVertexUIDs = v39;
-          v40 = v38 >> 16;
-          *v15->pVertexVIDs = v40;
-          //v41 = v15->uNumVertices < 1u;
-          //v9 = v15->uNumVertices == 1;
-          //v83 = v40;
-          v84 = v39;
-          v82 = v40;
-          //if (v15->uNumVertices > 1)
-          for (uint j = 1; j < v15->uNumVertices; ++j)
-          {
-            //do
-            //{
-              //v42 = v15->pVertexIDs;
-              //v75 = 2 * v85;
-              v43 = &pIndoor->pVertices[v15->pVertexIDs[j]];
-              //v79 = v43->z;
-              //v44 = v43->y;
-              //v45 = v43->x;
-              //v78 = v43->y;
-              v76 = ((__int64)v70.z * v43->z + (__int64)v70.x * v43->x + (__int64)v70.y * v43->y) >> 16;
-              //v46 = (v67 * v45 + v68 * v44 + v79 * v69) >> 16;
-              v77 = ((__int64)v67.x * v43->x + (__int64)v67.y * v43->y + (__int64)v43->z * v67.z) >> 16;
-              if ( v76 < v39 )
-                v39 = v76;
-              if ( v77 < v40 )
-                v40 = v77;
-              if ( v76 > v84 )
-                v84 = v76;
-              if ( v77 > v82 )
-                v82 = v77;
-              //v40 = v83;
-              //v47 = v15->pVertexUIDs;
-              //v48 = v75;
-              //++v85;
-              v15->pVertexUIDs[j] = v76;
-              v15->pVertexVIDs[j] = v77;
-            //}
-            //while ( v85 < v15->uNumVertices );
-            //v26 = v87;
-          }
-          v49 = v15->uAttributes;
-          if ( BYTE1(v49) & 0x10 )
-            goto LABEL_50;
-          if ( SBYTE1(v49) < 0 )
-          {
-            v50 = v15->uBitmapID;
-            if ( v50 != -1 )
-              break;
-          }
-LABEL_51:
-          v51 = v15->uAttributes;
-          if ( v51 & 8 )
-          {
-            v28->sTextureDeltaV -= v40;
-          }
-          else
-          {
-            if ( v51 & 0x20000 )
-            {
-              v52 = v15->uBitmapID;
-              if ( v52 != -1 )
-                v28->sTextureDeltaV -= v82 + pBitmaps_LOD->GetTexture(v52)->uTextureHeight;
-            }
-          }
-          if ( BYTE2(v15->uAttributes) & 4 )
-          {
-            //v75 = door->vDirection.x;
-            v84 = (unsigned __int64)(door->vDirection.x * (signed __int64)v70.x) >> 16;
-            //v82 = v71;
-            //v75 = door->vDirection.y;
-            v82 = (unsigned __int64)(door->vDirection.y * (signed __int64)v70.y) >> 16;
-            //v83 = v72;
-            //v75 = door->vDirection.z;
-            v83 = (unsigned __int64)(door->vDirection.z * (signed __int64)v70.z) >> 16;
-            v75 = v84 + v82 + v83;
-            v53 = v89;
-            v82 = (unsigned __int64)(v75 * (signed __int64)v89) >> 16;
-            v28->sTextureDeltaU = -v82;
-            //v75 = door->vDirection.x;
-            v84 = (unsigned __int64)(door->vDirection.x * (signed __int64)v67.x) >> 16;
-            //v82 = v68;
-            //v75 = door->vDirection.y;
-            v82 = (unsigned __int64)(door->vDirection.y * (signed __int64)v67.y) >> 16;
-            //v83 = v69;
-            //v75 = door->vDirection.z;
-            v83 = (unsigned __int64)(door->vDirection.z * (signed __int64)v67.z) >> 16;
-            //v54 = v82 + v83;
-            v75 = v84 + v82 + v83;
-            v55 = v75 * (signed __int64)v53;
-            //v82 = v55 >> 16;
-            v32 = v55 >> 16;
+          if ( face->uBitmapID != -1 )
+            v28->sTextureDeltaV -= v82 + pBitmaps_LOD->GetTexture(face->uBitmapID)->uTextureHeight;
+        }
+      }
+      if ( face->uAttributes & FACE_TEXTURE_FLOW )
+      {
+        v84 = (unsigned __int64)(door->vDirection.x * (signed __int64)v70.x) >> 16;
+        v82 = (unsigned __int64)(door->vDirection.y * (signed __int64)v70.y) >> 16;
+        v83 = (unsigned __int64)(door->vDirection.z * (signed __int64)v70.z) >> 16;
+        v75 = v84 + v82 + v83;
+        v53 = v89;
+        v82 = (unsigned __int64)(v75 * (signed __int64)v89) >> 16;
+        v28->sTextureDeltaU = -v82;
+        v84 = (unsigned __int64)(door->vDirection.x * (signed __int64)v67.x) >> 16;
+        v82 = (unsigned __int64)(door->vDirection.y * (signed __int64)v67.y) >> 16;
+        v83 = (unsigned __int64)(door->vDirection.z * (signed __int64)v67.z) >> 16;
+        v75 = v84 + v82 + v83;
+        v55 = v75 * (signed __int64)v53;
+        v32 = v55 >> 16;
 LABEL_58:
-            v56 = v88;
-            v57 = -v32;
-            v28->sTextureDeltaV = v57;
-            v28->sTextureDeltaU += door->pDeltaUs[v56];
-            v28->sTextureDeltaV = v57 + door->pDeltaVs[v56];
-          }
-LABEL_59:
-          //v58 = door->uNumFaces;
-          ++v88;
-          if ( v88 >= door->uNumFaces)
-          {
-            //v1 = v81;
-            //v0 = 0;
-            goto LABEL_62;
-          }
-          //v2 = v87;
-        }
-        LOWORD(v39) = v84;
-        if (v15->uBitmapID != -1)
-          LOWORD(v39) += pBitmaps_LOD->pTextures[v15->uBitmapID].uTextureWidth;
-LABEL_50:
-        v28->sTextureDeltaU -= v39;
-        goto LABEL_51;
+        v57 = -v32;
+        v28->sTextureDeltaV = v57;
+        v28->sTextureDeltaU += door->pDeltaUs[v88];
+        v28->sTextureDeltaV = v57 + door->pDeltaVs[v88];
       }
-LABEL_62:
-      ;
-      //v80 += 80;
-      //++v1;
-      //v81 = v1;
-    //}
-    //while ( v1 < pIndoor->uNumDoors );
+    }
   }
 }
 // 6BE13C: using guessed type int dword_6BE13C_uCurrentlyLoadedLocationID;
@@ -7298,7 +7038,7 @@
             v1 = 0;
             v2 = 0;
           }
-          if ( pParty->floor_face_pid != PID_ID(stru_721530.uFaceID) && BYTE3(pFace->uAttributes) & 4 )
+          if ( pParty->floor_face_pid != PID_ID(stru_721530.uFaceID) && pFace->Pressure_Plate() )
             uFaceEvent = pIndoor->pFaceExtras[pFace->uFaceExtraID].uEventID;
         }
         else
@@ -7323,7 +7063,7 @@
               new_party_y += v52 * pFace->pFacePlane_old.vNormal.y >> 16;
               v87 += v52 * pFace->pFacePlane_old.vNormal.z >> 16;
             }
-            if ( pParty->floor_face_pid != PID_ID(stru_721530.uFaceID) && BYTE3(pFace->uAttributes) & 4 )
+            if ( pParty->floor_face_pid != PID_ID(stru_721530.uFaceID) && pFace->Pressure_Plate() )
               uFaceEvent = pIndoor->pFaceExtras[pFace->uFaceExtraID].uEventID;
           }
           if ( pFace->uPolygonType == POLYGON_InBetweenFloorAndWall )
@@ -7336,7 +7076,7 @@
             pParty->uFallSpeed += (unsigned __int64)(v80 * (signed __int64)pFace->pFacePlane_old.vNormal.z) >> 16;
             if ( v2 * v2 + v1 * v1 >= 400 )
             {
-              if ( pParty->floor_face_pid != PID_ID(stru_721530.uFaceID) && BYTE3(pFace->uAttributes) & 4 )
+              if ( pParty->floor_face_pid != PID_ID(stru_721530.uFaceID) && pFace->Pressure_Plate() )
                 uFaceEvent = pIndoor->pFaceExtras[pFace->uFaceExtraID].uEventID;
             }
             else
@@ -7410,4 +7150,98 @@
     pParty->uFlags |= 0x200;
   if (uFaceEvent)
     EventProcessor(uFaceEvent, 0, 1);
+}
+
+//----- (00449A49) --------------------------------------------------------
+void Door_switch_animation(unsigned int uDoorID, int a2)
+{
+  int old_state; // eax@1
+  signed int door_id; // esi@2
+
+  if ( !pIndoor->pDoors )
+    return;
+  for ( door_id = 0; door_id < 200; ++door_id )
+  {
+    if ( pIndoor->pDoors[door_id].uDoorID == uDoorID )
+      break;
+  }
+  if ( door_id >= 200 )
+  {
+    Error("Unable to find Door ID: %i!", uDoorID);
+  }
+  old_state = pIndoor->pDoors[door_id].uState;
+  //old_state: 0 -   /
+  //           2 -   /,
+  //a2: 1 - 
+  //    2 - /
+  if ( a2 == 2 )
+  {
+    if ( pIndoor->pDoors[door_id].uState == BLVDoor::Closing || pIndoor->pDoors[door_id].uState == BLVDoor::Opening )
+      return;
+    if ( pIndoor->pDoors[door_id].uState )
+    {
+      if ( pIndoor->pDoors[door_id].uState != BLVDoor::Closed && pIndoor->pDoors[door_id].uState != BLVDoor::Closing )
+      {
+        pIndoor->pDoors[door_id].uState = BLVDoor::Closing;
+        if ( old_state == BLVDoor::Open )
+        {
+          pIndoor->pDoors[door_id].uTimeSinceTriggered = 0;
+          return;
+        }
+        if ( pIndoor->pDoors[door_id].uTimeSinceTriggered != 15360 )
+        {
+          pIndoor->pDoors[door_id].uTimeSinceTriggered = (pIndoor->pDoors[door_id].uMoveLength << 7) / pIndoor->pDoors[door_id].uOpenSpeed
+             - ((signed int)(pIndoor->pDoors[door_id].uTimeSinceTriggered * pIndoor->pDoors[door_id].uCloseSpeed)
+             / 128 << 7) / pIndoor->pDoors[door_id].uOpenSpeed;
+          return;
+        }
+        pIndoor->pDoors[door_id].uTimeSinceTriggered = 15360;
+      }
+      return;
+    }
+  }
+  else
+  {
+    if ( a2 == 0 )
+    {
+      if ( pIndoor->pDoors[door_id].uState != BLVDoor::Closed && pIndoor->pDoors[door_id].uState != BLVDoor::Closing )
+      {
+        pIndoor->pDoors[door_id].uState = BLVDoor::Closing;
+        if ( old_state == BLVDoor::Open )
+        {
+          pIndoor->pDoors[door_id].uTimeSinceTriggered = 0;
+          return;
+        }
+        if ( pIndoor->pDoors[door_id].uTimeSinceTriggered != 15360 )
+        {
+          pIndoor->pDoors[door_id].uTimeSinceTriggered = (pIndoor->pDoors[door_id].uMoveLength << 7) / pIndoor->pDoors[door_id].uOpenSpeed
+             - ((signed int)(pIndoor->pDoors[door_id].uTimeSinceTriggered * pIndoor->pDoors[door_id].uCloseSpeed)
+             / 128 << 7) / pIndoor->pDoors[door_id].uOpenSpeed;
+          return;
+        }
+        pIndoor->pDoors[door_id].uTimeSinceTriggered = 15360;
+      }
+      return;
+    }
+    if ( a2 != 1 )
+      return;
+  }
+  if ( old_state != BLVDoor::Open && old_state != BLVDoor::Opening )
+  {
+    pIndoor->pDoors[door_id].uState = BLVDoor::Opening;
+    if ( old_state == BLVDoor::Closed )
+    {
+      pIndoor->pDoors[door_id].uTimeSinceTriggered = 0;
+      return;
+    }
+    if ( pIndoor->pDoors[door_id].uTimeSinceTriggered != 15360 )
+    {
+      pIndoor->pDoors[door_id].uTimeSinceTriggered = (pIndoor->pDoors[door_id].uMoveLength << 7) / pIndoor->pDoors[door_id].uCloseSpeed
+         - ((signed int)(pIndoor->pDoors[door_id].uTimeSinceTriggered * pIndoor->pDoors[door_id].uOpenSpeed)
+         / 128 << 7) / pIndoor->pDoors[door_id].uCloseSpeed;
+      return;
+    }
+    pIndoor->pDoors[door_id].uTimeSinceTriggered = 15360;
+  }
+  return;
 }
\ No newline at end of file
--- a/Indoor.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Indoor.h	Thu Jan 02 09:11:28 2014 +0600
@@ -228,16 +228,21 @@
 #define FACE_CAN_SATURATE_COLOR 0x00000002
 #define FACE_FLUID              0x00000010 // wavy animated water or lava
 #define FACE_DONT_CACHE_TEXTURE 0x00000040 // do not load face texture if it isn't loaded already
+#define FACE_UNKNOW4            0x00000080
 #define FACE_XY_PLANE           0x00000100
 #define FACE_XZ_PLANE           0x00000200
 #define FACE_YZ_PLANE           0x00000400
+#define FACE_UNKNOW3            0x00001000
 #define FACE_INVISIBLE          0x00002000
 #define FACE_TEXTURE_FRAME      0x00004000 // Texture ID is a frameset from TextureFrameTable, otherwise BitmapID
 #define FACE_OUTLINED           0x00010000 // outline face edges
 #define FACE_TEXTURE_FLOW       0x00040000 // The texture moves slowly. For horizontal facets only.
+#define FACE_UNKNOW             0x00100000
 #define FACE_INDOOR_SKY         0x00400000
 #define FACE_CLICKABLE          0x02000000 // Event can be triggered by clicking on the facet.
 #define FACE_PRESSURE_PLATE     0x04000000 // Event can be triggered by stepping on the facet.
+#define FACE_INDICATE           0x06000000 // Event can be triggered by indicating on the facet.
+#define FACE_UNKNOW2            0x10000000
 #define FACE_ETHEREAL           0x20000000 // Untouchable. You can pass through it.
 #define FACE_PICKED             0x80000000
 
@@ -257,7 +262,7 @@
     this->pXInterceptDisplacements = 0;
   }
 
-  char _get_normals(Vec3_int_ *a2, Vec3_int_ *a3);
+  void _get_normals(Vec3_int_ *a2, Vec3_int_ *a3);
   struct Texture *GetTexture();
   void FromODM(struct ODMFace *face);
 
@@ -265,7 +270,9 @@
   inline bool Visible() const   {return !Invisible();}
   inline bool Portal() const    {return (uAttributes & FACE_PORTAL) != 0;}
   inline bool Fluid() const     {return (uAttributes & FACE_FLUID) != 0;}
+  inline bool Indoor_sky() const     {return (uAttributes & FACE_INDOOR_SKY) != 0;}
   inline bool Clickable() const {return (uAttributes & FACE_CLICKABLE) != 0;}
+  inline bool Pressure_Plate() const {return (uAttributes & FACE_PRESSURE_PLATE) != 0;}
   inline bool Ethereal() const {return (uAttributes & FACE_ETHEREAL) != 0;}
 
   struct Plane_float_ pFacePlane;
@@ -495,7 +502,7 @@
   float _unused_fSineNegX;   // the same
   int fov_rad_fixpoint;
   int fov_rad_inv_fixpoint;//float
-  unsigned __int16 *pRenderTarget;
+  void *pRenderTarget;
   unsigned int uTargetWidth;
   unsigned int uTargetHeight;
   unsigned int uViewportX;
--- a/Indoor_stuff.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Indoor_stuff.h	Thu Jan 02 09:11:28 2014 +0600
@@ -93,7 +93,7 @@
   void AddFaceToRenderList_sw(unsigned int node_id, unsigned int uFaceID);
   void AddFaceToRenderList_d3d(unsigned int node_id, unsigned int uFaceID);
   void MakeVisibleSectorList();
-  void DrawFaceOutlines();
+  //void DrawFaceOutlines();
 
   unsigned int num_faces;
   //__int16 pFaceIDs[2000];
--- a/LOD.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/LOD.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -484,7 +484,7 @@
   LODSprite_stru0 *v44; // ecx@66
   int v45; // edx@69
   int v46; // edx@77
-  unsigned __int16 *pTarget; // [sp+Ch] [bp-50h]@2
+  //unsigned __int16 *pTarget; // [sp+Ch] [bp-50h]@2
   signed int v48; // [sp+10h] [bp-4Ch]@2
   signed int v49; // [sp+14h] [bp-48h]@2
   int v50; // [sp+14h] [bp-48h]@19
@@ -545,7 +545,9 @@
   v70 = (this->uHeight << 16) - v8;
   v49 = v7;
   v69 = v3->uTargetPitch;
-  pTarget = v3->pTarget;
+
+  __debugbreak(); // target surface  will most likely be 32bit, but this sub awaits 16bits
+  auto pTarget = (unsigned __int16 *)v3->pTarget;
   v57 = v3->sZValue;
   v61 = v3->pPalette;
   v9 = (v6 * this->uWidth + 32768) >> 16;
@@ -839,7 +841,9 @@
   result = (int)a2;
   v14 = this;
   v4 = a2->uTargetPitch;
-  v16 = a2->pTarget;
+
+  __debugbreak(); // sub expects 16bit target surface, we may have 32bit
+  v16 = (unsigned short *)a2->pTarget;
   v15 = a2->pPalette;
   v5 = this->uHeight - 1;
   for ( i = v4 * a2->uScreenSpaceY - (this->uWidth >> 1) + a2->uScreenSpaceX + 1; v5 >= 0; --v5 )
@@ -2375,40 +2379,41 @@
 //----- (004103BB) --------------------------------------------------------
 void LODFile_IconsBitmaps::ReleaseHardwareTextures()
 {
-  LODFile_IconsBitmaps *v1; // esi@1
+  //LODFile_IconsBitmaps *v1; // esi@1
   unsigned int v2; // edi@1
-  struct IDirect3DTexture2 **v3; // eax@2
-  struct IDirect3DTexture2 *v4; // eax@3
-  struct IDirectDrawSurface **v5; // eax@5
-  struct IDirectDrawSurface *v6; // eax@6
+  //struct IDirect3DTexture2 **v3; // eax@2
+  //struct IDirect3DTexture2 *v4; // eax@3
+  //struct IDirectDrawSurface **v5; // eax@5
+  //struct IDirectDrawSurface *v6; // eax@6
 
-  v1 = this;
-  v2 = this->uNumLoadedFiles;
-  while ( 1 )
+  //v1 = this;
+  
+  //while ( 1 )
+  for ( uint i = 0; i < this->uNumLoadedFiles; i++ )
   {
-    --v2;
-    if ( (v2 & 0x80000000u) != 0 )
-      break;
-    v3 = v1->pHardwareTextures;
-    if ( v3 )
+    
+    //if ( (v2 & 0x80000000u) != 0 )
+      //break;
+    //v3 = this->pHardwareTextures;
+    if ( this->pHardwareTextures )
     {
-      v4 = v3[v2];
-      if ( v4 )
+      //v4 = this->pHardwareTextures[v2];
+      if ( this->pHardwareTextures[i] )
       {
-        v4->Release();
-        v1->pHardwareTextures[v2] = 0;
-        v1->ptr_011BB4[v2] = 1;
+        this->pHardwareTextures[i]->Release();
+        this->pHardwareTextures[i] = 0;
+        this->ptr_011BB4[i] = 1;
       }
     }
-    v5 = v1->pHardwareSurfaces;
-    if ( v5 )
+    //v5 = this->pHardwareSurfaces;
+    if ( this->pHardwareSurfaces )
     {
-      v6 = v5[v2];
-      if ( v6 )
+      //v6 = this->pHardwareSurfaces[v2];
+      if ( this->pHardwareSurfaces[i] )
       {
-        v6->Release();
-        v1->pHardwareSurfaces[v2] = 0;
-        v1->ptr_011BB4[v2] = 1;
+        this->pHardwareSurfaces[i]->Release();
+        this->pHardwareSurfaces[i] = 0;
+        this->ptr_011BB4[i] = 1;
       }
     }
   }
--- a/MapInfo.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/MapInfo.h	Thu Jan 02 09:11:28 2014 +0600
@@ -102,4 +102,4 @@
 
 
 void TeleportToStartingPoint(MapStartPoint point); // idb
-void sub_44987B(const char *pMapName, MapStartPoint point); // idb
\ No newline at end of file
+void Transition_StopSound_Autosave(const char *pMapName, MapStartPoint point); // sub_44987B idb
\ No newline at end of file
--- a/Mouse.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Mouse.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -144,27 +144,27 @@
 //----- (00469BA3) --------------------------------------------------------
 void Mouse::ClearCursor()
 {
-  Mouse *v1; // esi@1
-  void *v2; // eax@1
-  void **v3; // esi@5
+  //Mouse *v1; // esi@1
+  //void *v2; // eax@1
+  //void **v3; // esi@5
 
-  v1 = this;
-  v2 = this->pCursorBitmap_sysmem;
+  //v1 = this;
+  //v2 = this->pCursorBitmap_sysmem;
   this->bActive = 0;
-  if ( v2 )
+  if ( this->pCursorBitmap_sysmem )
   {
-    free(v2);
-    v1->pCursorBitmap_sysmem = 0;
+    free(this->pCursorBitmap_sysmem);
+    this->pCursorBitmap_sysmem = 0;
   }
-  if ( v1->pCursorBitmap2_sysmem )
+  if ( this->pCursorBitmap2_sysmem )
   {
-    free(v1->pCursorBitmap2_sysmem);
-    v1->pCursorBitmap2_sysmem = 0;
+    free(this->pCursorBitmap2_sysmem);
+    this->pCursorBitmap2_sysmem = 0;
   }
-  v3 = &v1->ptr_90;
-  if ( *v3 )
-    free(*v3);
-  *v3 = 0;
+  //v3 = &this->ptr_90;
+  if ( this->ptr_90 )
+    free(this->ptr_90);
+  this->ptr_90 = 0;
 }
 
 //----- (00469BE6) --------------------------------------------------------
@@ -228,81 +228,61 @@
 //----- (00469CCD) --------------------------------------------------------
 void Mouse::DrawCursor()
 {
-  Mouse *v1; // esi@1
-  char v11; // zf@6
-  signed int v3; // eax@6
-  signed int v4; // ecx@6
-  Vec4_int_ *v5; // edx@21
-  int v6; // edi@21
-  int v7; // ebx@21
-  int v8; // eax@29
   unsigned int v9; // eax@31
 
-  v1 = this;
   if ( this->bInitialized )
   {
     if ( !this->field_8 && this->bActive && !this->field_C )
       pMouse->_469AE4();
-    v11 = v1->field_C == 0;
-    v3 = v1->uMouseClickX;
-    v4 = v1->uMouseClickY;
-    v1->field_F4 = 1;
-    if ( !v11 )
-      goto LABEL_12;
+    this->field_F4 = 1;
+    if ( this->field_C )
+    {
+      this->field_F4 = 0;
+      return;
+    }
     if ( pRenderer->bWindowMode )
     {
-      if ( v3 < 0 || v4 < 0 || v3 > 639 || v4 > 479 )
+      if ( this->uMouseClickX < 0 || this->uMouseClickY < 0 || this->uMouseClickX > 639 || this->uMouseClickY > 479 )
       {
-LABEL_12:
-        v1->field_F4 = 0;
+        this->field_F4 = 0;
         return;
       }
     }
     else
     {
-      if ( v3 < 0 )
-        v3 = 0;
-      if ( v4 < 0 )
-        v4 = 0;
-      if ( v3 > 639 )
-        v3 = 639;
-      if ( v4 > 479 )
-        v4 = 479;
+      if ( this->uMouseClickX < 0 )
+        this->uMouseClickX = 0;
+      if ( this->uMouseClickY < 0 )
+        this->uMouseClickY = 0;
+      if ( this->uMouseClickX > 639 )
+        this->uMouseClickX = 639;
+      if ( this->uMouseClickY > 479 )
+        this->uMouseClickY = 479;
     }
-    v5 = &v1->pCursorBitmapRect;
-    v6 = v3 + v1->uCursorBitmapPitch;
-    v7 = v4 + v1->field_5C[0];
-    v1->pCursorBitmapRect.y = v4;
-    v1->pCursorBitmapRect.x = v3;
-    v1->pCursorBitmapRect.z = v6;
-    v1->pCursorBitmapRect.w = v7;
-    if ( v3 < 0 )
-      v5->x = 0;
-    if ( v4 < 0 )
-      v1->pCursorBitmapRect.y = 0;
-    if ( v6 > 640 )
-      v1->pCursorBitmapRect.z = 640;
-    if ( v7 > 480 )
-      v1->pCursorBitmapRect.w = 480;
-    v8 = v1->pCursorBitmapRect.z;
-    v1->bActive = 0;
-    v1->uCursorBitmapWidth = v8 - v5->x;
-    v11 = v1->bRedraw == 0;
-    v1->uCursorBitmapHeight = v1->pCursorBitmapRect.w - v1->pCursorBitmapRect.y;
-    if ( !v11 )
+    this->pCursorBitmapRect.x = this->uMouseClickX;
+    this->pCursorBitmapRect.w = this->uMouseClickY + this->field_5C[0];
+    this->pCursorBitmapRect.y = this->uMouseClickY;
+    this->pCursorBitmapRect.z = this->uMouseClickX + this->uCursorBitmapPitch;
+    if ( this->uMouseClickX < 0 )
+      this->pCursorBitmapRect.x = 0;
+    if ( this->uMouseClickY < 0 )
+      this->pCursorBitmapRect.y = 0;
+    if ( this->pCursorBitmapRect.z > 640 )
+      this->pCursorBitmapRect.z = 640;
+    if ( this->pCursorBitmapRect.w > 480 )
+      this->pCursorBitmapRect.w = 480;
+    this->bActive = 0;
+    this->uCursorBitmapWidth = this->pCursorBitmapRect.z - this->pCursorBitmapRect.x;
+    this->uCursorBitmapHeight = this->pCursorBitmapRect.w - this->pCursorBitmapRect.y;
+    if ( this->bRedraw )
     {
       if ( pMouse->ptr_90 )
         v9 = 2 * pMouse->uCursorBitmapPitch;
       else
         v9 = 0;
-      pRenderer->_4A6DF5(
-        v1->pCursorBitmap_sysmem,
-        v9,
-        &v1->pCursorBitmapPos,
-        pRenderer->pTargetSurface,
-        pRenderer->uTargetSurfacePitch,
-        &v1->pCursorBitmapRect);
-      v1->bRedraw = false;
+      pRenderer->_4A6DF5( this->pCursorBitmap_sysmem, v9, &this->pCursorBitmapPos, pRenderer->pTargetSurface, pRenderer->uTargetSurfacePitch,
+        &this->pCursorBitmapRect);//      
+      this->bRedraw = false;
     }
   }
 }
@@ -332,7 +312,8 @@
   ushort* pSrc = pCursorBitmap3_sysmembits_16bit;
   for (uint y = field_44; y < field_4C; ++y)
     for (uint x = field_40; x < field_48; ++x)
-      pRenderer->pTargetSurface[y * pRenderer->uTargetSurfacePitch + x] = *pSrc++;
+      //pRenderer->pTargetSurface[y * pRenderer->uTargetSurfacePitch + x] = *pSrc++;
+        pRenderer->WritePixel16(x, y, *pSrc++);
 }
 
 //----- (00469EA4) --------------------------------------------------------
@@ -349,13 +330,13 @@
   int v9; // ebx@26
   unsigned int v10; // eax@26
   int v11; // edx@27
-  unsigned __int16 *v12; // edx@29
-  unsigned __int16 *v13; // ebx@29
+  //unsigned __int16 *v12; // edx@29
+  //unsigned __int16 *v13; // ebx@29
   unsigned int a2; // [sp+Ch] [bp-1Ch]@5
   unsigned int v15; // [sp+10h] [bp-18h]@5
-  unsigned int v16; // [sp+14h] [bp-14h]@25
-  unsigned __int16 *v17; // [sp+18h] [bp-10h]@25
-  int v18; // [sp+1Ch] [bp-Ch]@27
+  //unsigned int v16; // [sp+14h] [bp-14h]@25
+  //unsigned __int16 *v17; // [sp+18h] [bp-10h]@25
+  //int v18; // [sp+1Ch] [bp-Ch]@27
   int v19; // [sp+20h] [bp-8h]@15
   unsigned __int16 *v20; // [sp+20h] [bp-8h]@28
   int pTextureWidth; // [sp+24h] [bp-4h]@12
@@ -412,9 +393,21 @@
       }
       v8 = this->field_44;
       v22 = this->pCursorBitmap3_sysmembits_16bit;
-      v17 = pRenderer->pTargetSurface;
-      v16 = pRenderer->uTargetSurfacePitch;
-      if ( v8 < this->field_4C )
+      //v17 = pRenderer->pTargetSurface;
+      //v16 = pRenderer->uTargetSurfacePitch;
+      
+        v10 = pRenderer->uTargetSurfacePitch * v8;
+          v11 = this->field_40;
+      for (int y = this->field_44; y < this->field_4C; ++y)
+      {
+            //v20 = &v17[v10 + v11];
+        for (int x = this->field_40; x < this->field_48; ++x)
+        {
+              //++v18;
+              *v22++ = pRenderer->ReadPixel16(x, y);
+        }
+      }
+      /*if ( v8 < this->field_4C )
       {
         v9 = this->field_48;
         v10 = pRenderer->uTargetSurfacePitch * v8;
@@ -427,13 +420,10 @@
             v20 = &v17[v10 + v11];
             do
             {
-              v12 = v20;
-              v13 = v22;
+              //v12 = v20;
               ++v18;
-              ++v20;
-              ++v22;
-              *v13 = *v12;
-              v9 = this->field_48;
+              //++v20;
+              *v22++ = *v20++;
             }
             while ( v18 < v9 );
           }
@@ -442,7 +432,9 @@
         }
         while ( v8 < this->field_4C );
         v6 = v15;
-      }
+      }*/
+
+      v6 = v15;
       if (pParty->pPickedItem.IsBroken())
         pRenderer->DrawTransparentRedShade(a2, v6, pTexture);
       else if (!pParty->pPickedItem.IsIdentified())
@@ -476,34 +468,27 @@
 //----- (004175C0) --------------------------------------------------------
 void UI_OnMouseLeftClick(int *pXY)
 {
-  int *pXY_; // esi@1
   signed int y; // eax@7
   signed int x; // ecx@7
-  signed int v4; // eax@11
   signed int v5; // eax@17
-  signed int v6; // esi@19
-  int v7; // esi@30
-  GUIWindow *v8; // edx@31
-  GUIButton *i; // esi@37
+  GUIButton *control; // esi@37
   signed int v10; // eax@50
   int v11; // ecx@52
   unsigned int pX; // [sp+14h] [bp-8h]@7
   unsigned int pY; // [sp+18h] [bp-4h]@7
 
-  pXY_ = pXY;
-  if ( pCurrentScreen == SCREEN_VIDEO
-    || sub_4637E0_is_there_popup_onscreen() )
+  if ( pCurrentScreen == SCREEN_VIDEO || sub_4637E0_is_there_popup_onscreen() )
     return;
   if ( pGUIWindow2 && pGUIWindow2->ptr_1C == (void *)33 )
   {
     sub_4452BB();
     return;
   }
-  if ( pXY_ )
+  if ( pXY )
   {
-    x = *pXY_;
-    y = pXY_[1];
-    pX = *pXY_;
+    x = *pXY;
+    y = pXY[1];
+    pX = *pXY;
     pY = y;
   }
   else
@@ -514,81 +499,83 @@
   }
 
   extern bool _507B98_ctrl_pressed;
-  if ( pCurrentScreen != SCREEN_GAME || !_507B98_ctrl_pressed ) // stealing cursor
-    goto LABEL_30;
-  v4 = GetCurrentMenuID();
   x = pX;
-  if ( v4 != -1
-    || (signed int)pX < (signed int)pViewport->uViewportTL_X
-    || (signed int)pX > (signed int)pViewport->uViewportBR_X )
+  if ( GetCurrentMenuID() != -1 || pCurrentScreen != SCREEN_GAME || !_507B98_ctrl_pressed // stealing cursor
+      || (signed int)pX < (signed int)pViewport->uViewportTL_X || (signed int)pX > (signed int)pViewport->uViewportBR_X
+      || (signed int)pY < (signed int)pViewport->uViewportTL_Y || (signed int)pY > (signed int)pViewport->uViewportBR_Y)
   {
     y = pY;
-LABEL_30:
-    v7 = uNumVisibleWindows;
-    if ( uNumVisibleWindows < 0 )
-      return;
-    while ( 1 )
-    {
-      //v8 = (GUIWindow *)&pWindowList_at_506F50_minus1_indexing[21 * pVisibleWindowsIdxs[v7]];
-      v8 = &pWindowList[pVisibleWindowsIdxs[v7] - 1];
-      if ( x >= (signed int)v8->uFrameX )
-      {
-        if ( x <= (signed int)v8->uFrameZ && y >= (signed int)v8->uFrameY && y <= (signed int)v8->uFrameW )
-          break;
-      }
-      --v7;
-      if ( v7 < 0 )
-        return;
-    }
-    for ( i = v8->pControlsHead; ; i = i->pNext )
+    for ( int i = uNumVisibleWindows; i >= 0; --i )
     {
-      if ( !i )
-        return;
-      if ( i->uButtonType == 1 )
-        goto LABEL_41;
-      if ( i->uButtonType != 2 )
-        break;
-      if ( (signed int)(signed __int64)sqrt((double)((x - i->uX) * (x - i->uX) + (y - i->uY) * (y - i->uY))) < (signed int)i->uWidth )
-        goto LABEL_50;
-      y = pY;
-      x = pX;
-LABEL_45:
-      ;
+      if ( x >= (signed int)pWindowList[pVisibleWindowsIdxs[i] - 1].uFrameX && x <= (signed int)pWindowList[pVisibleWindowsIdxs[i] - 1].uFrameZ
+        && y >= (signed int)pWindowList[pVisibleWindowsIdxs[i] - 1].uFrameY && y <= (signed int)pWindowList[pVisibleWindowsIdxs[i] - 1].uFrameW )
+      {
+        for ( control = pWindowList[pVisibleWindowsIdxs[i] - 1].pControlsHead; control; control = control->pNext )
+        {
+          if ( control->uButtonType == 1 )
+          {
+            if ( x >= (signed int)control->uX && x <= (signed int)control->uZ && y >= (signed int)control->uY && y <= (signed int)control->uW )
+            {
+              control->field_2C_is_pushed = 1;
+              v10 = pMessageQueue_50CBD0->uNumMessages;
+              if ( pMessageQueue_50CBD0->uNumMessages )
+              {
+                v10 = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
+                pMessageQueue_50CBD0->uNumMessages = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
+              }
+              pMessageQueue_50CBD0->AddMessage(control->msg, control->msg_param, 0);
+              return;
+            }
+            continue;
+          }
+          if ( control->uButtonType == 2 )//    
+          {
+            if ( (signed int)(signed __int64)sqrt((double)((x - control->uX) * (x - control->uX) + (y - control->uY) * (y - control->uY))) < (signed int)control->uWidth )
+            {
+              control->field_2C_is_pushed = 1;
+              v10 = pMessageQueue_50CBD0->uNumMessages;
+              if ( pMessageQueue_50CBD0->uNumMessages )
+              {
+                v10 = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
+                pMessageQueue_50CBD0->uNumMessages = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
+              }
+              pMessageQueue_50CBD0->AddMessage(control->msg, control->msg_param, 0);
+              return;
+            }
+            continue;
+          }
+          if ( control->uButtonType == 3 )//   
+          {
+            if ( x >= (signed int)control->uX && x <= (signed int)control->uZ && y >= (signed int)control->uY && y <= (signed int)control->uW )
+            {
+              control->field_2C_is_pushed = 1;
+              v10 = pMessageQueue_50CBD0->uNumMessages;
+              if ( pMessageQueue_50CBD0->uNumMessages )
+              {
+                v10 = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
+                pMessageQueue_50CBD0->uNumMessages = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
+              }
+              pMessageQueue_50CBD0->AddMessage(control->msg, control->msg_param, 0);
+              return;
+            }
+            continue;
+          }
+          y = pY;
+          x = pX;
+        }
+      }
     }
-    if ( i->uButtonType != 3 )
-      goto LABEL_45;
-LABEL_41:
-    if ( x >= (signed int)i->uX && x <= (signed int)i->uZ && y >= (signed int)i->uY && y <= (signed int)i->uW )
-    {
-LABEL_50:
-      i->field_2C_is_pushed = 1;
-      v10 = pMessageQueue_50CBD0->uNumMessages;
-      if ( pMessageQueue_50CBD0->uNumMessages )
-      {
-        v10 = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
-        pMessageQueue_50CBD0->uNumMessages = pMessageQueue_50CBD0->pMessages[0].field_8 != 0;
-      }
-      //v11 = i->uControlParam;
-      pMessageQueue_50CBD0->AddMessage(i->msg, i->msg_param, 0);
-      return;
-    }
-    goto LABEL_45;
+    return;
   }
   y = pY;
-  if ( (signed int)pY < (signed int)pViewport->uViewportTL_Y || (signed int)pY > (signed int)pViewport->uViewportBR_Y )
-    goto LABEL_30;
   if ( pRenderer->pRenderD3D )
     v5 = pGame->pVisInstance->get_picked_object_zbuf_val();
   else
     v5 = pRenderer->pActiveZBuffer[pX + pSRZBufferLineOffsets[pY]];
-  v6 = (unsigned __int16)v5;
 
-  uint type = PID_TYPE(v6);
-  if (type == OBJECT_Actor
-    && uActiveCharacter
-    && v5 < 0x2000000
-    && pPlayers[uActiveCharacter]->CanAct()
-    && pPlayers[uActiveCharacter]->CanSteal() )
+  uint type = PID_TYPE((unsigned __int16)v5);
+  if (type == OBJECT_Actor && uActiveCharacter && v5 < 0x2000000
+    && pPlayers[uActiveCharacter]->CanAct() && pPlayers[uActiveCharacter]->CanSteal() )
   {
     /*if ( (signed int)pMessageQueue_50CBD0->uNumMessages < 40 )
     {
@@ -597,7 +584,7 @@
       *(&pMessageQueue_50CBD0->uNumMessages + 3 * pMessageQueue_50CBD0->uNumMessages + 3) = 0;
       ++pMessageQueue_50CBD0->uNumMessages;
     }*/
-    pMessageQueue_50CBD0->AddMessage(UIMSG_STEALFROMACTOR, PID_ID(v6), 0);
+    pMessageQueue_50CBD0->AddMessage(UIMSG_STEALFROMACTOR, PID_ID((unsigned __int16)v5), 0);
 
     if ( pParty->bTurnBasedModeOn == 1 )
     {
@@ -812,48 +799,26 @@
       }
       case VK_NEXT:
       {  
-        //if ( pWindowList[v3].field_30 != 0 )   //crashed at skill draw
-        //{
-        //  pMouse->GetClickPos(&uClickX, &uClickY);
-        //  v4 = pWindowList[v3].pStartingPosActiveItem;
-        //  v29 = v4 + pWindowList[v3].pNumPresenceButton; //num buttons more than buttons 
-        //  if ( v4 < v29 )
-        //  {
-        //    while ( 1 )
-        //    {
-        //      pButton = pWindowList[v3].pControlsHead;
-        //      if ( v4 > 0 )
-        //      {
-        //        v15 = v4;
-        //        do
-        //        {
-        //          pButton = pButton->pNext;
-        //          --v15;
-        //        }
-        //        while ( v15 );
-        //      }
-        //      if ( (signed int)uClickX >= (signed int)pButton->uX
-        //        && (signed int)uClickX <= (signed int)pButton->uZ
-        //        && (signed int)uClickY >= (signed int)pButton->uY
-        //        && (signed int)uClickY <= (signed int)pButton->uW )
-        //      {
-        //        pWindowList[v3].pCurrentPosActiveItem = v4;
-        //        return true;
-        //      }
-        //      ++v4;
-        //      if ( v4 >= v29 )
-        //      {
-        //        //v1 = 0;
-        //        //v2 = pMessageQueue_50CBD0->uNumMessages;
-        //        break;
-        //      }
-        //    }
-        //  }
-        //  else
-        //  {
-        //    //v2 = pMessageQueue_50CBD0->uNumMessages;
-        //  }
-        //}
+        if ( pWindowList[v3].field_30 != 0 )   //crashed at skill draw
+        {
+          pMouse->GetClickPos(&uClickX, &uClickY);
+          v29 = pWindowList[v3].pStartingPosActiveItem + pWindowList[v3].pNumPresenceButton; //num buttons more than buttons 
+          for ( v4 = pWindowList[v3].pStartingPosActiveItem; v4 < v29; ++v4 )
+          {
+            pButton = pWindowList[v3].pControlsHead;
+            if ( v4 > 0 )
+            {
+              for ( v15 = v4; v15; --v15 )
+                pButton = pButton->pNext;
+            }
+            if ( (signed int)uClickX >= (signed int)pButton->uX && (signed int)uClickX <= (signed int)pButton->uZ
+              && (signed int)uClickY >= (signed int)pButton->uY && (signed int)uClickY <= (signed int)pButton->uW )
+            {
+              pWindowList[v3].pCurrentPosActiveItem = v4;
+              return true;
+            }
+          }
+        }
         break;
       }
       default:
--- a/NPC.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/NPC.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -1386,10 +1386,11 @@
     if ( uMessageParam == 77 )
     {
       //v16 = pCurrentNPCInfo->uProfession;
+    __debugbreak();  // probably hirelings found in buildings, not present in MM7, changed "pCurrentNPCInfo->uProfession - 1" to "pCurrentNPCInfo->uProfession", have to check in other versions whether it's ok
       if (dialogue_show_profession_details)
-        v17 = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession - 1].pJoinText;
+        v17 = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession].pJoinText;
       else
-        v17 = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession - 1].pBenefits;
+        v17 = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession].pBenefits;
       current_npc_text = v17;
       v18 = BuildDialogueString(v17, uActiveCharacter - 1, 0, 0, 0, 0);
       dialogue_show_profession_details = ~dialogue_show_profession_details;
@@ -1502,15 +1503,16 @@
     ShowStatusBarString(pGlobalTXT_LocalizationStrings[533], 2);// ""I cannot join you, you're party is full""
     goto _return;
   }
-  if ( pCurrentNPCInfo->uProfession != 51 )
+  if ( pCurrentNPCInfo->uProfession != 51 ) //burglars have no hiring price
   {
-    pPrice = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession - 1].uHirePrice;
+    __debugbreak();  // probably hirelings found in buildings, not present in MM7, changed "pCurrentNPCInfo->uProfession - 1" to "pCurrentNPCInfo->uProfession", have to check in other versions whether it's ok
+    pPrice = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession].uHirePrice;
     if ( pParty->uNumGold < pPrice )
     {
       ShowStatusBarString(pGlobalTXT_LocalizationStrings[155], 2);
       dialogue_show_profession_details = false;
       uDialogueType = 13;
-      current_npc_text = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession - 1].pJoinText;
+      current_npc_text = pNPCStats->pProfessions[pCurrentNPCInfo->uProfession].pJoinText;
       current_npc_text = BuildDialogueString(current_npc_text, uActiveCharacter - 1, 0, 0, 0, 0);
       if ( uActiveCharacter )
         pPlayers[uActiveCharacter]->PlaySound(SPEECH_NotEnoughGold, 0);
--- a/OSWindow.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/OSWindow.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -67,6 +67,8 @@
     {
       if (wparam == VK_CONTROL)
         _507B98_ctrl_pressed = false;
+      if (wparam == VK_SNAPSHOT)
+        pRenderer->SavePCXScreenshot();
 
       OnKey(wparam);
       return *result = 0, true;
@@ -272,15 +274,15 @@
         if (dword_6BE364_game_settings_1 & GAME_SETTINGS_APP_INACTIVE)
         {
           dword_4E98BC_bApplicationActive = 1;
-          if ( pRenderer->bWindowMode )
+          /*if ( pRenderer->bWindowMode )
           {
             HDC hDC = GetDC(api_handle);
             int bitsPerPixel = GetDeviceCaps(hDC, BITSPIXEL);
             int planes = GetDeviceCaps(hDC, PLANES);
             ReleaseDC(api_handle, hDC);
             if (bitsPerPixel != 16 || planes != 1)
-              Error(pGlobalTXT_LocalizationStrings[62]);
-          }
+              Error(L"%S", pGlobalTXT_LocalizationStrings[62]);
+          }*/
           dword_6BE364_game_settings_1 &= ~GAME_SETTINGS_APP_INACTIVE;
 
           if ( pArcomageGame->bGameInProgress )
@@ -331,7 +333,7 @@
           else
             pMiscTimer->Pause();
 
-          pAudioPlayer->StopChannels(-1, -1);
+          pAudioPlayer->StopChannels(-1, -1);//      
           if ( pAudioPlayer->hAILRedbook )
             AIL_redbook_pause(pAudioPlayer->hAILRedbook);
         }
@@ -402,7 +404,9 @@
     return false;
 
   api_handle = CreateWindowExW(0, wcxw.lpszClassName, title, 0,
-                               0, 0, window_width, window_height, nullptr,
+                               ReadWindowsRegistryInt("window X", (GetSystemMetrics(SM_CXSCREEN) - window_width) / 2),
+                               ReadWindowsRegistryInt("window Y", (GetSystemMetrics(SM_CYSCREEN) - window_height) / 2),
+                               window_width, window_height, nullptr,
                                nullptr, wcxw.hInstance, this);
   if (!api_handle)
   {
@@ -499,6 +503,9 @@
 
 void OSWindow::SetWindowedMode(int new_window_width, int new_window_height)
 {
+  RECT rcWindowPos;
+  GetWindowRect(api_handle, &rcWindowPos);
+
   SetWindowLongW(api_handle, GWL_EXSTYLE, 0);
   SetWindowLongW(api_handle, GWL_STYLE,   WS_VISIBLE | WS_OVERLAPPEDWINDOW);
   SetWindowPos(api_handle, HWND_TOP, 0, 0, -1, -1, 0);
@@ -518,13 +525,16 @@
     if (!GetMenu(api_handle))
       window_total_height += GetSystemMetrics(SM_CYMENU);
   #endif
-  MoveWindow(api_handle, ReadWindowsRegistryInt("window X", (GetSystemMetrics(SM_CXSCREEN) - window_total_width) / 2),
-                         ReadWindowsRegistryInt("window Y", (GetSystemMetrics(SM_CYSCREEN) - window_total_height) / 2),
+  MoveWindow(api_handle, rcWindowPos.left,
+                         rcWindowPos.top,
                          window_total_width,
                          window_total_height, 0);
   #ifdef _DEBUG
     static HMENU debug_menu = CreateDebugMenuPanel();
     SetMenu(api_handle, debug_menu);
+    
+    GetWindowRect(api_handle, &rcWindow);
+    GetClientRect(api_handle, &rcClient);
   #endif
 }
 
@@ -685,14 +695,14 @@
     default: return false;
 
 
-    case 103:  pRenderer->SavePCXScreenshot(); break;
+    //case 103:  pRenderer->SavePCXScreenshot(); break;
     case 101:  // Quit game
-    case 40001:
-		pGame->Deinitialize();
+    case 40001: // Menu "File"-> "Exit"
+      pGame->Deinitialize();
       SendMessageW(api_handle, WM_DESTROY, 0, 0);
     break;
 
-    case 104:
+    case 104: //F4 button
       pRenderer->ChangeBetweenWinFullscreenModes();
       if (pArcomageGame->bGameInProgress)
         pArcomageGame->field_F6 = 1;
--- a/Outdoor.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Outdoor.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -176,7 +176,7 @@
   pOutdoor->ExecDraw(redrawWorld);
 
   pGame->DrawParticles();
-  pWeather->Draw();
+  //pWeather->Draw();//    
   trail_particle_generator.UpdateParticles();
 }
 
@@ -1001,7 +1001,6 @@
   signed int result; // eax@2
   unsigned __int16 *v5; // edx@3
   double v6; // st7@3
-  char v7; // bl@3
   int v8; // eax@3
   int v9; // eax@4
   int v10; // eax@5
@@ -1012,10 +1011,6 @@
   signed int v15; // ecx@10
   char v16[256]; // [sp+4h] [bp-124h]@9
   unsigned __int16 *v17; // [sp+104h] [bp-24h]@3
-  unsigned int v18; // [sp+108h] [bp-20h]@3
-  unsigned int v19; // [sp+10Ch] [bp-1Ch]@3
-  unsigned int v20; // [sp+110h] [bp-18h]@3
-  unsigned int v21; // [sp+114h] [bp-14h]@3
   float v22; // [sp+118h] [bp-10h]@3
   float v23; // [sp+11Ch] [bp-Ch]@3
   int i; // [sp+120h] [bp-8h]@3
@@ -1025,23 +1020,25 @@
   float a3a; // [sp+138h] [bp+10h]@7
   int a3b; // [sp+138h] [bp+10h]@9
 
+  int num_r_bits = 5;
+  int num_g_bits = 6;
+  int num_b_bits = 5;
+
+  int r_mask = 0xF800;
+  int g_mask = 0x7E0;
+  int b_mask = 0x1F;
+
   if ( pRenderer->pRenderD3D )
-  {
     result = 0;
-  }
   else
   {
+    __debugbreak();
     v5 = PaletteManager::Get_Dark_or_Red_LUT(a2, 0, 1);
     v6 = 0.0;
-    v7 = LOBYTE(pRenderer->uTargetBBits);
-    v19 = pRenderer->uTargetRMask;
-    v21 = pRenderer->uTargetGMask;
     v22 = 0.0;
-    v20 = pRenderer->uTargetBMask;
     v8 = 0;
     v17 = v5;
     v23 = 0.0;
-    v18 = pRenderer->uTargetBBits;
     a2a = 0;
     for ( i = 0; i < a3; ++i )
     {
@@ -1049,11 +1046,11 @@
       if ( v9 )
       {
         v10 = v5[v9];
-        v6 = v6 + (double)((signed int)(v19 & v10) >> (LOBYTE(pRenderer->uTargetBBits) + LOBYTE(pRenderer->uTargetGBits)));
+        v6 = v6 + (double)((signed int)(r_mask & v10) >> (num_b_bits + num_g_bits));
         ++a2a;
-        v25 = v20 & v10;
-        v22 = (double)((signed int)(v21 & v10) >> SLOBYTE(pRenderer->uTargetBBits)) + v22;
-        v23 = (double)(signed int)(v20 & v10) + v23;
+        v25 = b_mask & v10;
+        v22 = (double)((signed int)(g_mask & v10) >> num_b_bits) + v22;
+        v23 = (double)(signed int)(b_mask & v10) + v23;
       }
       v8 = i + 1;
     }
@@ -1062,16 +1059,15 @@
     v25 = (signed __int64)(a3a * v22);
     i = (signed __int64)(a3a * v23);
     v12 = 0;
-    a2b = pRenderer->uTargetBBits + pRenderer->uTargetGBits;
+    a2b = num_b_bits + num_g_bits;
     while ( 1 )
     {
       v13 = v17[v12];
-      a3b = abs((__int64)(signed __int64)(v11 * v6) - ((signed int)(v19 & v17[v12]) >> a2b));
-      BYTE3(a3b) = abs((signed)v25 - ((signed int)(v21 & v13) >> v7)) + a3b;
-      v16[v12++] = abs((signed)i - (signed)(v20 & v13)) + BYTE3(a3b);
+      a3b = abs((__int64)(signed __int64)(v11 * v6) - ((signed int)(r_mask & v17[v12]) >> a2b));
+      BYTE3(a3b) = abs((signed)v25 - ((signed int)(g_mask & v13) >> num_b_bits)) + a3b;
+      v16[v12++] = abs((signed)i - (signed)(b_mask & v13)) + BYTE3(a3b);
       if ( v12 >= 256 )
         break;
-      v7 = v18;
     }
     result = 0;
     v14 = (char *)&pPaletteManager->field_D1600[42][23][116];
@@ -1126,60 +1122,60 @@
 //----- (0047CDE2) --------------------------------------------------------
 void OutdoorLocation::CreateDebugLocation()
 {
-  OutdoorLocation *v1; // esi@1
+  //OutdoorLocation *v1; // esi@1
   void *v2; // eax@1
   void *v3; // ST14_4@1
   void *v4; // eax@1
   void *v5; // ST14_4@1
   void *v6; // eax@1
-  unsigned int v7; // eax@1
+  //unsigned int v7; // eax@1
   //char v8; // zf@1
 
-  v1 = this;
+  //v1 = this;
   strcpy(this->pLevelFilename, "blank");
-  strcpy(v1->pLocationFileName, "i6.odm");
-  strcpy(v1->pLocationFileDescription, "MM6 Outdoor v1.00");
-  v1->uNumBModels = 0;
-  v1->pTileTypes[0].tileset = Tileset_Grass;
-  v1->pTileTypes[1].tileset = Tileset_Water;
-  v1->pTileTypes[2].tileset = Tileset_6;
-  v1->pTileTypes[3].tileset = Tileset_RoadGrassCobble;
-  v1->LoadTileGroupIds();
-  v1->LoadRoadTileset();
-  free(v1->pBModels);
-  free(v1->pSpawnPoints);
-  v1->pBModels = 0;
-  v1->pSpawnPoints = 0;
-  v1->pTerrain.Initialize();
-  v1->pTerrain.ZeroLandscape();
-  v1->pTerrain.FillDMap(0, 0, 128, 128);
-  free(v1->pCmap);
-  v1->pCmap = 0;
+  strcpy(this->pLocationFileName, "i6.odm");
+  strcpy(this->pLocationFileDescription, "MM6 Outdoor v1.00");
+  this->uNumBModels = 0;
+  this->pTileTypes[0].tileset = Tileset_Grass;
+  this->pTileTypes[1].tileset = Tileset_Water;
+  this->pTileTypes[2].tileset = Tileset_6;
+  this->pTileTypes[3].tileset = Tileset_RoadGrassCobble;
+  this->LoadTileGroupIds();
+  this->LoadRoadTileset();
+  free(this->pBModels);
+  free(this->pSpawnPoints);
+  this->pBModels = 0;
+  this->pSpawnPoints = 0;
+  this->pTerrain.Initialize();
+  this->pTerrain.ZeroLandscape();
+  this->pTerrain.FillDMap(0, 0, 128, 128);
+  free(this->pCmap);
+  this->pCmap = 0;
   v2 = malloc(0x8000u);
-  v3 = v1->pOMAP;
-  v1->pCmap = v2;
+  v3 = this->pOMAP;
+  this->pCmap = v2;
   free(v3);
-  v1->pOMAP = 0;
+  this->pOMAP = 0;
   v4 = malloc(0x10000u);
-  v1->pOMAP = (unsigned int *)v4;
+  this->pOMAP = (unsigned int *)v4;
   memset(v4, 0, 0x10000u);
-  v5 = v1->pFaceIDLIST;
-  v1->numFaceIDListElems = 0;
+  v5 = this->pFaceIDLIST;
+  this->numFaceIDListElems = 0;
   free(v5);
-  v1->pFaceIDLIST = 0;
+  this->pFaceIDLIST = 0;
   v6 = malloc(2);
-  v1->pFaceIDLIST = (unsigned __int16 *)v6;
+  this->pFaceIDLIST = (unsigned __int16 *)v6;
   *(short *)v6 = 0;
-  strcpy(v1->pSkyTextureName, pDefaultSkyTexture.data());
-  v1->sSky_TextureID = pBitmaps_LOD->LoadTexture(v1->pSkyTextureName);
-  strcpy(v1->pGroundTileset, byte_6BE124_cfg_textures_DefaultGroundTexture.data());
-  v7 = pBitmaps_LOD->LoadTexture(v1->pGroundTileset);
-  v1->sMainTile_BitmapID = v7;
-
-  if ( v1->sSky_TextureID == -1 )
+  strcpy(this->pSkyTextureName, pDefaultSkyTexture.data());
+  this->sSky_TextureID = pBitmaps_LOD->LoadTexture(this->pSkyTextureName);
+  strcpy(this->pGroundTileset, byte_6BE124_cfg_textures_DefaultGroundTexture.data());
+  //v7 = pBitmaps_LOD->LoadTexture(this->pGroundTileset);
+  this->sMainTile_BitmapID = pBitmaps_LOD->LoadTexture(this->pGroundTileset);
+
+  if ( this->sSky_TextureID == -1 )
     Error("Invalid Sky Tex Handle");
 
-  if ( v1->sMainTile_BitmapID == -1 )
+  if ( this->sMainTile_BitmapID == -1 )
     Error("Invalid Ground Tex Handle");
 }
 
@@ -2049,7 +2045,7 @@
   //v73 = strlen(pContainer);
   strcpy(Str + strlen(Str) - 4, ".ddm");
   //strcpy((char *)v141 + v73, (const char *)v108);
-  v39 = pNew_LOD->FindContainer(Str, 1);//
+  v39 = pNew_LOD->FindContainer(Str, 1);//error
   fread(&header, 0x10u, 1u, v39);
   Str2 = 0;
   if (header.uVersion != 91969 ||
@@ -2334,7 +2330,9 @@
   //v100 = HIDWORD(uLastVisitDay);
   //LODWORD(v142) = LODWORD(uLastVisitDay);
   //HIDWORD(v142) = v100;
-  if (loc_time.uLastVisitDay)
+  if ( pWeather->bRenderSnow ) //Ritor1: it's include
+    strcpy(loc_time.sky_texture_name, "sky19");
+  else if (loc_time.uLastVisitDay)
   {
     if ( (signed int)((signed int)(signed __int64)((double)loc_time.uLastVisitDay * 0.234375) / 60 / 60 / 24) % 28 != pParty->uDaysPlayed )
     {
@@ -2346,9 +2344,8 @@
     }
   }
   else
-  {
     strcpy(loc_time.sky_texture_name, "plansky3");
-  }
+
   //v101 = pBitmaps_LOD->LoadTexture(field_4F8);
   sSky_TextureID = pBitmaps_LOD->LoadTexture(loc_time.sky_texture_name);
   if (sSky_TextureID != -1)
@@ -2361,40 +2358,39 @@
   pSoundList->LoadSound(96, 0);
   pSoundList->LoadSound(64, 0);
   pSoundList->LoadSound(103, 0);
-  for (int i=0; i<3;++i) 
+  for (int i=0; i < 3;++i) 
   {
-    
-      switch ( pTileTypes[i].tileset )
-      {
-        case Tileset_Grass:
-            pSoundList->LoadSound(54, 0);
-            pSoundList->LoadSound(93, 0);
-            break;
-        case Tileset_Snow:
-          pSoundList->LoadSound(58, 0);
-          pSoundList->LoadSound(97, 0);
-          break;
-        case Tileset_2:
-          pSoundList->LoadSound(52, 0);
-          pSoundList->LoadSound(91, 0);
-          break;
-        case Tileset_3:
-          pSoundList->LoadSound(51, 0);
-          pSoundList->LoadSound(90, 0);
-          break;
-        case Tileset_Water:
-          pSoundList->LoadSound(62, 0);
-          pSoundList->LoadSound(101, 0);
-          break;
-        case Tileset_6:
-          pSoundList->LoadSound(49, 0);
-          pSoundList->LoadSound(88, 0);
-          break;
-        case Tileset_Swamp:
-          pSoundList->LoadSound(61, 0);
-          pSoundList->LoadSound(100, 0);
-          break;
-      }   
+    switch ( pTileTypes[i].tileset )
+    {
+      case Tileset_Grass:
+        pSoundList->LoadSound(54, 0);
+        pSoundList->LoadSound(93, 0);
+        break;
+      case Tileset_Snow:
+        pSoundList->LoadSound(58, 0);
+        pSoundList->LoadSound(97, 0);
+        break;
+      case Tileset_2:
+        pSoundList->LoadSound(52, 0);
+         pSoundList->LoadSound(91, 0);
+        break;
+      case Tileset_3:
+        pSoundList->LoadSound(51, 0);
+        pSoundList->LoadSound(90, 0);
+        break;
+      case Tileset_Water:
+        pSoundList->LoadSound(62, 0);
+        pSoundList->LoadSound(101, 0);
+        break;
+      case Tileset_6:
+        pSoundList->LoadSound(49, 0);
+        pSoundList->LoadSound(88, 0);
+        break;
+      case Tileset_Swamp:
+        pSoundList->LoadSound(61, 0);
+        pSoundList->LoadSound(100, 0);
+        break;
+    }
   }
   return true;
 }
@@ -2852,10 +2848,10 @@
   //double v7; // ST30_8@10
   unsigned int v8; // eax@11
   int v9; // edx@11
-  __int16 v10; // dx@11
-  unsigned int v11; // eax@13
+  //__int16 v10; // dx@11
+  //unsigned int v11; // eax@13
   signed int v12; // eax@16
-  __int16 v13; // cx@21
+  //__int16 v13; // cx@21
   SpriteFrame *v14; // eax@24
   SpriteFrame *v15; // ebx@25
   //int *v16; // eax@25
@@ -2881,8 +2877,8 @@
   int v36; // ecx@54
   //unsigned __int8 v37; // zf@54
   //unsigned __int8 v38; // sf@54
-  unsigned int v39; // [sp-8h] [bp-68h]@23
-  unsigned int v40; // [sp-4h] [bp-64h]@23
+  //unsigned int v39; // [sp-8h] [bp-68h]@23
+  //unsigned int v40; // [sp-4h] [bp-64h]@23
   int v41; // [sp+24h] [bp-3Ch]@11
   int v42; // [sp+28h] [bp-38h]@38
   int v43; // [sp+28h] [bp-38h]@45
@@ -2914,75 +2910,59 @@
     //v1 = pActors;//[0].vPosition.z;
     //do
     //{
-    Actor* actor = &pActors[i];
+    //Actor* actor = &pActors[i];
 	  //v2 = actor->uAIState;
 
-	actor->uAttributes &= 0xFFFFFFF7u;
-    if (actor->uAIState == Removed || actor->uAIState == Disabled)
+    pActors[i].uAttributes &= 0xFFFFFFF7u;
+    if (pActors[i].uAIState == Removed || pActors[i].uAIState == Disabled)
       continue;
 
-	  z = actor->vPosition.z;
+	  z = pActors[i].vPosition.z;
       v49 = 0;
-	  x = actor->vPosition.x;
-	  y = actor->vPosition.y;
-      if (actor->uAIState == Summoned)
+	  x = pActors[i].vPosition.x;
+	  y = pActors[i].vPosition.y;
+      if (pActors[i].uAIState == Summoned)
       {
-		if (PID_TYPE(actor->uSummonerID) != OBJECT_Actor ||
-             pActors[PID_ID(actor->uSummonerID)].pMonsterInfo.uSpecialAbilityDamageDiceSides != 1 )
+		if (PID_TYPE(pActors[i].uSummonerID) != OBJECT_Actor ||
+             pActors[PID_ID(pActors[i].uSummonerID)].pMonsterInfo.uSpecialAbilityDamageDiceSides != 1 )
         {
-          z += floorf(actor->uActorHeight * 0.5f + 0.5f);
+          z += floorf(pActors[i].uActorHeight * 0.5f + 0.5f);
         }
         else
         {
           v49 = 1;
-		  pGame->pStru6Instance->_4A7F74(actor->vPosition.x, actor->vPosition.y, z);
-          v4 = (1.0 - (double)actor->uCurrentActionTime / (double)actor->uCurrentActionLength) *
-			   (double)(2 * actor->uActorHeight);
+		  pGame->pStru6Instance->_4A7F74(pActors[i].vPosition.x, pActors[i].vPosition.y, z);
+          v4 = (1.0 - (double)pActors[i].uCurrentActionTime / (double)pActors[i].uCurrentActionLength) *
+			   (double)(2 * pActors[i].uActorHeight);
           z -= floorf(v4 + 0.5f);
-          if ( z > actor->vPosition.z )
-            z = actor->vPosition.z;
+          if ( z > pActors[i].vPosition.z )
+            z = pActors[i].vPosition.z;
         }
       }
-      v8 = stru_5C6E00->Atan2(actor->vPosition.x - pGame->pIndoorCameraD3D->vPartyPos.x,
-                              actor->vPosition.y - pGame->pIndoorCameraD3D->vPartyPos.y);
-	  LOWORD(v9) = actor->uYawAngle;
+      v8 = stru_5C6E00->Atan2(pActors[i].vPosition.x - pGame->pIndoorCameraD3D->vPartyPos.x,
+                              pActors[i].vPosition.y - pGame->pIndoorCameraD3D->vPartyPos.y);
+	  LOWORD(v9) = pActors[i].uYawAngle;
       v41 = ((signed int)(stru_5C6E00->uIntegerPi + ((signed int)stru_5C6E00->uIntegerPi >> 3) + v9 - v8) >> 8) & 7;
-	  v10 = actor->uCurrentActionAnimation;
       if ( pParty->bTurnBasedModeOn )
       {
-        if ( v10 != 1 )
-        {
-LABEL_17:
-			v12 = actor->uCurrentActionTime;
-          goto LABEL_18;
-        }
-        v11 = pMiscTimer->uTotalGameTimeElapsed;
+        v12 = pActors[i].uCurrentActionTime;
+        if ( pActors[i].uCurrentActionAnimation == 1 )
+          v12 = 32 * i + pMiscTimer->uTotalGameTimeElapsed;
       }
       else
       {
-        if ( v10 != 1 )
-          goto LABEL_17;
-        v11 = pEventTimer->uTotalGameTimeElapsed;
+        v12 = pActors[i].uCurrentActionTime;
+        if ( pActors[i].uCurrentActionAnimation == 1 )
+          v12 = 32 * i + pEventTimer->uTotalGameTimeElapsed;
       }
-      v12 = 32 * i + v11;
-LABEL_18:
-      if ( (signed __int64)actor->pActorBuffs[ACTOR_BUFF_STONED].uExpireTime > 0 || (signed __int64)actor->pActorBuffs[ACTOR_BUFF_PARALYZED].uExpireTime > 0 )
+      if ( (signed __int64)pActors[i].pActorBuffs[ACTOR_BUFF_STONED].uExpireTime > 0 || (signed __int64)pActors[i].pActorBuffs[ACTOR_BUFF_PARALYZED].uExpireTime > 0 )
         v12 = 0;
-	  v13 = actor->uAIState;
-      if ( v13 == 17 && !v49 )
-      {
-        v40 = v12;
-        v39 = uSpriteID_Spell11;
-LABEL_24:
-        v14 = pSpriteFrameTable->GetFrame(v39, v40);
-        goto LABEL_25;
-      }
-      v40 = v12;
-	  v39 = actor->pSpriteIDs[v10];
-      if ( v13 != 16 )
-        goto LABEL_24;
-      v14 = pSpriteFrameTable->GetFrameBy_x(v39, v12);
-LABEL_25:
+      if ( pActors[i].uAIState == 17 && !v49 )
+        v14 = pSpriteFrameTable->GetFrame(uSpriteID_Spell11, v12);
+      else if ( pActors[i].uAIState == 16 )
+        v14 = pSpriteFrameTable->GetFrameBy_x(pActors[i].pSpriteIDs[pActors[i].uCurrentActionAnimation], v12);
+      else
+        v14 = pSpriteFrameTable->GetFrame(pActors[i].pSpriteIDs[pActors[i].uCurrentActionAnimation], v12);
       v62 = 0;
       v15 = v14;
       //v16 = (int *)v14->uFlags;
@@ -3055,19 +3035,19 @@
           return;
         ++uNumBillboardsToDraw;
         ++uNumSpritesDrawnThisFrame;
-		actor->uAttributes |= 8u;
+        pActors[i].uAttributes |= 8u;
         v28->uHwSpriteID = v15->pHwSpriteIDs[v41];
         v28->uIndoorSectorID = 0;
         v28->uPalette = v15->uPaletteIndex;
         v28->_screenspace_x_scaler_packedfloat = (unsigned __int64)(v15->scale * (signed __int64)v58) >> 16;
-        v30 = HIDWORD(actor->pActorBuffs[ACTOR_BUFF_SHRINK].uExpireTime) == 0;
-        v31 = SHIDWORD(actor->pActorBuffs[ACTOR_BUFF_SHRINK].uExpireTime) < 0;
+        v30 = HIDWORD(pActors[i].pActorBuffs[ACTOR_BUFF_SHRINK].uExpireTime) == 0;
+        v31 = SHIDWORD(pActors[i].pActorBuffs[ACTOR_BUFF_SHRINK].uExpireTime) < 0;
         v28->_screenspace_y_scaler_packedfloat = (unsigned __int64)(v15->scale * (signed __int64)v57) >> 16;
-        if ( v31 || v31 | v30 && LODWORD(actor->pActorBuffs[ACTOR_BUFF_SHRINK].uExpireTime) <= 0u )
+        if ( v31 || v31 | v30 && LODWORD(pActors[i].pActorBuffs[ACTOR_BUFF_SHRINK].uExpireTime) <= 0u )
         {
-          if ( (signed __int64)actor->pActorBuffs[ACTOR_BUFF_MASS_DISTORTION].uExpireTime > 0i64 )
+          if ( (signed __int64)pActors[i].pActorBuffs[ACTOR_BUFF_MASS_DISTORTION].uExpireTime > 0i64 )
           {
-            v52 = (unsigned __int64)(pGame->pStru6Instance->_4A806F(actor)
+            v52 = (unsigned __int64)(pGame->pStru6Instance->_4A806F(&pActors[i])
                                    * (signed __int64)v28->_screenspace_y_scaler_packedfloat) >> 16;
 LABEL_53:
             LOWORD(v27) = v43;
@@ -3076,10 +3056,10 @@
         }
         else
         {
-          v32 = actor->pActorBuffs[ACTOR_BUFF_SHRINK].uPower;
+          v32 = pActors[i].pActorBuffs[ACTOR_BUFF_SHRINK].uPower;
           if ( v32 )
           {
-            v33 = actor->pActorBuffs[ACTOR_BUFF_SHRINK].uPower;
+            v33 = pActors[i].pActorBuffs[ACTOR_BUFF_SHRINK].uPower;
             v28->_screenspace_x_scaler_packedfloat = (unsigned __int64)(65536 / (unsigned __int16)v32 * (signed __int64)v28->_screenspace_x_scaler_packedfloat) >> 16;
             v52 = (unsigned __int64)(65536 / v33 * (signed __int64)v28->_screenspace_y_scaler_packedfloat) >> 16;
             goto LABEL_53;
@@ -3096,11 +3076,11 @@
         v28->sZValue = v34 + PID(OBJECT_Actor, i);
         v28->field_14_actor_id = i;
         v35 = pMonsterList->pMonsters;
-		v36 = actor->pMonsterInfo.uID;
+		v36 = pActors[i].pMonsterInfo.uID;
         v28->field_1E = v62 | 0x200;
         v28->pSpriteFrame = v15;
-        v28->sTintColor = pMonsterList->pMonsters[actor->pMonsterInfo.uID-1].sTintColor;//*((int *)&v35[v36] - 36);
-        if (actor->pActorBuffs[ACTOR_BUFF_STONED].uExpireTime)
+        v28->sTintColor = pMonsterList->pMonsters[pActors[i].pMonsterInfo.uID-1].sTintColor;//*((int *)&v35[v36] - 36);
+        if (pActors[i].pActorBuffs[ACTOR_BUFF_STONED].uExpireTime)
           v28->field_1E = v62 | 0x200;
       }
 //LABEL_58:
@@ -4209,10 +4189,7 @@
   {
 	  if ( !bUnderwater && v34 <= 0)
 	  {
-		if ( v34 < -500
-		  && !pParty->bFlying
-		  && pParty->vPosition.z - v111 > 1000
-		  && !pParty->FeatherFallActive())
+		if ( v34 < -500 && !pParty->bFlying && pParty->vPosition.z - v111 > 1000 && !pParty->FeatherFallActive())
 		{ // falling scream
 		  for (int i = 0; i < 4; ++i)
 		  {
@@ -4258,9 +4235,9 @@
     if ( stru_721530._47050A(v36) )
       break;
     _46E889_collide_against_bmodels(1);
-    v37 = WorldPosToGridCellZ(pParty->vPosition.y);
-    v38 = WorldPosToGridCellX(pParty->vPosition.x);
-    _46E26D_collide_against_sprites(v38, v37);
+    //v37 = WorldPosToGridCellZ(pParty->vPosition.y);
+    //v38 = WorldPosToGridCellX(pParty->vPosition.x);
+    _46E26D_collide_against_sprites(WorldPosToGridCellX(pParty->vPosition.x), WorldPosToGridCellZ(pParty->vPosition.y));
     _46ED8A_collide_against_sprite_objects(4);
     for ( i = 0; i < (signed int)uNumActors; ++i )
       Actor::_46DF1A_collide_against_actor(i, 0);
@@ -4383,7 +4360,7 @@
             v2 = 0;
             *(float *)&v128 = 0.0;
           }
-          if ( pParty->floor_face_pid != v45 && (pODMFace->uAttributes & FACE_PRESSURE_PLATE))
+          if ( pParty->floor_face_pid != v45 && pODMFace->Pressure_Plate() )
           {
             pParty->floor_face_pid = v45;
             v103 = pODMFace->sCogTriggeredID; //
@@ -4419,7 +4396,7 @@
             if ( !v119 )
               pZ = v122 + (pODMFace->pFacePlane.vNormal.z * v55 >> 16);
           }
-          if ( pParty->floor_face_pid != stru_721530.uFaceID && BYTE3(pODMFace->uAttributes) & 4 )
+          if ( pParty->floor_face_pid != stru_721530.uFaceID && pODMFace->Pressure_Plate() )
           {
             pParty->floor_face_pid = stru_721530.uFaceID;
             v103 = pODMFace->sCogTriggeredID; //
@@ -4440,7 +4417,7 @@
         pParty->uFallSpeed += (unsigned __int64)(v118 * (signed __int64)pODMFace->pFacePlane.vNormal.z) >> 16;
         if ( v2 * v2 + v128 * v128 >= 400 )
         {
-          if ( pParty->floor_face_pid != stru_721530.uFaceID && BYTE3(pODMFace->uAttributes) & 4 )
+          if ( pParty->floor_face_pid != stru_721530.uFaceID && pODMFace->Pressure_Plate() )
           {
             pParty->floor_face_pid = stru_721530.uFaceID;
             v103 = pODMFace->sCogTriggeredID; //
@@ -4554,8 +4531,8 @@
           {
             for ( uint i = 1; i <= 4; ++i )
             {
-              v110 = pPlayers[i]->GetMaxHealth();
-              pPlayers[i]->ReceiveDamage((signed int)((pParty->uFallStartY - pZ) * (unsigned __int64)(signed __int64)((double)v110 * 0.1)) / 256,
+              //v110 = pPlayers[i]->GetMaxHealth();
+              pPlayers[i]->ReceiveDamage((signed int)((pParty->uFallStartY - pZ) * (unsigned __int64)(signed __int64)((double)pPlayers[i]->GetMaxHealth() * 0.1)) / 256,
                 DMGT_PHISYCAL);
               v110 = 20 - pPlayers[i]->GetParameterBonus(pPlayers[i]->GetActualEndurance());
               pPlayers[i]->SetRecoveryTime((signed __int64)((double)v110 * flt_6BE3A4_debug_recmod1 * 2.133333333333333));
--- a/Outdoor.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Outdoor.h	Thu Jan 02 09:11:28 2014 +0600
@@ -88,7 +88,9 @@
   inline bool Visible() const   {return !Invisible();}
   inline bool Portal() const    {return (uAttributes & FACE_PORTAL) != 0;}
   inline bool Fluid() const     {return (uAttributes & FACE_FLUID) != 0;}
+  inline bool Indoor_sky() const {return (uAttributes & FACE_INDOOR_SKY) != 0;}
   inline bool Clickable() const {return (uAttributes & FACE_CLICKABLE) != 0;}
+  inline bool Pressure_Plate() const {return (uAttributes & FACE_PRESSURE_PLATE) != 0;}
   inline bool Ethereal() const {return (uAttributes & FACE_ETHEREAL) != 0;}
 
   struct Plane_int_ pFacePlane;
--- a/ParticleEngine.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/ParticleEngine.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -649,8 +649,28 @@
         p->uScreenSpaceY >= pBLVRenderParams->uViewportY &&
         p->uScreenSpaceY < pBLVRenderParams->uViewportW)
     {
-      if (pRenderer->pRenderD3D)
+      if (!pRenderer->pRenderD3D)
       {
+        __debugbreak();
+                    /*v11 = 13 * p->_screenspace_scale >> 16;
+                     if ( v11 > 30 )
+                       v11 = 30;
+                    v12 = p->uScreenSpaceY - v11;
+                    v13 = p->uScreenSpaceX - (v11 >> 1);
+                     if ( v13 + v11 < (signed int)pViewport->uViewportTL_X
+                       || v13 >= (signed int)pViewport->uViewportBR_X
+                       || v12 + v11 < (signed int)pViewport->uViewportTL_Y
+                       || v12 >= (signed int)pViewport->uViewportBR_Y )
+                     {
+                      ;
+                     }
+                     else
+                     {
+                       pRenderer->MakeParticleBillboardAndPush_BLV_Software(v13, v12, p->sZValue, p->uLightColor_bgr, v11);
+                     }*/
+      }
+      //else
+
         if (p->type & ParticleType_Diffuse)
         {
           //v14 = &pParticles[i];
@@ -703,26 +723,6 @@
           v15.sZValue = p->sZValue;
           pRenderer->MakeParticleBillboardAndPush_BLV(&v15, pSprites_LOD->pHardwareSprites[p->uTextureID].pTexture, p->uLightColor_bgr, p->angle);
         }
-      }
-      else
-      {
-                    v11 = 13 * p->_screenspace_scale >> 16;
-                     if ( v11 > 30 )
-                       v11 = 30;
-                    v12 = p->uScreenSpaceY - v11;
-                    v13 = p->uScreenSpaceX - (v11 >> 1);
-                     if ( v13 + v11 < (signed int)pViewport->uViewportTL_X
-                       || v13 >= (signed int)pViewport->uViewportBR_X
-                       || v12 + v11 < (signed int)pViewport->uViewportTL_Y
-                       || v12 >= (signed int)pViewport->uViewportBR_Y )
-                     {
-                      ;
-                     }
-                     else
-                     {
-                       pRenderer->MakeParticleBillboardAndPush_BLV_Software(v13, v12, p->sZValue, p->uLightColor_bgr, v11);
-                     }
-      }
     }
   }
 }
@@ -759,8 +759,28 @@
     if (particle->type == ParticleType_Invalid || !ViewProject_TrueIfStillVisible_ODM(i))
       continue;
 
-        if ( pRenderer->pRenderD3D )
+        if ( !pRenderer->pRenderD3D )
         {
+          __debugbreak();
+          /*v10 = 13 * particle->_screenspace_scale >> 16;
+          if ( v10 > 30 )
+            v10 = 30;
+          v11 = particle->uScreenSpaceX - (v10 >> 1);
+          v12 = particle->uScreenSpaceY - v10;
+          if ( v11 + v10 < pViewport->uViewportTL_X
+            || v11 >= pViewport->uViewportBR_X
+            || particle->uScreenSpaceY < pViewport->uViewportTL_Y
+            || v12 >= (signed int)pViewport->uViewportBR_Y )
+          {
+            ;
+          }
+          else
+          {
+            pRenderer->MakeParticleBillboardAndPush_BLV_Software(v11, v12, particle->sZValue, particle->uLightColor_bgr, v10);
+          }*/
+        }
+        //else
+
           //v8 = *(_DWORD *)(v7 - 82);
           if (particle->type & ParticleType_Diffuse)
           {
@@ -813,26 +833,6 @@
             pBillboard.uScreenSpaceY = particle->uScreenSpaceY;
             pBillboard.sZValue = particle->sZValue;
             pRenderer->MakeParticleBillboardAndPush_ODM(&pBillboard, pSprites_LOD->pHardwareSprites[particle->uTextureID].pTexture, particle->uLightColor_bgr, particle->angle);
-          }
-        }
-        else
-        {
-          v10 = 13 * particle->_screenspace_scale >> 16;
-          if ( v10 > 30 )
-            v10 = 30;
-          v11 = particle->uScreenSpaceX - (v10 >> 1);
-          v12 = particle->uScreenSpaceY - v10;
-          if ( v11 + v10 < pViewport->uViewportTL_X
-            || v11 >= pViewport->uViewportBR_X
-            || particle->uScreenSpaceY < pViewport->uViewportTL_Y
-            || v12 >= (signed int)pViewport->uViewportBR_Y )
-          {
-            ;
-          }
-          else
-          {
-            pRenderer->MakeParticleBillboardAndPush_BLV_Software(v11, v12, particle->sZValue, particle->uLightColor_bgr, v10);
-          }
-        }      
+          }   
   }
 }
\ No newline at end of file
--- a/Party.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Party.h	Thu Jan 02 09:11:28 2014 +0600
@@ -50,6 +50,7 @@
 /*  355 */
 enum PARTY_FLAGS_1: __int32
 {
+  PARTY_FLAGS_1_0002 = 0x0002,
   PARTY_FLAGS_1_WATER_DAMAGE = 0x0004,
   PARTY_FLAGS_1_FALLING = 0x0008,
   PARTY_FLAGS_1_ALERT_RED = 0x0010,
--- a/Player.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Player.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -579,11 +579,11 @@
       {
         for (int i = 0; i < pSoundList->sNumSounds; i++)
         {
-          if (pSoundList->pSounds[i].uSoundID == pickedSoundID)
+          if (pSoundList->pSL_Sounds[i].uSoundID == pickedSoundID)
             pSoundID = i;
         }
       }
-      if ( pSoundList->pSounds[pSoundID].pSoundData[0] )
+      if ( pSoundList->pSL_Sounds[pSoundID].pSoundData[0] )
         expressionDuration = (sLastTrackLengthMS << 7) / 1000;
     }
     PlayEmotion(expression, expressionDuration);
--- a/Render.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Render.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -87,7 +87,7 @@
 signed int __stdcall RenderD3D__DeviceEnumerator(GUID *lpGUID, const char *lpDevDesc, const char *lpDriverName, RenderD3D__DevInfo *pOut); // idb
 
 //----- (0049E79F) --------------------------------------------------------
-bool  CheckTextureStages()
+bool CheckTextureStages()
 {
   bool v0; // edi@1
   IDirectDrawSurface4 *pSurface2; // [sp+Ch] [bp-14h]@1
@@ -1206,7 +1206,7 @@
 {
   HRESULT v2; // esi@2
 
-  if ( Src->dwFlags & 0x400 | 0x2000 )
+  if ( Src->dwFlags & (0x400 | 0x2000))
   {
     v2 = 0;
     if ( Src->dwRGBBitCount == 16 && !Src->dwRBitMask )
@@ -1215,7 +1215,7 @@
     {
       v2 = 1;
 LABEL_6:
-      memcpy(Dst, Src, 0x20u);
+      memcpy(Dst, Src, sizeof(DDPIXELFORMAT));
       return v2;
     }
   }
@@ -1236,9 +1236,6 @@
 //----- (0049DC58) --------------------------------------------------------
 RenderD3D::RenderD3D()
 {
-  RenderD3D *v1; // esi@1
-
-  v1 = this;
   this->pHost = 0;
   this->pDirect3D = 0;
   this->pUnk = 0;
@@ -1375,7 +1372,7 @@
 }
 
 //----- (0049DE14) --------------------------------------------------------
-bool RenderD3D::CreateDevice(unsigned int uDeviceID, int bWindowed, HWND hWnd)
+bool RenderD3D::CreateDevice(unsigned int uDeviceID, int bWindowed, OSWindow *window)
 {
   //IDirectDraw4 *v8; // eax@12
   //IDirectDraw4 *v9; // eax@16
@@ -1391,6 +1388,10 @@
   IDirectDrawClipper *v30; // [sp+C4h] [bp-14h]@18
   LPDIRECTDRAW lpDD; // [sp+C8h] [bp-10h]@1
 
+  auto hWnd = window->GetApiHandle();
+  int game_width = window->GetWidth();
+  int game_height = window->GetHeight();
+
   this->bWindowed = bWindowed;
   this->hWindow = hWnd;
 
@@ -1432,7 +1433,7 @@
     {
       ddsd2.dwSize = sizeof(DDSURFACEDESC2);
       pHost->GetDisplayMode(&ddsd2);
-      if ( ddsd2.ddpfPixelFormat.dwRGBBitCount != 16 )
+      if ( FORCE_16_BITS && ddsd2.ddpfPixelFormat.dwRGBBitCount != 16 )
       {
         v24 = "Init - Desktop isn't in 16 bit mode.\n";
         goto LABEL_14;
@@ -1440,8 +1441,8 @@
 
       ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
       ddsd2.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE;
-      ddsd2.dwWidth = 640;
-      ddsd2.dwHeight = 480;
+      ddsd2.dwWidth = game_width;
+      ddsd2.dwHeight = game_height;
       if (pHost->CreateSurface(&ddsd2, &pBackBuffer, 0) )
       {
         v24 = "Init - Failed to create back buffer.\n";
@@ -1469,8 +1470,8 @@
 
       ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
       ddsd2.ddsCaps.dwCaps = DDSCAPS_ZBUFFER;
-      ddsd2.dwWidth = 640;
-      ddsd2.dwHeight = 480;
+      ddsd2.dwWidth = game_width;
+      ddsd2.dwHeight = game_height;
 
       if ( pDirect3D->EnumZBufferFormats(*pAvailableDevices[uDeviceID].pGUID,
              (HRESULT (__stdcall *)(DDPIXELFORMAT *, void *))D3DZBufferFormatEnumerator,
@@ -1610,8 +1611,8 @@
 LABEL_54:
   d3dvp2.dwSize = sizeof(D3DVIEWPORT2);
   //v17 = *hWnda;
-  d3dvp2.dwWidth = 640;
-  d3dvp2.dwHeight = 480;
+  d3dvp2.dwWidth = game_width;
+  d3dvp2.dwHeight = game_height;
   d3dvp2.dvClipX = -1.0;
   //v18 = v17->lpVtbl;
   //v32 = &v4->pViewport;
@@ -2106,14 +2107,14 @@
   v1->pRenderD3D = 0;
   v1->uNumSceneBegins = 0;
   v1->uNumD3DSceneBegins = 0;
-  v1->field_40110 = 0;
+  v1->using_software_screen_buffer = 0;
   v1->pTargetSurface = 0;
   v1->uTargetSurfacePitch = 0;
   v1->uClipY = 0;
   v1->uClipX = 0;
   v1->uClipW = 480;
   v1->bClip = 1;
-  v1->bColorKeySupported = 0;
+  //v1->bColorKeySupported = 0;
   v1->bRequiredTextureStagesAvailable = 0;
   v1->bTinting = 1;
   LOBYTE(v1->field_103668) = 0;
@@ -2127,12 +2128,12 @@
   sub_4A19B0();
 }
 
-bool Render::Initialize(bool bWindowed, OSWindow *window, bool bColoredLights, uint32_t uDetailLevel, bool bTinting)
+bool Render::Initialize(OSWindow *window, bool bColoredLights, uint32_t uDetailLevel, bool bTinting)
 {
   //bUserDirect3D = true;//ReadWindowsRegistryInt("Use D3D", 0);
 
   this->window = window;
-  bStartInWindow = bWindowed;
+  //bStartInWindow = true;
   //windowed_mode_width = windowed_width;
   //windowed_mode_height = windowed_height;
 
@@ -2149,62 +2150,13 @@
   return r1 && r2;
 }
 
-//----- (0049EBF1) --------------------------------------------------------
-void Render::_49EBF1()
-{
-  signed int uNumRedBits; // edx@1
-  signed int uNuGreenBits; // edi@1
-  signed int uNumBlueBits; // esi@1
-  unsigned int v4; // edx@4
-  unsigned int v5; // edi@4
-  int v6; // ebx@4
-  int v7; // edx@4
-  signed int v8; // [sp+8h] [bp-24h]@1
-  signed int v9; // [sp+Ch] [bp-20h]@1
-  signed int v10; // [sp+20h] [bp-Ch]@1
-  signed int i; // [sp+24h] [bp-8h]@2
-  signed int v12; // [sp+28h] [bp-4h]@3
-
-  v10 = 0;
-  uNumRedBits = 1 << this->uTargetRBits;
-  uNuGreenBits = 1 << this->uTargetGBits;
-  uNumBlueBits = 1 << this->uTargetBBits;
-  v9 = 1 << this->uTargetRBits;
-  v8 = 1 << this->uTargetGBits;
-  if ( uNumRedBits > 0 )
-  {
-    do
-    {
-      for ( i = 0; i < uNuGreenBits; ++i )
-      {
-        v12 = 0;
-        if ( uNumBlueBits > 0 )
-        {
-          do
-          {
-            v4 = this->uTargetBBits;
-            v5 = v4 + this->uTargetGBits;
-            v6 = (v12 >> 1) + (v10 >> 1 << v5) + (i >> 1 << this->uTargetBBits);
-            v7 = (v10 << v5) + v12++ + (i << v4);
-            this->field_2C[v7] = v6;
-          }
-          while ( v12 < uNumBlueBits );
-          uNumRedBits = v9;
-          uNuGreenBits = v8;
-        }
-      }
-      ++v10;
-    }
-    while ( v10 < uNumRedBits );
-  }
-}
 
 //----- (0049ECC4) --------------------------------------------------------
 void Render::ClearBlack()
 {
   if (pRenderD3D)
   {
-    if (field_40110)
+    if (using_software_screen_buffer)
       pRenderD3D->ClearTarget(true, 0, false, 0.0);
   }
   else
@@ -2238,84 +2190,74 @@
 //----- (0049EDB6) --------------------------------------------------------
 void Render::SavePCXScreenshot()
 {
-  Render *v1; // esi@1
-  __int16 v2; // di@1
-  int v3; // eax@4
-  int v4; // ecx@4
   int v5; // eax@8
-  FILE *v6; // edi@10
-  int v7; // ecx@11
-  int v8; // eax@11
+  FILE *pOutFile; // edi@10
+  unsigned short *v8; // eax@11
   int v9; // eax@13
   int v10; // ecx@15
-  unsigned __int8 v11; // dl@15
   signed int v12; // eax@18
-  char v13; // zf@27
   HRESULT v14; // eax@29
   char v15[56]; // [sp+Ch] [bp-158h]@10
-  __int16 v16; // [sp+44h] [bp-120h]@10
   DDSURFACEDESC2 Dst; // [sp+48h] [bp-11Ch]@7
   char color_map[48]; // [sp+C4h] [bp-A0h]@10
   char Filename[40]; // [sp+F4h] [bp-70h]@3
-  char *v20; // [sp+11Ch] [bp-48h]@14
-  char *v21; // [sp+120h] [bp-44h]@14
-  int v24; // [sp+124h] [bp-40h]@11
+  char *lineB; // [sp+11Ch] [bp-48h]@14
+  char *lineG; // [sp+120h] [bp-44h]@14
+  //int v24; // [sp+124h] [bp-40h]@11
   FILE *File; // [sp+128h] [bp-3Ch]@3
-  int var38; // [sp+12Ch] [bp-38h]@4
   PCXHeader_1 header1; // [sp+130h] [bp-34h]@10
   PCXHeader_2 header2; // [sp+140h] [bp-24h]@10
-  void *ptr; // [sp+148h] [bp-1Ch]@10
-  void *v28; // [sp+14Ch] [bp-18h]@8
-  int v29; // [sp+150h] [bp-14h]@4
-  int v30; // [sp+154h] [bp-10h]@4
+  char *lineRGB; // [sp+148h] [bp-1Ch]@10
+  void *surface; // [sp+14Ch] [bp-18h]@8
+  int image_width; // [sp+150h] [bp-14h]@4
+  int pitch; // [sp+154h] [bp-10h]@4
   char v31; // [sp+15Ah] [bp-Ah]@25
-  unsigned __int8 v32; // [sp+15Bh] [bp-9h]@17
-  int i; // [sp+15Ch] [bp-8h]@10
-  unsigned __int8 v34; // [sp+163h] [bp-1h]@17
-
-  v1 = this;
-  v2 = 0;
-  if ( !this->pRenderD3D || this->field_40110 )
-  {
-    sprintf(Filename, "screen%0.2i.pcx", dword_4EFA80++ % 100);
+  unsigned char pict_byte; // [sp+15Bh] [bp-9h]@17
+  unsigned short *line_picture_data; // [sp+15Ch] [bp-8h]@10
+  byte test_byte; // [sp+163h] [bp-1h]@17
+
+  int num_r_bits = 5;
+  int num_g_bits = 6;
+  int num_b_bits = 5;
+
+  int r_mask = 0xF800;
+  int g_mask = 0x7E0;
+  int b_mask = 0x1F;
+
+  if ( !this->pRenderD3D || this->using_software_screen_buffer )
+  {
+    sprintf(Filename, "screen%0.2i.pcx", ScreenshotFileNumber++ % 100);
     File = fopen(Filename, "wb");
     if ( File )
     {
-      v3 = v1->field_10;
-      v4 = v1->field_14;
-      var38 = v3;
-      v29 = v4;
-      v30 = v3;
-      if ( v3 & 1 )
-        v30 = v3 + 1;
-      if ( v1->pRenderD3D )
-      {
-        memset(&Dst, 0, 0x7Cu);
+      pitch = this->field_10;
+      if ( this->field_10 & 1 )
+        pitch = this->field_10 + 1;
+      if ( this->pRenderD3D )
+      {
+        memset(&Dst, 0, 0x7C);
         Dst.dwSize = 124;
         if ( !pRenderer->LockSurface_DDraw4(pRenderer->pBackBuffer4, &Dst, DDLOCK_WAIT) )
           return;
-        v28 = Dst.lpSurface;
-        v5 = Dst.lPitch >> 1;
-        v2 = 0;
+        surface = Dst.lpSurface;
+        v5 = Dst.lPitch / 2;
       }
       else
       {
         pRenderer->BeginScene();
-        v28 = pRenderer->pTargetSurface;
+        surface = pRenderer->pTargetSurface;
         v5 = pRenderer->uTargetSurfacePitch;
       }
-      i = v5;
-      header1.right = var38 - 1;
-      header1.left = v2;
-      header1.bottom = v29 - 1;
-      header1.up = v2;
-      header2.pitch = v30;
+      header1.right = this->field_10 - 1;
+      header1.left = 0;
+      header1.bottom = this->field_14 - 1;
+      header1.up = 0;
+      header2.pitch = pitch;
       memset(color_map, 0, sizeof(color_map));
       memset(v15, 0, sizeof(v15));
       header2.reserved = 0;
       header1.manufacturer = 10;
-      v16 = 0;
-      v6 = File;
+      pOutFile = File;
       header1.version = 5;
       header1.encoding = 1;
       header1.bpp = 8;
@@ -2323,128 +2265,105 @@
       header1.vdpi = 75;
       header2.planes = 3;
       header2.palette_info = 1;
-      fwrite(&header1, 1u, 1u, File);
-      fwrite(&header1.version, 1u, 1u, v6);
-      fwrite(&header1.encoding, 1u, 1u, v6);
-      fwrite(&header1.bpp, 1u, 1u, v6);
-      fwrite(&header1.left, 2u, 1u, v6);
-      fwrite(&header1.up, 2u, 1u, v6);
-      fwrite(&header1.right, 2u, 1u, v6);
-      fwrite(&header1.bottom, 2u, 1u, v6);
-      fwrite(&header1.hdpi, 2u, 1u, v6);
-      fwrite(&header1.vdpi, 2u, 1u, v6);
-      fwrite(color_map, 0x30u, 1u, v6);
-      fwrite(&header2, 1u, 1u, v6);
-      fwrite(&header2.planes, 1u, 1u, v6);
-      fwrite(&header2.pitch, 2u, 1u, v6);
-      fwrite(&header2.palette_info, 2u, 1u, v6);
-      fwrite(v15, 0x3Au, 1u, v6);
-      ptr = malloc(3 * var38 + 6);
-      if ( v29 > 0 )
-      {
-        v7 = v30;
-        File = (FILE *)v29;
-        v29 = 3 * v30;
-        v24 = 2 * i;
-        v8 = (int)v28;
-        while ( 1 )
+      fwrite(&header1, 1, 1, File);
+      fwrite(&header1.version, 1, 1, pOutFile);
+      fwrite(&header1.encoding, 1, 1, pOutFile);
+      fwrite(&header1.bpp, 1, 1, pOutFile);
+      fwrite(&header1.left, 2, 1, pOutFile);
+      fwrite(&header1.up, 2, 1, pOutFile);
+      fwrite(&header1.right, 2, 1, pOutFile);
+      fwrite(&header1.bottom, 2, 1, pOutFile);
+      fwrite(&header1.hdpi, 2, 1, pOutFile);
+      fwrite(&header1.vdpi, 2, 1, pOutFile);
+      fwrite(color_map, 0x30u, 1, pOutFile);
+      fwrite(&header2, 1, 1, pOutFile);
+      fwrite(&header2.planes, 1, 1, pOutFile);
+      fwrite(&header2.pitch, 2, 1, pOutFile);
+      fwrite(&header2.palette_info, 2, 1, pOutFile);
+      fwrite(v15, 0x3Au, 1, pOutFile);
+      lineRGB = (char *)malloc(3 * this->field_10 + 6);
+      if ( this->field_14 > 0 )
+      {
+        image_width = 3 * pitch;
+        //v24 = 2 * v5;
+        v8 = (unsigned short *)surface;
+        for ( int y = 0; y < this->field_14; y++ )
         {
-          i = v8;
-          v9 = 0;
-          if ( var38 > 0 )
+          line_picture_data = v8;
+          if ( this->field_10 > 0 )
           {
-            v21 = (char *)ptr + v7;
-            v20 = (char *)ptr + 2 * v30;
-            do
+            lineG = (char *)lineRGB + pitch;
+            lineB = (char *)lineRGB + 2 * pitch;
+            for ( uint x = 0; x < this->field_10; x++ )
             {
-              *((char *)ptr + v9) = (signed int)(v1->uTargetRMask & *(short *)i) >> (LOBYTE(v1->uTargetGBits)
-                                                                                    + LOBYTE(v1->uTargetBBits)
-                                                                                    + v1->uTargetRBits
-                                                                                    - 8);
-              v21[v9] = (signed int)(v1->uTargetGMask & *(short *)i) >> (LOBYTE(v1->uTargetBBits)
-                                                                       + LOBYTE(v1->uTargetGBits)
-                                                                       - 8);
-              v10 = i;
-              v11 = LOBYTE(v1->uTargetBMask);
-              i += 2;
-              v20[v9++] = (*(char *)v10 & v11) << (8 - LOBYTE(v1->uTargetBBits));
+			  int p = *line_picture_data; //0x2818
+              int for_rad = (pRenderer->uTargetGBits + pRenderer->uTargetBBits );//16 = 8 + 8
+			  int value = (pRenderer->uTargetRMask & *line_picture_data);//0 = 0xFF0000 & 0x2818
+			  int result = (pRenderer->uTargetRMask & *line_picture_data) >> (pRenderer->uTargetGBits + pRenderer->uTargetBBits );
+              lineRGB[x] = (pRenderer->uTargetRMask & *line_picture_data) >> (pRenderer->uTargetGBits + pRenderer->uTargetBBits );// + pRenderer->uTargetRBits - 8);
+              lineG[x] = (pRenderer->uTargetGMask & *line_picture_data) >> (pRenderer->uTargetBBits);// + pRenderer->uTargetGBits - 8);
+			  int value2 = (pRenderer->uTargetGMask & *line_picture_data); //10240 = 0xFF00 & 0x2818
+			  int result2 = (pRenderer->uTargetGMask & *line_picture_data) >> (pRenderer->uTargetBBits);
+              lineB[x] = (pRenderer->uTargetBMask & *line_picture_data);// << (8 - pRenderer->uTargetBBits);
+		      int value3 = (pRenderer->uTargetBMask & *line_picture_data);//24 = 0xFF & 0x2818
+              line_picture_data += 2;
             }
-            while ( v9 < var38 );
           }
-          for ( i = 0; i < v29; i += v34 )
+          for ( uint i = 0; i < image_width; i += test_byte )
           {
-            v34 = 1;
-            v32 = *((char *)ptr + i);
-            do
+            pict_byte = lineRGB[i];
+            for ( test_byte = 1; test_byte < 0x3F; ++test_byte )
             {
-              v12 = i + v34;
-              if ( *((char *)ptr + v12) != v32 )
+              v12 = i + test_byte;
+              if ( lineRGB[v12] != pict_byte )
                 break;
-              if ( !(v12 % v30) )
+              if ( !(v12 % pitch) )
                 break;
-              ++v34;
-            }
-            while ( v34 < 0x3Fu );
-            if ( i + v34 > v29 )
-              v34 = 3 * v30 - i;
-            if ( v34 > 1u || v32 >= 0xC0u )
-            {
-              v31 = v34 | 0xC0;
-              fwrite(&v31, 1u, 1u, v6);
             }
-            fwrite(&v32, 1u, 1u, v6);
+            if ( i + test_byte > image_width )
+              test_byte = 3 * pitch - i;
+            if ( test_byte > 1 || pict_byte >= 0xC0 )
+            {
+              v31 = test_byte | 0xC0;
+              fwrite(&v31, 1, 1, pOutFile);
+            }
+            fwrite(&pict_byte, 1, 1, pOutFile);
           }
-          v8 = (int)((char *)v28 + v24);
-          v13 = File == (FILE *)1;
-          File = (FILE *)((char *)File - 1);
-          v28 = (char *)v28 + v24;
-          if ( v13 )
-            break;
-          v7 = v30;
+          v8 += v5;
         }
       }
-      if ( v1->pRenderD3D )
-      {
+      if ( this->pRenderD3D )
         ErrD3D(pRenderer->pBackBuffer4->Unlock(0));
-      }
       else
-      {
         pRenderer->EndScene();
-      }
-
-      free(ptr);
-      fclose(v6);
+
+      free(lineRGB);
+      fclose(pOutFile);
     }
   }
 }
 // 4EFA80: using guessed type int dword_4EFA80;
 
 //----- (0049F1BC) --------------------------------------------------------
-void Render::_49F1BC(const char *a1)
-{
-  Render *v2; // esi@1
-  __int16 v3; // di@1
-  int v4; // eax@4
-  char *v5; // ecx@4
+void Render::SaveWinnersCertificate(const char *a1)
+{
   unsigned int v6; // eax@8
-  FILE *v7; // edi@10
+  //FILE *v7; // edi@10
   int v8; // ecx@11
-  int v9; // eax@11
+  unsigned short *v9; // eax@11
   int v10; // eax@13
-  const char *v11; // ecx@15
-  unsigned __int8 v12; // dl@15
   signed int v13; // eax@18
   char v14; // zf@27
   HRESULT v15; // eax@29
-  char v16; // [sp+Ch] [bp-12Ch]@10
+  char v16[56]; // [sp+Ch] [bp-12Ch]@10
   __int16 v17; // [sp+44h] [bp-F4h]@10
-  int Dst; // [sp+48h] [bp-F0h]@7
+  DDSURFACEDESC2 Dst; // [sp+48h] [bp-F0h]@7
   int v19; // [sp+58h] [bp-E0h]@8
   unsigned __int16 *v20; // [sp+6Ch] [bp-CCh]@8
-  char v21; // [sp+C4h] [bp-74h]@10
+  char color_map[48]; // [sp+C4h] [bp-74h]@10
   unsigned int v22; // [sp+F4h] [bp-44h]@11
-  char *v23; // [sp+F8h] [bp-40h]@14
-  int v24; // [sp+FCh] [bp-3Ch]@11
+  char *lineB; // [sp+F8h] [bp-40h]@14
+  int image_width; // [sp+FCh] [bp-3Ch]@11
   int v25; // [sp+100h] [bp-38h]@4
   FILE *File; // [sp+104h] [bp-34h]@3
   char Str; // [sp+108h] [bp-30h]@10
@@ -2461,58 +2380,57 @@
   char v38; // [sp+119h] [bp-1Fh]@10
   __int16 v39; // [sp+11Ah] [bp-1Eh]@10
   __int16 v40; // [sp+11Ch] [bp-1Ch]@10
-  void *ptr; // [sp+120h] [bp-18h]@10
-  unsigned __int16 *v42; // [sp+124h] [bp-14h]@8
-  int v43; // [sp+128h] [bp-10h]@4
+  char *lineRGB; // [sp+120h] [bp-18h]@10
+  void *surface; // [sp+124h] [bp-14h]@8
+  int pitch; // [sp+128h] [bp-10h]@4
   char v44; // [sp+12Fh] [bp-9h]@25
-  char *i; // [sp+130h] [bp-8h]@10
-  unsigned __int8 v46; // [sp+137h] [bp-1h]@17
-
-  v2 = this;
-  v3 = 0;
-  if ( !this->pRenderD3D || this->field_40110 )
+  char *lineG; // [sp+130h] [bp-8h]@10
+  unsigned char pict_byte; // [sp+137h] [bp-1h]@17
+  byte test_byte;
+
+  int num_r_bits = 5;
+  int num_g_bits = 6;
+  int num_b_bits = 5;
+
+  int r_mask = 0xF800;
+  int g_mask = 0x7E0;
+  int b_mask = 0x1F;
+
+  if ( !this->pRenderD3D || this->using_software_screen_buffer )
   {
     ++dword_4EFA84;
     File = fopen(a1, "wb");
     if ( File )
     {
-      v4 = v2->field_10;
-      v5 = (char *)v2->field_14;
-      v25 = v4;
-      a1 = v5;
-      v43 = v4;
-      if ( v4 & 1 )
-        v43 = v4 + 1;
-      if ( v2->pRenderD3D )
-      {
-        memset(&Dst, 0, 0x7Cu);
-        Dst = 124;
+      v25 = this->field_10;
+      pitch = this->field_10;
+      if ( this->field_10 & 1 )
+        pitch = this->field_10 + 1;
+      if ( this->pRenderD3D )
+      {
+        memset(&Dst, 0, 0x7C);
+        Dst.dwSize = 124;
         if ( !pRenderer->LockSurface_DDraw4(pRenderer->pBackBuffer4, (DDSURFACEDESC2 *)&Dst, DDLOCK_WAIT) )
           return;
-        __debugbreak(); // warning C4700: uninitialized local variable 'v20' used
-        v42 = v20;
-        __debugbreak(); // warning C4700: uninitialized local variable 'v19' used
-        v6 = v19 >> 1;
-        v3 = 0;
+        surface = Dst.lpSurface;
+        v6 = Dst.lPitch / 2;
       }
       else
       {
         pRenderer->BeginScene();
-        v42 = pRenderer->pTargetSurface;
+        surface = pRenderer->pTargetSurface;
         v6 = pRenderer->uTargetSurfacePitch;
       }
-      i = (char *)v6;
-      v33 = v25 - 1;
-      v31 = v3;
-      v34 = (short)a1 - 1;
-      v32 = v3;
-      v39 = v43;
-      memset(&v21, 0, 0x30u);
-      memset(&v16, 0, 0x38u);
+      v33 = this->field_10 - 1;
+      v31 = 0;
+      v34 = (short)this->field_14 - 1;
+      v32 = 0;
+      v39 = pitch;
+      memset(&color_map, 0, sizeof(color_map));
+      memset(&v16, 0, sizeof(v16));
       v37 = 0;
       Str = 10;
       v17 = 0;
-      v7 = File;
       v28 = 5;
       v29 = 1;
       v30 = 8;
@@ -2520,96 +2438,71 @@
       v36 = 75;
       v38 = 3;
       v40 = 1;
-      fwrite(&Str, 1u, 1u, File);
-      fwrite(&v28, 1u, 1u, v7);
-      fwrite(&v29, 1u, 1u, v7);
-      fwrite(&v30, 1u, 1u, v7);
-      fwrite(&v31, 2u, 1u, v7);
-      fwrite(&v32, 2u, 1u, v7);
-      fwrite(&v33, 2u, 1u, v7);
-      fwrite(&v34, 2u, 1u, v7);
-      fwrite(&v35, 2u, 1u, v7);
-      fwrite(&v36, 2u, 1u, v7);
-      fwrite(&v21, 0x30u, 1u, v7);
-      fwrite(&v37, 1u, 1u, v7);
-      fwrite(&v38, 1u, 1u, v7);
-      fwrite(&v39, 2u, 1u, v7);
-      fwrite(&v40, 2u, 1u, v7);
-      fwrite(&v16, 0x3Au, 1u, v7);
-      ptr = malloc(3 * v25 + 6);
-      if ( (signed int)a1 > 0 )
-      {
-        v8 = v43;
-        File = (FILE *)a1;
-        v24 = 3 * v43;
-        v22 = 2 * (int)i;
-        v9 = (int)v42;
-        while ( 1 )
+      fwrite(&Str, 1, 1, File);
+      fwrite(&v28, 1, 1, File);
+      fwrite(&v29, 1, 1, File);
+      fwrite(&v30, 1, 1, File);
+      fwrite(&v31, 2, 1, File);
+      fwrite(&v32, 2, 1, File);
+      fwrite(&v33, 2, 1, File);
+      fwrite(&v34, 2, 1, File);
+      fwrite(&v35, 2, 1, File);
+      fwrite(&v36, 2, 1, File);
+      fwrite(&color_map, 0x30, 1, File);
+      fwrite(&v37, 1, 1, File);
+      fwrite(&v38, 1, 1, File);
+      fwrite(&v39, 2, 1, File);
+      fwrite(&v40, 2, 1, File);
+      fwrite(&v16, 0x3A, 1, File);
+      lineRGB = (char *)malloc(3 * (v25 + 2));
+      if ( (signed int)this->field_14 > 0 )
+      {
+        image_width = 3 * pitch;
+        v9 = (unsigned short *)surface;
+        for ( uint j = 0; j < this->field_14; j++)
         {
           a1 = (const char *)v9;
-          v10 = 0;
           if ( v25 > 0 )
           {
-            i = (char *)ptr + v8;
-            v23 = (char *)ptr + 2 * v43;
-            do
+            lineG = (char *)lineRGB + pitch;
+            lineB = (char *)lineRGB + 2 * pitch;
+            for ( v10 = 0; v10 < v25; v10++ )
             {
-              *((char *)ptr + v10) = (signed int)(v2->uTargetRMask & *(short *)a1) >> (LOBYTE(v2->uTargetGBits)
-                                                                                      + LOBYTE(v2->uTargetBBits)
-                                                                                      + v2->uTargetRBits
-                                                                                      - 8);
-              i[v10] = (signed int)(v2->uTargetGMask & *(short *)a1) >> (LOBYTE(v2->uTargetBBits)
-                                                                       + LOBYTE(v2->uTargetGBits)
-                                                                       - 8);
-              v11 = a1;
-              v12 = LOBYTE(v2->uTargetBMask);
+              lineRGB[v10] = (signed int)(r_mask & *(short *)a1) >> (num_g_bits + num_b_bits + num_r_bits - 8);
+              lineG[v10] = (signed int)(g_mask & *(short *)a1) >> (num_b_bits + num_g_bits - 8);
+              lineB[v10] = (b_mask & *(short *)a1) << (8 - num_b_bits);
               a1 += 2;
-              v23[v10++] = ((unsigned __int8)*v11 & v12) << (8 - LOBYTE(v2->uTargetBBits));
             }
-            while ( v10 < v25 );
           }
-          for ( i = 0; (signed int)i < v24; i += BYTE3(a1) )
+          for ( uint i = 0; i < image_width; i += test_byte )
           {
-            BYTE3(a1) = 1;
-            v46 = *((char *)ptr + (int)i);
-            do
+            pict_byte = lineRGB[i];
+            for ( test_byte = 1; test_byte < 0x3F; test_byte )
             {
-              v13 = (signed int)&i[BYTE3(a1)];
-              if ( *((char *)ptr + v13) != v46 )
+              v13 = i + test_byte;
+              if ( lineRGB[v13] != pict_byte )
                 break;
-              if ( !(v13 % v43) )
+              if ( !(v13 % pitch) )
                 break;
-              ++BYTE3(a1);
             }
-            while ( BYTE3(a1) < 0x3Fu );
-            if ( (signed int)&i[BYTE3(a1)] > v24 )
-              BYTE3(a1) = 3 * v43 - (char)i;
-            if ( BYTE3(a1) > 1u || v46 >= 0xC0u )
+            if ( i + test_byte > image_width )
+              test_byte = 3 * pitch - i;
+            if ( test_byte > 1 || pict_byte >= 0xC0 )
             {
-              v44 = BYTE3(a1) | 0xC0;
-              fwrite(&v44, 1u, 1u, v7);
+              v44 = test_byte | 0xC0;
+              fwrite(&v44, 1, 1, File);
             }
-            fwrite(&v46, 1u, 1u, v7);
+            fwrite(&pict_byte, 1, 1, File);
           }
-          v9 = (int)&v42[v22 / 2];
-          v14 = File == (FILE *)1;
-          File = (FILE *)((char *)File - 1);
-          v42 = (unsigned __int16 *)((char *)v42 + v22);
-          if ( v14 )
-            break;
-          v8 = v43;
+          v9 += pitch;
         }
       }
-      if ( v2->pRenderD3D )
-      {
+      if ( this->pRenderD3D )
         ErrD3D(pRenderer->pBackBuffer4->Unlock(0));
-      }
       else
-      {
         pRenderer->EndScene();
-      }
-      free(ptr);
-      fclose(v7);
+      free(lineRGB);
+      fclose(File);
     }
   }
 }
@@ -2617,20 +2510,16 @@
 
 //----- (0049F5A2) --------------------------------------------------------
 void Render::PackPCXpicture( unsigned short* picture_data, int wight, int heidth, void *data_buff, int max_buff_size,unsigned int* packed_size )
-    {
-  Render *v7; // ebx@1
+{
   void *v8; // esi@3
   void *v9; // esi@3
-  int v10; // ecx@4
   unsigned short* v11; // eax@4
-  int v12; // eax@6
   int v13; // eax@8
   int v14; // ecx@8
   signed int v15; // eax@11
   char v16; // zf@20
   int result; // eax@21
   char v18[58]; // [sp+Ch] [bp-ACh]@3
- // __int16 v19; // [sp+44h] [bp-74h]@3
   char v20[48]; // [sp+48h] [bp-70h]@3
   char *lineG; // [sp+78h] [bp-40h]@7
   char *lineB; // [sp+7Ch] [bp-3Ch]@7
@@ -2644,11 +2533,18 @@
   int pitch; // [sp+ACh] [bp-Ch]@1
   char v43; // [sp+B3h] [bp-5h]@18
   int i; // [sp+B4h] [bp-4h]@6
-  unsigned short* line_pictute_data;
+  unsigned short* line_picture_data;
   byte test_byte;
   unsigned char pict_byte;
 
-  v7 = this;
+  int num_r_bits = 5;
+  int num_g_bits = 6;
+  int num_b_bits = 5;
+
+  int r_mask = 0xF800;
+  int g_mask = 0x7E0;
+  int b_mask = 0x1F;
+
   pitch = wight;
   if ( wight & 1 )
       pitch = wight + 1;
@@ -2670,35 +2566,35 @@
   Src.vdpi = 75;
   v27.planes = 3;
   v27.palette_info = 1;
-  memcpy(data_buff, &Src, 1u);
+  memcpy(data_buff, &Src, 1);
   v8 = (char *)v8 + 1;
-  memcpy(v8, &Src.version, 1u);
+  memcpy(v8, &Src.version, 1);
   v8 = (char *)v8 + 1;
-  memcpy(v8, &Src.encoding, 1u);
+  memcpy(v8, &Src.encoding, 1);
   v8 = (char *)v8 + 1;
-  memcpy(v8, &Src.bpp, 1u);
+  memcpy(v8, &Src.bpp, 1);
   v8 = (char *)v8 + 1;
-  memcpy(v8, &Src.left, 2u);
+  memcpy(v8, &Src.left, 2);
   v8 = (char *)v8 + 2;
-  memcpy(v8, &Src.up, 2u);
+  memcpy(v8, &Src.up, 2);
   v8 = (char *)v8 + 2;
-  memcpy(v8, &Src.right, 2u);
+  memcpy(v8, &Src.right, 2);
   v8 = (char *)v8 + 2;
-  memcpy(v8, &Src.bottom, 2u);
+  memcpy(v8, &Src.bottom, 2);
   v8 = (char *)v8 + 2;
-  memcpy(v8, &Src.hdpi, 2u);
+  memcpy(v8, &Src.hdpi, 2);
   v8 = (char *)v8 + 2;
-  memcpy(v8, &Src.vdpi, 2u);
+  memcpy(v8, &Src.vdpi, 2);
   v8 = (char *)v8 + 2;
   memcpy(v8, &v20, 0x30u);
   v8 = (char *)v8 + 48;
   memcpy(v8, &v27, 1u);
   v8 = (char *)v8 + 1;
-  memcpy(v8, &v27.planes, 1u);
+  memcpy(v8, &v27.planes, 1);
   v8 = (char *)v8 + 1;
-  memcpy(v8, &v27.pitch, 2u);
+  memcpy(v8, &v27.pitch, 2);
   v8 = (char *)v8 + 2;
-  memcpy(v8, &v27.palette_info, 2u);
+  memcpy(v8, &v27.palette_info, 2);
   v8 = (char *)v8 + 2;
   memcpy(v8, &v18, 0x3Au);
   v9 = (char *)v8 + 58;
@@ -2706,106 +2602,99 @@
   lineRGB = (char*)malloc(3 * (wight + 2));
   if ( heidth > 0 )
   {
-    v10 = pitch;
-    v25 = heidth;
     v26 = 3 * pitch;
     v23 = 2 * wight;
     v11 = picture_data;
     v24 = (int)picture_data;
-    while ( 1 )
-    {
-      line_pictute_data = v11;
-      v12 = 0;
-      i = 0;
+    for ( v25 = heidth; v25; v25-- )
+    {
+      line_picture_data = v11;
       if ( wight > 0 )
       {
         lineG = (char *)lineRGB + pitch;
         lineB = (char *)lineRGB + 2 * pitch;
-        do
+        for ( uint i = 0; i < wight; i++ )
         {
-          lineRGB[v12] = (signed int)(v7->uTargetRMask & *line_pictute_data) >> (v7->uTargetGBits  + v7->uTargetBBits  + v7->uTargetRBits  - 8);
-          lineG[v12] = (signed int)(v7->uTargetGMask & *line_pictute_data) >> ( v7->uTargetBBits + v7->uTargetGBits- 8);
-          lineB[v12] = (v7->uTargetBMask & *line_pictute_data) << (8 - v7->uTargetBBits);
-
-          v12++;
+          lineRGB[i] = (signed int)(r_mask & *line_picture_data) >> (num_g_bits  + num_b_bits  + num_r_bits  - 8);
+          lineG[i] = (signed int)(g_mask & *line_picture_data) >> ( num_b_bits + num_g_bits- 8);
+          lineB[i] = (b_mask & *line_picture_data) << (8 - num_b_bits);
+          line_picture_data += 1;
         }
-        while ( v12 < wight );
       }
       for ( i = 0; i < v26; v9 = (char *)v9 + 1 )
       {
-        test_byte = 1;
-        pict_byte = lineRGB [i];
-        do
+        pict_byte = lineRGB[i];
+        for ( test_byte = 1; test_byte < 63; ++test_byte )
         {
           v15 = i + test_byte;
-          if ( *((char *)lineRGB + v15) != pict_byte )
+          if ( lineRGB[v15] != pict_byte )
             break;
           if ( !(v15 % pitch) )
             break;
-          ++test_byte;
         }
-        while ( test_byte < 0x3Fu );
         if ( i + test_byte > v26 )
           test_byte = 3 * pitch - i;
-        if ( test_byte > 1u || pict_byte >= 0xC0u )
+        if ( test_byte > 1 || pict_byte >= 192 )
         {
           v43 = test_byte | 0xC0;
-          memcpy(v9, &v43, 1u);
+          memcpy(v9, &v43, 1);
           v9 = (char *)v9 + 1;
         }
-        memcpy(v9, &pict_byte, 1u);
+        memcpy(v9, &pict_byte, 1);
         i += test_byte;
       }
-      v11 +=wight ;
-      v16 = v25-- == 1;
-     
-      if ( v16 )
-        break;
-      v10 = pitch;
+      v11 += wight;
     }
   }
   free(lineRGB);
   *(int *)packed_size = (char *)v9 - data_buff;
- 
 }
 
 //----- (0049F8B5) --------------------------------------------------------
-FILE *Render::SavePCXImage(const char *Filename, char *a3, int a4, int a5)
-{
-  //Render *v5; // esi@1
+FILE *Render::SavePCXImage(const char *Filename, unsigned short* picture_data, int width, int height)
+{
   FILE *result; // eax@1
-  FILE *v7; // edi@4
-  int v8; // ecx@5
-  int v9; // eax@5
+  FILE *pOutFile; // edi@4
+  unsigned short* v9; // eax@5
   int v10; // eax@7
-  int v11; // ecx@9
   signed int v12; // eax@12
   char v13; // zf@21
   char v14[56]; // [sp+4h] [bp-A0h]@4
   __int16 v15; // [sp+3Ch] [bp-68h]@4
   char color_map[48]; // [sp+40h] [bp-64h]@4
-  int v17; // [sp+70h] [bp-34h]@5
   int v18; // [sp+74h] [bp-30h]@5
   char *v19; // [sp+78h] [bp-2Ch]@5
-  int v20; // [sp+7Ch] [bp-28h]@5
+  int image_width; // [sp+7Ch] [bp-28h]@5
   PCXHeader_1 header1; // [sp+80h] [bp-24h]@4
   PCXHeader_2 header2; // [sp+90h] [bp-14h]@4
-  void *ptr; // [sp+98h] [bp-Ch]@4
-  int v24; // [sp+9Ch] [bp-8h]@2
-  char *i; // [sp+A0h] [bp-4h]@8
+  char *lineRGB; // [sp+98h] [bp-Ch]@4
+  int pitch; // [sp+9Ch] [bp-8h]@2
+  char *lineB; // [sp+A0h] [bp-4h]@8
+  char *lineG;
+  unsigned short* line_pictute_data;
+  byte test_byte;
+  char v43;
+
+  int num_r_bits = 5;
+  int num_g_bits = 6;
+  int num_b_bits = 5;
+
+  int r_mask = 0xF800;
+  int g_mask = 0x7E0;
+  int b_mask = 0x1F;
 
   result = fopen(Filename, "wb");
   Filename = (const char *)result;
   if ( result )
   {
-    v24 = a4;
-    if ( a4 & 1 )
-      v24 = a4 + 1;
+    pitch = width;
+    if ( width & 1 )
+      pitch = width + 1;
     header1.left = 0;
     header1.up = 0;
-    header1.right = a4 - 1;
-    header1.bottom = a5 - 1;
-    header2.pitch = v24;
+    header1.right = width - 1;
+    header1.bottom = height - 1;
+    header2.pitch = pitch;
     memset(color_map, 0, sizeof(color_map));
     header2.reserved = 0;
     memset(v14, 0, sizeof(v14));
@@ -2818,88 +2707,67 @@
     header1.vdpi = 75;
     header2.planes = 3;
     header2.palette_info = 1;
-    fwrite(&header1, 1u, 1u, (FILE *)Filename);
-    v7 = (FILE *)Filename;
-    fwrite(&header1.version, 1u, 1u, (FILE *)Filename);
-    fwrite(&header1.encoding, 1u, 1u, v7);
-    fwrite(&header1.bpp, 1u, 1u, v7);
-    fwrite(&header1.left, 2u, 1u, v7);
-    fwrite(&header1.up, 2u, 1u, v7);
-    fwrite(&header1.right, 2u, 1u, v7);
-    fwrite(&header1.bottom, 2u, 1u, v7);
-    fwrite(&header1.hdpi, 2u, 1u, v7);
-    fwrite(&header1.vdpi, 2u, 1u, v7);
-    fwrite(color_map, 0x30u, 1u, v7);
-    fwrite(&header2, 1u, 1u, v7);
-    fwrite(&header2.planes, 1u, 1u, v7);
-    fwrite(&header2.pitch, 2u, 1u, v7);
-    fwrite(&header2.palette_info, 2u, 1u, v7);
-    fwrite(v14, 0x3Au, 1u, v7);
-    ptr = malloc(3 * a4 + 6);
-    if ( a5 > 0 )
-    {
-      v8 = v24;
-      v18 = a5;
-      v20 = 3 * v24;
-      v17 = 2 * a4;
-      v9 = (int)a3;
-      v19 = a3;
-      while ( 1 )
-      {
-        a5 = v9;
-        v10 = 0;
-        if ( a4 > 0 )
+    fwrite(&header1, 1, 1, (FILE *)Filename);
+    pOutFile = (FILE *)Filename;
+    fwrite(&header1.version, 1, 1, (FILE *)Filename);
+    fwrite(&header1.encoding, 1, 1, pOutFile);
+    fwrite(&header1.bpp, 1, 1, pOutFile);
+    fwrite(&header1.left, 2, 1, pOutFile);
+    fwrite(&header1.up, 2, 1, pOutFile);
+    fwrite(&header1.right, 2, 1, pOutFile);
+    fwrite(&header1.bottom, 2, 1, pOutFile);
+    fwrite(&header1.hdpi, 2, 1, pOutFile);
+    fwrite(&header1.vdpi, 2, 1, pOutFile);
+    fwrite(color_map, 0x30u, 1, pOutFile);
+    fwrite(&header2, 1, 1, pOutFile);
+    fwrite(&header2.planes, 1, 1, pOutFile);
+    fwrite(&header2.pitch, 2, 1, pOutFile);
+    fwrite(&header2.palette_info, 2, 1, pOutFile);
+    fwrite(v14, 0x3Au, 1, pOutFile);
+
+    lineRGB = (char *)malloc(3 * (width + 2));
+    //               
+    //      .
+    image_width = 3 * pitch;
+    v9 = picture_data;
+    for ( v18 = 0; v18 < height; v18++ )//
+    {
+      line_pictute_data = v9;
+      lineG = (char *)lineRGB + pitch;
+      lineB = (char *)lineRGB + 2 * pitch;
+
+      for ( int i = 0; i < width; i++ )//
+      {
+        lineRGB[i] = (signed int)(r_mask & *line_pictute_data) >> (num_g_bits + num_b_bits + num_r_bits - 8);
+        lineG[i] = (signed int)(g_mask & *line_pictute_data) >> (num_b_bits + num_g_bits - 8);
+        lineB[i] = (b_mask & *line_pictute_data) << (8 - num_b_bits);
+        line_pictute_data += 1;
+      }
+      test_byte = 1;
+      for ( int i = 0; (signed int)i < image_width; i += test_byte )
+      {
+        unsigned char pic_byte = lineRGB[i];
+         for ( test_byte; test_byte < 63; ++test_byte )//    
         {
-          a3 = (char *)ptr + v8;
-          i = (char *)ptr + 2 * v24;
-          do
-          {
-            *((char *)ptr + v10) = (signed int)(this->uTargetRMask & *(short *)a5) >> (LOBYTE(this->uTargetGBits)
-                                                                                    + LOBYTE(this->uTargetBBits)
-                                                                                    + this->uTargetRBits
-                                                                                    - 8);
-            a3[v10] = (signed int)(this->uTargetGMask & *(short *)a5) >> (LOBYTE(this->uTargetBBits)
-                                                                      + LOBYTE(this->uTargetGBits)
-                                                                      - 8);
-            v11 = a5;
-            a5 += 2;
-            i[v10++] = (this->uTargetBMask & *(char *)v11) << (8 - LOBYTE(this->uTargetBBits));
-          }
-          while ( v10 < a4 );
+          v12 = i + test_byte;
+          if ( lineRGB[v12] != pic_byte )
+            break;
+          if ( !(v12 % pitch) )
+            break;
         }
-        for ( i = 0; (signed int)i < v20; i += BYTE3(a5) )
+        if ( i + test_byte > image_width )
+          test_byte = 3 * pitch - i;
+        if ( test_byte > 1 || pic_byte >= 0xC0 )
         {
-          BYTE3(a5) = 1;
-          BYTE3(Filename) = *((char *)ptr + (int)i);
-          do
-          {
-            v12 = (signed int)&i[BYTE3(a5)];
-            if ( *((char *)ptr + v12) != BYTE3(Filename) )
-              break;
-            if ( !(v12 % v24) )
-              break;
-            ++BYTE3(a5);
-          }
-          while ( BYTE3(a5) < 0x3Fu );
-          if ( (signed int)&i[BYTE3(a5)] > v20 )
-            BYTE3(a5) = 3 * v24 - (char)i;
-          if ( BYTE3(a5) > 1u || BYTE3(Filename) >= 0xC0u )
-          {
-            BYTE3(a3) = BYTE3(a5) | 0xC0;
-            fwrite((char *)&a3 + 3, 1u, 1u, v7);
-          }
-          fwrite((char *)&Filename + 3, 1u, 1u, v7);
+          v43 = test_byte | 0xC0;//- 
+          fwrite(&v43, 1, 1, pOutFile);
         }
-        v9 = (int)&v19[v17];
-        v13 = v18-- == 1;
-        v19 += v17;
-        if ( v13 )
-          break;
-        v8 = v24;
-      }
-    }
-    free(ptr);
-    result = (FILE *)fclose(v7);
+        fwrite(&pic_byte, 1, 1, pOutFile);
+      }
+      v9 += width;
+    }
+    free(lineRGB);
+    result = (FILE *)fclose(pOutFile);
   }
   return result;
 }
@@ -2909,7 +2777,7 @@
 {
   if (pRenderD3D)
   {
-    if (field_40110)
+    if (using_software_screen_buffer)
       pRenderD3D->ClearTarget(true, uColor, false, 0.0);
   }
   else
@@ -2932,12 +2800,12 @@
   struct tagPOINT Point; // [sp+28h] [bp-8h]@11
 
   v1 = this;
-  if ( !pRenderer->pRenderD3D || this->field_40110 )
+  if ( !pRenderer->pRenderD3D || this->using_software_screen_buffer )
   {
     this->pBeforePresentFunction();
     if ( v1->pRenderD3D )
     {
-      if ( v1->field_40110 )
+      if ( v1->using_software_screen_buffer )
       {
         pRenderD3D->Present(false);
       }
@@ -3031,7 +2899,7 @@
   v1 = this;
   if (pRenderD3D)
   {
-    if ( v1->field_40110 )
+    if ( v1->using_software_screen_buffer )
     {
       pRenderD3D->ClearTarget(true, 0, false, 1.0);
       pRenderD3D->Present(0);
@@ -3043,9 +2911,9 @@
     v1->pDirectDraw4 = 0;
     if (v1->pTargetSurface)
     {
-      free(v1->ptr_400E8);
+      delete [] v1->pTargetSurface_unaligned;
       v1->pTargetSurface = 0;
-      v1->ptr_400E8 = 0;
+      v1->pTargetSurface_unaligned = 0;
     }
     if (pRenderD3D)
     {
@@ -3155,11 +3023,11 @@
   int v13; // ecx@25
   int v14; // eax@27
   signed int v15; // ebx@31
-  bool v16; // eax@35
-  char v17; // zf@35
+  //bool v16; // eax@35
+  //char v17; // zf@35
   IDirectDraw4 *v18; // eax@38
   HRESULT v19; // eax@38
-  int *v20; // eax@39
+  //int *v20; // eax@39
   int *v22; // eax@42
   int v23; // ecx@42
   D3DDEVICEDESC refCaps; // [sp+Ch] [bp-300h]@25
@@ -3169,13 +3037,15 @@
   void *v28; // [sp+2FCh] [bp-10h]@2
   int v29; // [sp+308h] [bp-4h]@2
 
+  __debugbreak(); // Nomad
+
   //v2 = this;
-  this->field_40110 = 0;
+  this->using_software_screen_buffer = 0;
   this->pColorKeySurface4 = 0;
   this->pBackBuffer4 = 0;
   this->pFrontBuffer4 = 0;
   this->pDirectDraw4 = 0;
-  this->bColorKeySupported = 0;
+  //this->bColorKeySupported = 0;
   Release();
   //v3 = hWnd;
   this->window = window;
@@ -3198,14 +3068,14 @@
     v7 = pRenderD3D->pAvailableDevices;
     if ( v7[v6].bIsDeviceCompatible )
     {
-      v8 = pRenderD3D->CreateDevice(v6, 0, window->GetApiHandle());
+      v8 = pRenderD3D->CreateDevice(v6, /*0*/true, window);
       uAcquiredDirect3DDevice = uDesiredDirect3DDevice;
     }
     else
     {
       if ( v7[1].bIsDeviceCompatible )
       {
-        v8 = pRenderD3D->CreateDevice(1u, 0, window->GetApiHandle());
+        v8 = pRenderD3D->CreateDevice(1, /*0*/true, window);
         uAcquiredDirect3DDevice = 1;
       }
       else
@@ -3213,7 +3083,7 @@
         if ( !v7->bIsDeviceCompatible )
           Error("There aren't any D3D devices to create.");
 
-        v8 = pRenderD3D->CreateDevice(0, 0, window->GetApiHandle());
+        v8 = pRenderD3D->CreateDevice(0, /*0*/true, window);
         uAcquiredDirect3DDevice = 1;
       }
     }
@@ -3302,13 +3172,18 @@
     ErrD3D(pRenderD3D->pDevice->SetTextureStageState(0, D3DTSS_COLORARG2, 0));
     ErrD3D(pRenderD3D->pDevice->SetTextureStageState(0, D3DTSS_COLOROP, 4u));
   //}
-  ddpfPrimareSuface.dwSize = 32;
-  GetTargetPixelFormat(&ddpfPrimareSuface);
+  ddpfPrimarySuface.dwSize = 32;
+  GetTargetPixelFormat(&ddpfPrimarySuface);
   ParseTargetPixelFormat();
-  _49EBF1();
-  if ( pRenderD3D )
-  {
-    v16 = IsColorKeySupported(pDirectDraw4);
+
+  if (!pRenderD3D)
+  {
+    __debugbreak();
+    pBeforePresentFunction = 0;//nullsub_1;
+  }
+  //else
+  //{
+    /*v16 = IsColorKeySupported(pDirectDraw4);
     v17 = uAcquiredDirect3DDevice == v15;
     bColorKeySupported = v16;
     if ( !v17 )
@@ -3327,35 +3202,30 @@
       ErrD3D(v18->CreateSurface(&ddsd2, &pColorKeySurface4, 0));
       pBeforePresentFunction = Present_ColorKey;
     }
-    else
+    else*/
     {
       pTargetSurface = 0;
-      ptr_400E8 = 0;
-      v20 = (int *)malloc(0x96020u);
-      ptr_400E8 = v20;
-      if ( !v20
+      pTargetSurface_unaligned = 0;
+      pTargetSurface_unaligned = (unsigned int *)malloc(640 * 480 * 2 + 32);
+      if ( !pTargetSurface_unaligned
         || (memset(&pDesc, 0, 0x7Cu),
             pDesc.dwSize = 124,
             !pRenderer->LockSurface_DDraw4(pRenderer->pBackBuffer4, &pDesc, v15)) )
         return 0;
       pBackBuffer4->Unlock(0);
-      v22 = ptr_400E8 + 4;
+      v22 = (int *)pTargetSurface_unaligned + 4;
       v23 = (unsigned int)pDesc.lpSurface & 7;
       LOBYTE(v22) = (unsigned __int8)v22 & 0xF8;
       uTargetSurfacePitch = 640;
       pBeforePresentFunction = Present_NoColorKey;
       v15 = 1;
-      pTargetSurface = (unsigned __int16 *)((char *)v22 + 2 * v23);
-    }
-    field_40110 = v15;
-  }
-  else
-  {
-    pBeforePresentFunction = 0;//nullsub_1;
-  }
+      pTargetSurface = (unsigned __int32 *)((char *)v22 + 2 * v23);
+    }
+    using_software_screen_buffer = v15;
+  //}
   bWindowMode = 0;
   pParty->uFlags |= 2u;
-  LODWORD(flt_6BE3A0) = 0x3F0CCCCDu;  __debugbreak(); // replace with actual float
+  flt_6BE3A0 = 0.55000001f;
   pViewport->_4C02F8(36044);
   return v15 != 0;
 }
@@ -3375,11 +3245,11 @@
   HRESULT v11; // eax@24
   int v12; // eax@24
   int v13; // eax@26
-  bool v14; // eax@32
-  char v15; // zf@32
+  //bool v14; // eax@32
+  //char v15; // zf@32
   IDirectDraw4 *v16; // eax@35
   HRESULT v17; // eax@35
-  int *v18; // eax@36
+  //int *v18; // eax@36
   int *v19; // edx@38
   int v20; // eax@38
   unsigned int v21; // ecx@38
@@ -3391,17 +3261,17 @@
   //RenderD3D *thisa; // [sp+2FCh] [bp-10h]@2
   int v29; // [sp+308h] [bp-4h]@2
 
-  pParty->uFlags |= 2u;
+  pParty->uFlags |= PARTY_FLAGS_1_0002;
   //v2 = this;
   flt_6BE3A0 = 0.55000001f;
   pViewport->_4C02F8(36044);
-  field_40110 = 0;
+  using_software_screen_buffer = 0;
   Release();
   pColorKeySurface4 = 0;
   pBackBuffer4 = 0;
   pFrontBuffer4 = 0;
   pDirectDraw4 = 0;
-  bColorKeySupported = 0;
+  //bColorKeySupported = 0;
   CreateZBuffer();
   /*if (!bUserDirect3D)
   {
@@ -3431,7 +3301,7 @@
     if (pRenderD3D->pAvailableDevices[uDesiredDirect3DDevice].bIsDeviceCompatible &&
         uDesiredDirect3DDevice != 1 )
     {
-      v7 = pRenderD3D->CreateDevice(uDesiredDirect3DDevice, 1, window->GetApiHandle());
+      v7 = pRenderD3D->CreateDevice(uDesiredDirect3DDevice, true, window);
       uAcquiredDirect3DDevice = uDesiredDirect3DDevice;
     }
     else
@@ -3439,7 +3309,7 @@
       if ( !pRenderD3D->pAvailableDevices[0].bIsDeviceCompatible )
         Error("There aren't any D3D devices to init.");
 
-      v7 = pRenderD3D->CreateDevice(0, 1, window->GetApiHandle());
+      v7 = pRenderD3D->CreateDevice(0, true, window);
       uAcquiredDirect3DDevice = 0;
     }
     if ( !v7 )
@@ -3500,7 +3370,7 @@
     refCaps.dwSize = 252;
     ErrD3D(pRenderD3D->pDevice->GetCaps(&halCaps, &refCaps));
     v12 = halCaps.dwMinTextureWidth;
-    if ( (unsigned int)halCaps.dwMinTextureWidth >= halCaps.dwMinTextureHeight )
+    if ( (unsigned int)halCaps.dwMinTextureWidth > halCaps.dwMinTextureHeight )
       v12 = halCaps.dwMinTextureHeight;
     uMinDeviceTextureDim = v12;
     v13 = halCaps.dwMaxTextureWidth;
@@ -3525,23 +3395,25 @@
     ErrD3D(pRenderD3D->pDevice->SetTextureStageState(0, D3DTSS_COLOROP, 4u));
   //}
 
-  ddpfPrimareSuface.dwSize = 32;
-  GetTargetPixelFormat(&ddpfPrimareSuface);
+  ddpfPrimarySuface.dwSize = 32;
+  GetTargetPixelFormat(&ddpfPrimarySuface);
   ParseTargetPixelFormat();
-  _49EBF1();
+
   if ( !pRenderD3D )
   {
-    pBeforePresentFunction = 0;//nullsub_1;
-    goto LABEL_47;
-  }
-  v14 = IsColorKeySupported(pDirectDraw4);
+    __debugbreak();
+    //pBeforePresentFunction = 0;//nullsub_1;
+    //goto LABEL_47;
+  }
+  /*v14 = IsColorKeySupported(pDirectDraw4);
   v15 = uAcquiredDirect3DDevice == 1;
   bColorKeySupported = v14;
   if ( !v15 )
-    bColorKeySupported = 0;
-  if ( bColorKeySupported )
-  {
-    memset(&ddsd2, 0, 0x7Cu);
+    bColorKeySupported = 0;*/
+  //if ( bColorKeySupported )
+  if (false)
+  {
+    /*memset(&ddsd2, 0, 0x7Cu);
     ddsd2.ddckCKSrcBlt.dwColorSpaceLowValue = uTargetGMask | uTargetBMask;
     ddsd2.ddckCKSrcBlt.dwColorSpaceHighValue = ddsd2.ddckCKSrcBlt.dwColorSpaceLowValue;
     v16 = pDirectDraw4;
@@ -3551,27 +3423,36 @@
     ddsd2.dwWidth = 640;
     ddsd2.dwHeight = 480;
     ErrD3D(v16->CreateSurface(&ddsd2, &pColorKeySurface4, 0));
-    pBeforePresentFunction = Present_ColorKey;
+    pBeforePresentFunction = Present_ColorKey;*/
 LABEL_45:
-    field_40110 = 1;
-LABEL_47:
+    using_software_screen_buffer = 1;
+//LABEL_47:
     bWindowMode = 1;
     //hWnd = hWnd;
     return 0;
   }
   pTargetSurface = 0;
-  ptr_400E8 = 0;
-  v18 = (int *)new char[0x96020];
-  memset(v18, -1, 0x96020);
-  ptr_400E8 = v18;
-  if ( v18 )
-  {
-    memset(&pDesc, 0, 0x7Cu);
-    pDesc.dwSize = 124;
-    if ( pRenderer->LockSurface_DDraw4(pRenderer->pBackBuffer4, &pDesc, DDLOCK_WAIT) )
-    {
+  pTargetSurface_unaligned = 0;
+
+  uint num_pixels = window->GetWidth() * window->GetHeight();
+  pTargetSurface_unaligned = new unsigned int[num_pixels];
+
+  if (!pTargetSurface_unaligned)
+    return false;
+
+  memset(&pDesc, 0, 0x7Cu);
+  pDesc.dwSize = 124;
+  if (!pRenderer->LockSurface_DDraw4(pRenderer->pBackBuffer4, &pDesc, DDLOCK_WAIT))
+  {
+    delete [] pTargetSurface_unaligned;
+    return false;
+  }
+
+  memset32(pTargetSurface_unaligned, -1, num_pixels);
+
+
       pRenderer->pBackBuffer4->Unlock(0);
-      v19 = ptr_400E8;
+      /*v19 = pTargetSurface_unaligned;
       v20 = (unsigned int)pDesc.lpSurface & 7;
       v21 = (unsigned int)ptr_400E8 & 7;
       if ( v21 == v20 )
@@ -3585,33 +3466,19 @@
         else
           v22 = (int)((char *)v19 + 2 * (v20 - v21) + 16);
         pTargetSurface = (unsigned __int16 *)v22;
-      }
-      uTargetSurfacePitch = 640;
+      }*/
+      pTargetSurface = pTargetSurface_unaligned;
+      uTargetSurfacePitch = window->GetWidth();
       pBeforePresentFunction = Present_NoColorKey;
       goto LABEL_45;
-    }
-  }
-  return 0;
 }
 
 //----- (004A0BEE) --------------------------------------------------------
-char Render::RasterLine2D(unsigned int uX, unsigned int uY, unsigned int uZ, unsigned int uW, unsigned __int16 uColor)
-{
-  int v6; // edi@1
-  int v7; // edx@5
-  unsigned int v8; // ebx@5
-  int v9; // eax@7
-  unsigned int v10; // ecx@9
-  unsigned int v11; // esi@13
-  int v12; // eax@17
-  int v13; // eax@21
-  Render *v14; // edi@21
-  int v15; // eax@25
-  int v16; // eax@27
-  signed int v17; // eax@28
-  signed int v18; // edi@30
-  signed __int64 v19; // qax@41
-  int v20; // edi@41
+void Render::RasterLine2D(signed int uX, signed int uY, signed int uZ, signed int uW, unsigned __int16 uColor)
+{
+  signed int v12; // eax@17
+  //signed int v19; // qax@41
+  //int v20; // edi@41
   unsigned int v21; // edi@46
   int v22; // esi@47
   int v23; // ebx@47
@@ -3624,51 +3491,47 @@
   int v30; // ebx@60
   int v31; // edx@61
   int v32; // edi@61
-  int v34; // [sp+Ch] [bp-10h]@3
-  Render *v35; // [sp+10h] [bp-Ch]@1
   __int64 v36; // [sp+14h] [bp-8h]@1
   signed int v37; // [sp+18h] [bp-4h]@28
   unsigned int uXa; // [sp+24h] [bp+8h]@49
-  unsigned int uYa; // [sp+28h] [bp+Ch]@28
+  //unsigned int uYa; // [sp+28h] [bp+Ch]@28
   int uYb; // [sp+28h] [bp+Ch]@47
-  int uZa; // [sp+2Ch] [bp+10h]@38
+  //int uZa; // [sp+2Ch] [bp+10h]@38
+  bool left_border;
 
   v36 = 0i64;
-  v6 = this->raster_clip_x;
-  v35 = this;
-  if ( (signed int)uX < v6 )
-    HIDWORD(v36) = 8;
-  v34 = this->raster_clip_z;
-  if ( (signed int)uX > this->raster_clip_z )
-    HIDWORD(v36) |= 4u;
-  v7 = this->raster_clip_y;
-  v8 = uY;
-  if ( (signed int)uY < v7 )
-    HIDWORD(v36) |= 2u;
-  v9 = this->raster_clip_w;
-  if ( (signed int)uY > v9 )
-    HIDWORD(v36) |= 1u;
-  v10 = uZ;
-  if ( (signed int)uZ < v6 )
-    LODWORD(v36) = 8;
-  if ( (signed int)uZ > v34 )
-    LODWORD(v36) = v36 | 4;
-  v11 = uW;
-  if ( (signed int)uW < v7 )
-    LODWORD(v36) = v36 | 2;
-  if ( (signed int)uW > v9 )
-    LODWORD(v36) = v36 | 1;
-  LOBYTE(v12) = v36;
+  if ( uX < this->raster_clip_x )// x     
+    HIDWORD(v36) = 8; //left_border = true;
+  if ( uX > this->raster_clip_z )// x     
+    HIDWORD(v36) |= 4;//right_border = true;
+
+  if ( uZ < this->raster_clip_x )// z     
+    LODWORD(v36) = 8;//
+  if ( uZ > this->raster_clip_z )// z     
+    LODWORD(v36) |= 4;
+
+  if ( uY < this->raster_clip_y )// y     
+    HIDWORD(v36) |= 2;//upper_border = true;
+  if ( uY > this->raster_clip_w )// y     
+    HIDWORD(v36) |= 1;//bottom_border = true;
+
+  if ( uW < this->raster_clip_y )// w     
+    LODWORD(v36) |= 2;
+  if ( uW > this->raster_clip_w )// w     
+    LODWORD(v36) |= 1;
+
+  //LOBYTE(v12) = v36;
   if ( (unsigned int)v36 & HIDWORD(v36) )
-    return v12;
-  if ( !v36 )
+    return;
+
+  if ( !v36 ) //  
   {
 LABEL_46:
     v21 = pRenderer->uTargetSurfacePitch;
     if ( pRenderer->uTargetSurfacePitch )
     {
-      v12 = uX + v8 * pRenderer->uTargetSurfacePitch;
-      v22 = v11 - v8;
+      v12 = uX + uY * pRenderer->uTargetSurfacePitch;
+      v22 = uW - uY;
       v23 = v22;
       uYb = v22;
       if ( v22 < 0 )
@@ -3677,7 +3540,7 @@
         uYb = -v22;
         v21 = -pRenderer->uTargetSurfacePitch;
       }
-      uXa = v10 - uX;
+      uXa = uZ - uX;
       if ( (uXa & 0x80000000u) == 0 )
       {
         v24 = 1;
@@ -3688,10 +3551,11 @@
         v24 = -1;
       }
       v25 = 0;
-      v26 = v35->pTargetSurface;
+
+      v26 = (unsigned __int16 *)this->pTargetSurface;
       if ( v26 )
       {
-        if ( (signed int)uXa <= v23 )
+        if ( (signed int)uXa <= v23 )//  
         {
           v30 = v23 + 1;
           if ( v30 > 0 )
@@ -3699,132 +3563,138 @@
             v31 = 2 * v24;
             v32 = 2 * v21;
             v12 = (int)&v26[v12];
-            do
+            int y = 0;
+            int x = 0;
+            for ( v30; v30; --v30 )
             {
               v25 += uXa;
-              *(short *)v12 = uColor;
-              v12 += v32;
+              //*(short *)v12 = uColor;
+              //v12 += v32;
+              WritePixel16(uX + x, uY + y, uColor);
+              if ( v32 >= 0 )
+                y += 1;
+              else
+                y -= 1;
               if ( v25 > 0 )
               {
                 v25 -= uYb;
-                v12 += v31;
+                //v12 += v31;
+                if ( v31 >= 0 )
+                  x += 1;
+                else
+                  x -= 1;
               }
-              --v30;
             }
-            while ( v30 );
           }
         }
-        else
+        else//  
         {
           v27 = uXa + 1;
           if ( (signed int)(uXa + 1) > 0 )
           {
             v28 = 2 * v21;
             v29 = 2 * v24;
+            int y = 0;
+            int x = 0;
             v12 = (int)&v26[v12];
-            do
+            for ( v27; v27; --v27 )
             {
               v25 += uYb;
-              *(short *)v12 = uColor;
-              v12 += v29;
+              //*(short *)v12 = uColor;
+              //v12 += v29;
+              WritePixel16(uX + x, uY + y, uColor);
+              if ( v29 >= 0 )
+                x += 1;
+              else
+                x -= 1;
               if ( v25 > (signed int)uXa )
               {
                 v25 -= uXa;
-                v12 += v28;
+                //v12 += v28;
+                if ( v28 >= 0 )
+                  y += 1;
+                else
+                  y -= 1;
               }
-              --v27;
             }
-            while ( v27 );
           }
         }
       }
     }
-    return v12;
-  }
-  if ( (BYTE4(v36) ^ (unsigned __int8)v36) & 8 )
-  {
-    if ( BYTE4(v36) & 8 )
-    {
-      v13 = (signed int)((uW - uY) * (v6 - uX)) / (signed int)(uZ - uX);
-      v14 = v35;
-      v8 = v13 + uY;
-      uX = v35->raster_clip_x;
-      goto LABEL_24;
-    }
-    v10 = v6;
-    v11 = (signed int)((uY - uW) * (v6 - uZ)) / (signed int)(uX - uZ) + uW;
-  }
-  v14 = v35;
-LABEL_24:
-  if ( (BYTE4(v36) ^ (unsigned __int8)v36) & 4 )
-  {
-    v15 = v14->raster_clip_z;
-    if ( BYTE4(v36) & 4 )
-    {
-      v14 = v35;
-      v8 += (signed int)((v11 - v8) * (v15 - uX)) / (signed int)(v10 - uX);
-      uX = v35->raster_clip_z;
+    return;
+  }
+
+  if ( (BYTE4(v36) ^ (unsigned __int8)v36) & 8 )//  
+  {
+    if ( BYTE4(v36) & 8 )//left_border = true;
+    {
+      uY += ((uW - uY) * (this->raster_clip_x - uX)) / (uZ - uX);
+      uX = this->raster_clip_x;
     }
     else
     {
-      v16 = (signed int)((v8 - v11) * (v15 - v10)) / (signed int)(uX - v10);
-      v10 = v14->raster_clip_z;
-      v11 += v16;
-    }
-  }
-  v17 = v14->raster_clip_y;
+      uZ = this->raster_clip_x;
+      uW += ((uY - uW) * (this->raster_clip_x - uZ)) / (uX - uZ);
+    }
+  }
+  if ( (BYTE4(v36) ^ (unsigned __int8)v36) & 4 )
+  {
+    if ( BYTE4(v36) & 4 ) //right_border = true
+    {
+      uY += ((uW - uY) * (this->raster_clip_z - uX)) / (uZ - uX);
+      uX = this->raster_clip_z;
+    }
+    else
+    {
+      uW += ((uY - uW) * (this->raster_clip_z - uZ)) / (uX - uZ);
+      uY = this->raster_clip_z;
+    }
+  }
   v37 = 0;
-  uYa = v14->raster_clip_y;
-  if ( (signed int)v8 < v17 )
+  if ( uY < this->raster_clip_y )
     v37 = 2;
-  v18 = v14->raster_clip_w;
-  if ( (signed int)v8 > v18 )
-    v37 |= 1u;
-  if ( (signed int)v11 >= v17 )
+  if ( uY > this->raster_clip_w )
+    v37 |= 1;
+
+  if ( uW >= this->raster_clip_y )
     v12 = 0;
   else
     v12 = 2;
-  if ( (signed int)v11 > v18 )
-    LOBYTE(v12) = v12 | 1;
+  if ( uW > this->raster_clip_w )
+    v12 |= 1;
+
   if ( !(v12 & v37) )
   {
     v12 ^= v37;
-    uZa = v12;
     if ( v12 & 2 )
     {
       if ( v37 & 2 )
       {
-        uX += (signed int)((v10 - uX) * (uYa - v8)) / (signed int)(v11 - v8);
-        LOBYTE(v12) = (char)v35;
-        v8 = v35->raster_clip_y;
+        uX += ((uZ - uX) * (this->raster_clip_y - uY)) / (uW - uY);
+        uY = this->raster_clip_y;
       }
       else
       {
-        v19 = (signed int)((uX - v10) * (uYa - v11));
-        v20 = v8 - v11;
-        v11 = uYa;
-        v12 = v19 / v20;
-        v10 += v12;
-      }
-    }
-    if ( uZa & 1 )
+        uZ += (uX - uZ) * (this->raster_clip_y - uW) / (uY - uW);
+        uW = this->raster_clip_y;
+      }
+    }
+    if ( v12 & 1 )
     {
       if ( v37 & 1 )
       {
-        uX += (signed int)((v10 - uX) * (v35->raster_clip_w - v8)) / (signed int)(v11 - v8);
-        LOBYTE(v12) = (char)v35;
-        v8 = v35->raster_clip_w;
+        uX += ((uZ - uX) * (this->raster_clip_w - uY)) / (uW - uY);
+        uY = this->raster_clip_w;
       }
       else
       {
-        v12 = (signed int)((uX - v10) * (v35->raster_clip_w - v11)) / (signed int)(v8 - v11);
-        v11 = v35->raster_clip_w;
-        v10 += v12;
+        uZ += ((uX - uZ) * (this->raster_clip_w - uW)) / (uY - uW);
+        uW = this->raster_clip_w;
       }
     }
     goto LABEL_46;
   }
-  return v12;
+  return;
 }
 
 //----- (004A0E80) --------------------------------------------------------
@@ -3845,68 +3715,65 @@
 //----- (004A0EB6) --------------------------------------------------------
 void Render::ParseTargetPixelFormat()
 {
-  Render *v1; // eax@1
   signed int v2; // ecx@1
   DWORD uRedMask; // edx@1
   unsigned int uGreenMask; // esi@5
   signed int v5; // ecx@5
   unsigned int uBlueMask; // edx@9
   signed int v7; // ecx@9
-  unsigned int v8; // ecx@13
-
-  v1 = this;
+  //unsigned int v8; // ecx@13
+
   v2 = 0;
-  uRedMask = v1->ddpfPrimareSuface.dwRBitMask;
-  v1->uTargetBBits = 0;
-  v1->uTargetGBits = 0;
-  v1->uTargetRBits = 0;
+  uRedMask = this->ddpfPrimarySuface.dwRBitMask;
+  this->uTargetBBits = 0;
+  this->uTargetGBits = 0;
+  this->uTargetRBits = 0;
   do
   {
     if ( (1 << v2) & uRedMask )
-      ++v1->uTargetRBits;
+      ++this->uTargetRBits;
     ++v2;
   }
-  while ( v2 < 16 );
-  uGreenMask = v1->ddpfPrimareSuface.dwGBitMask;
+  while ( v2 < 32 );
+  uGreenMask = this->ddpfPrimarySuface.dwGBitMask;
   v5 = 0;
   do
   {
     if ( (1 << v5) & uGreenMask )
-      ++v1->uTargetGBits;
+      ++this->uTargetGBits;
     ++v5;
   }
-  while ( v5 < 16 );
-  uBlueMask = v1->ddpfPrimareSuface.dwBBitMask;
+  while ( v5 < 32 );
+  uBlueMask = this->ddpfPrimarySuface.dwBBitMask;
   v7 = 0;
   do
   {
     if ( (1 << v7) & uBlueMask )
-      ++v1->uTargetBBits;
+      ++this->uTargetBBits;
     ++v7;
   }
-  while ( v7 < 16 );
-  v8 = v1->ddpfPrimareSuface.dwRBitMask;
-  v1->uTargetGMask = uGreenMask;
-  v1->uTargetRMask = v8;
-  v1->uTargetBMask = uBlueMask;
+  while ( v7 < 32 );
+  this->uTargetGMask = uGreenMask;
+  this->uTargetRMask = this->ddpfPrimarySuface.dwRBitMask;
+  this->uTargetBMask = uBlueMask;
 }
 
 //----- (004A0F40) --------------------------------------------------------
 bool Render::LockSurface_DDraw4(IDirectDrawSurface4 *pSurface, DDSURFACEDESC2 *pDesc, unsigned int uLockFlags)
 {
-  IDirectDrawSurface4 *v4; // esi@1
+  //IDirectDrawSurface4 *v4; // esi@1
   HRESULT result; // eax@1
   HRESULT v6; // eax@4
   int v7; // [sp-8h] [bp-14h]@10
   unsigned int v8; // [sp-4h] [bp-10h]@10
   char v9; // [sp+Bh] [bp-1h]@1
 
-  v4 = pSurface;
+  //v4 = pSurface;
   v9 = 1;
   result = pSurface->Lock(0, pDesc, uLockFlags, 0);
   if ( result == DDERR_SURFACELOST )
   {
-    v6 = v4->Restore();
+    v6 = pSurface->Restore();
     if ( v6 )
     {
       if ( v6 != DDERR_IMPLICITLYCREATED )
@@ -3917,9 +3784,9 @@
         goto LABEL_21;
       }
       pRenderer->pFrontBuffer4->Restore();
-      v4->Restore();
-    }
-    result = v4->Lock(0, pDesc, DDLOCK_WAIT, 0);
+      pSurface->Restore();
+    }
+    result = pSurface->Lock(0, pDesc, DDLOCK_WAIT, 0);
     if ( result == DDERR_INVALIDRECT || result == DDERR_SURFACEBUSY )
       goto LABEL_20;
     ErrD3D(result);
@@ -4260,17 +4127,15 @@
 //----- (004A1605) --------------------------------------------------------
 void Render::LockRenderSurface(void **pOutSurfacePtr, unsigned int *pOutPixelsPerRow)
 {
-  Render *v3; // esi@1
   signed int v4; // eax@3
 
-  v3 = this;
   if (pVersion->pVersionInfo.dwPlatformId != VER_PLATFORM_WIN32_NT ||
       pVersion->pVersionInfo.dwMajorVersion != 4 )
   {
   DDSURFACEDESC2 pDesc; // [sp+4h] [bp-7Ch]@3
     memset(&pDesc, 0, 0x7Cu);
     pDesc.dwSize = 124;
-    LockSurface_DDraw4(v3->pBackBuffer4, &pDesc, DDLOCK_WAIT);
+    LockSurface_DDraw4(this->pBackBuffer4, &pDesc, DDLOCK_WAIT);
     *pOutSurfacePtr = pDesc.lpSurface;
     v4 = pDesc.lPitch;
   }
@@ -4279,7 +4144,7 @@
   DDSURFACEDESC pDesc; // [sp+4h] [bp-7Ch]@3
     memset(&pDesc.lPitch, 0, 0x6Cu);
     pDesc.lPitch = 108;
-    LockSurface_DDraw2(v3->pBackBuffer2, &pDesc, 1u);
+    LockSurface_DDraw2(this->pBackBuffer2, &pDesc, 1);
     *pOutSurfacePtr = (void *)pDesc.lpSurface;
     v4 = pDesc.dwReserved;
   }
@@ -4299,16 +4164,14 @@
 //----- (004A172E) --------------------------------------------------------
 void Render::LockFrontBuffer(void **pOutSurface, unsigned int *pOutPixelsPerRow)
 {
-  Render *v3; // esi@1
   signed int v4; // eax@3
 
-  v3 = this;
   if ( pVersion->pVersionInfo.dwPlatformId != VER_PLATFORM_WIN32_NT || pVersion->pVersionInfo.dwMajorVersion != 4 )
   {
   DDSURFACEDESC2 pDesc; // [sp+4h] [bp-7Ch]@3
     memset(&pDesc, 0, 0x7Cu);
     pDesc.dwSize = 124;
-    LockSurface_DDraw4(v3->pFrontBuffer4, &pDesc, DDLOCK_WAIT);
+    LockSurface_DDraw4(this->pFrontBuffer4, &pDesc, DDLOCK_WAIT);
     *pOutSurface = pDesc.lpSurface;
     v4 = pDesc.lPitch;
   }
@@ -4317,7 +4180,7 @@
   DDSURFACEDESC pDesc; // [sp+4h] [bp-7Ch]@3
     memset(&pDesc.lPitch, 0, 0x6Cu);
     pDesc.lPitch = 108;
-    LockSurface_DDraw2(v3->pFrontBuffer2, &pDesc, 1u);
+    LockSurface_DDraw2(this->pFrontBuffer2, &pDesc, 1);
     *pOutSurface = (void *)pDesc.lpSurface;
     v4 = pDesc.dwReserved;
   }
@@ -6155,62 +6018,6 @@
     pBillboardRenderListD3D[v8].uOpacity = RenderBillboardD3D::Transparent;
 }
 
-//----- (004A48E4) --------------------------------------------------------
-int Render::MakeParticleBillboardAndPush_BLV_Software(int screenSpaceX, int screenSpaceY, int z, int lightColor, int a6)
-{
-  int v6; // ecx@1
-  int v7; // ebx@1
-  int v8; // ecx@1
-  int v9; // edx@1
-  int v10; // edi@1
-  unsigned int x; // esi@1
-  int result; // eax@8
-  int v13; // [sp+Ch] [bp-10h]@1
-  int v14; // [sp+10h] [bp-Ch]@1
-  int v15; // [sp+14h] [bp-8h]@1
-  int v16; // [sp+18h] [bp-4h]@1
-  int v17; // [sp+24h] [bp+8h]@1
-  unsigned int v18; // [sp+28h] [bp+Ch]@1
-  int v19; // [sp+34h] [bp+18h]@1
-
-  v6 = screenSpaceX;
-  v7 = (a6 >> 1) + screenSpaceY;
-  v17 = 0;
-  v15 = 0;
-  v8 = (a6 >> 1) + v6;
-  v14 = (a6 >> 1) * (a6 >> 1);
-  v9 = 2 * (a6 >> 1);
-  v10 = (a6 >> 1) * ((a6 >> 1) - 1);
-  x = v8 - (a6 >> 1);
-  v16 = (a6 >> 1) + screenSpaceY - v8;
-  v19 = a6 >> 1;
-  v13 = v9;
-  v18 = v8;
-  do
-  {
-    sr_4A46E6_draw_particle_segment(x, v16 + v18, z, 2 * v19, lightColor);
-    if ( v15 )
-      sr_4A46E6_draw_particle_segment(x, v17 + v7, z, 2 * v19, lightColor);
-    v14 -= v15;
-    if ( v14 <= v10 )
-    {
-      if ( v19 != v17 )
-      {
-        sr_4A46E6_draw_particle_segment(v18, v16 + x, z, 2 * v17, lightColor);
-        sr_4A46E6_draw_particle_segment(v18, v19 + v7, z, 2 * v17, lightColor);
-      }
-      --v19;
-      v13 -= 2;
-      ++x;
-      v10 -= v13;
-    }
-    result = v17++;
-    v15 += 2;
-    --v18;
-  }
-  while ( result < v19 );
-  return result;
-}
 
 //----- (004A49D0) --------------------------------------------------------
 void Render::DrawProjectile(float srcX, float srcY, float a3, float a4, float dstX, float dstY, float a7, float a8, IDirect3DTexture2 *a9)
@@ -6536,7 +6343,7 @@
   {
     if ( this->pRenderD3D )
     {
-      if ( this->bColorKeySupported )
+      /*if ( this->bColorKeySupported )
       {
         memset(&Dst, 0, 0x7Cu);
         Dst.dwSize = 124;
@@ -6547,7 +6354,7 @@
           this->field_18_locked_pitch = Dst.lPitch >> 1;
         }
         --this->uNumSceneBegins;
-      }
+      }*/
     }
     else
     {
@@ -6575,13 +6382,13 @@
     {
       if ( this->pRenderD3D )
       {
-        if ( this->bColorKeySupported )
+        /*if ( this->bColorKeySupported )
         {
           this->pTargetSurface = 0;
           this->uTargetSurfacePitch = 0;
           this->field_18_locked_pitch = 0;
           ErrD3D(this->pColorKeySurface4->Unlock(0));
-        }
+        }*/
       }
       else
       {
@@ -6827,11 +6634,33 @@
   this->uClipZ = 640;
 }
 
+unsigned __int32 Color32(unsigned __int16 color16)
+{
+  unsigned __int32 c = color16;
+  unsigned int b = (c & 31) * 8;
+  unsigned int g = ((c >> 5) & 63) * 4;
+  unsigned int r = ((c >> 11) & 31) * 8;
+
+  return  (r << 16) | (g << 8) | b;//
+}
+
+//----- (0040DEF3) --------------------------------------------------------
+unsigned __int16 Color16(unsigned __int32 r, unsigned __int32 g, unsigned __int32 b)
+{
+  //return ((unsigned int)b >> (8 - LOBYTE(pRenderer->uTargetBBits))) | pRenderer->uTargetGMask & (g << (LOBYTE(pRenderer->uTargetGBits) + 
+  //                         LOBYTE(pRenderer->uTargetBBits) - 8)) | pRenderer->uTargetRMask & (r << (LOBYTE(pRenderer->uTargetGBits) + 
+  //                         LOBYTE(pRenderer->uTargetRBits) + LOBYTE(pRenderer->uTargetBBits) - 8));
+  return (b >> (8 - 5)) |
+         0x7E0 & (g << (6 + 5 - 8)) |
+         0xF800 & (r << (6 + 5 + 5 - 8));
+}
+
+
 //----- (004A5BE3) --------------------------------------------------------
 void Render::DrawTextureRGB(unsigned int uOutX, unsigned int uOutY, RGBTexture *a4)
 {
   int v4; // edi@3
-  unsigned __int16 *v5; // edx@3
+  //unsigned __int16 *v5; // edx@3
   unsigned __int16 *v6; // esi@3
   unsigned int v8; // eax@5
   unsigned int v9; // ebx@5
@@ -6845,7 +6674,7 @@
   if ( this->uNumSceneBegins && a4 )
   {
     v4 = a4->uWidth;
-    v5 = &this->pTargetSurface[uOutX + uOutY * this->uTargetSurfacePitch];
+    //v5 = &this->pTargetSurface[uOutX + uOutY * this->uTargetSurfacePitch];
     v6 = a4->pPixels;
     v23 = a4->uHeight;
     v19 = v4;
@@ -6858,14 +6687,14 @@
         v8 *= 2;
         v4 += v9;
         v6 = (unsigned __int16 *)((char *)v6 + v8);
-        v5 = (unsigned __int16 *)((char *)v5 + v8);
+        //v5 = (unsigned __int16 *)((char *)v5 + v8);
       }
       if ( (signed int)uOutY < (signed int)this->uClipY )
       {
         v11 = this->uClipY - uOutY;
         v6 += v19 * v11;
         v23 += uOutY - this->uClipY;
-        v5 += this->uTargetSurfacePitch * v11;
+        //v5 += this->uTargetSurfacePitch * v11;
       }
       v12 = max(this->uClipX, uOutX);
       if ( (signed int)(v4 + v12) > (signed int)this->uClipZ )
@@ -6879,16 +6708,17 @@
       }
     }
 
-    for (int outerCounter = 0; outerCounter < v23; outerCounter++)
-    {
-      for (int counter = 0; counter < v4; counter++)
-      {
-        *v5 = *v6;
-        ++v5;
+    for (int y = 0; y < v23; y++)
+    {
+      for (int x = 0; x < v4; x++)
+      {
+        WritePixel16(uOutX + x, uOutY + y, *v6);
+        //*v5 = *v6;
+        //++v5;
         ++v6;
       }
       v6 += v19 - v4;
-      v5 += this->uTargetSurfacePitch - v4;
+      //v5 += this->uTargetSurfacePitch - v4;
     }
   }
 }
@@ -6896,15 +6726,19 @@
 //----- (004A5D33) --------------------------------------------------------
 void Render::CreditsTextureScroll(unsigned int pX, unsigned int pY, int move_X, int move_Y, RGBTexture *pTexture)
 {
-  unsigned __int16 *v7; // ebx@3
+  //unsigned __int16 *v7; // ebx@3
   int full_width; // ecx@3
   int full_height; // edi@3
-  int v23; // edi@23
+  //int v23; // edi@23
   unsigned __int16 *pTexturea; // [sp+28h] [bp+18h]@3
 
   if ( this->uNumSceneBegins && pTexture )
   {
-    v7 = &this->pTargetSurface[pX + pY * this->uTargetSurfacePitch];
+    /*auto v7 = this->pTargetSurface;
+    if (FORCE_16_BITS)
+      v7 = (unsigned __int32 *)((char *)v7 + (pX + pY * this->uTargetSurfacePitch) * 2);
+    else
+      v7 = (unsigned __int32 *)((char *)v7 + (pX + pY * this->uTargetSurfacePitch) * 4);*/
     full_width = pTexture->uWidth - move_X;
     full_height = pTexture->uHeight - move_Y;
     pTexturea = &pTexture->pPixels[move_X + move_Y * pTexture->uWidth];
@@ -6914,13 +6748,13 @@
       {
         pTexturea = (unsigned __int16 *)((char *)pTexturea + (2 * (this->uClipX - pX)));
         full_width += pX - this->uClipX;
-        v7 = (unsigned __int16 *)((char *)v7 + (2 * (this->uClipX - pX)));
+        //v7 = (unsigned __int32 *)((char *)v7 + ((FORCE_16_BITS ? 2 : 4) * (this->uClipX - pX)));
       }
       if ( pY < this->uClipY )//     
       {
         pTexturea += pTexture->uWidth * (this->uClipY - pY);
         full_height += pY - this->uClipY;
-        v7 += this->uTargetSurfacePitch * (this->uClipY - pY);
+        //v7 = (unsigned __int32 *)((char *)v7 + (FORCE_16_BITS ? 2 : 4) * this->uTargetSurfacePitch * (this->uClipY - pY));
       }
       if ( this->uClipX < pX )//       
         this->uClipX = pX;
@@ -6939,36 +6773,32 @@
         full_height = this->uClipW - this->uClipY;
       }
     }
-    if ( full_height > 0 )
-    {
-      do
-      {
-        if ( full_width > 0 )
-        {
-          v23 = full_width;
-          do
-          {
-            if ( *pTexturea != TargetColor(0, 0xFFu, 0xFFu) )
-              *v7 = *pTexturea;
+
+    for (int y = 0; y < full_height; ++y)
+    {
+      for (int x = 0; x < full_width; ++x)
+      {
+            if ( *pTexturea != Color16(0, 0xFFu, 0xFFu) )
+            {
+              WritePixel16(pX + x, pY + y, *pTexturea);
+              /*if (FORCE_16_BITS)
+                *(unsigned __int16 *)v7 = *pTexturea;
+              else
+                *(unsigned __int32 *)v7 = r5g6b5_2_r8g8b8(*pTexturea);*/
+            }
             ++pTexturea;
-            ++v7;
-            --v23;
-          }
-          while ( v23 );
+            //++v7;
         }
-        v7 += this->uTargetSurfacePitch - full_width;
+        //v7 += this->uTargetSurfacePitch - full_width;
         pTexturea = (unsigned __int16 *)((char *)pTexturea + 2 * (pTexture->uWidth - full_width));
-        --full_height;
-      }
-      while ( full_height );
-    }
+      }
   }
 }
 
 //----- (004A6E7E) --------------------------------------------------------
 void Render::_4A6E7E(unsigned int a2, unsigned int a3, Texture *a4)
 {
-  unsigned __int16 *v4; // eax@4
+  //unsigned __int16 *v4; // eax@4
   int v5; // edx@4
   unsigned int v6; // edi@4
   unsigned int v7; // edx@5
@@ -6992,12 +6822,14 @@
 
   if ( this->uNumSceneBegins && a4 && a4->pPalette16 )
   {
-    v4 = &this->pTargetSurface[a2 + a3 * this->uTargetSurfacePitch];
+    //v4 = &this->pTargetSurface[a2 + a3 * this->uTargetSurfacePitch];
     v20 = a4->pLevelOfDetail0_prolly_alpha_mask;
     v5 = a4->uTextureWidth;
     v6 = a4->uTextureHeight;
     v19 = a4->uTextureWidth;
     v18 = a4->uTextureWidth;
+    int clipped_out_x = a2;
+    int clipped_out_y = a3;
     if ( this->bClip )
     {
       v7 = this->uClipX;
@@ -7006,7 +6838,8 @@
         v8 = v7 - a2;
         v20 += v8;
         v19 += a2 - this->uClipX;
-        v4 += v8;
+        //v4 += v8;
+        clipped_out_x = uClipX;
       }
       v9 = this->uClipY;
       if ( (signed int)a3 < (signed int)v9 )
@@ -7014,7 +6847,8 @@
         v10 = v9 - a3;
         v20 += v18 * v10;
         v6 = a3 - this->uClipY + a4->uTextureHeight;
-        v4 += this->uTargetSurfacePitch * v10;
+        //v4 += this->uTargetSurfacePitch * v10;
+        clipped_out_y = uClipY;
       }
       v11 = this->uClipX;
       v5 = v19;
@@ -7040,7 +6874,19 @@
         v6 = v15 - v16;
       }
     }
-    if ( pRenderer->uTargetGBits == 5 )
+
+    for (int y = 0; y < v6; ++y)
+    {
+      for (int x = 0; x < v5; ++x)
+      {
+        if ( *v20 )
+          WritePixel16(clipped_out_x + x, clipped_out_y + y, ((unsigned int)a4->pPalette16[*v20] >> 1) & 0x7BEF);
+        ++v20;
+      }
+          v20 += v18 - v5;
+    }
+
+    /*if ( pRenderer->uTargetGBits == 5 )
     {
       if ( (signed int)v6 > 0 )
       {
@@ -7093,57 +6939,32 @@
         }
         while ( !v17 );
       }
-    }
+    }*/
   }
 }
 
 //----- (004A6DF5) --------------------------------------------------------
-int Render::_4A6DF5(unsigned __int16 *pBitmap, unsigned int uBitmapPitch, Vec2_int_ *pBitmapXY, unsigned __int16 *pTarget, unsigned int uTargetPitch, Vec4_int_ *a7)
-{
-  int result; // eax@0
+void Render::_4A6DF5(unsigned __int16 *pBitmap, unsigned int uBitmapPitch, Vec2_int_ *pBitmapXY, void *pTarget, unsigned int uTargetPitch, Vec4_int_ *a7)
+{
   int v8; // ecx@3
-  unsigned __int16 *v9; // edi@4
   unsigned __int16 *v10; // ebx@4
   int v11; // esi@4
-  unsigned __int16 *pBitmapa; // [sp+14h] [bp+8h]@3
-  unsigned __int16 *pTargeta; // [sp+20h] [bp+14h]@3
-
-  if ( pBitmap )
-  {
-    if ( pTarget )
-    {
-      pBitmapa = &pBitmap[pBitmapXY->x + uBitmapPitch * pBitmapXY->y];
-      pTargeta = &pTarget[a7->x + uTargetPitch * a7->y];
-      v8 = a7->z - a7->x;
-      result = a7->w - a7->y;
-      if ( result > 0 )
-      {
-        v9 = pBitmapa;
-        v10 = pTargeta;
-        v11 = a7->w - a7->y;
-        do
-        {
-          if ( v8 > 0 )
-          {
-            result = v8;
-            do
-            {
-              *v9 = *v10;
-              ++v9;
-              ++v10;
-              --result;
-            }
-            while ( result );
-          }
-          v9 += uBitmapPitch - v8;
-          v10 += uTargetPitch - v8;
-          --v11;
-        }
-        while ( v11 );
-      }
-    }
-  }
-  return result;
+
+  if ( !pBitmap || !pTarget)
+    return;
+
+  v8 = a7->z - a7->x;
+  v11 = a7->w - a7->y;
+  v10 = (unsigned short *)pTarget + a7->x + uTargetPitch * a7->y;
+  for ( int y = 0; y < v11; ++y )
+  {
+    for ( int x = 0; x < v8; ++x )
+    {
+      WritePixel16(a7->x + x, a7->y + y, *v10);
+      ++v10;
+    }
+    v10 += uTargetPitch - v8;
+  }
 }
 
 //----- (004A6D87) --------------------------------------------------------
@@ -7155,20 +6976,25 @@
   unsigned __int32 twoColors = (uColor16 << 16) | uColor16;
   for (uint y = 0; y < uHeight; ++y)
   {
-    ushort* pDst = &pTargetSurface[uX + (y + uY) * uTargetSurfacePitch];
-
-    memset32(pDst, twoColors, uWidth / 2);
-    if (uWidth & 1)
-      pDst[uWidth - 1] = uColor16;
+    void *pDst = (char *)pTargetSurface + (FORCE_16_BITS ? 2 : 4) * (uX + (y + uY) * uTargetSurfacePitch);
+
+    memset32(pDst,
+             FORCE_16_BITS ? twoColors : 0xFF000000 | Color32(uColor16),  // two colors per int (16bit) or 1 (32bit)
+             uWidth / (FORCE_16_BITS ? 2 : 1));                      // two pixels per int (16bit) or 1 (32bit)
+
+    if (FORCE_16_BITS && uWidth & 1) // we may miss one pixel for 16bit
+      ((unsigned __int16 *)pTargetSurface)[uX + uWidth - 1 + (y + uY) * uTargetSurfacePitch] = uColor16;
     }
 }
 
 //----- (004A6C4F) --------------------------------------------------------
-void Render::DrawText(signed int uOutX, signed int uOutY, unsigned __int8 *pFontPixels, unsigned int uCharWidth, unsigned int uCharHeight, unsigned __int16 *pFontPalette, unsigned __int16 uFaceColor, unsigned __int16 uShadowColor)
+void Render::DrawText(signed int uOutX, signed int uOutY, unsigned __int8 *pFontPixels, unsigned int uCharWidth, 
+                       unsigned int uCharHeight, unsigned __int16 *pFontPalette, 
+                       unsigned __int16 uFaceColor, unsigned __int16 uShadowColor)
 {
   unsigned int v9; // edi@2
   unsigned int v10; // esi@2
-  unsigned __int16 *v11; // eax@2
+  //unsigned __int16 *v11; // eax@2
   unsigned int v12; // ebx@3
   signed int v13; // edx@5
   int v14; // edx@6
@@ -7178,25 +7004,29 @@
   signed int v18; // ebx@13
   unsigned int v19; // edx@15
   signed int v20; // esi@16
-  unsigned int v21; // esi@22
+  //unsigned int v21; // esi@22
   unsigned __int16 v22; // dx@24
-  char v23; // zf@28
+  //char v23; // zf@28
   unsigned __int8 *v24; // [sp+Ch] [bp-4h]@2
-  unsigned int uOutXa; // [sp+18h] [bp+8h]@20
-
-  if ( this->uNumSceneBegins )
-  {
+  //unsigned int uOutXa; // [sp+18h] [bp+8h]@20
+
+  if (!this->uNumSceneBegins)
+    return;
+
     v9 = uCharWidth;
     v10 = uCharHeight;
-    v11 = &this->pTargetSurface[uOutX + uOutY * this->uTargetSurfacePitch];
+    //v11 = &this->pTargetSurface[uOutX + uOutY * this->uTargetSurfacePitch];
     v24 = pFontPixels;
+
+    int clipped_out_x = uOutX, clipped_out_y = uOutY;
     if ( this->bClip )
     {
       v12 = this->uClipX;
       if ( uOutX < (signed int)v12 )
       {
         v24 = &pFontPixels[v12 - uOutX];
-        v11 += v12 - uOutX;
+        //v11 += v12 - uOutX;
+        clipped_out_x = uClipX;
         v9 = uCharWidth + uOutX - v12;
       }
       v13 = this->uClipY;
@@ -7205,7 +7035,8 @@
         v14 = v13 - uOutY;
         v24 += uCharWidth * v14;
         v10 = uCharHeight + uOutY - this->uClipY;
-        v11 += this->uTargetSurfacePitch * v14;
+        //v11 += this->uTargetSurfacePitch * v14;
+        clipped_out_y = uClipY;
       }
       v15 = this->uClipX;
       if ( v15 < uOutX )
@@ -7230,36 +7061,24 @@
         v10 = v19 - v20;
       }
     }
-    if ( (signed int)v10 > 0 )
-    {
-      uOutXa = v10;
-      do
-      {
-        if ( (signed int)v9 > 0 )
+
+    for (int y = 0; y < v10; ++y)
+    {
+      for (int x = 0; x < v9; ++x)
+      {
+        if (*v24)
         {
-          v21 = v9;
-          do
-          {
-            if ( *v24 )
-            {
-              v22 = uShadowColor;
-              if ( *v24 != 1 )
-                v22 = uFaceColor;
-              *v11 = v22;
-            }
-            ++v11;
-            ++v24;
-            --v21;
-          }
-          while ( v21 );
+          v22 = uShadowColor;
+          if ( *v24 != 1 )
+            v22 = uFaceColor;
+           WritePixel16(clipped_out_x + x, clipped_out_y + y, v22);
         }
-        v24 += uCharWidth - v9;
-        v23 = uOutXa-- == 1;
-        v11 += this->uTargetSurfacePitch - v9;
-      }
-      while ( !v23 );
-    }
-  }
+        ++v24;
+      } 
+      v24 += uCharWidth - v9;
+        //v23 = uOutXa-- == 1;
+        //v11 += this->uTargetSurfacePitch - v9;
+    }
 }
 
 //----- (004A6A68) --------------------------------------------------------
@@ -7278,7 +7097,7 @@
     {
   int v8; // edi@2
   unsigned int v9; // esi@2
-  unsigned __int16 *v10; // eax@2
+  //unsigned __int16 *v10; // eax@2
   unsigned char *v11; // edx@2
   unsigned int v12; // ebx@3
   signed int v13; // edx@5
@@ -7303,21 +7122,25 @@
   int a2 = x;
   int a3 = y;
   uint a6 = uFontHeight;
-  if ( this->uNumSceneBegins )
-  {
+  if (!this->uNumSceneBegins)
+    return;
+
     v8 = a5;
     v9 = a6;
-    v10 = &pTargetSurface[x + y * uTargetSurfacePitch];
+    //v10 = &pTargetSurface[x + y * uTargetSurfacePitch];
     v11 = (unsigned char *)font_pixels;
     v25 = (int)font_pixels;
+    int clipped_out_x = x;
+    int clipped_out_y = y;
     if ( this->bClip )
     {
       v12 = this->uClipX;
       if ( a2 < (signed int)v12 )
       {
         v25 = v12 - a2 + (int)font_pixels;
-        v10 += v12 - a2;
+        //v10 += v12 - a2;
         v8 = a5 + a2 - v12;
+        clipped_out_x = uClipX;
       }
       v13 = this->uClipY;
       if ( a3 < v13 )
@@ -7325,7 +7148,8 @@
         v14 = v13 - a3;
         v25 += a5 * v14;
         v9 = a6 + a3 - this->uClipY;
-        v10 += this->uTargetSurfacePitch * v14;
+        //v10 += this->uTargetSurfacePitch * v14;
+        clipped_out_y = uClipY;
       }
       v15 = this->uClipX;
       if ( v15 < a2 )
@@ -7351,10 +7175,28 @@
       }
       v11 = (unsigned char *)v25;
     }
+
     if ( a8 )
     {
-      v28 = pRenderer->uTargetGMask | pRenderer->uTargetBMask;
-      if ( (signed int)v9 > 0 )
+      v28 = 0x7FF; // 16bit pRenderer->uTargetGMask | pRenderer->uTargetBMask;
+      for (int dy = 0; dy < v9; ++dy)
+      {
+        for (int dx = 0; dx < v8; ++dx)
+        {
+              if ( *v11 )
+                v24 = pPalette[*v11];
+              else
+                v24 = v28;
+              WritePixel16(clipped_out_x + dx, clipped_out_y + dy, v24);
+              //*v10 = v24;
+              //++v10;
+              ++v11;
+              //--v27;
+
+        }
+          v11 += a5 - v8;
+      }
+      /*if ( (signed int)v9 > 0 )
       {
         v23 = a5;
         v30 = v9;
@@ -7381,11 +7223,25 @@
           v10 += this->uTargetSurfacePitch - v8;
         }
         while ( !v22 );
-      }
+      }*/
     }
     else
     {
-      if ( (signed int)v9 > 0 )
+      for (int dy = 0; dy < v9; ++dy)
+      {
+        for (int dx = 0; dx < v8; ++dx)
+        {
+            if ( *v11 )       
+              WritePixel16(clipped_out_x + dx, clipped_out_y + dy, pPalette[*v11]);
+              //*v10 = v24;
+              //++v10;
+              ++v11;
+              //--v27;
+        }
+          v11 += a5 - v8;
+      }
+
+      /*if ( (signed int)v9 > 0 )
       {
         v21 = a5;
         v29 = v9;
@@ -7409,124 +7265,22 @@
           v10 += this->uTargetSurfacePitch - v8;
         }
         while ( !v22 );
-      }
-    }
-  }
+      }*/
+    }
 }
 
 //----- (004A68EF) --------------------------------------------------------
 void Render::DrawTransparentGreenShade(signed int a2, signed int a3, Texture *pTexture)
 {
-  Texture *v4; // edi@2
-  unsigned int v5; // ebx@4
-  unsigned __int16 *v6; // eax@4
-  signed int v7; // edx@5
-  int v8; // edx@6
-  signed int v9; // edx@7
-  int v10; // edx@8
-  signed int v11; // edx@9
-  signed int v12; // esi@12
-  signed int v13; // esi@15
-  unsigned int v14; // edx@17
-  signed int v15; // esi@18
-  unsigned __int8 *v16; // ebx@22
-  char v17; // zf@28
-  int v18; // [sp+10h] [bp-10h]@4
-  unsigned __int8 *v19; // [sp+18h] [bp-8h]@4
-  int v20; // [sp+1Ch] [bp-4h]@4
-  int v21; // [sp+28h] [bp+8h]@24
-  unsigned int v22; // [sp+2Ch] [bp+Ch]@22
-  unsigned int pTexturea; // [sp+30h] [bp+10h]@11
-
-  if ( this->uNumSceneBegins )
-  {
-    v4 = pTexture;
-    if ( pTexture )
-    {
-      if ( pTexture->pPalette16 )
-      {
-        v5 = pTexture->uTextureHeight;
-        v6 = &this->pTargetSurface[a2 + a3 * this->uTargetSurfacePitch];
-        v19 = pTexture->pLevelOfDetail0_prolly_alpha_mask;
-        v20 = pTexture->uTextureWidth;
-        v18 = pTexture->uTextureWidth;
-        if ( this->bClip )
-        {
-          v7 = this->uClipX;
-          if ( a2 < v7 )
-          {
-            v8 = v7 - a2;
-            v19 += v8;
-            v20 += a2 - this->uClipX;
-            v6 += v8;
-          }
-          v9 = this->uClipY;
-          v5 = pTexture->uTextureHeight;
-          if ( a3 < v9 )
-          {
-            v10 = v9 - a3;
-            v19 += v18 * v10;
-            v5 = a3 - this->uClipY + pTexture->uTextureHeight;
-            v4 = pTexture;
-            v6 += this->uTargetSurfacePitch * v10;
-          }
-          v11 = this->uClipX;
-          if ( v11 < a2 )
-            v11 = a2;
-          pTexturea = this->uClipZ;
-          if ( v11 + v20 > (signed int)pTexturea )
-          {
-            v12 = this->uClipX;
-            if ( v12 < a2 )
-              v12 = a2;
-            v20 = pTexturea - v12;
-          }
-          v13 = this->uClipY;
-          if ( v13 < a3 )
-            v13 = a3;
-          v14 = this->uClipW;
-          if ( (signed int)(v5 + v13) > (signed int)v14 )
-          {
-            v15 = this->uClipY;
-            if ( v15 < a3 )
-              v15 = a3;
-            v5 = v14 - v15;
-          }
-        }
-        if ( (signed int)v5 > 0 )
-        {
-          v22 = v5;
-          v16 = v19;
-          do
-          {
-            if ( v20 > 0 )
-            {
-              v21 = v20;
-              do
-              {
-                if ( *v16 )
-                  *v6 = this->uTargetGMask & v4->pPalette16[*v16];
-                ++v6;
-                ++v16;
-                --v21;
-              }
-              while ( v21 );
-            }
-            v16 += v18 - v20;
-            v17 = v22-- == 1;
-            v6 += this->uTargetSurfacePitch - v20;
-          }
-          while ( !v17 );
-        }
-      }
-    }
-  }
-}
+  DrawMasked(a2, a3, pTexture, 0x07E0);
+}
+
 
 //----- (004A6776) --------------------------------------------------------
 void Render::DrawTransparentRedShade(unsigned int a2, unsigned int a3, Texture *a4)
 {
-  Texture *v4; // edi@2
+  DrawMasked(a2, a3, a4, 0xF800);
+  /*Texture *v4; // edi@2
   unsigned int v5; // ebx@4
   unsigned __int16 *v6; // eax@4
   unsigned int v7; // edx@5
@@ -7629,13 +7383,138 @@
         }
       }
     }
-  }
-}
+  }*/
+}
+
+//----- (004A68EF) --------------------------------------------------------
+void Render::DrawMasked(signed int a2, signed int a3, Texture *pTexture, unsigned __int16 mask)
+{
+  Texture *v4; // edi@2
+  unsigned int v5; // ebx@4
+  //unsigned __int16 *v6; // eax@4
+  signed int v7; // edx@5
+  int v8; // edx@6
+  signed int v9; // edx@7
+  int v10; // edx@8
+  signed int v11; // edx@9
+  signed int v12; // esi@12
+  signed int v13; // esi@15
+  unsigned int v14; // edx@17
+  signed int v15; // esi@18
+  unsigned __int8 *v16; // ebx@22
+  char v17; // zf@28
+  int v18; // [sp+10h] [bp-10h]@4
+  unsigned __int8 *v19; // [sp+18h] [bp-8h]@4
+  int v20; // [sp+1Ch] [bp-4h]@4
+  int v21; // [sp+28h] [bp+8h]@24
+  unsigned int v22; // [sp+2Ch] [bp+Ch]@22
+  unsigned int pTexturea; // [sp+30h] [bp+10h]@11
+
+  if (!uNumSceneBegins || !pTexture)
+    return;
+
+    v4 = pTexture;
+
+      if ( pTexture->pPalette16 )
+      {
+        v5 = pTexture->uTextureHeight;
+        //v6 = &this->pTargetSurface[a2 + a3 * this->uTargetSurfacePitch];
+        v19 = pTexture->pLevelOfDetail0_prolly_alpha_mask;
+        v20 = pTexture->uTextureWidth;
+        v18 = pTexture->uTextureWidth;
+        int clipped_out_x = a2;
+        int clipped_out_y = a3;
+        if ( this->bClip )
+        {
+          v7 = this->uClipX;
+          if ( a2 < v7 )
+          {
+            v8 = v7 - a2;
+            v19 += v8;
+            v20 += a2 - this->uClipX;
+            //v6 += v8;
+            clipped_out_x = uClipX;
+          }
+          v9 = this->uClipY;
+          v5 = pTexture->uTextureHeight;
+          if ( a3 < v9 )
+          {
+            v10 = v9 - a3;
+            v19 += v18 * v10;
+            v5 = a3 - this->uClipY + pTexture->uTextureHeight;
+            v4 = pTexture;
+            //v6 += this->uTargetSurfacePitch * v10;
+            clipped_out_y = uClipY;
+          }
+          v11 = this->uClipX;
+          if ( v11 < a2 )
+            v11 = a2;
+          pTexturea = this->uClipZ;
+          if ( v11 + v20 > (signed int)pTexturea )
+          {
+            v12 = this->uClipX;
+            if ( v12 < a2 )
+              v12 = a2;
+            v20 = pTexturea - v12;
+          }
+          v13 = this->uClipY;
+          if ( v13 < a3 )
+            v13 = a3;
+          v14 = this->uClipW;
+          if ( (signed int)(v5 + v13) > (signed int)v14 )
+          {
+            v15 = this->uClipY;
+            if ( v15 < a3 )
+              v15 = a3;
+            v5 = v14 - v15;
+          }
+        }
+        
+          v16 = v19;
+        for (int y = 0; y < v5; ++y)
+        {
+          for (int x = 0; x < v20; ++x)
+          {
+                if ( *v16 )
+                  WritePixel16(clipped_out_x + x, clipped_out_y + y, v4->pPalette16[*v16] & mask);
+                ++v16;
+          }
+            v16 += v18 - v20;
+        }
+
+        /*if ( (signed int)v5 > 0 )
+        {
+          v22 = v5;
+          v16 = v19;
+          do
+          {
+            if ( v20 > 0 )
+            {
+              v21 = v20;
+              do
+              {
+                if ( *v16 )
+                  *v6 = this->uTargetGMask & v4->pPalette16[*v16];
+                ++v6;
+                ++v16;
+                --v21;
+              }
+              while ( v21 );
+            }
+            v16 += v18 - v20;
+            v17 = v22-- == 1;
+            v6 += this->uTargetSurfacePitch - v20;
+          }
+          while ( !v17 );
+        }*/
+      }
+}
+
 
 //----- (004A65CC) --------------------------------------------------------
 void Render::_4A65CC(unsigned int x, unsigned int y, Texture *a4, Texture *a5, int a6, int a7, int a8)
 {
-  unsigned __int16 *v8; // esi@6
+  //unsigned __int16 *v8; // esi@6
   unsigned int v9; // edi@6
   unsigned int v10; // eax@7
   unsigned int v11; // eax@8
@@ -7658,11 +7537,13 @@
 
   if ( this->uNumSceneBegins && a4 && a4->pPalette16 && a5 && a5->pPalette16 )
   {
-    v8 = &this->pTargetSurface[x + y * this->uTargetSurfacePitch];
+    //v8 = &this->pTargetSurface[x + y * this->uTargetSurfacePitch];
     v24 = a4->pLevelOfDetail0_prolly_alpha_mask;
     v27 = a4->uTextureWidth;
     v9 = a4->uTextureHeight;
     v22 = a4->uTextureWidth;
+    int clipped_out_x = x;
+    int clipped_out_y = y;
     if ( this->bClip )
     {
       v10 = this->uClipX;
@@ -7671,7 +7552,8 @@
         v11 = v10 - x;
         v24 += v11;
         v27 += x - this->uClipX;
-        v8 += v11;
+        //v8 += v11;
+        clipped_out_x = uClipX;
       }
       v12 = this->uClipY;
       if ( (signed int)y < (signed int)v12 )
@@ -7679,7 +7561,8 @@
         v13 = v12 - y;
         v24 += v22 * v13;
         v9 = y - this->uClipY + a4->uTextureHeight;
-        v8 += this->uTargetSurfacePitch * v13;
+        //v8 += this->uTargetSurfacePitch * v13;
+        clipped_out_y = uClipY;
       }
       v14 = this->uClipX;
       if ( (signed int)v14 < (signed int)x )
@@ -7704,7 +7587,25 @@
         v9 = v18 - v19;
       }
     }
-    if ( (signed int)v9 > 0 )
+
+    for (int dy = 0; dy < v9; ++dy)
+    {
+      for (int dx = 0; dx < v27; ++dx)
+      {
+            v20 = *v24;
+            if ( v20 >= a7 && v20 <= a8 )
+            {
+              v21 = a7 + (a6 + v20) % (2 * (a8 - a7));
+              if ( (a6 + v20) % (2 * (a8 - a7)) >= a8 - a7 )
+                v21 = 2 * a8 - v21 - a7;
+              //*v8 = a4->pPalette16[v21];
+              WritePixel16(clipped_out_x + dx, clipped_out_y + dy, a4->pPalette16[v21]);
+            }
+            ++v24;
+      }
+        v24 += v22 - v27;
+    }
+    /*if ( (signed int)v9 > 0 )
     {
       ya = v9;
       v23 = v22 - v27;
@@ -7734,7 +7635,7 @@
         --ya;
       }
       while ( ya );
-    }
+    }*/
   }
 }
 
@@ -7742,8 +7643,8 @@
 void Render::DrawAura(unsigned int a2, unsigned int a3, Texture *a4, Texture *a5, int a6, int a7, int a8)
 {
   Texture *v8; // eax@2
-  Texture *v9; // ebx@4
-  unsigned __int16 *v10; // esi@6
+  //Texture *v9; // ebx@4
+  //unsigned __int16 *v10; // esi@6
   unsigned int v11; // edi@7
   unsigned int v12; // eax@9
   unsigned int v13; // eax@10
@@ -7770,16 +7671,18 @@
     {
       if ( a4->pPalette16 )
       {
-        v9 = a5;
         if ( a5 )
         {
           if ( a5->pPalette16 )
           {
-            v10 = &this->pTargetSurface[a2 + a3 * this->uTargetSurfacePitch];
+            //v10 = &this->pTargetSurface[a2 + a3 * this->uTargetSurfacePitch];
             v28 = a4->pLevelOfDetail0_prolly_alpha_mask;
             v25 = v8->uTextureWidth;
             v24 = v8->uTextureHeight;
             v22 = v8->uTextureWidth;
+
+            int clipped_out_x = a2;
+            int clipped_out_y = a3;
             if ( this->bClip )
             {
               v11 = this->uClipX;
@@ -7787,17 +7690,17 @@
               {
                 v28 += v11 - a2;
                 v25 += a2 - v11;
-                v9 = a5;
-                v10 += v11 - a2;
+                //v10 += v11 - a2;
+                clipped_out_x = uClipX;
               }
               v12 = this->uClipY;
               if ( (signed int)a3 < (signed int)v12 )
               {
                 v13 = v12 - a3;
-                v9 = a5;
                 v28 += v22 * v13;
                 v24 += a3 - this->uClipY;
-                v10 += this->uTargetSurfacePitch * v13;
+                //v10 += this->uTargetSurfacePitch * v13;
+                clipped_out_y = uClipY;
               }
               v14 = this->uClipX;
               if ( (signed int)v14 < (signed int)a2 )
@@ -7822,8 +7725,34 @@
                 v24 = v18 - v19;
               }
             }
+
             v27 = 0;
-            if ( v24 > 0 )
+            for (int y = 0; y < v24; ++y)
+            {
+              for (int x = 0; x < v25; ++x)
+              {
+                  if ( *v28 )
+                  {
+                    v20 = *(&a5->pLevelOfDetail0_prolly_alpha_mask[x & a5->uWidthMinus1] + a5->uTextureWidth * (v27 & a5->uHeightMinus1));
+                    if ( v20 >= a7 )
+                    {
+                      if ( v20 <= a8 )
+                      {
+                        v21 = a7 + (a6 + v20) % (2 * (a8 - a7));
+                        if ( (a6 + v20) % (2 * (a8 - a7)) >= a8 - a7 )
+                          v21 = 2 * a8 - v21 - a7;
+                        //v9 = a5;
+                        //*v10 = a5->pPalette16[v21];
+                        WritePixel16(clipped_out_x + x, clipped_out_y + y, a5->pPalette16[v21]);
+                      }
+                    }
+                  }
+                  v28++;
+              }
+                v28 += v22 - v25;
+            }
+
+            /*if ( v24 > 0 )
             {
               v23 = v22 - v25;
               do
@@ -7853,7 +7782,10 @@
                 v28 += v23;
               }
               while ( v27 < v24 );
-            }
+            }*/
+
+
+
           }
         }
       }
@@ -7866,7 +7798,7 @@
 {
   Texture *pCurrentTexture; // edi@2
   int uHeight; // ebx@4
-  unsigned __int16 *v6; // eax@4
+  //unsigned __int16 *v6; // eax@4
   unsigned int v7; // edx@5
   unsigned int v8; // edx@6
   unsigned int v9; // edx@7
@@ -7893,10 +7825,13 @@
       if ( pTexture->pPalette16 )
       {
         uHeight = pTexture->uTextureHeight;
-        v6 = &this->pTargetSurface[uX + uY * this->uTargetSurfacePitch];
+        //v6 = &this->pTargetSurface[uX + uY * this->uTargetSurfacePitch];
         v19 = pTexture->pLevelOfDetail0_prolly_alpha_mask;
         uWidth = pTexture->uTextureWidth;
         v18 = pTexture->uTextureWidth;
+
+        int clipped_out_x = uX;
+        int clipped_out_y = uY;
         if ( this->bClip )
         {
           v7 = this->uClipX;
@@ -7905,7 +7840,8 @@
             v8 = v7 - uX;
             v19 += v8;
             uWidth += uX - this->uClipX;
-            v6 += v8;
+            //v6 += v8;
+            clipped_out_x = uClipX;
           }
           v9 = this->uClipY;
           uHeight = pTexture->uTextureHeight;
@@ -7915,7 +7851,8 @@
             v19 += v18 * v10;
             uHeight = uY - this->uClipY + pTexture->uTextureHeight;
             pCurrentTexture = pTexture;
-            v6 += this->uTargetSurfacePitch * v10;
+            //v6 += this->uTargetSurfacePitch * v10;
+            clipped_out_y = uClipY;
           }
           v11 = this->uClipX;
           if ( (signed int)v11 < (signed int)uX )
@@ -7940,7 +7877,19 @@
             uHeight = v14 - v15;
           }
         }
-        if ( (signed int)uHeight > 0 )
+        
+          v16 = v19;
+        for (int y = 0; y < uHeight; ++y)
+        {
+          for (int x = 0; x < uWidth; ++x)
+          {
+                if ( *v16 )
+                  WritePixel16(clipped_out_x + x, clipped_out_y + y, pCurrentTexture->pPalette16[*v16]);
+                ++v16;
+          }
+            v16 += v18 - uWidth;
+        }
+        /*if ( (signed int)uHeight > 0 )
         {
           uYa = uHeight;
           v16 = v19;
@@ -7963,7 +7912,7 @@
             v6 += this->uTargetSurfacePitch - uWidth;
           }
           while ( !uFlag );
-        }
+        }*/
       }
     }
   }
@@ -8159,8 +8108,8 @@
 void Render::DrawTextureIndexed(unsigned int uX, unsigned int uY, Texture *a4)
 {
   Texture *v4; // edi@2
-  unsigned int v5; // ebx@4
-  unsigned __int16 *pTarget; // eax@4
+  int v5; // ebx@4
+  //unsigned __int16 *pTarget; // eax@4
   unsigned int v7; // edx@5
   unsigned int v8; // edx@6
   unsigned int v9; // edx@7
@@ -8168,7 +8117,7 @@
   unsigned int v11; // edx@9
   unsigned int v12; // esi@12
   unsigned int v13; // esi@15
-  unsigned int v14; // edx@17
+  //unsigned int v14; // edx@17
   unsigned int v15; // esi@18
   unsigned __int8 *v16; // edx@22
   char v17; // zf@26
@@ -8187,10 +8136,13 @@
       if ( a4->pPalette16 )
       {
         v5 = a4->uTextureHeight;
-        pTarget = &this->pTargetSurface[uX + uY * this->uTargetSurfacePitch];
+        //pTarget = &this->pTargetSurface[uX + uY * this->uTargetSurfacePitch];
         v19 = a4->pLevelOfDetail0_prolly_alpha_mask;
         v20 = a4->uTextureWidth;
         v18 = a4->uTextureWidth;
+
+        int clipped_out_x = uX;
+        int clipped_out_y = uY;
         if ( this->bClip )
         {
           v7 = this->uClipX;
@@ -8199,7 +8151,8 @@
             v8 = v7 - uX;
             v19 += v8;
             v20 += uX - this->uClipX;
-            pTarget += v8;
+            //pTarget += v8;
+            clipped_out_x = uClipX;
           }
           v9 = this->uClipY;
           v5 = a4->uTextureHeight;
@@ -8209,7 +8162,8 @@
             v19 += v18 * v10;
             v5 = uY - this->uClipY + a4->uTextureHeight;
             v4 = a4;
-            pTarget += this->uTargetSurfacePitch * v10;
+            //pTarget += this->uTargetSurfacePitch * v10;
+            clipped_out_y = uClipY;
           }
           v11 = this->uClipX;
           if ( (signed int)v11 < (signed int)uX )
@@ -8225,16 +8179,27 @@
           v13 = this->uClipY;
           if ( (signed int)v13 < (signed int)uY )
             v13 = uY;
-          v14 = this->uClipW;
-          if ( (signed int)(v5 + v13) > (signed int)v14 )
+
+          if ( (signed int)(v5 + v13) > (signed int)uClipW )
           {
             v15 = this->uClipY;
             if ( (signed int)v15 < (signed int)uY )
               v15 = uY;
-            v5 = v14 - v15;
+            v5 = uClipW - v15;
           }
         }
-        if ( (signed int)v5 > 0 )
+        
+          v16 = v19;
+        for (int y = 0; y < v5; ++y)
+        {
+          for (int x = 0; x < v20; ++x)
+          {
+                WritePixel16(clipped_out_x + x, clipped_out_y + y, v4->pPalette16[*v16]);
+                ++v16;
+          }
+            v16 += v18 - v20;
+        }
+        /*if ( (signed int)v5 > 0 )
         {
           uYa = v5;
           v16 = v19;
@@ -8257,7 +8222,7 @@
             pTarget += this->uTargetSurfacePitch - v20;
           }
           while ( !v17 );
-        }
+        }*/
       }
     }
   }
@@ -8623,18 +8588,18 @@
 
   }*/
 
-  for (uint i = pRenderer->uNumBillboardsToDraw - 1; i != (uint)-1; --i)
-  {
-    RenderBillboardD3D* p = &pRenderer->pBillboardRenderListD3D[i];
-
-    if (p->uOpacity != RenderBillboardD3D::NoBlend)
-      SetBillboardBlendOptions(p->uOpacity);
+  for (int i = pRenderer->uNumBillboardsToDraw - 1; i >= 0; --i)
+  {
+    if((int)pRenderer->pBillboardRenderListD3D[i].pTexture == 0xcdcdcdcd)
+      __debugbreak();//Ritor1: error
+    if (pRenderer->pBillboardRenderListD3D[i].uOpacity != RenderBillboardD3D::NoBlend)
+      SetBillboardBlendOptions(pRenderer->pBillboardRenderListD3D[i].uOpacity);
     
-	//if((int)p->pTexture!=0xcdcdcdcd)
-    pRenderer->pRenderD3D->pDevice->SetTexture(0, p->pTexture);
+
+    pRenderer->pRenderD3D->pDevice->SetTexture(0, pRenderer->pBillboardRenderListD3D[i].pTexture);
     ErrD3D(pRenderer->pRenderD3D->pDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,
                                                          D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_SPECULAR | D3DFVF_TEX1,
-                                                         p->pQuads, p->uNumVertices,
+                                                         pRenderer->pBillboardRenderListD3D[i].pQuads, pRenderer->pBillboardRenderListD3D[i].uNumVertices,
                                                          D3DDP_DONOTLIGHT | D3DDP_DONOTUPDATEEXTENTS));
   }
 
@@ -9029,7 +8994,6 @@
   signed __int64 v17; // qtt@13
   signed int v18; // ecx@13
   struct Polygon pSkyPolygon; // [sp+14h] [bp-150h]@1
-  double v26; // [sp+120h] [bp-44h]@4
   int v30; // [sp+134h] [bp-30h]@1
   int v32; // [sp+13Ch] [bp-28h]@6
   int v33; // [sp+140h] [bp-24h]@2
@@ -9039,13 +9003,12 @@
   int v37; // [sp+154h] [bp-10h]@8
   int v38; // [sp+158h] [bp-Ch]@1
   int v39; // [sp+15Ch] [bp-8h]@4
-  int v40; // [sp+160h] [bp-4h]@7
 
   v30 = (signed __int64)((double)(pODMRenderParams->int_fov_rad * pGame->pIndoorCameraD3D->vPartyPos.z)
                        / ((double)pODMRenderParams->int_fov_rad + 8192.0)
-                       + (double)(pViewport->uScreenCenterY + 7));//include "+ 7"
-  v34 = cos((double)pGame->pIndoorCameraD3D->sRotationX * 0.0030664064) * 0x2000;//(double)pODMRenderParams->shading_dist_mist
-  v38 = (signed __int64)((double)(pViewport->uScreenCenterY + 7)
+                       + (double)(pViewport->uScreenCenterY));
+  v34 = cos((double)pGame->pIndoorCameraD3D->sRotationX * 0.0030664064) * 0x2000;//(double)pODMRenderParams->shading_dist_mist, 8192
+  v38 = (signed __int64)((double)(pViewport->uScreenCenterY)
                        - (double)pODMRenderParams->int_fov_rad
                        / (v34 + 0.0000001)
                        * (sin((double)pGame->pIndoorCameraD3D->sRotationX * 0.0030664064)
@@ -9059,7 +9022,7 @@
   {
     pSkyPolygon.dimming_level = 0;
     pSkyPolygon.uNumVertices = 4;
-  //centering()--  ----------------------------------------
+  //centering()-----------------------------------------------------------------
     pSkyPolygon.v_18.x = -stru_5C6E00->Sin(pGame->pIndoorCameraD3D->sRotationX + 16);
     pSkyPolygon.v_18.y = 0;
     pSkyPolygon.v_18.z = -stru_5C6E00->Cos(pGame->pIndoorCameraD3D->sRotationX + 16);
@@ -9075,77 +9038,64 @@
   //  |8,351                468,351 |
   // 1._____________________________.2
   // 
-    array_50AC10[0].vWorldViewProjX = (double)(signed int)pViewport->uViewportTL_X;
-    array_50AC10[0].vWorldViewProjY = (double)(signed int)pViewport->uViewportTL_Y;
-
-    array_50AC10[1].vWorldViewProjX = (double)(signed int)pViewport->uViewportTL_X;
-    array_50AC10[1].vWorldViewProjY = (double)v38;
-
-    array_50AC10[2].vWorldViewProjX = (double)(signed int)pViewport->uViewportBR_X;
-    array_50AC10[2].vWorldViewProjY = (double)v38;
-
-    array_50AC10[3].vWorldViewProjX = (double)(signed int)pViewport->uViewportBR_X;
-    array_50AC10[3].vWorldViewProjY = (double)(signed int)pViewport->uViewportTL_Y;
-
-    pSkyPolygon.sTextureDeltaU = 224 * pMiscTimer->uTotalGameTimeElapsed;
-    pSkyPolygon.sTextureDeltaV = 224 * pMiscTimer->uTotalGameTimeElapsed;
-
-    pSkyPolygon.field_24 = 0x2000000u;
-    v33 = 65536 / (signed int)(signed __int64)(((double)(pViewport->uViewportBR_X - pViewport->uViewportTL_X) * 0.5) / tan(0.6457717418670654) + 0.5);
+    array_50AC10[0].vWorldViewProjX = (double)(signed int)pViewport->uViewportTL_X;//8
+    array_50AC10[0].vWorldViewProjY = (double)(signed int)pViewport->uViewportTL_Y;//8
+
+    array_50AC10[1].vWorldViewProjX = (double)(signed int)pViewport->uViewportTL_X;//8
+    array_50AC10[1].vWorldViewProjY = (double)v38;//247
+
+    array_50AC10[2].vWorldViewProjX = (double)(signed int)pViewport->uViewportBR_X;//468
+    array_50AC10[2].vWorldViewProjY = (double)v38;//247
+
+    array_50AC10[3].vWorldViewProjX = (double)(signed int)pViewport->uViewportBR_X;//468
+    array_50AC10[3].vWorldViewProjY = (double)(signed int)pViewport->uViewportTL_Y;//8
+
+    pSkyPolygon.sTextureDeltaU = 224 * pMiscTimer->uTotalGameTimeElapsed;//7168
+    pSkyPolygon.sTextureDeltaV = 224 * pMiscTimer->uTotalGameTimeElapsed;//7168
+
+    pSkyPolygon.field_24 = 0x2000000u;//maybe attributes
+    v33 = 65536 / (signed int)(signed __int64)(((double)(pViewport->uViewportBR_X - pViewport->uViewportTL_X) / 2) / tan(0.6457717418670654) + 0.5);
     for ( uint i = 0; i < pSkyPolygon.uNumVertices; ++i )
     {
-      v26 = array_50AC10[i].vWorldViewProjY + 6.7553994e15;
       //rotate skydome(  )--------------------------------------
       //       .   (180).   0  
       //    /  (   / ),  65536 (010000)   90.
-	  //       . field_14    . field_20    
+      //       . field_14    . field_20    
       //  -25080  25080
-      v39 = (unsigned __int64)(pSkyPolygon.ptr_38->viewing_angle_from_west_east * (signed __int64)(v33 * (v30 - array_50AC10[i].vWorldViewProjY))) >> 16;
+      v39 = (unsigned __int64)(pSkyPolygon.ptr_38->viewing_angle_from_west_east * (signed __int64)(v33 * (v30 - floor(array_50AC10[i].vWorldViewProjY + 0.5)))) >> 16;
       v35 = v39 + pSkyPolygon.ptr_38->angle_from_north;
 
-      v39 = (unsigned __int64)(pSkyPolygon.ptr_38->viewing_angle_from_north_south * (signed __int64)(v33 * (v30 - array_50AC10[i].vWorldViewProjY))) >> 16;
+      v39 = (unsigned __int64)(pSkyPolygon.ptr_38->viewing_angle_from_north_south * (signed __int64)(v33 * (v30 - floor(array_50AC10[i].vWorldViewProjY + 0.f)))) >> 16;
       v36 = v39 + pSkyPolygon.ptr_38->angle_from_east;
 
-      v38 = pSkyPolygon.v_18.z;
-      v9 = (unsigned __int64)(pSkyPolygon.v_18.z * (signed __int64)(v33 * (v30 - array_50AC10[i].vWorldViewProjY))) >> 16;
+      v9 = (unsigned __int64)(pSkyPolygon.v_18.z * (signed __int64)(v33 * (v30 - floor(array_50AC10[i].vWorldViewProjY + 0.5)))) >> 16;
       v10 = pSkyPolygon.v_18.x + v9;
-      v39 = pSkyPolygon.v_18.x + v9;
-      if ( pSkyPolygon.v_18.x + v9 > 0 )
-      {
+      if ( v10 > 0 )
         v10 = 0;
-        v39 = 0;
-      }
-      v38 = v10;
       v13 = v33 * (pViewport->uScreenCenterX - (signed __int64)array_50AC10[i].vWorldViewProjX);
       v34 = -pSkyPolygon.field_24;
-      v32 = (signed __int64)array_50AC10[i].vWorldViewProjX;
-      v14 = v33 * (v30 - (signed __int64)array_50AC10[i].vWorldViewProjX);
+      v32 = (signed __int64)array_50AC10[i].vWorldViewProjY - 1.0;
+      v14 = v33 * (v30 - v32);
       while ( 1 )
       {
-        v40 = v14;
-        if ( !v10 )
-          goto LABEL_12;
-        v37 = abs((int)v34 >> 14);
-        v15 = abs(v10);
-        if ( v37 <= v15 || v32 <= (signed int)pViewport->uViewportTL_Y )
+        if ( v10 )
         {
-          if ( v39 <= 0 )
-            break;
+          v37 = abs((int)v34 >> 14);
+          v15 = abs(v10);
+          if ( v37 <= v15 || v32 <= (signed int)pViewport->uViewportTL_Y )
+          {
+            if ( v10 <= 0 )
+              break;
+          }
         }
-        v14 = v40;
-LABEL_12:
-        v37 = pSkyPolygon.v_18.z;
         v16 = (unsigned __int64)(pSkyPolygon.v_18.z * (signed __int64)v14) >> 16;
         --v32;
         v14 += v33;
         v10 = pSkyPolygon.v_18.x + v16;
-        v39 = pSkyPolygon.v_18.x + v16;
-        v38 = pSkyPolygon.v_18.x + v16;
       }
       LODWORD(v17) = LODWORD(v34) << 16;
       HIDWORD(v17) = v34 >> 16;
-      //v40 = v17 / v38;
-      v18 = v17 / v38;
+      v18 = v17 / v10;
       if ( v18 < 0 )
         v18 = pODMRenderParams->shading_dist_mist;
       v37 = v35 + ((unsigned __int64)(pSkyPolygon.ptr_38->angle_from_west * (signed __int64)v13) >> 16);
@@ -9158,14 +9108,14 @@
          + ((signed int)((unsigned __int64)(v36 * (signed __int64)v18) >> 16) >> 3);
       array_50AC10[i].v = (double)v35 / ((double)pSkyPolygon.pTexture->uTextureHeight * 65536.0);
 
-      array_50AC10[i].vWorldViewPosition.x = (double)0x2000;//pODMRenderParams->shading_dist_mist
+      array_50AC10[i].vWorldViewPosition.x = (double)0x2000;//pODMRenderParams->shading_dist_mist 8192
       array_50AC10[i]._rhw = 1.0 / (double)(v18 >> 16);
     }
     pRenderer->DrawOutdoorSkyPolygon(pSkyPolygon.uNumVertices, &pSkyPolygon, pBitmaps_LOD->pHardwareTextures[(signed __int16)pSkyPolygon.uTileBitmapID]);
-    array_50AC10[0].vWorldViewProjY = (double)v38;
+    array_50AC10[0].vWorldViewProjY = (double)v10;
     array_50AC10[1].vWorldViewProjY = array_50AC10[1].vWorldViewProjY + 30.0;
     array_50AC10[2].vWorldViewProjY = array_50AC10[2].vWorldViewProjY + 30.0;
-    array_50AC10[3].vWorldViewProjY = (double)v38;
+    array_50AC10[3].vWorldViewProjY = (double)v10;
     pRenderer->DrawOutdoorSkyPolygon(pSkyPolygon.uNumVertices, &pSkyPolygon, pBitmaps_LOD->pHardwareTextures[(signed __int16)pSkyPolygon.uTileBitmapID]);
     return;
   }
--- a/Render.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Render.h	Thu Jan 02 09:11:28 2014 +0600
@@ -15,6 +15,9 @@
 struct ODMFace;
 
 
+unsigned __int16 Color16(unsigned __int32 r, unsigned __int32 g, unsigned __int32 b);
+unsigned __int32 Color32(unsigned __int16 color16);
+
 /*  119 */
 #pragma pack(push, 1)
 struct RenderVertexSoft
@@ -228,7 +231,7 @@
   
   void GetAvailableDevices(RenderD3D__DevInfo **pOutDevices);
   void Release();
-  bool CreateDevice(unsigned int uDeviceID, int bWindowed, HWND hWnd);
+  bool CreateDevice(unsigned int uDeviceID, int bWindowed, struct OSWindow *window);
   unsigned int GetDeviceCaps();
   void ClearTarget(unsigned int bClearColor, unsigned int uClearColor, unsigned int bClearDepth, float z_clear);
   void Present(bool bForceBlit);
@@ -269,17 +272,17 @@
 
   static Render *Create() {return new Render;}
 
-  bool Initialize(bool bWindowed, OSWindow *window, bool bColoredLights, uint32_t uDetailLevel, bool bTinting);
+  bool Initialize(OSWindow *window, bool bColoredLights, uint32_t uDetailLevel, bool bTinting);
 
 
   bool IsColorKeySupported(IDirectDraw4 *);
-  void _49EBF1();
+  void _stub_49EBF1();
   void ClearBlack();
   void PresentBlackScreen();
   void SavePCXScreenshot();
-  void _49F1BC(const char *a1);
+  void SaveWinnersCertificate(const char *a1);
   void PackPCXpicture(unsigned short* picture_data, int wight, int heidth, void *data_buff, int max_buff_size,unsigned int* packed_size);
-  FILE *SavePCXImage(const char *Filename, char *a3, int a4, int a5);
+  FILE *SavePCXImage(const char *Filename, unsigned short* picture_data, int width, int height);
   void ClearTarget(unsigned int uColor);
   void Release2();
   void Present();
@@ -289,7 +292,7 @@
   void CreateSomeTexture();
   bool InitializeFullscreen();
   bool SwitchToWindow();
-  char RasterLine2D(unsigned int uX, unsigned int uY, unsigned int uZ, unsigned int uW, unsigned __int16 uColor);
+  void RasterLine2D(signed int uX, signed int uY, signed int uZ, signed int uW, unsigned __int16 uColor);
   void ClearZBuffer(int a2, int a3);
   void SetRasterClipRect(unsigned int uX, unsigned int uY, unsigned int uZ, unsigned int uW);
   void ParseTargetPixelFormat();
@@ -328,7 +331,7 @@
   void MakeParticleBillboardAndPush_ODM(RenderBillboardTransform_local0 *a2, IDirect3DTexture2 *a3, unsigned int uDiffuse, int angle);
   void TransformBillboard(RenderBillboardTransform_local0 *a2, Sprite *pSprite, int dimming_level, RenderBillboard *pBillboard);
   void DrawBillboard_Indoor(RenderBillboardTransform_local0 *pSoftBillboard, Sprite *pSprite, int dimming_level);
-  int MakeParticleBillboardAndPush_BLV_Software(int screenSpaceX, int screenSpaceY, int z, int lightColor, int a6);
+  //int MakeParticleBillboardAndPush_BLV_Software(int screenSpaceX, int screenSpaceY, int z, int lightColor, int a6);
   void DrawProjectile(float srcX, float srcY, float a3, float a4, float dstX, float dstY, float a7, float a8, IDirect3DTexture2 *a9);
   void _4A4CC9_AddSomeBillboard(struct stru6_stru1_indoor_sw_billboard *a1, int diffuse);
   bool LoadTexture(const char *pName, unsigned int bMipMaps, IDirectDrawSurface4 **pOutSurface, IDirect3DTexture2 **pOutTexture);
@@ -348,11 +351,12 @@
   void _4A65CC(unsigned int x, unsigned int y, struct Texture *a4, struct Texture *a5, int a6, int a7, int a8);
   void DrawTransparentRedShade(unsigned int a2, unsigned int a3, struct Texture *a4);
   void DrawTransparentGreenShade(signed int a2, signed int a3, struct Texture *pTexture);
+  void DrawMasked(signed int a2, signed int a3, struct Texture *pTexture, unsigned __int16 mask);
   void GetLeather(unsigned int a2, unsigned int a3, struct Texture *a4, __int16 height);
   void DrawTextPalette(int x, int y, unsigned char* font_pixels, int a5, unsigned int uFontHeight, unsigned __int16 *pPalette, int a8);
   void DrawText(signed int uOutX, signed int uOutY, unsigned __int8 *pFontPixels, unsigned int uCharWidth, unsigned int uCharHeight, unsigned __int16 *pFontPalette, unsigned __int16 uFaceColor, unsigned __int16 uShadowColor);
   void FillRectFast(unsigned int uX, unsigned int uY, unsigned int uWidth, unsigned int uHeight, unsigned int uColor16);
-  int _4A6DF5(unsigned __int16 *pBitmap, unsigned int uBitmapPitch, struct Vec2_int_ *pBitmapXY, unsigned __int16 *pTarget, unsigned int uTargetPitch, Vec4_int_ *a7);
+  void _4A6DF5(unsigned __int16 *pBitmap, unsigned int uBitmapPitch, struct Vec2_int_ *pBitmapXY, void *pTarget, unsigned int uTargetPitch, Vec4_int_ *a7);
   void _4A6E7E(unsigned int a2, unsigned int a3, struct Texture *a4);
   void DrawBuildingsD3D();
   //struct BSPModel *DrawBuildingsSW();
@@ -372,7 +376,7 @@
   void __cdecl sub_4A19B0();
 
   //unsigned int bUserDirect3D;
-  unsigned int bStartInWindow;
+  //unsigned int bStartInWindow;
   unsigned int uDesiredDirect3DDevice;
   unsigned int uAcquiredDirect3DDevice;
   int field_10;
@@ -382,8 +386,8 @@
   int raster_clip_y;    // clipping rect for raster ops
   int raster_clip_z;    //    like RasterLine2D for (mini)map
   int raster_clip_w;
-  __int16 field_2C[65536];
-  __int16 field_2002C[65536];
+  __int16 unused_2C[65536];
+  __int16 unused_2002C[65536];
   int field_4002C;
   int field_40030;
   int *pActiveZBuffer;
@@ -407,7 +411,7 @@
   IDirectDrawSurface2 *pFrontBuffer2;
   IDirectDrawSurface2 *pBackBuffer2;
   IDirectDrawSurface2 *pSomeSurface2;
-  DDPIXELFORMAT ddpfPrimareSuface;
+  DDPIXELFORMAT ddpfPrimarySuface;
   unsigned int uTargetRBits;
   unsigned int uTargetGBits;
   unsigned int uTargetBBits;
@@ -415,17 +419,17 @@
   unsigned int uTargetGMask;
   unsigned int uTargetBMask;
   unsigned int uNumSceneBegins;
-  int *ptr_400E8;
-  unsigned __int16 *pTargetSurface;
+  unsigned __int32 *pTargetSurface_unaligned;
+  void             *pTargetSurface;
   unsigned int uTargetSurfacePitch;
   unsigned int uClipY;
   unsigned int uClipX;
   unsigned int uClipW;
   unsigned int uClipZ;
   unsigned int bClip;
-  unsigned int bColorKeySupported;
+  //unsigned int bColorKeySupported;
   unsigned int uNumD3DSceneBegins;
-  int field_40110;
+  int using_software_screen_buffer;
   RenderHWLContainer pD3DBitmaps;
   RenderHWLContainer pD3DSprites;
   unsigned int bUseColoredLights;
@@ -453,9 +457,39 @@
   RenderBillboardD3D pBillboardRenderListD3D[1000];
   unsigned int uNumBillboardsToDraw;
   int field_129834;
-  unsigned int uCurrentlyLockedSurfacePitch;
-  unsigned __int16 *pCurrentlyLockedSurfaceDataPtr;
-  unsigned __int16 *pCurrentlyLockedSoftSurface;
+  //unsigned int uCurrentlyLockedSurfacePitch;
+  //unsigned __int16 *pCurrentlyLockedSurfaceDataPtr;
+  //void             *pCurrentlyLockedSoftSurface;
+
+  inline void WritePixel16(int x, int y, unsigned __int16 color)
+  {
+    if (ddpfPrimarySuface.dwRGBBitCount == 32)
+    {
+      auto p = (unsigned __int32 *)pTargetSurface + x + y * uTargetSurfacePitch;
+      *p = Color32(color);
+    }
+    else if (ddpfPrimarySuface.dwRGBBitCount == 16)
+    {
+      auto p = (unsigned __int16 *)pTargetSurface + x + y * uTargetSurfacePitch;
+      *p = color;
+    }
+    else __debugbreak();
+  }
+
+  inline unsigned __int16 ReadPixel16(int x, int y)
+  {
+    if (ddpfPrimarySuface.dwRGBBitCount == 32)
+    {
+      auto p = (unsigned __int32 *)pTargetSurface + x + y * uTargetSurfacePitch;
+      return Color16((*p >> 16) & 255, (*p >> 8) & 255, *p & 255);
+    }
+    else if (ddpfPrimarySuface.dwRGBBitCount == 16)
+    {
+      auto p = (unsigned __int16 *)pTargetSurface + x + y * uTargetSurfacePitch;
+      return *p;
+    }
+    else __debugbreak();
+  }
 
 
   //int windowed_mode_width;
@@ -473,7 +507,7 @@
 #pragma pack(push, 1)
 struct RenderBillboardTransform_local0
 {
-  unsigned __int16 *pTarget;
+  void *pTarget;
   int *pTargetZ;
   int uScreenSpaceX;
   int uScreenSpaceY;
--- a/SaveLoad.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/SaveLoad.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -24,6 +24,7 @@
 #include "Log.h"
 #include "VideoPlayer.h"
 #include "Level/Decoration.h"
+#include "Render.h"
 
 #include "mm7_data.h"
 
@@ -76,14 +77,14 @@
     for (uint i = 0; i < 4; ++i)
     {
       for (uint j = 0; j < pSoundList->sNumSounds; ++j)
-        if (pSoundList->pSounds[j].uSoundID == 2 * (SoundSetAction[24][0] + 50 * pParty->pPlayers[i].uVoiceID) + 4998)
+        if (pSoundList->pSL_Sounds[j].uSoundID == 2 * (SoundSetAction[24][0] + 50 * pParty->pPlayers[i].uVoiceID) + 4998)
         {
           pSoundList->UnloadSound(j, 1);
           break;
         }
 
         for (uint j = 0; j < pSoundList->sNumSounds; ++j)
-        if (pSoundList->pSounds[j].uSoundID == 2 * (SoundSetAction[24][0] + 50 * pParty->pPlayers[i].uVoiceID) + 4999)
+        if (pSoundList->pSL_Sounds[j].uSoundID == 2 * (SoundSetAction[24][0] + 50 * pParty->pPlayers[i].uVoiceID) + 4999)
         {
           pSoundList->UnloadSound(j, 1);
           break;
@@ -177,7 +178,7 @@
   {
     uchar uQuickspell = pParty->pPlayers[i].uQuickSpell;
     if (uQuickspell)
-      stru_AA1058[i]._494836(uQuickspell, i + 9 - 8);
+      stru_AA1058[i]._494836(uQuickspell, i + 1);
 
     for (uint j = 0; j < 2; ++j)
     {
@@ -321,7 +322,7 @@
   pLodDirectory.uDataSize = sizeof(Party); //90680;
   if ( pNew_LOD->Write(&pLodDirectory, pParty, 0) )
   {
-    sprintf(work_string, pGlobalTXT_LocalizationStrings[612], 202);
+    sprintf(work_string, pGlobalTXT_LocalizationStrings[612], 202);//Save game corrupted!  Code=%d
     MessageBoxA(nullptr, work_string, "E:\\WORK\\MSDEV\\MM7\\MM7\\Code\\LoadSave.cpp:793", 0);
   }
   strcpy(pLodDirectory.pFilename, "clock.bin");
@@ -379,7 +380,7 @@
       }
 	}
   }
-  if ( !NotSaveWorld )
+  if ( !NotSaveWorld )//autosave for change location
   {
     //__debugbreak();
     CompactLayingItemsList();
@@ -669,20 +670,15 @@
   free(pSave);
 }
 //----- (0045E03A) --------------------------------------------------------
-unsigned short * MakeScreenshot( signed int width, signed int height )
+unsigned short *MakeScreenshot( signed int width, signed int height )
 {
-  //signed int v2; // edi@1
   unsigned __int16 *v3; // ebx@1
   int v4; // edx@7
   unsigned __int8 v5; // cf@9
   unsigned int v6; // ecx@9
   unsigned __int16 *v7; // edi@9
   int j; // ecx@9
-  //unsigned __int16 *v9; // edi@15
-  //int v10; // ecx@15
-  //LONG v11; // esi@15
-  //signed __int64 v12; // qax@18
-  //unsigned int v13; // ST10_4@21
+  unsigned int screen_x; // qax@18
   HRESULT v14; // eax@21
   int v15; // edi@29
   signed __int64 v16; // qax@30
@@ -691,27 +687,23 @@
   int k; // ecx@36
   DDSURFACEDESC2 Dst; // [sp+4h] [bp-A0h]@6
   unsigned __int16 *pPixels; // [sp+80h] [bp-24h]@1
-  float v23; // [sp+84h] [bp-20h]@1
+  float interval_x; // [sp+84h] [bp-20h]@1
   unsigned __int16 *_this; // [sp+88h] [bp-1Ch]@21
-  float v25; // [sp+8Ch] [bp-18h]@1
-  unsigned int v26; // [sp+90h] [bp-14h]@17
-  //int v27; // [sp+94h] [bp-10h]@1
+  float interval_y; // [sp+8Ch] [bp-18h]@1
+  unsigned int screen_y; // [sp+90h] [bp-14h]@17
   int v28; // [sp+98h] [bp-Ch]@16
   int v29; // [sp+9Ch] [bp-8h]@15
-  //int v30; // [sp+A0h] [bp-4h]@1
 
-  //v30 = width;
-  //v2 = height;
-  //v27 = height;
-  v23 = game_viewport_width / (double)width;
-  v25 = game_viewport_height / (double)height;
+  interval_x = game_viewport_width / (double)width;
+  interval_y = game_viewport_height / (double)height;
 
   pPixels = (unsigned __int16 *)malloc(2 * height * width);
   memset(pPixels, 0 , 2 * height * width);
 
   v3 = pPixels;
-  if ( pRenderer->pRenderD3D )
-  {
+  if (!pRenderer->pRenderD3D)
+    __debugbreak();
+
     pRenderer->BeginSceneD3D();
 
     if (uCurrentlyLoadedLevelType == LEVEL_Indoor)
@@ -720,30 +712,29 @@
       pOutdoor->Draw();
 
     pRenderer->DrawBillboards_And_MaybeRenderSpecialEffects_And_EndScene();
-    memset(&Dst, 0, 0x7Cu);
+    memset(&Dst, 0, 0x7C);
     Dst.dwSize = sizeof(Dst);
 
     if ( pRenderer->LockSurface_DDraw4(pRenderer->pBackBuffer4, &Dst, DDLOCK_WAIT) )
     {
-      ushort* src = (unsigned __int16 *)Dst.lpSurface;
-      ulong src_width = (Dst.lPitch / sizeof(short));
-      ulong src_height = Dst.dwHeight;
-      ushort* dst = pPixels;
       for (uint y = 0; y < height; ++y)
       {
-        //uint src_y = (game_viewport_y + y * v25) * (Dst.lPitch / sizeof(short));
-        uint src_y = game_viewport_y + y * v25;
-        Assert(game_viewport_y + y * v25 < src_height);
-        Assert(y < height);
-
         for (uint x = 0; x < width; ++x)
         {
-          //uint src_x = game_viewport_x + x * v23;
-          uint src_x = game_viewport_x + x * v23;
-          Assert(src_x < src_width);
-          Assert(x < width);
+          //*v3 = pRenderer->ReadPixel16((int)(x* interval_x + 8.0), (int)(y * interval_y + 8.0));//screen_data[screen_y + (int)(x* interval_x + 8.0)];
 
-          dst[y * width + x] = (((63*y)/117) << 5) | 31*x/155;//31*y/117;//src[src_y * src_width + src_x];
+          if (Dst.ddpfPixelFormat.dwRGBBitCount == 32)
+          {
+            auto p = (unsigned __int32 *)Dst.lpSurface + (int)(x * interval_x + 8.0) + y/* (int)(y * interval_y + 8.0)*/ * Dst.lPitch;
+            *v3 = Color16((*p >> 16) & 255, (*p >> 8) & 255, *p & 255);
+          }
+          else if (Dst.ddpfPixelFormat.dwRGBBitCount == 16)
+          {
+            auto p = (unsigned __int16 *)Dst.lpSurface + (int)(x * interval_x + 8.0) + y * Dst.lPitch;
+            *v3 = *p;
+          }
+          else __debugbreak();
+          ++v3;
         }
       }
       ErrD3D(pRenderer->pBackBuffer4->Unlock(0));
@@ -774,8 +765,9 @@
         while ( v4 );
       }
     }
-  }
-  else
+
+    
+  /*if (!pRenderer->pRenderD3D)
   {
     pRenderer->BeginScene();
     if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
@@ -828,15 +820,15 @@
       }
     }
     pRenderer->EndScene();
-  }
+  }*/
   return pPixels;
 }
 //----- (0045E26C) --------------------------------------------------------
 void  SaveScreenshot(const char *pFilename)
 {
-  unsigned __int16 *v2; // esi@1
+  unsigned short *screenshot; // esi@1
 
-  v2 = MakeScreenshot(92, 68);
-  pRenderer->SavePCXImage(pFilename, (char *)v2, 92, 68);
-  free(v2);
+  screenshot = MakeScreenshot(92, 68);
+  pRenderer->SavePCXImage(pFilename, screenshot, 92, 68);
+  free(screenshot);
 }
\ No newline at end of file
--- a/Spells.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Spells.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -412,17 +412,17 @@
 							test= tolower(test_string[j]);
 							switch (test)
 							{
-							case 109:
-								pSpellDatas[i].field_12|=1;
+							case 'm':
+								pSpellDatas[i].stats|=1;
 								break;
-							case 101:
-								pSpellDatas[i].field_12|=2;
+							case 'e':
+								pSpellDatas[i].stats|=2;
 								break;
-							case 99:
-								pSpellDatas[i].field_12|=4;
+							case 'c':
+								pSpellDatas[i].stats|=4;
 								break;
-							case 120:
-								pSpellDatas[i].field_12|=8;
+							case 'x':
+								pSpellDatas[i].stats|=8;
 								break;
 							}					
 						}
@@ -554,9 +554,9 @@
   a1.uType = stru_4E3ACC[uSpellID].uType;
   if ( uSpellID > 58 )
   {
-    if ( uSpellID == 69 )
+    if ( uSpellID == SPELL_BODY_PROTECTION_FROM_BODY )
       goto LABEL_117;
-    if ( uSpellID != 83 )
+    if ( uSpellID != SPELL_LIGHT_DAY_OF_THE_GODS )
       return;
     v40 = v15 - 2;
     if ( v40 )
@@ -574,7 +574,8 @@
         v37 = &pParty->pPartyBuffs[PARTY_BUFF_DAY_OF_GODS];
         v36 = pParty->uTimePlayed + v39;
         v37->Apply(v36, a7b, v43, 0, 0);
-        goto LABEL_139;
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
       }
       if ( v41 == 1 )
       {
@@ -588,7 +589,8 @@
        v37 = &pParty->pPartyBuffs[PARTY_BUFF_DAY_OF_GODS];
        v36 = pParty->uTimePlayed + v39;
        v37->Apply(v36, a7b, v43, 0, 0);
-       goto LABEL_139;
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
       }
     }
     v42 = 10800 * uSkill;
@@ -601,20 +603,21 @@
     v37 = &pParty->pPartyBuffs[PARTY_BUFF_DAY_OF_GODS];
     v36 = pParty->uTimePlayed + v39;
     v37->Apply(v36, a7b, v43, 0, 0);
-    goto LABEL_139;
+    pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+    return;
   }
   if ( uSpellID != 58 )
   {
     switch ( uSpellID )
     {
-      case 2:
-      case 6:
-      case 18:
-      case 26:
-      case 29:
-      case 32:
-      case 39:
-      case 41:
+      case SPELL_FIRE_FIRE_BOLT:
+      case SPELL_FIRE_FIREBALL:
+      case SPELL_AIR_LIGHNING_BOLT:
+      case SPELL_WATER_ICE_BOLT:
+      case SPELL_WATER_ACID_BURST:
+      case SPELL_WATER_ICE_BLAST:
+      case SPELL_EARTH_BLADES:
+      case SPELL_EARTH_ROCK_BLAST:
         a1.stru_24.Reset();
         v16 = 0;
         a1.spell_id = uSpellID;
@@ -622,22 +625,23 @@
         a1.spell_skill = v15;
         if ( (signed int)pObjectList->uNumObjects <= 0 )
         {
-          v18 = 0;
-          a1.uObjectDescID = v18;
+          //v18 = 0;
+          a1.uObjectDescID = 0;
           *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
           a1.vPosition.x = fromx;
           a1.uAttributes = 16;
           a1.uSectorID = pIndoor->GetSector(fromx, fromy, fromz);
           a1.field_60_distance_related_prolly_lod = v55;
-          v20 = yaw;
+          //v20 = yaw;
           a1.uSpriteFrameID = 0;
           a1.spell_caster_pid = 8000 | OBJECT_Item;
           a1.spell_target_pid = 0;
           a1.uFacing = yaw;
           a1.uSoundID = 0;
           v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-          a1.Create(v20, pitch, v49, 0);
-          goto LABEL_139;
+          a1.Create(yaw, pitch, v49, 0);
+          pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+          return;
         }
         v17 = (char *)&pObjectList->pObjects->uObjectID;
         while ( (short)a1.uType != *(short *)v17 )
@@ -646,22 +650,23 @@
           v17 += 56;
           if ( v16 >= (signed int)pObjectList->uNumObjects )
           {
-            v18 = 0;
-            a1.uObjectDescID = v18;
+            //v18 = 0;
+            a1.uObjectDescID = 0;
             *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
             a1.vPosition.x = fromx;
             a1.uAttributes = 16;
             a1.uSectorID = pIndoor->GetSector(fromx, fromy, fromz);
             a1.field_60_distance_related_prolly_lod = v55;
-            v20 = yaw;
+            //v20 = yaw;
             a1.uSpriteFrameID = 0;
             a1.spell_caster_pid = 8000 | OBJECT_Item;
             a1.spell_target_pid = 0;
             a1.uFacing = yaw;
             a1.uSoundID = 0;
             v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-            a1.Create(v20, pitch, v49, 0);
-            goto LABEL_139;
+            a1.Create(yaw, pitch, v49, 0);
+            pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+            return;
           }
         }
         v18 = v16;
@@ -671,16 +676,17 @@
         a1.uAttributes = 16;
         a1.uSectorID = pIndoor->GetSector(fromx, fromy, fromz);
         a1.field_60_distance_related_prolly_lod = v55;
-        v20 = yaw;
+        //v20 = yaw;
         a1.uSpriteFrameID = 0;
         a1.spell_caster_pid = 8000 | OBJECT_Item;
         a1.spell_target_pid = 0;
         a1.uFacing = yaw;
         a1.uSoundID = 0;
         v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-        a1.Create(v20, pitch, v49, 0);
-        goto LABEL_139;
-      case 24:
+        a1.Create(yaw, pitch, v49, 0);
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
+      case SPELL_WATER_POISON_SPRAY:
         switch ( v15 )
         {
           case 1:
@@ -706,9 +712,7 @@
           a1.spell_level = uSkill;
           a1.spell_skill = v15;
           if ( (signed int)pObjectList->uNumObjects <= 0 )
-          {
             v23 = 0;
-          }
           else
           {
             v22 = (char *)&pObjectList->pObjects->uObjectID;
@@ -734,7 +738,8 @@
                   a1.uFacing = i + yaw;
                   a1.Create((signed __int16)(i + (short)yaw), pitch, pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed, 0);
                 }
-                goto LABEL_139;
+                pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+                return;
               }
             }
             v23 = v21;
@@ -754,81 +759,82 @@
             a1.uFacing = i + yaw;
             a1.Create((signed __int16)(i + (short)yaw), pitch, pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed, 0);
           }
-          goto LABEL_139;
+          pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+          return;
         }
         a1.stru_24.Reset();
-        v16 = 0;
         a1.spell_id = uSpellID;
         a1.spell_level = uSkill;
         a1.spell_skill = v15;
         if ( (signed int)pObjectList->uNumObjects <= 0 )
-       {
-         v18 = 0;
-         a1.uObjectDescID = v18;
-         *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
-         a1.vPosition.x = fromx;
-         a1.uAttributes = 16;
-         a1.uSectorID = pIndoor->GetSector(fromx, fromy, fromz);
-         a1.field_60_distance_related_prolly_lod = v55;
-         v20 = yaw;
-         a1.uSpriteFrameID = 0;
-         a1.spell_caster_pid = 8000 | OBJECT_Item;
-         a1.spell_target_pid = 0;
-         a1.uFacing = yaw;
-         a1.uSoundID = 0;
-         v51 = 0;
-         v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-         v47 = pitch;
-         a1.Create(v20, v47, v49, v51);
-         goto LABEL_139;
-       }
-        v19 = (char *)&pObjectList->pObjects->uObjectID;
-        do
         {
-          if ( (short)a1.uType == *(short *)v19 )
+          //v18 = 0;
+          a1.uObjectDescID = 0;
+          *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
+          a1.vPosition.x = fromx;
+          a1.uAttributes = 16;
+          a1.uSectorID = pIndoor->GetSector(fromx, fromy, fromz);
+          a1.field_60_distance_related_prolly_lod = v55;
+          //v20 = yaw;
+          a1.uSpriteFrameID = 0;
+          a1.spell_caster_pid = 8000 | OBJECT_Item;
+          a1.spell_target_pid = 0;
+          a1.uFacing = yaw;
+          a1.uSoundID = 0;
+          //v51 = 0;
+          v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
+          //v47 = pitch;
+          a1.Create(yaw, pitch, v49, 0);
+          pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+          return;
+        }
+        //v19 = (char *)&pObjectList->pObjects->uObjectID;
+        for ( v16 = 0; v16 < (signed int)pObjectList->uNumObjects; ++v16 )
+        {
+          if ( (short)a1.uType == pObjectList->pObjects[v16].uObjectID )
           {
-            v18 = v16;
-            a1.uObjectDescID = v18;
+            //v18 = v16;
+            a1.uObjectDescID = v16;
             *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
             a1.vPosition.x = fromx;
             a1.uAttributes = 16;
             a1.uSectorID = pIndoor->GetSector(fromx, fromy, fromz);
             a1.field_60_distance_related_prolly_lod = v55;
-            v20 = yaw;
+            //v20 = yaw;
             a1.uSpriteFrameID = 0;
             a1.spell_caster_pid = 8000 | OBJECT_Item;
             a1.spell_target_pid = 0;
             a1.uFacing = yaw;
             a1.uSoundID = 0;
-            v51 = 0;
+            //v51 = 0;
             v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-            v47 = pitch;
-            a1.Create(v20, v47, v49, v51);
-            goto LABEL_139;
+            //v47 = pitch;
+            a1.Create(yaw, pitch, v49, 0);
+            pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+            return;
           }
-          ++v16;
-          v19 += 56;
+          //v19 += 56;
         }
-        while ( v16 < (signed int)pObjectList->uNumObjects );
-        v18 = 0;
-        a1.uObjectDescID = v18;
+        //v18 = 0;
+        a1.uObjectDescID = 0;
         *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
         a1.vPosition.x = fromx;
         a1.uAttributes = 16;
         a1.uSectorID = pIndoor->GetSector(fromx, fromy, fromz);
         a1.field_60_distance_related_prolly_lod = v55;
-        v20 = yaw;
+        //v20 = yaw;
         a1.uSpriteFrameID = 0;
         a1.spell_caster_pid = 8000 | OBJECT_Item;
         a1.spell_target_pid = 0;
         a1.uFacing = yaw;
         a1.uSoundID = 0;
-        v51 = 0;
+        //v51 = 0;
         v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-        v47 = pitch;
-        a1.Create(v20, v47, v49, v51);
-        goto LABEL_139;
-      case 15:
+        //v47 = pitch;
+        a1.Create(yaw, pitch, v49, 0);
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
+      case SPELL_AIR_SPARKS:
         switch ( v15 )
         {
           case 1:
@@ -853,8 +859,8 @@
         a1.spell_skill = v15;
         if ( (signed int)pObjectList->uNumObjects <= 0 )
         {
-          v27 = 0;
-          a1.uObjectDescID = v27;
+          //v27 = 0;
+          a1.uObjectDescID = 0;
           *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
           a1.vPosition.x = fromx;
           a1.uAttributes = 16;
@@ -869,7 +875,8 @@
             a1.uFacing = j + yaw;
             a1.Create((signed __int16)(j + (short)yaw), pitch, pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed, 0);
           }
-          goto LABEL_139;
+          pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+          return;
         }
         v26 = (char *)&pObjectList->pObjects->uObjectID;
         while ( (short)a1.uType != *(short *)v26 )
@@ -894,7 +901,8 @@
               a1.uFacing = j + yaw;
               a1.Create((signed __int16)(j + (short)yaw), pitch, pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed, 0);
             }
-            goto LABEL_139;
+            pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+            return;
           }
         }
         v27 = v25;
@@ -911,14 +919,12 @@
         for ( j = a7d / -2; j <= a7d / 2; j += a8c )
         {
           a1.uFacing = j + yaw;
-          a1.Create(
-            (signed __int16)(j + (short)yaw),
-            pitch,
-            pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed,
-            0);
+          a1.Create((signed __int16)(j + (short)yaw), pitch,
+            pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed, 0);
         }
-        goto LABEL_139;
-      case 43:
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
+      case SPELL_EARTH_DEATH_BLOSSOM:
         if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
           return;
         a1.stru_24.Reset();
@@ -928,8 +934,8 @@
         a1.spell_skill = v15;
         if ( (signed int)pObjectList->uNumObjects <= 0 )
         {
-          v31 = 0;
-          a1.uObjectDescID = v31;
+          //v31 = 0;
+          a1.uObjectDescID = 0;
           *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
           a1.vPosition.x = fromx;
           a1.uAttributes = 16;
@@ -939,12 +945,13 @@
           a1.spell_caster_pid = 8000 | OBJECT_Item;
           a1.spell_target_pid = 4;
           a1.uSoundID = 0;
-          v51 = 0;
+          //v51 = 0;
           v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-          v20 = yaw;
+          //v20 = yaw;
           v47 = (signed int)stru_5C6E00->uIntegerHalfPi / 2;
-          a1.Create(v20, v47, v49, v51);
-          goto LABEL_139;
+          a1.Create(yaw, v47, v49, 0);
+          pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+          return;
         }
         v30 = (char *)&pObjectList->pObjects->uObjectID;
         break;
@@ -953,21 +960,11 @@
         if ( v15 > 0 )
         {
           if ( v15 <= 2 )
-          {
             v9 = 60 * (uSkill + 60);
-          }
-          else
-          {
-            if ( v15 == 3 )
-            {
-              v9 = 180 * (uSkill + 20);
-            }
-            else
-            {
-              if ( v15 == 4 )
-                v9 = 240 * (uSkill + 15);
-            }
-          }
+          else if ( v15 == 3 )
+            v9 = 180 * (uSkill + 20);
+          else if ( v15 == 4 )
+            v9 = 240 * (uSkill + 15);
         }
         //levela = 1;
         //v32 = pParty->pPlayers;//[0].pConditions[1];
@@ -979,19 +976,17 @@
         //if ( !levela )
         //  return;
         pParty->pPartyBuffs[PARTY_BUFF_HASTE].Apply(pParty->uTimePlayed + (signed int)(signed __int64)((double)(v9 * 128) * 0.033333335),
-          v15,
-          0,
-          0,
-          0);
+          v15, 0, 0, 0);
         //v33 = spellnum_;
         pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 0);
         pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 1);
         pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 2);
         pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 3);
-        goto LABEL_138;
-      case 17:
-      case 38:
-      case 51:
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);// 
+        return;
+      case SPELL_AIR_SHIELD:
+      case SPELL_EARTH_STONESKIN:
+      case SPELL_SPIRIT_HEROISM:
         switch ( v15 )
         {
           case 1:
@@ -1026,15 +1021,16 @@
         pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 1);
         pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 2);
         pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 3);
-        v52 = 0;
-        v50 = 0;
-        v48 = v60;
-        v46 = v15;
+        //v52 = 0;
+        //v50 = 0;
+        //v48 = v60;
+        //v46 = v15;
         v36 = pParty->uTimePlayed + (signed int)(signed __int64)((double)(v9 << 7) * 0.033333335);
-        v37 = &pParty->pPartyBuffs[uSkill];
-        v37->Apply(v36, v46, v48, v50, v52);
-        goto LABEL_139;;
-      case 8:
+        //v37 = &pParty->pPartyBuffs[uSkill];
+        pParty->pPartyBuffs[uSkill].Apply(v36, v15, v60, 0, 0);
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
+      case SPELL_FIRE_IMMOLATION:
         if ( v15 == 2 || v15 == 3 || v15 != 4 )
           v38 = 60 * uSkill;
         else
@@ -1051,11 +1047,12 @@
         v37 = &pParty->pPartyBuffs[PARTY_BUFF_IMMOLATION];
         v36 = pParty->uTimePlayed + v39;
         v37->Apply(v36, v46, v48, v50, v52);
-        goto LABEL_139;
-      case 3:
-      case 14:
-      case 25:
-      case 36:
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
+      case SPELL_FIRE_PROTECTION_FROM_FIRE:
+      case SPELL_AIR_PROTECTION_FROM_AIR:
+      case SPELL_WATER_PROTECTION_FROM_WATER:
+      case SPELL_EARTH_PROTECTION_FROM_EARTH:
         goto LABEL_117;
       default:
         return;
@@ -1066,8 +1063,8 @@
       v30 += 56;
       if ( v29 >= (signed int)pObjectList->uNumObjects )
       {
-        v31 = 0;
-        a1.uObjectDescID = v31;
+        //v31 = 0;
+        a1.uObjectDescID = 0;
         *(_QWORD *)&a1.vPosition.y = __PAIR__(fromz, fromy);
         a1.vPosition.x = fromx;
         a1.uAttributes = 16;
@@ -1077,12 +1074,13 @@
         a1.spell_caster_pid = 8000 | OBJECT_Item;
         a1.spell_target_pid = 4;
         a1.uSoundID = 0;
-        v51 = 0;
+        //v51 = 0;
         v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-        v20 = yaw;
+        //v20 = yaw;
         v47 = (signed int)stru_5C6E00->uIntegerHalfPi / 2;
-        a1.Create(v20, v47, v49, v51);
-        goto LABEL_139;
+        a1.Create(yaw, v47, v49, 0);
+        pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+        return;
       }
     }
     v31 = v29;
@@ -1096,12 +1094,13 @@
     a1.spell_caster_pid = 8000 | OBJECT_Item;
     a1.spell_target_pid = 4;
     a1.uSoundID = 0;
-    v51 = 0;
+    //v51 = 0;
     v49 = pObjectList->pObjects[(signed __int16)a1.uObjectDescID].uSpeed;
-    v20 = yaw;
+    //v20 = yaw;
     v47 = (signed int)stru_5C6E00->uIntegerHalfPi / 2;
-    a1.Create(v20, v47, v49, v51);
-    goto LABEL_139;
+    a1.Create(yaw, v47, v49, 0);
+    pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
+    return;
   }
 LABEL_117:
   v44 = uSkill;
@@ -1158,22 +1157,15 @@
   pGame->pStru6Instance->SetPlayerBuffAnim(uSpellID, 3);
   pParty->pPartyBuffs[uSkill].Apply(pParty->uTimePlayed + (signed int)(signed __int64)((double)a6_4 * 4.2666669), v15, v60, 0, 0);
   //levela = 1;
-LABEL_138:
+//LABEL_138:
   //if ( levela )
-LABEL_139:
+//LABEL_139:
     pAudioPlayer->PlaySound((SoundID)word_4EE088_sound_ids[uSpellID], 0, 0, fromx, fromy, 0, 0, 0);
 }
 //----- (00427769) --------------------------------------------------------
-bool __fastcall sub_427769_spell(unsigned int uSpellID)
+bool sub_427769_isSpellQuickCastableOnShiftClick(unsigned int uSpellID)
 {
-  bool result; // eax@2
-
-  __debugbreak(); // wut is dat?
-  if ( pSpellDatas[uSpellID].field_12 & 0xC )
-    result = 1;
-  else
-    result = 0;
-  return result;
+  return ( pSpellDatas[uSpellID].stats & 0xC );
 }
 //----- (0043AFE3) --------------------------------------------------------
 int __fastcall _43AFE3_calc_spell_damage(int a1, int a2, signed int a3, int a4)
--- a/Spells.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Spells.h	Thu Jan 02 09:11:28 2014 +0600
@@ -242,7 +242,7 @@
     };
   };
   __int16 field_10;
-  __int16 field_12;
+  __int16 stats;
  // char field_12;
  // char field_13;
  // __int16 field_14;
--- a/SpriteObject.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/SpriteObject.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -917,10 +917,17 @@
 {
   int new_obj_pos = 0;
 
-  for (int i=0; i < MAX_SPRITE_OBJECTS; ++i)
+  for ( int i = 0; i < MAX_SPRITE_OBJECTS; ++i )
   {
-    if (pSpriteObjects[i].uObjectDescID)
-      memcpy(&pSpriteObjects[new_obj_pos++], &pSpriteObjects[i],sizeof(SpriteObject));
+    if ( pSpriteObjects[i].uObjectDescID )
+    {
+      if ( i != new_obj_pos )// 
+      {
+        memcpy(&pSpriteObjects[new_obj_pos], &pSpriteObjects[i],sizeof(SpriteObject));
+        pSpriteObjects[i].uObjectDescID = 0;
+      }
+      new_obj_pos++;
+    }
   }
   uNumSpriteObjects = new_obj_pos;
 }
--- a/Texture.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Texture.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -431,7 +431,7 @@
 //----- (0040F5F5) --------------------------------------------------------
 int RGBTexture::Reload(const char *pContainer)
 {
-  RGBTexture *v2; // esi@1
+  //RGBTexture *v2; // esi@1
   FILE *v3; // eax@3
   FILE *v4; // edi@3
   void *v5; // ebx@7
@@ -447,8 +447,8 @@
   size_t Count; // [sp+9Ch] [bp-4h]@6
   void *uSourceLena; // [sp+A8h] [bp+8h]@7
 
-  v2 = this;
-  if ( !v2->pPixels )
+ // v2 = this;
+  if ( !this->pPixels )
     return 2;
   v3 = pIcons_LOD->FindContainer(pContainer, 0);
   v4 = v3;
@@ -456,13 +456,13 @@
   if ( !v3 )
     Error("Unable to load %s", pContainer);
 
-  fread(&DstBuf, 1u, 0x30u, v3);
+  fread(&DstBuf, 1, 0x30, v3);
   Count = DstBuf.uTextureSize;
   if ( DstBuf.uDecompressedSize )
   {
     v5 = malloc(DstBuf.uDecompressedSize);
     uSourceLena = malloc(DstBuf.uTextureSize);
-    fread(uSourceLena, 1u, Count, File);
+    fread(uSourceLena, 1, Count, File);
     zlib::MemUnzip(v5, &DstBuf.uDecompressedSize, uSourceLena, DstBuf.uTextureSize);
     DstBuf.uTextureSize = DstBuf.uDecompressedSize;
     free(uSourceLena);
@@ -470,22 +470,22 @@
   else
   {
     v5 = malloc(DstBuf.uTextureSize);
-    fread(v5, 1u, Count, v4);
+    fread(v5, 1, Count, v4);
   }
   memcpy(&header1, v5, 0x10u);
-  memcpy(color_map, (char *)v5 + 16, 0x30u);
-  memcpy(&header2, (char *)v5 + 64, 6u);
+  memcpy(color_map, (char *)v5 + 16, 0x30);
+  memcpy(&header2, (char *)v5 + 64, 6);
   if ( header1.bpp != 8 )
     return 3;
   v7 = (signed __int16)(header1.right - header1.left + 1);
-  if ( (signed int)(v7 * (signed __int16)(header1.bottom - header1.up + 1)) <= (signed int)v2->uNumPixels )
+  if ( (signed int)(v7 * (signed __int16)(header1.bottom - header1.up + 1)) <= (signed int)this->uNumPixels )
   {
-    v2->uWidth = header1.right - header1.left + 1;
-    v8 = v2->pPixels;
-    v9 = v7 * v2->uHeight;
-    v2->uNumPixels = v9;
-    v2->uHeight = v9;
-    v2->DecodePCX((char *)v5, v8, v7);
+    this->uWidth = header1.right - header1.left + 1;
+    v8 = this->pPixels;
+    v9 = v7 * this->uHeight;
+    this->uNumPixels = v9;
+    this->uHeight = v9;
+    this->DecodePCX((char *)v5, v8, v7);
     free(v5);
     result = 0;
   }
@@ -684,7 +684,14 @@
   case 12:  field_1E = 4095; break;
 	  }
 
- 
+  unsigned int r_mask = 0xF800;
+  unsigned int num_r_bits = 5;
+  unsigned int g_mask = 0x07E0;
+  unsigned int num_g_bits = 6;
+  unsigned int b_mask = 0x001F;
+  unsigned int num_b_bits = 5;
+  //               
+  //      .
  read_offset = 128;
  if (psx_head2.planes != 3)
  	  return 0;
@@ -703,28 +710,23 @@
      {
       test_byte = pPcx[read_offset];
       ++read_offset;
-      if ((test_byte & 0xC0) == 0xC0)
+      if ((test_byte & 0xC0) == 0xC0)//  
       {	
 	    value = pPcx[read_offset];
        	++read_offset; 
       
        if ((test_byte & 0x3F) > 0)
        {
-        count = test_byte & 0x3F;
+        count = test_byte & 0x3F;//  
         do
         {
-
          ++row_position;
           //*temp_dec_position =0xFF000000;
-		  //*temp_dec_position|=(unsigned long)value<<16;
-         *temp_dec_position |= LOWORD(pRenderer->uTargetRMask) & ((unsigned __int8)value << (LOBYTE(pRenderer->uTargetGBits)
-                                                                                    + LOBYTE(pRenderer->uTargetRBits)
-                                                                                    + LOBYTE(pRenderer->uTargetBBits)
-                                                                                    - 8));
-
-		   temp_dec_position++;
-       if (row_position == psx_head2.pitch)
-			 break;
+          //*temp_dec_position|=(unsigned long)value<<16;
+         *temp_dec_position |= r_mask & ((unsigned __int8)value << (num_g_bits + num_r_bits + num_b_bits - 8));
+         temp_dec_position++;
+         if (row_position == psx_head2.pitch)
+           break;
         }
         while (count-- != 1);
        }
@@ -735,10 +737,7 @@
 	   //*temp_dec_position =0xFF000000; 
 	  //*temp_dec_position|= (unsigned long)test_byte<<16;
        
-       *temp_dec_position |= LOWORD(pRenderer->uTargetRMask) & ((unsigned __int8)test_byte << (LOBYTE(pRenderer->uTargetGBits)
-                                                                                    + LOBYTE(pRenderer->uTargetRBits)
-                                                                                    + LOBYTE(pRenderer->uTargetBBits)
-                                                                                    - 8));
+       *temp_dec_position |= r_mask & ((unsigned __int8)test_byte << (num_g_bits + num_r_bits + num_b_bits - 8));
 
        temp_dec_position++;
       }
@@ -766,9 +765,7 @@
         //*temp_dec_position|= (unsigned int)value<<8;
 		//temp_dec_position++;
          
-         *temp_dec_position|= pRenderer->uTargetGMask & (unsigned __int16)((unsigned __int8)value << (LOBYTE(pRenderer->uTargetGBits)
-                                                                                             + LOBYTE(pRenderer->uTargetBBits)
-                                                                                             - 8));
+         *temp_dec_position|= g_mask & (unsigned __int16)((unsigned __int8)value << (num_g_bits + num_b_bits - 8));
          
        temp_dec_position++;
         ++row_position;
@@ -784,9 +781,7 @@
       //*temp_dec_position |=(unsigned int) test_byte<<8;
 	  //temp_dec_position++;
        
-         *temp_dec_position|= pRenderer->uTargetGMask & (unsigned __int16)((unsigned __int8)test_byte << (LOBYTE(pRenderer->uTargetGBits)
-                                                                                             + LOBYTE(pRenderer->uTargetBBits)
-                                                                                             - 8));
+         *temp_dec_position|= g_mask & (unsigned __int16)((unsigned __int8)test_byte << (num_g_bits + num_b_bits - 8));
        temp_dec_position++;
       ++row_position;
      }
@@ -811,7 +806,7 @@
         //*temp_dec_position|= value;
 		 //temp_dec_position++;
 
-         *temp_dec_position |= value >> (8 - LOBYTE(pRenderer->uTargetBBits));
+         *temp_dec_position |= value >> (8 - num_b_bits);
        temp_dec_position++;
 
         ++row_position;
@@ -825,7 +820,7 @@
      {
       //*temp_dec_position|= test_byte;
 	   //temp_dec_position++;
-         *temp_dec_position |= test_byte >> (8 - LOBYTE(pRenderer->uTargetBBits));
+         *temp_dec_position |= test_byte >> (8 - num_b_bits);
        temp_dec_position++;
 
       ++row_position;
@@ -1133,6 +1128,14 @@
 	short int width, height;
 	BYTE  color_map[48];	// Colormap for 16-color images
 
+  unsigned int num_r_bits = 5;
+  unsigned int num_g_bits = 6;
+  unsigned int num_b_bits = 5;
+
+  unsigned int r_mask = 0xF800;
+  unsigned int g_mask = 0x07E0;
+  unsigned int b_mask = 0x001F;
+
   if (!pFile)
     return 1;
   
@@ -1168,9 +1171,6 @@
         }
       }
 
-
-
-
       ushort* pOutPixels = pPixels;
  
  memset(pOutPixels, 0, uNumPixels * sizeof(__int16));
@@ -1221,7 +1221,6 @@
   case 12:  field_1E = 4095; break;
 	  }
 
-
   fseek(pFile, 128 - 70, SEEK_CUR);
 
 
@@ -1240,22 +1239,14 @@
         uint clr = 0;
         fread(&clr, 1, 1, pFile);
         for (uint i = 0; i < uNumPixels; ++i)
-          pDst[x++] = pRenderer->uTargetRMask & (clr << (pRenderer->uTargetGBits +
-                                                         pRenderer->uTargetRBits +
-                                                         pRenderer->uTargetBBits - 8));
+          pDst[x++] = r_mask & (clr << (num_g_bits + num_r_bits + num_b_bits - 8));
       }
       else
       {
-        pDst[x++] = pRenderer->uTargetRMask & (ctrl << (pRenderer->uTargetGBits +
-                                                        pRenderer->uTargetRBits +
-                                                        pRenderer->uTargetBBits - 8));
+        pDst[x++] = r_mask & (ctrl << (num_g_bits + num_r_bits + num_b_bits - 8));
       }
     } while (x < psx_head2.pitch);
 
-
-
-
-
     x = 0;
     do
     {
@@ -1267,19 +1258,13 @@
         uint clr = 0;
         fread(&clr, 1, 1, pFile);
         for (uint i = 0; i < uNumPixels; ++i)
-          pDst[x++] |= pRenderer->uTargetGMask & (clr << (pRenderer->uTargetGBits +
-                                                         pRenderer->uTargetBBits - 8));
+          pDst[x++] |= g_mask & (clr << (num_g_bits + num_b_bits - 8));
       }
       else
       {
-        pDst[x++] |= pRenderer->uTargetGMask & (ctrl << (pRenderer->uTargetGBits +
-                                                        pRenderer->uTargetBBits - 8));
+        pDst[x++] |= g_mask & (ctrl << (num_g_bits + num_b_bits - 8));
       }
     } while (x < psx_head2.pitch);
- 
-
-
-
 
     x = 0;
     do
@@ -1292,11 +1277,11 @@
         uint clr = 0;
         fread(&clr, 1, 1, pFile);
         for (uint i = 0; i < uNumPixels; ++i)
-          pDst[x++] |= pRenderer->uTargetBMask & (clr >> (8 - pRenderer->uTargetBBits));
+          pDst[x++] |= b_mask & (clr >> (8 - num_b_bits));
       }
       else
       {
-        pDst[x++] |= pRenderer->uTargetBMask & (ctrl >> (8 - pRenderer->uTargetRBits));
+        pDst[x++] |= b_mask & (ctrl >> (8 - num_b_bits));
       }
     } while (x < psx_head2.pitch);
   }
@@ -1309,46 +1294,33 @@
 //----- (0040E51F) --------------------------------------------------------
 void RGBTexture::Release()
 {
-  RGBTexture *v1; // esi@1
-  char v2; // zf@1
-  void *v3; // [sp-4h] [bp-Ch]@1
-
-  v1 = this;
-  v2 = (this->_allocation_flags & 1) == 0;
-  v3 = this->pPixels;
   this->pName[0] = 0;
-  if ( v2 )
-    free(v3);
-  else
-    free(v3);
-  v1->_allocation_flags = 0;
-  v1->pPixels = 0;
-  v1->uNumPixels = 0;
-  v1->uHeight = 0;
-  v1->uWidth = 0;
-  v1->field_1A = 0;
-  v1->field_18 = 0;
+  //if ( !(this->_allocation_flags & 1) )
+    //free(this->pPixels);
+  //else
+    free(this->pPixels);
+  this->_allocation_flags = 0;
+  this->pPixels = 0;
+  this->uNumPixels = 0;
+  this->uHeight = 0;
+  this->uWidth = 0;
+  this->field_1A = 0;
+  this->field_18 = 0;
 }
 
 //----- (0040E55E) --------------------------------------------------------
-int RGBTexture::_40E55E(const char *Filename, unsigned int a3)
+int RGBTexture::LoadPCXFile(const char *Filename, unsigned int a3)
 {
-  RGBTexture *v3; // esi@1
   signed int result; // eax@2
   char *v6; // eax@3
   int v7; // edx@3
   char v8; // cl@4
-  unsigned __int16 v9; // cx@9
-  unsigned __int16 v10; // ax@9
-  int v11; // eax@9
-  char v12; // zf@9
-  void *v13; // eax@12
   signed int v14; // ecx@19
   signed int v15; // ecx@24
   int v16; // eax@57
   unsigned __int16 *v17; // ecx@57
   unsigned __int16 *v18; // edi@57
-  signed int v19; // eax@59
+  signed int x; // eax@59
   unsigned __int16 *v20; // edi@64
   signed int v21; // eax@66
   unsigned __int16 *v22; // edi@71
@@ -1357,11 +1329,18 @@
   char v25[48]; // [sp+Ch] [bp-54h]@3
   PCXHeader1 pcx_header1;
   PCXHeader2 pcx_header2;
-  int v37; // [sp+54h] [bp-Ch]@3
-  int v38; // [sp+58h] [bp-8h]@57
+  int y; // [sp+54h] [bp-Ch]@3
   FILE *File; // [sp+5Ch] [bp-4h]@1
 
-  v3 = this;
+  unsigned int num_r_bits = 5;
+  unsigned int num_g_bits = 6;
+  unsigned int num_b_bits = 5;
+
+  unsigned int r_mask = 0xF800;
+  unsigned int g_mask = 0x07E0;
+  unsigned int b_mask = 0x001F;
+
+
   File = fopen(Filename, "rb");
   if ( !File )
     return 1;
@@ -1371,257 +1350,141 @@
   fread(&pcx_header2, 4, 1, File);
 
   v6 = (char *)Filename;
-  v37 = 0;
-  v7 = (char *)v3 - Filename;
-  do
+  v7 = (char *)this - Filename;
+  uint i = 0;
+  for ( i; i < 15; ++i )
   {
     v8 = *v6;
     if ( !*v6 )
       break;
     if ( v8 == 46 )
       break;
-    ++v37;
     (v6++)[v7] = v8;
   }
-  while ( v37 < 15 );
-  v3->pName[v37] = 0;
+  this->pName[i] = 0;
   if ( pcx_header1.bpp != 8 )
     return 3;
-  v9 = pcx_header1.right - pcx_header1.left + 1;
-  v10 = pcx_header1.bottom - pcx_header1.up;
-  v3->uWidth = v9;
-  ++v10;
-  v3->uHeight = v10;
-  v11 = (signed __int16)v9 * (signed __int16)v10;
-  v12 = a3 == 0;
-  v3->uNumPixels = v11;
-  if ( v12 )
+  this->uWidth = pcx_header1.right - pcx_header1.left + 1;
+  this->uHeight = pcx_header1.bottom - pcx_header1.up + 1;
+  this->uNumPixels = (signed __int16)this->uWidth * (signed __int16)this->uHeight;
+  if ( !a3 )
   {
-    if ( v3->pPixels )
-      free(v3->pPixels);
-    v13 = malloc(2 * v3->uNumPixels + 4);
-    goto LABEL_16;
+    if ( this->pPixels )
+      free(this->pPixels);
+    this->pPixels = (unsigned __int16 *)malloc(2 * this->uNumPixels + 4);
   }
-  if ( a3 != 1 && a3 == 2 )
+  if ( a3 == 2 )
   {
-    v13 = malloc(4 * v11 + 8);
-    v3->_allocation_flags |= 1u;
-LABEL_16:
-    v3->pPixels = (unsigned __int16 *)v13;
+    this->_allocation_flags |= 1;
+    this->pPixels = (unsigned __int16 *)malloc((uNumPixels + 2) * sizeof(unsigned __int16));
   }
-  if ( v3->pPixels )
+  if ( this->pPixels )
   {
-    v14 = 1;
-    while ( 1 << v14 != v3->uWidth )
+    for ( v14 = 1; v14 < 15; ++v14 )
     {
-      ++v14;
-      if ( v14 >= 15 )
-        goto LABEL_24;
+      if ( 1 << v14 == this->uWidth )
+        this->field_18 = v14;
     }
-    v3->field_18 = v14;
-LABEL_24:
-    v15 = 1;
-    while ( 1 << v15 != v3->uHeight )
+    for ( v15 = 1; v15 < 15; ++v15 )
     {
-      ++v15;
-      if ( v15 >= 15 )
-        goto LABEL_29;
+      if ( 1 << v15 == this->uHeight  )
+        this->field_1A = v15;
     }
-    v3->field_1A = v15;
-LABEL_29:
-    switch ( v3->field_18 )
+    switch ( this->field_18 )
     {
-      case 2:
-        v3->field_1C = 3;
-        break;
-      case 3:
-        v3->field_1C = 7;
-        break;
-      case 4:
-        v3->field_1C = 15;
-        break;
-      case 5:
-        v3->field_1C = 31;
-        break;
-      case 6:
-        v3->field_1C = 63;
-        break;
-      case 7:
-        v3->field_1C = 127;
-        break;
-      case 8:
-        v3->field_1C = 255;
-        break;
-      case 9:
-        v3->field_1C = 511;
-        break;
-      case 10:
-        v3->field_1C = 1023;
-        break;
-      case 11:
-        v3->field_1C = 2047;
-        break;
-      case 12:
-        v3->field_1C = 4095;
-        break;
-      default:
-        break;
+      case 2: this->field_1C = 3; break;
+      case 3: this->field_1C = 7; break;
+      case 4: this->field_1C = 15; break;
+      case 5: this->field_1C = 31; break;
+      case 6: this->field_1C = 63; break;
+      case 7: this->field_1C = 127; break;
+      case 8: this->field_1C = 255; break;
+      case 9: this->field_1C = 511; break;
+      case 10: this->field_1C = 1023; break;
+      case 11: this->field_1C = 2047; break;
+      case 12: this->field_1C = 4095; break;
+      default: break;
     }
-    switch ( v3->field_1A )
+    switch ( this->field_1A )
     {
-      case 2:
-        v3->field_1E = 3;
-        break;
-      case 3:
-        v3->field_1E = 7;
-        break;
-      case 4:
-        v3->field_1E = 15;
-        break;
-      case 5:
-        v3->field_1E = 31;
-        break;
-      case 6:
-        v3->field_1E = 63;
-        break;
-      case 7:
-        v3->field_1E = 127;
-        break;
-      case 8:
-        v3->field_1E = 255;
-        break;
-      case 9:
-        v3->field_1E = 511;
-        break;
-      case 10:
-        v3->field_1E = 1023;
-        break;
-      case 11:
-        v3->field_1E = 2047;
-        break;
-      case 12:
-        v3->field_1E = 4095;
-        break;
-      default:
-        break;
+      case 2: this->field_1E = 3; break;
+      case 3: this->field_1E = 7; break;
+      case 4: this->field_1E = 15; break;
+      case 5: this->field_1E = 31; break;
+      case 6: this->field_1E = 63; break;
+      case 7: this->field_1E = 127; break;
+      case 8: this->field_1E = 255; break;
+      case 9: this->field_1E = 511; break;
+      case 10: this->field_1E = 1023; break;
+      case 11: this->field_1E = 2047; break;
+      case 12: this->field_1E = 4095; break;
+      default: break;
     }
     fseek(File, 128, 0);
     ftell(File);
-	if ( pcx_header2.planes == 1 )
+    if ( pcx_header2.planes == 1 )
       Error("24bit PCX Only!");
 
     if ( pcx_header2.planes == 3 )
     {
-      v37 = 0;
-      if ( v3->uHeight > 0 )
+      for ( y = 0; y < this->uHeight; ++y )
       {
+        unsigned __int16 *pDst = pPixels + y * uWidth;
+        uint x = 0;
+        do
+        {
+          uint ctrl = 0;
+          fread(&ctrl, 1, 1, File);
+          if ( (ctrl & 0xC0) == 0xC0 )
+          {
+            uint uNumPixels = ctrl & 0x3F;
+            uint clr = 0;
+            ctrl &= 0x3F;
+            fread(&clr, 1, 1, File);
+            for ( uint i = 0; i < uNumPixels; ++i )
+              pDst[x++] = r_mask & (clr << (num_r_bits + num_g_bits + num_b_bits - 8));
+          }
+          else
+            pDst[x++] = r_mask & (ctrl << (num_g_bits + num_r_bits + num_b_bits - 8));
+        }
+        while ( x < pcx_header2.pitch );
+
+        x = 0;
         do
         {
-          v16 = v37 * v3->uWidth;
-          v17 = v3->pPixels;
-          v38 = 0;
-          v18 = &v17[v16];
-		  if ( pcx_header2.pitch )
-          {
-            do
-            {
-              fread((char *)&Filename + 3, 1u, 1u, File);
-              if ( (BYTE3(Filename) & 0xC0) == -64 )
-              {
-                BYTE3(Filename) &= 0x3Fu;
-                fread((char *)&a3 + 3, 1u, 1u, File);
-                v19 = 0;
-                if ( BYTE3(Filename) )
-                {
-                  do
-                  {
-                    ++v38;
-                    *v18 = LOWORD(pRenderer->uTargetRMask) & (BYTE3(a3) << (LOBYTE(pRenderer->uTargetGBits)
-                                                                         + LOBYTE(pRenderer->uTargetRBits)
-                                                                         + LOBYTE(pRenderer->uTargetBBits)
-                                                                         - 8));
-                    ++v18;
-                    ++v19;
-                  }
-                  while ( v19 < BYTE3(Filename) );
-                }
-              }
-              else
-              {
-                ++v38;
-                *v18 = LOWORD(pRenderer->uTargetRMask) & (BYTE3(Filename) << (LOBYTE(pRenderer->uTargetGBits)
-                                                                           + LOBYTE(pRenderer->uTargetRBits)
-                                                                           + LOBYTE(pRenderer->uTargetBBits)
-                                                                           - 8));
-                ++v18;
-              }
-            }
-			while ( v38 < (unsigned __int16)pcx_header2.pitch);
-          }
-          v20 = &v3->pPixels[v37 * v3->uWidth];
-		  while ( v38 < 2 * (unsigned __int16)pcx_header2.pitch )
+          uint ctrl = 0;
+          fread(&ctrl, 1, 1, File);
+          if ( (ctrl & 0xC0) == 0xC0 )
           {
-            fread((char *)&Filename + 3, 1u, 1u, File);
-            if ( (BYTE3(Filename) & 0xC0) == -64 )
-            {
-              BYTE3(Filename) &= 0x3Fu;
-              fread((char *)&a3 + 3, 1u, 1u, File);
-              v21 = 0;
-              if ( BYTE3(Filename) )
-              {
-                do
-                {
-                  *v20 |= pRenderer->uTargetGMask & (unsigned __int16)(BYTE3(a3) << (LOBYTE(pRenderer->uTargetGBits)
-                                                                                  + LOBYTE(pRenderer->uTargetBBits)
-                                                                                  - 8));
-                  ++v38;
-                  ++v20;
-                  ++v21;
-                }
-                while ( v21 < BYTE3(Filename) );
-              }
-            }
-            else
-            {
-              *v20 |= pRenderer->uTargetGMask & (unsigned __int16)(BYTE3(Filename) << (LOBYTE(pRenderer->uTargetGBits)
-                                                                                    + LOBYTE(pRenderer->uTargetBBits)
-                                                                                    - 8));
-              ++v38;
-              ++v20;
-            }
+            uint uNumPixels = ctrl & 0x3F;
+            uint clr = 0;
+            ctrl &= 0x3F;
+            fread(&clr, 1, 1, File);
+            for ( uint i = 0; i < uNumPixels; ++i )
+              pDst[x++] |= g_mask & (clr << (num_g_bits + num_b_bits - 8));
           }
-          v22 = &v3->pPixels[v37 * v3->uWidth];
-		  while ( v38 < 3 * (unsigned __int16)pcx_header2.pitch )
+          else
+            pDst[x++] |= g_mask & (ctrl << (num_g_bits + num_b_bits - 8));
+        }
+        while (x < pcx_header2.pitch);
+
+        x = 0;
+        do
+        {
+          uint ctrl = 0;
+          fread(&ctrl, 1, 1, File);
+          if ( (ctrl & 0xC0) == 0xC0 )
           {
-            fread((char *)&Filename + 3, 1u, 1u, File);
-            if ( (BYTE3(Filename) & 0xC0) == -64 )
-            {
-              BYTE3(Filename) &= 0x3Fu;
-              fread((char *)&a3 + 3, 1u, 1u, File);
-              v23 = 0;
-              if ( BYTE3(Filename) )
-              {
-                do
-                {
-                  *v22 |= BYTE3(a3) >> (8 - LOBYTE(pRenderer->uTargetBBits));
-                  ++v38;
-                  ++v22;
-                  ++v23;
-                }
-                while ( v23 < BYTE3(Filename) );
-              }
-            }
-            else
-            {
-              *v22 |= BYTE3(Filename) >> (8 - LOBYTE(pRenderer->uTargetBBits));
-              ++v38;
-              ++v22;
-            }
+            uint uNumPixels = ctrl & 0x3F;
+            uint clr = 0;
+            fread(&clr, 1, 1, File);
+            for ( uint i = 0; i < uNumPixels; ++i )
+              pDst[x++] |= b_mask & (clr >> (8 - num_b_bits));
           }
-          v24 = v3->uHeight;
-          ++v37;
+          else
+            pDst[x++] |= b_mask & (ctrl >> (8 - num_b_bits));
         }
-        while ( v37 < v24 );
+        while (x < pcx_header2.pitch);
       }
     }
     fclose(File);
@@ -1634,7 +1497,6 @@
   return result;
 }
 
-
 //----- (0040D73D) --------------------------------------------------------
 RGBTexture::RGBTexture()
 {
--- a/Texture.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Texture.h	Thu Jan 02 09:11:28 2014 +0600
@@ -10,7 +10,7 @@
 {
   RGBTexture();
   void Release();
-  int _40E55E(const char *Filename, unsigned int a3);
+  int LoadPCXFile(const char *Filename, unsigned int a3);
   unsigned int LoadFromFILE(FILE *pFile, unsigned int mode, unsigned int bCloseFile);
   int DecodePCX(char *pPcx, unsigned __int16 *pOutPixels, unsigned int uNumPixels);
   int Load(const char *pContainer, int mode);
--- a/TurnEngine.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/TurnEngine.h	Thu Jan 02 09:11:28 2014 +0600
@@ -75,7 +75,7 @@
 
 
   int turns_count;
-  int turn_stage;
+  int turn_stage; //if = 2 - action
   int ai_turn_timer;
   int uActorQueueSize; //c
   int turn_initiative;
--- a/UI/Books/UIMapBook.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/Books/UIMapBook.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -311,12 +311,12 @@
   unsigned __int16 v69; // cx@99
   signed int v73; // [sp-4h] [bp-48068h]@59
   unsigned __int16 v74; // [sp-4h] [bp-48068h]@79
-  unsigned short map_texture_16[147456]; // [sp+Ch] [bp-48058h]@23
+  //unsigned short map_texture_16[320 * 460 + 256]; // [sp+Ch] [bp-48058h]@23
   int v76; // [sp+4800Ch] [bp-58h]@23
-  unsigned __int16 *v77; // [sp+48010h] [bp-54h]@27
+  //unsigned __int16 *v77; // [sp+48010h] [bp-54h]@27
   unsigned __int16 *pPalette_16; // [sp+48014h] [bp-50h]@23
   int map_tile_X; // [sp+48020h] [bp-44h]@23
-  unsigned __int16* render16_data;
+  //unsigned __int16* render16_data;
   unsigned char* texture8_data;
   unsigned char* curr_line;
   int scale_increment;
@@ -339,7 +339,7 @@
   int map_tile_Y; // [sp+4805Ch] [bp-8h]@10
   const void *v97; // [sp+48060h] [bp-4h]@16
   unsigned short *a4a; // [sp+4806Ch] [bp+8h]@85
-  int a5a; // [sp+48070h] [bp+Ch]@86
+  //int a5a; // [sp+48070h] [bp+Ch]@86
 
   screenCenter_X = (signed int)(tl_x + br_x) / 2;
   screenCenterY = (signed int)(tl_y + br_y) / 2;
@@ -366,7 +366,7 @@
   {
     screenWidth = br_x - tl_x + 1;
     screenHeight = br_y - tl_y + 1;
-    render16_data = &pRenderer->pTargetSurface[tl_x + tl_y * pRenderer->uTargetSurfacePitch];
+    //render16_data = &pRenderer->pTargetSurface[tl_x + tl_y * pRenderer->uTargetSurfacePitch];
     texture8_data = pIcons_LOD->pTextures[viewparams->uTextureID_LocationMap].pLevelOfDetail0_prolly_alpha_mask;
     pPalette_16 = pIcons_LOD->pTextures[viewparams->uTextureID_LocationMap].pPalette16;
     scale_increment = (1 << (pIcons_LOD->pTextures[viewparams->uTextureID_LocationMap].uWidthLn2 + 16)) / viewparams->uMapBookMapZoom;
@@ -390,36 +390,38 @@
         for( uint j = 0; j < screenWidth; ++j )
         {
           scaled_posX=stepX_r>>16;
-          map_texture_16[i*screenWidth+j]=pPalette_16[*(curr_line+scaled_posX)];
+          //map_texture_16[i*screenWidth+j]=pPalette_16[*(curr_line+scaled_posX)];
+          pRenderer->WritePixel16(tl_x + j, tl_y + i, pPalette_16[*(curr_line+scaled_posX)]);
           stepX_r+=scale_increment;      
         }
         stepY_r+=scale_increment;
         scaled_posY=stepY_r>>16;
       }
     }
-    //move visible square to render
+
+    /*//move visible square to render
     for( uint i = 0; i < screenHeight; ++i )
     {
       if ( screenWidth > 0 )
         memcpy((void*)&render16_data[pRenderer->uTargetSurfacePitch * i],(void*)&map_texture_16[i*screenWidth], screenWidth*2);
-    }
+    }*/
   }
   else
   {
-    black = TargetColor(0, 0, 0);
-    teal = TargetColor(0, 0xFFu, 0xFFu);
+    black = Color16(0, 0, 0);
+    teal = Color16(0, 0xFFu, 0xFFu);
     uNumBlueFacesInBLVMinimap = 0;
     if ( pIndoor->pMapOutlines->uNumOutlines )
     {
      for ( uint i = 0; i < pIndoor->pMapOutlines->uNumOutlines; ++i )
       {
-        if ( !(BYTE1(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace1ID].uAttributes) & 0x20 
-           || (BYTE1(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace2ID].uAttributes) & 0x20) ))
+        if ( !(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace1ID].Invisible() 
+           || (pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace2ID].Invisible()) ))
         {
           if ( !(pIndoor->pMapOutlines->pOutlines[i].uFlags & 1) )
           {
             if ( !(!(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace1ID].uAttributes & 0x80)
-                && !(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace2ID].uAttributes & 0x80u) ))
+                && !(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace2ID].uAttributes & 0x80) ))
             {
               pIndoor->pMapOutlines->pOutlines[i].uFlags = pIndoor->pMapOutlines->pOutlines[i].uFlags | 1;
               pIndoor->_visible_outlines[i >> 3] |= 1 << (7 - i % 8);
@@ -427,7 +429,7 @@
           }
           if ( (!(pIndoor->pMapOutlines->pOutlines[i].uFlags & 1) 
             && !(!(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace1ID].uAttributes & 0x80)
-            && !(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace2ID].uAttributes & 0x80u) ))
+            && !(pIndoor->pFaces[pIndoor->pMapOutlines->pOutlines[i].uFace2ID].uAttributes & 0x80) ))
             || pIndoor->pMapOutlines->pOutlines[i].uFlags & 1)
           {
             v93 = (unsigned __int16 *)(pIndoor->pVertices[pIndoor->pMapOutlines->pOutlines[i].uVertex1ID].x - viewparams->sViewCenterX);
@@ -535,14 +537,14 @@
         {
           if ( viewparams->uMapBookMapZoom > 512 )
           {
-            pRenderer->RasterLine2D(v54 - 1, v55 - 1, v54 - 1, v55 + 1, TargetColor(0xFFu, 0xFFu, 0xFFu));
-            pRenderer->RasterLine2D(v54,     v55 - 1, v54,     v55 + 1, TargetColor(0xFFu, 0xFFu, 0xFFu));
-            pRenderer->RasterLine2D(v54 + 1, v55 - 1, v54 + 1, v55 + 1, TargetColor(0xFFu, 0xFFu, 0xFFu));
+            pRenderer->RasterLine2D(v54 - 1, v55 - 1, v54 - 1, v55 + 1, Color16(0xFFu, 0xFFu, 0xFFu));
+            pRenderer->RasterLine2D(v54,     v55 - 1, v54,     v55 + 1, Color16(0xFFu, 0xFFu, 0xFFu));
+            pRenderer->RasterLine2D(v54 + 1, v55 - 1, v54 + 1, v55 + 1, Color16(0xFFu, 0xFFu, 0xFFu));
           }
           else
             pRenderer->RasterLine2D(v54, screenCenterY - (int)v97,
                    ((unsigned __int64)((signed int)v93 * (signed __int64)viewparams->uMapBookMapZoom) >> 16) + screenCenter_X,
-                   screenCenterY - (int)v97, TargetColor(0xFFu, 0xFFu, 0xFFu));
+                   screenCenterY - (int)v97, Color16(0xFFu, 0xFFu, 0xFFu));
         }
       }
     }
@@ -551,7 +553,7 @@
   {
     screenCenterY = br_x - tl_x + 1;
     v95 = br_y - tl_y + 1;
-    v77 = &pRenderer->pTargetSurface[tl_x + tl_y * pRenderer->uTargetSurfacePitch];
+    //v77 = &pRenderer->pTargetSurface[tl_x + tl_y * pRenderer->uTargetSurfacePitch];
     black = (1 << (pIcons_LOD->pTextures[viewparams->uTextureID_LocationMap].uWidthLn2 + 16)) / viewparams->uMapBookMapZoom;
     v57 = (double)(1 << (16 - pIcons_LOD->pTextures[viewparams->uTextureID_LocationMap].uWidthLn2));
     v60 = (int)((signed __int64)((double)(viewparams->sViewCenterX - (22528 / (viewparams->uMapBookMapZoom / 384)) + 32768) / v57)) << 16;
@@ -560,7 +562,37 @@
     v97 = (const void *)((int)((signed __int64)((double)(viewparams->sViewCenterX - (22528 / (viewparams->uMapBookMapZoom / 384)) + 32768) / v57)) << 16);
     v62 = (int)((signed __int64)((double)(32768 - (22528 / (viewparams->uMapBookMapZoom / 384)) - pCenterY) / v57)) << 16;
     v63 = (signed __int16)((signed __int64)((double)(32768 - (22528 / (viewparams->uMapBookMapZoom / 384)) - pCenterY) / v57));
-    a4a = map_texture_16;
+
+
+    for (int y = 0; y < (signed int)v95; ++y)
+    {
+        map_tile_Y = (v63 - 80) / 4;
+        v64 = teal;
+        for (int x = 0; x < screenCenterY; ++x)
+        {
+          map_tile_X = (v64 - 80) / 4;
+          if ( !pOutdoor->_47F04C(map_tile_X, map_tile_Y) )
+          {
+            if ( pOutdoor->_47F097(map_tile_X, map_tile_Y) )
+            {
+              if ( !((x + screenCenter_X) % 2) )
+                //*a4a = Color16(12, 12, 12);
+                  pRenderer->WritePixel16(tl_x + x, tl_y + y, Color16(12, 12, 12));
+            }
+            else
+              //*a4a = 0;
+                  pRenderer->WritePixel16(tl_x + x, tl_y + y, Color16(0, 0, 0));
+          }
+          v97 = (char *)v97 + black;
+          v64 = (signed int)v97 >> 16;
+        }
+
+      v62 += black;
+      v97 = (const void *)v60;
+      v63 = v62 >> 16;
+      teal = (unsigned int)pPalette_16;
+    }
+    /*a4a = map_texture_16;
     for ( screenCenter_X = 0; screenCenter_X < (signed int)v95; ++screenCenter_X )
     {
       if ( screenCenterY > 0 )
@@ -575,7 +607,7 @@
             if ( pOutdoor->_47F097(map_tile_X, map_tile_Y) )
             {
               if ( !((a5a + screenCenter_X) % 2) )
-                *a4a = TargetColor(0xCu, 0xCu, 0xCu);
+                *a4a = Color16(0xCu, 0xCu, 0xCu);
             }
             else
               *a4a = 0;
@@ -591,6 +623,7 @@
       v63 = v62 >> 16;
       teal = (unsigned int)pPalette_16;
     }
+
     v66 = map_texture_16;
     if ( (signed int)v95 > 0 )
     {
@@ -611,7 +644,7 @@
         }
         v67 = (unsigned __int16 *)((char *)v67 + result);
       }
-    }
+    }*/
   }
 }
 
--- a/UI/UICharacter.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UICharacter.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -89,101 +89,101 @@
 
 void set_default_ui_skin()
 {
-  ui_mainmenu_copyright_color = TargetColor(255, 255, 255);
+  ui_mainmenu_copyright_color = Color16(255, 255, 255);
 
-  ui_character_tooltip_header_default_color = TargetColor(255, 255, 155);
-  ui_character_default_text_color = TargetColor(255, 255, 255);
-  ui_character_header_text_color = TargetColor(255, 255, 155);
-  ui_character_bonus_text_color = TargetColor(0, 255, 0);
-  ui_character_bonus_text_color_neg = TargetColor(255, 0, 0);
+  ui_character_tooltip_header_default_color = Color16(255, 255, 155);
+  ui_character_default_text_color = Color16(255, 255, 255);
+  ui_character_header_text_color = Color16(255, 255, 155);
+  ui_character_bonus_text_color = Color16(0, 255, 0);
+  ui_character_bonus_text_color_neg = Color16(255, 0, 0);
 
-  ui_character_skill_upgradeable_color = TargetColor(0, 175, 255);
-  ui_character_skill_default_color = TargetColor(255, 0, 0);
-  ui_character_skill_highlight_color = TargetColor(255, 0, 0);  
+  ui_character_skill_upgradeable_color = Color16(0, 175, 255);
+  ui_character_skill_default_color = Color16(255, 0, 0);
+  ui_character_skill_highlight_color = Color16(255, 0, 0);  
   
-  ui_character_stat_default_color = TargetColor(255, 255, 255);
-  ui_character_stat_buffed_color = TargetColor(0,   255,   0);
-  ui_character_stat_debuffed_color = TargetColor(255,  35,   0);
+  ui_character_stat_default_color = Color16(255, 255, 255);
+  ui_character_stat_buffed_color = Color16(0,   255,   0);
+  ui_character_stat_debuffed_color = Color16(255,  35,   0);
   
-  ui_character_skillinfo_can_learn = TargetColor(255, 255, 255);
-  ui_character_skillinfo_can_learn_gm = TargetColor(255, 255, 0);
-  ui_character_skillinfo_cant_learn = TargetColor(255, 0, 0);
+  ui_character_skillinfo_can_learn = Color16(255, 255, 255);
+  ui_character_skillinfo_can_learn_gm = Color16(255, 255, 0);
+  ui_character_skillinfo_cant_learn = Color16(255, 0, 0);
   
-  ui_character_condition_normal_color = TargetColor(255, 255, 255);
-  ui_character_condition_light_color = TargetColor(0, 255, 0);
-  ui_character_condition_moderate_color = TargetColor(225, 205, 35);
-  ui_character_condition_severe_color = TargetColor(255, 35, 0);
+  ui_character_condition_normal_color = Color16(255, 255, 255);
+  ui_character_condition_light_color = Color16(0, 255, 0);
+  ui_character_condition_moderate_color = Color16(225, 205, 35);
+  ui_character_condition_severe_color = Color16(255, 35, 0);
 
-  ui_character_award_color[0] = TargetColor(248, 108, 160);
-  ui_character_award_color[1] = TargetColor(112, 220, 248);
-  ui_character_award_color[2] = TargetColor(192, 192, 240);
-  ui_character_award_color[3] = TargetColor( 64, 244,  96);
-  ui_character_award_color[4] = TargetColor(232, 244,  96);
-  ui_character_award_color[5] = TargetColor(240, 252, 192);
+  ui_character_award_color[0] = Color16(248, 108, 160);
+  ui_character_award_color[1] = Color16(112, 220, 248);
+  ui_character_award_color[2] = Color16(192, 192, 240);
+  ui_character_award_color[3] = Color16( 64, 244,  96);
+  ui_character_award_color[4] = Color16(232, 244,  96);
+  ui_character_award_color[5] = Color16(240, 252, 192);
   
-  ui_game_minimap_outline_color = TargetColor(0, 0, 255);
-  ui_game_minimap_actor_friendly_color = TargetColor(0, 255, 0);
-  ui_game_minimap_actor_hostile_color = TargetColor(255, 0, 0);
-  ui_game_minimap_actor_corpse_color = TargetColor(255, 255, 0);
-  ui_game_minimap_decoration_color_1 = TargetColor(255, 255, 255);
-  ui_game_minimap_projectile_color = TargetColor(255, 0, 0);
-  ui_game_minimap_treasure_color = TargetColor(0, 0, 255);
+  ui_game_minimap_outline_color = Color16(0, 0, 255);
+  ui_game_minimap_actor_friendly_color = Color16(0, 255, 0);
+  ui_game_minimap_actor_hostile_color = Color16(255, 0, 0);
+  ui_game_minimap_actor_corpse_color = Color16(255, 255, 0);
+  ui_game_minimap_decoration_color_1 = Color16(255, 255, 255);
+  ui_game_minimap_projectile_color = Color16(255, 0, 0);
+  ui_game_minimap_treasure_color = Color16(0, 0, 255);
 
-  ui_game_character_record_playerbuff_colors[0] = TargetColor(150, 212, 255);
-  ui_game_character_record_playerbuff_colors[1] = TargetColor(225, 225, 225);
-  ui_game_character_record_playerbuff_colors[2] = TargetColor(255, 128, 0);
-  ui_game_character_record_playerbuff_colors[3] = TargetColor(128, 128, 128);
-  ui_game_character_record_playerbuff_colors[4] = TargetColor(225, 225, 225);
-  ui_game_character_record_playerbuff_colors[5] = TargetColor(255, 85, 0);
-  ui_game_character_record_playerbuff_colors[6] = TargetColor(255, 128, 0);
-  ui_game_character_record_playerbuff_colors[7] = TargetColor(255, 85, 0);
-  ui_game_character_record_playerbuff_colors[8] = TargetColor(225, 225, 225);
-  ui_game_character_record_playerbuff_colors[9] = TargetColor(235, 15, 255);
-  ui_game_character_record_playerbuff_colors[10] = TargetColor(192, 192, 240);
-  ui_game_character_record_playerbuff_colors[11] = TargetColor(225, 225, 225);
-  ui_game_character_record_playerbuff_colors[12] = TargetColor(255, 128, 0);
-  ui_game_character_record_playerbuff_colors[13] = TargetColor(150, 212, 255);
-  ui_game_character_record_playerbuff_colors[14] = TargetColor(128, 128, 128);
-  ui_game_character_record_playerbuff_colors[15] = TargetColor(255, 255, 155);
-  ui_game_character_record_playerbuff_colors[16] = TargetColor(255, 255, 155);
-  ui_game_character_record_playerbuff_colors[17] = TargetColor(255, 255, 155);
-  ui_game_character_record_playerbuff_colors[18] = TargetColor(255, 255, 155);
-  ui_game_character_record_playerbuff_colors[19] = TargetColor(255, 255, 155);
-  ui_game_character_record_playerbuff_colors[20] = TargetColor(255, 255, 155);
-  ui_game_character_record_playerbuff_colors[21] = TargetColor(255, 255, 155);
-  ui_game_character_record_playerbuff_colors[22] = TargetColor(0, 128, 255);
-  ui_game_character_record_playerbuff_colors[23] = TargetColor(0, 128, 255);
+  ui_game_character_record_playerbuff_colors[0] = Color16(150, 212, 255);
+  ui_game_character_record_playerbuff_colors[1] = Color16(225, 225, 225);
+  ui_game_character_record_playerbuff_colors[2] = Color16(255, 128, 0);
+  ui_game_character_record_playerbuff_colors[3] = Color16(128, 128, 128);
+  ui_game_character_record_playerbuff_colors[4] = Color16(225, 225, 225);
+  ui_game_character_record_playerbuff_colors[5] = Color16(255, 85, 0);
+  ui_game_character_record_playerbuff_colors[6] = Color16(255, 128, 0);
+  ui_game_character_record_playerbuff_colors[7] = Color16(255, 85, 0);
+  ui_game_character_record_playerbuff_colors[8] = Color16(225, 225, 225);
+  ui_game_character_record_playerbuff_colors[9] = Color16(235, 15, 255);
+  ui_game_character_record_playerbuff_colors[10] = Color16(192, 192, 240);
+  ui_game_character_record_playerbuff_colors[11] = Color16(225, 225, 225);
+  ui_game_character_record_playerbuff_colors[12] = Color16(255, 128, 0);
+  ui_game_character_record_playerbuff_colors[13] = Color16(150, 212, 255);
+  ui_game_character_record_playerbuff_colors[14] = Color16(128, 128, 128);
+  ui_game_character_record_playerbuff_colors[15] = Color16(255, 255, 155);
+  ui_game_character_record_playerbuff_colors[16] = Color16(255, 255, 155);
+  ui_game_character_record_playerbuff_colors[17] = Color16(255, 255, 155);
+  ui_game_character_record_playerbuff_colors[18] = Color16(255, 255, 155);
+  ui_game_character_record_playerbuff_colors[19] = Color16(255, 255, 155);
+  ui_game_character_record_playerbuff_colors[20] = Color16(255, 255, 155);
+  ui_game_character_record_playerbuff_colors[21] = Color16(255, 255, 155);
+  ui_game_character_record_playerbuff_colors[22] = Color16(0, 128, 255);
+  ui_game_character_record_playerbuff_colors[23] = Color16(0, 128, 255);
 
-  ui_gamemenu_video_gamma_title_color = TargetColor(255, 255, 155);
-  ui_gamemenu_keys_action_name_color = TargetColor(255, 255, 255);
-  ui_gamemenu_keys_key_selection_blink_color_1 = TargetColor(50, 0, 0);
-  ui_gamemenu_keys_key_selection_blink_color_2 = TargetColor(225, 205, 35);
-  ui_gamemenu_keys_key_default_color = TargetColor(255, 255, 255);
+  ui_gamemenu_video_gamma_title_color = Color16(255, 255, 155);
+  ui_gamemenu_keys_action_name_color = Color16(255, 255, 255);
+  ui_gamemenu_keys_key_selection_blink_color_1 = Color16(50, 0, 0);
+  ui_gamemenu_keys_key_selection_blink_color_2 = Color16(225, 205, 35);
+  ui_gamemenu_keys_key_default_color = Color16(255, 255, 255);
 
-  ui_book_quests_title_color = TargetColor(255, 255, 255);
-  ui_book_quests_text_color = TargetColor(255, 255, 255);
-  ui_book_autonotes_title_color = TargetColor(255, 255, 255);
-  ui_book_autonotes_text_color = TargetColor(255, 255, 255);
-  ui_book_map_title_color = TargetColor(255, 255, 255);
-  ui_book_map_coordinates_color = TargetColor(255, 255, 255);
+  ui_book_quests_title_color = Color16(255, 255, 255);
+  ui_book_quests_text_color = Color16(255, 255, 255);
+  ui_book_autonotes_title_color = Color16(255, 255, 255);
+  ui_book_autonotes_text_color = Color16(255, 255, 255);
+  ui_book_map_title_color = Color16(255, 255, 255);
+  ui_book_map_coordinates_color = Color16(255, 255, 255);
 
-  ui_book_calendar_title_color = TargetColor(255, 255, 255);
-  ui_book_calendar_time_color = TargetColor(75, 75, 75);
-  ui_book_calendar_day_color = TargetColor(75, 75, 75);
-  ui_book_calendar_month_color = TargetColor(75, 75, 75);
-  ui_book_calendar_year_color = TargetColor(75, 75, 75);
-  ui_book_calendar_moon_color = TargetColor(75, 75, 75);
-  ui_book_calendar_location_color = TargetColor(75, 75, 75);
+  ui_book_calendar_title_color = Color16(255, 255, 255);
+  ui_book_calendar_time_color = Color16(75, 75, 75);
+  ui_book_calendar_day_color = Color16(75, 75, 75);
+  ui_book_calendar_month_color = Color16(75, 75, 75);
+  ui_book_calendar_year_color = Color16(75, 75, 75);
+  ui_book_calendar_moon_color = Color16(75, 75, 75);
+  ui_book_calendar_location_color = Color16(75, 75, 75);
 
-  ui_book_journal_title_color = TargetColor(255, 255, 255);
-  ui_book_journal_text_color = TargetColor(255, 255, 255);
-  ui_book_journal_text_shadow = TargetColor(0, 0, 0);
+  ui_book_journal_title_color = Color16(255, 255, 255);
+  ui_book_journal_text_color = Color16(255, 255, 255);
+  ui_book_journal_text_shadow = Color16(0, 0, 0);
 
-  ui_game_dialogue_npc_name_color = TargetColor(21, 153, 233);
-  ui_game_dialogue_option_highlight_color = TargetColor(225, 205, 35);
-  ui_game_dialogue_option_normal_color = TargetColor(255, 255, 255);
+  ui_game_dialogue_npc_name_color = Color16(21, 153, 233);
+  ui_game_dialogue_option_highlight_color = Color16(225, 205, 35);
+  ui_game_dialogue_option_normal_color = Color16(255, 255, 255);
 
-  ui_house_player_cant_interact_color = TargetColor(255, 255, 155);
+  ui_house_player_cant_interact_color = Color16(255, 255, 155);
 }
 
 std::array<unsigned int, 16> papredoll_dbrds;
@@ -792,27 +792,27 @@
         v166 = "item64v1";
       else
         v166 = item->GetIconName();
-      if ( !( item->uAttributes & 0xF0 ) )
+      if ( !( item->uAttributes & ITEM_ENCHANT_ANIMATION ) )
       {
-        if ( item->uAttributes & 2 )
+        if ( item->uAttributes & ITEM_BROKEN )
           pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(v166, TEXTURE_16BIT_PALETTE)));
         else
         {
-          if ( item->uAttributes & 1 )
+          if ( item->uAttributes & ITEM_IDENTIFIED )
             pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(v166, TEXTURE_16BIT_PALETTE)));
           else
             pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(v166, TEXTURE_16BIT_PALETTE)));
         }
       }
-      if ( item->uAttributes & 0xF0 )
+      if ( item->uAttributes & ITEM_ENCHANT_ANIMATION )
       {
-        if ( ( item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+        if ( ( item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
           container = "sptext01";
-        if ( ( item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+        if ( ( item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
           container = "sp28a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
           container = "sp30a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
           container = "sp91a";
         _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
         if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -836,13 +836,13 @@
       item = player->GetBowItem();
       item_X = pPaperdoll_BodyX + paperdoll_Weapon[pBodyComplection][2][0] - pItemsTable->pItems[item->uItemID].uEquipX;
       item_Y = pPaperdoll_BodyY + paperdoll_Weapon[pBodyComplection][2][1] - pItemsTable->pItems[item->uItemID].uEquipY;
-      if ( !(item->uAttributes & 0xF0) )//    
+      if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )//    
       {
-        if ( item->uAttributes & 2 )
+        if ( item->uAttributes & ITEM_BROKEN )
           pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(item->GetIconName(), TEXTURE_16BIT_PALETTE)));
         else
         {
-          if ( !(item->uAttributes & 1) )//   
+          if ( !(item->uAttributes & ITEM_IDENTIFIED) )//   
             pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(item->GetIconName(), TEXTURE_16BIT_PALETTE)));
           else //  
             pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(item->GetIconName(), TEXTURE_16BIT_PALETTE)));
@@ -850,13 +850,13 @@
       }
       else
       {
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
           container = "sptext01";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
           container = "sp28a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
           container = "sp30a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
           container = "sp91a";
         _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
         if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -902,22 +902,22 @@
       {
         item_X = pPaperdoll_BodyX + paperdoll_Cloak[pBodyComplection][index][0];
         item_Y = pPaperdoll_BodyY + paperdoll_Cloak[pBodyComplection][index][1];
-        if ( !(item->uAttributes & 0xF0) )
+        if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
         {
-          if ( item->uAttributes & 2 )
+          if ( item->uAttributes & ITEM_BROKEN )
             pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_cloak_texture[pBodyComplection][index]));
           else
             pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_cloak_texture[pBodyComplection][index]));
         }
         else
         {
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
             container = "sptext01";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
             container = "sp28a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
             container = "sp30a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
             container = "sp91a";
           _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
           if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -962,13 +962,13 @@
       {
         item_X = pPaperdoll_BodyX + paperdoll_Armor_Coord[pBodyComplection][index][0];
         item_Y = pPaperdoll_BodyY + paperdoll_Armor_Coord[pBodyComplection][index][1];
-        if ( !(item->uAttributes & 0xF0) )
+        if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
         {
-          if ( item->uAttributes & 2 )
+          if ( item->uAttributes & ITEM_BROKEN )
             pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_armor_texture[pBodyComplection][index][0]));
           else
           {
-            if ( !(item->uAttributes & 1) )
+            if ( !(item->uAttributes & ITEM_IDENTIFIED) )
               pRenderer->DrawTransparentGreenShade(item_X, item_Y, &pIcons_LOD->pTextures[paperdoll_armor_texture[pBodyComplection][index][0]]);
             else
               pRenderer->DrawTextureTransparent(item_X, item_Y, &pIcons_LOD->pTextures[paperdoll_armor_texture[pBodyComplection][index][0]]);
@@ -976,13 +976,13 @@
         }
         else
         {
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
             container = "sptext01";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
             container = "sp28a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
             container = "sp30a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
             container = "sp91a";
           _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
           if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1024,13 +1024,13 @@
       {
         item_X = pPaperdoll_BodyX + paperdoll_Boot[pBodyComplection][index][0];
         item_Y = pPaperdoll_BodyY + paperdoll_Boot[pBodyComplection][index][1];
-        if ( !(item->uAttributes & 0xF0) )
+        if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
         {
-          if ( item->uAttributes & 2 )
+          if ( item->uAttributes & ITEM_BROKEN )
             pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(v59));
           else
           {
-            if ( item->uAttributes & 1 )
+            if ( item->uAttributes & ITEM_IDENTIFIED )
               pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(v59));
             else
               pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(v59));
@@ -1038,13 +1038,13 @@
         }
         else
         {
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
             container = "sptext01";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
             container = "sp28a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
             container = "sp30a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
             container = "sp91a";
           _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
           if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1091,13 +1091,13 @@
             v75 = paperdoll_belt_texture[pBodyComplection][index];
           else
             v75 = paperdoll_belt_texture[pBodyComplection - 2][index];
-          if ( !(item->uAttributes & 0xF0) )
+          if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
           {
-            if ( item->uAttributes & 2 )
+            if ( item->uAttributes & ITEM_BROKEN )
               pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(v75));
             else
             {
-              if ( item->uAttributes & 1 )
+              if ( item->uAttributes & ITEM_IDENTIFIED )
                 pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(v75));
               else
                 pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(v75));
@@ -1107,13 +1107,13 @@
           }
           else
           {
-            if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+            if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
               container = "sptext01";
-            if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+            if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
               container = "sp28a";
-            if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+            if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
               container = "sp30a";
-            if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+            if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
               container = "sp91a";
             _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
             if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1179,13 +1179,13 @@
             }
             if ( v94 != pIcons_LOD->FindTextureByName("pending") )
             {
-              if ( !(item->uAttributes & 0xF0) )
+              if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
               {
-                if ( item->uAttributes & 2 )
+                if ( item->uAttributes & ITEM_BROKEN )
                   pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(v94));
                 else
                 {
-                  if ( item->uAttributes & 1 )
+                  if ( item->uAttributes & ITEM_IDENTIFIED )
                     pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(v94));
                   else
                     pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(v94));
@@ -1195,15 +1195,15 @@
               {
                 if ( paperdoll_armor_texture[pBodyComplection][index][2] != pIcons_LOD->FindTextureByName("pending") )
                 {
-                  if ( item->uAttributes & 0xF0 )
+                  if ( item->uAttributes & ITEM_ENCHANT_ANIMATION )
                   {
-                    if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+                    if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
                       container = "sptext01";
-                    if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+                    if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
                       container = "sp28a";
-                    if ( ( item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+                    if ( ( item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
                       container = "sp30a";
-                    if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+                    if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
                       container = "sp91a";
                     _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
                     if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1226,13 +1226,13 @@
             {
               item_X = pPaperdoll_BodyX + paperdoll_shoulder_coord[pBodyComplection][index][0];
               item_Y = pPaperdoll_BodyY + paperdoll_shoulder_coord[pBodyComplection][index][1];
-              if ( !(item->uAttributes & 0xF0) )
+              if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
               {
-                if ( item->uAttributes & 2 )
+                if ( item->uAttributes & ITEM_BROKEN )
                   pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_armor_texture[pBodyComplection][index][1]));
                 else
                 {
-                  if ( item->uAttributes & 1 )
+                  if ( item->uAttributes & ITEM_IDENTIFIED )
                     pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_armor_texture[pBodyComplection][index][1]));
                   else
                     pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_armor_texture[pBodyComplection][index][1]));
@@ -1240,13 +1240,13 @@
               }
               else
               {
-                if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+                if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
                   container = "sptext01";
-                if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+                if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
                   container = "sp28a";
-                if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+                if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
                   container = "sp30a";
-                if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+                if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
                   container = "sp91a";
                 _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
                 if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1292,9 +1292,9 @@
           item_Y = pPaperdoll_BodyY + paperdoll_CloakCollar[pBodyComplection][index][1];
           if ( paperdoll_cloak_collar_texture[pBodyComplection][index] != pIcons_LOD->FindTextureByName("pending") )
           {
-            if ( !(item->uAttributes & 0xF0) )
+            if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
             {
-              if ( item->uAttributes & 2 )
+              if ( item->uAttributes & ITEM_BROKEN )
                 pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_cloak_collar_texture[pBodyComplection][index]));
               else
                 pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(paperdoll_cloak_collar_texture[pBodyComplection][index]));
@@ -1304,13 +1304,13 @@
             }
             else
             {
-              if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+              if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
                 container = "sptext01";
-              if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+              if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
                 container = "sp28a";
-              if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+              if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
                 container = "sp30a";
-              if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+              if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
                 container = "sp91a";
               _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
               if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1365,15 +1365,15 @@
           v127 = paperdoll_helm_texture[player->GetSexByVoice()][index];
         else
           v127 = papredoll_dbrds[11];
-        if ( item->uAttributes & 0xF0 )
+        if ( item->uAttributes & ITEM_ENCHANT_ANIMATION )
         {
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
             container = "sptext01";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
             container = "sp28a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
             container = "sp30a";
-          if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+          if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
             container = "sp91a";
           _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
           if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1387,11 +1387,11 @@
         }
         else
         {
-          if ( item->uAttributes & 2 )
+          if ( item->uAttributes & ITEM_BROKEN )
             pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(v127));
           else
           {
-            if ( item->uAttributes & 1 )
+            if ( item->uAttributes & ITEM_IDENTIFIED )
               pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(v127));
             else
               pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(v127));
@@ -1411,13 +1411,13 @@
         v181 = "item64v1";
       else
         v181 = item->GetIconName();
-      if ( !(item->uAttributes & 0xF0) )
+      if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
       {
-        if ( item->uAttributes & 2 )
+        if ( item->uAttributes & ITEM_BROKEN )
           pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(v181, TEXTURE_16BIT_PALETTE)));
         else
         {
-          if ( item->uAttributes & 1 )
+          if ( item->uAttributes & ITEM_IDENTIFIED )
             pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(v181, TEXTURE_16BIT_PALETTE)));
           else
             pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(pIcons_LOD->LoadTexture(v181, TEXTURE_16BIT_PALETTE)));
@@ -1425,13 +1425,13 @@
       }
       else
       {
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
           container = "sptext01";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
           container = "sp28a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
            container = "sp30a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
           container = "sp91a";
         _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
         if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1482,14 +1482,14 @@
         item_Y = pPaperdoll_BodyY + paperdoll_Weapon[pBodyComplection][0][1] - pItemsTable->pItems[item->uItemID].uEquipY;
       }
       v153 = pIcons_LOD->LoadTexture(item->GetIconName(), TEXTURE_16BIT_PALETTE);
-      if ( !(item->uAttributes & 0xF0) )
+      if ( !(item->uAttributes & ITEM_ENCHANT_ANIMATION) )
       {
-        if ( item->uAttributes & 2 )
+        if ( item->uAttributes & ITEM_BROKEN )
           pRenderer->DrawTransparentRedShade(item_X, item_Y, pIcons_LOD->GetTexture(v153));
         else
         {
           //v160 = (char *)pIcons_LOD->GetTexture(v153);
-          if ( !(item->uAttributes & 1) )
+          if ( !(item->uAttributes & ITEM_IDENTIFIED) )
           pRenderer->DrawTransparentGreenShade(item_X, item_Y, pIcons_LOD->GetTexture(v153));
           else
             pRenderer->DrawTextureTransparent(item_X, item_Y, pIcons_LOD->GetTexture(v153));
@@ -1497,13 +1497,13 @@
       }
       else
       {
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_RED )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_RED )
           container = "sptext01";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_BLUE )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_BLUE )
           container = "sp28a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_GREEN )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_GREEN )
           container = "sp30a";
-        if ( (item->uAttributes & 0xF0) == ITEM_AURA_EFFECT_PURPLE )
+        if ( (item->uAttributes & ITEM_ENCHANT_ANIMATION) == ITEM_AURA_EFFECT_PURPLE )
           container = "sp91a";
         _50C9A8_item_enchantment_timer -= pEventTimer->uTimeElapsed;
         if ( _50C9A8_item_enchantment_timer <= 0 )
@@ -1545,7 +1545,7 @@
 {
   Texture *pTexture; // esi@6
   int v13; // eax@13
-  int v15; // eax@13
+  //int v15; // eax@13
   unsigned int v17; // edi@15
   unsigned int uCellX; // [sp+30h] [bp-8h]@5
   unsigned int uCellY; // [sp+34h] [bp-4h]@5
@@ -1567,16 +1567,17 @@
       pTexture->uTextureWidth = 14;
     if ( (pTexture->uTextureWidth - 14) / 32 == 0 && pTexture->uTextureWidth < 32)
       uCellX += (32 - pTexture->uTextureWidth) / 2;
-    v13 = pTexture->uTextureWidth - 14;
-    LOBYTE(v13) = v13 & 0xE0;
-    v15 = v13 + 32;
+    //v13 = pTexture->uTextureWidth - 14;
+    //LOBYTE(v13) = v13 & 0xE0;
+    //v15 = v13 + 32;
     if (pTexture->uTextureHeight < 14 )
       pTexture->uTextureHeight = 14;
-    v17 = uCellX + ((v15 - pTexture->uTextureWidth) >> 1) + pSRZBufferLineOffsets[uCellY + (( (int)((pTexture->uTextureHeight - 14) & 0xFFFFFFE0) - pTexture->uTextureHeight + 32) >> 1)];   //added typecast. without it the value in the brackets got cat to unsigned which messed stuff up
-    if (player->pInventoryItemList[player->pInventoryMatrix[i] - 1].uAttributes & 0xF0)
+    v17 = uCellX + (( (int)((pTexture->uTextureWidth - 14) & 0xE0) + 32 - pTexture->uTextureWidth) / 2)
+       + pSRZBufferLineOffsets[uCellY + (( (int)((pTexture->uTextureHeight - 14) & 0xFFFFFFE0) - pTexture->uTextureHeight + 32) / 2)];   //added typecast. without it the value in the brackets got cat to unsigned which messed stuff up
+    if (player->pInventoryItemList[player->pInventoryMatrix[i] - 1].uAttributes & ITEM_ENCHANT_ANIMATION)
     {
       Texture *loadedTextureptr = nullptr;
-      switch (player->pInventoryItemList[player->pInventoryMatrix[i] - 1].uAttributes & 0xF0)
+      switch (player->pInventoryItemList[player->pInventoryMatrix[i] - 1].uAttributes & ITEM_ENCHANT_ANIMATION)
       {
         case ITEM_AURA_EFFECT_RED:    loadedTextureptr = pIcons_LOD->LoadTexturePtr("sptext01", TEXTURE_16BIT_PALETTE); break;
         case ITEM_AURA_EFFECT_BLUE:   loadedTextureptr = pIcons_LOD->LoadTexturePtr("sp28a", TEXTURE_16BIT_PALETTE);    break;
@@ -1615,10 +1616,10 @@
 {
   Texture* item_texture = pIcons_LOD->LoadTexturePtr(item->GetIconName(), TEXTURE_16BIT_PALETTE);
 
-  if (item->uAttributes & 0xF0) // enchant animation
+  if (item->uAttributes & ITEM_ENCHANT_ANIMATION) // enchant animation
   {
     Texture *enchantment_texture = nullptr;
-    switch (item->uAttributes & 0xF0)
+    switch (item->uAttributes & ITEM_ENCHANT_ANIMATION)
     {
       case ITEM_AURA_EFFECT_RED:    enchantment_texture = pIcons_LOD->LoadTexturePtr("sptext01", TEXTURE_16BIT_PALETTE); break;
       case ITEM_AURA_EFFECT_BLUE:   enchantment_texture = pIcons_LOD->LoadTexturePtr("sp28a", TEXTURE_16BIT_PALETTE);    break;
@@ -1933,7 +1934,7 @@
     }
   }
   first_rows = 0;
-  //  a5 = pGUIWindow_CurrentMenu->uNumControls;
+  int a5 = pGUIWindow_CurrentMenu->uNumControls;
   curr_player = &pParty->pPlayers[uActiveCharacter-1];
 
   uCurrFontHeght=pFontLucida->uFontHeight;
@@ -1990,7 +1991,7 @@
   }
 
   if ( buttons_count )
-    pGUIWindow_CurrentMenu->_41D08F_set_keyboard_control_group(buttons_count, 1, 0, pGUIWindow_CurrentMenu->uNumControls);
+    pGUIWindow_CurrentMenu->_41D08F_set_keyboard_control_group(buttons_count, 1, 0, a5);
 }
 
 //----- (00418511) --------------------------------------------------------
--- a/UI/UIGuilds.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIGuilds.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -52,7 +52,7 @@
             guild_mambership_flags[(unsigned int)window_SpeakInHouse->ptr_1C - 139]) )
     { //you must me member
       pTextHeight = pFontArrus->CalcTextHeight(pNPCTopics[121].pText, &working_window, 0, 0);
-      working_window.DrawTitleText(pFontArrus, 0, (212 - pTextHeight) / 2 + 101, TargetColor(0xFFu, 0xFFu, 0x9Bu), pNPCTopics[121].pText, 3);
+      working_window.DrawTitleText(pFontArrus, 0, (212 - pTextHeight) / 2 + 101, Color16(0xFFu, 0xFFu, 0x9Bu), pNPCTopics[121].pText, 3);
       pDialogueWindow->pNumPresenceButton = 0;
       return;
     }
@@ -64,7 +64,7 @@
       strcat(pTmpBuf.data(), "\n \n");
       strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]); //"I can offer you nothing further."
       pTextHeight = pFontArrus->CalcTextHeight(pTmpBuf.data(), &working_window, 0, 0);
-      working_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+      working_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
       return;
     }
     v61 = 0;
@@ -95,7 +95,7 @@
       strcat(pTmpBuf.data(), "\n \n");
       strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]); //"I can offer you nothing further."
       pTextHeight = pFontArrus->CalcTextHeight(pTmpBuf.data(), &working_window, 0, 0);
-      working_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+      working_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
       return;
     }
     if ( pSkillFlag )
@@ -118,9 +118,9 @@
         pButton->uHeight = pTextHeight;
         v26 = pButton->uY + pTextHeight - 1;
         pButton->uW = v26;
-        pTextColor = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+        pTextColor = Color16(0xFFu, 0xFFu, 0x9Bu);
         if ( pDialogueWindow->pCurrentPosActiveItem != i )
-          pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+          pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
         working_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pGlobalTXT_LocalizationStrings[400], 3);//"Buy Spells"
       }
       else
@@ -133,9 +133,9 @@
           pButton->uHeight = pTextHeight;
           v26 = pButton->uY + pTextHeight - 1;
           pButton->uW = v26;
-          pTextColor = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+          pTextColor = Color16(0xFFu, 0xFFu, 0x9Bu);
           if ( pDialogueWindow->pCurrentPosActiveItem != i )
-            pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+            pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
           working_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pSkillNames[pButton->msg_param - 36], 3);
         }
         else
@@ -198,7 +198,7 @@
         v17 = pPlayers[uActiveCharacter]->SelectPhrasesTransaction( (ItemGen *)&pParty->pPlayers[1].uExpressionTimeLength + v13 + 12 * (int)window_SpeakInHouse->ptr_1C, BuildingType_MagicShop, (int)window_SpeakInHouse->ptr_1C,  2);
         v18 = BuildDialogueString(pMerchantsBuyPhrases[v17], uActiveCharacter - 1, v15, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
         pTextHeight = pFontArrus->CalcTextHeight(v18, &working_window, 0, 0);
-        working_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138,  TargetColor(0xFFu, 0xFFu, 0xFFu), v18, 3);
+        working_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138,  Color16(0xFFu, 0xFFu, 0xFFu), v18, 3);
         return;
       }
     }
--- a/UI/UIHouses.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIHouses.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -1459,9 +1459,9 @@
         {
   //get color for current string(   )----------
           if ( pDialogueWindow->pCurrentPosActiveItem == pCurrentButton )
-            sprintf(pTopicArray[index], "\f%05d", TargetColor(255, 255, 155));
+            sprintf(pTopicArray[index], "\f%05d", Color16(255, 255, 155));
           else
-            sprintf(pTopicArray[index], "\f%05d", TargetColor(255, 255, 255));
+            sprintf(pTopicArray[index], "\f%05d", Color16(255, 255, 255));
   //hired NPC premium(  )----------------------------------
           travel_time = transport_schedule[schedule_id].uTravelTime;
           if ( (unsigned int)window_SpeakInHouse->ptr_1C >= HOUSE_BOATS_EMERALD_ISLE )
@@ -1517,7 +1517,7 @@
       else
       {
         travel_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pGlobalTXT_LocalizationStrings[561], &travel_window, 0, 0)) / 2 + 138,//",    "
-                          TargetColor(255, 255, 255), pGlobalTXT_LocalizationStrings[561], 3);
+                          Color16(255, 255, 255), pGlobalTXT_LocalizationStrings[561], 3);
         pAudioPlayer->StopChannels(-1, -1);
       }
     }
@@ -1548,7 +1548,7 @@
           _5B65B8_npcdata_hiword_house_or_other = 0;
           dword_5B65BC = 0;
           _5B65B4_npcdata_loword_house_or_other = pTravel->arrival_rot_y;
-          uGameState = GAME_STATE_2;
+          uGameState = GAME_STATE_CHANGE_LOCATION;
           _5B65A8_npcdata_uflags_or_other = pTravel->arrival_x;
           _5B65AC_npcdata_fame_or_other = pTravel->arrival_y;
           _5B65B0_npcdata_rep_or_other = pTravel->arrival_z;
@@ -1647,7 +1647,7 @@
   townHall_window.uFrameWidth = 148;
   townHall_window.uFrameZ = 334;
   sprintf(pTmpBuf.data(), "%s: %d", pGlobalTXT_LocalizationStrings[605], pParty->uFine);// 
-  townHall_window.DrawTitleText(pFontArrus, 0, 260, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+  townHall_window.DrawTitleText(pFontArrus, 0, 260, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
   switch(dialog_menu_id)
   {
     case HOUSE_DIALOGUE_MAIN:
@@ -1678,9 +1678,9 @@
           pButton->uHeight = pTextHeight;
           v17 = pButton->uY + pTextHeight - 1;
           pButton->uW = v17;
-          pTextColor = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+          pTextColor = Color16(0xFFu, 0xFFu, 0x9Bu);
           if ( pDialogueWindow->pCurrentPosActiveItem != v31 )
-            pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+            pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
           townHall_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pShopOptions[j], 3);
           ++v31;
           ++j;
@@ -1690,8 +1690,8 @@
     }
     case HOUSE_DIALOGUE_TOWNHALL_MESSAGE:
     {
-      sprintf(pTmpBuf.data(), "\f%05d%s\f%05d", TargetColor(0xFFu, 0xFFu, 0x9Bu),
-      pMonsterStats->pInfos[bountyHunting_monster_id_for_hunting].pName, TargetColor(0xFFu, 0xFFu, 0xFFu));
+      sprintf(pTmpBuf.data(), "\f%05d%s\f%05d", Color16(0xFFu, 0xFFu, 0x9Bu),
+      pMonsterStats->pInfos[bountyHunting_monster_id_for_hunting].pName, Color16(0xFFu, 0xFFu, 0xFFu));
       sprintf(pTmpBuf2.data(), bountyHunting_text, pTmpBuf.data(), 100 * pMonsterStats->pInfos[bountyHunting_monster_id_for_hunting].uLevel);
       current_npc_text = pTmpBuf2.data();
       memcpy(&window, pDialogueWindow, sizeof(window));
@@ -1714,8 +1714,8 @@
       if ( window_SpeakInHouse->receives_keyboard_input_2 == WINDOW_INPUT_IN_PROGRESS)
       {
         sprintfex(pTmpBuf.data(), "%s\n%s", pGlobalTXT_LocalizationStrings[606], pGlobalTXT_LocalizationStrings[112]); // "Pay"   "How Much?"
-        townHall_window.DrawTitleText(pFontArrus, 0, 146, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
-        townHall_window.DrawTitleText(pFontArrus, 0, 186, TargetColor(0xFFu, 0xFFu, 0xFFu), (const char *)pKeyActionMap->pPressedKeysBuffer, 3);
+        townHall_window.DrawTitleText(pFontArrus, 0, 146, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+        townHall_window.DrawTitleText(pFontArrus, 0, 186, Color16(0xFFu, 0xFFu, 0xFFu), (const char *)pKeyActionMap->pPressedKeysBuffer, 3);
         townHall_window.DrawFlashingInputCursor(pFontArrus->GetLineWidth((const char *)pKeyActionMap->pPressedKeysBuffer) / 2 + 80, 185, pFontArrus);
         return;
       }
@@ -1768,18 +1768,18 @@
   bank_window.uFrameWidth = 148;
   bank_window.uFrameZ = 334;
   sprintf(pTmpBuf.data(), "%s: %d", pGlobalTXT_LocalizationStrings[25], pParty->uNumGoldInBank);//
-  bank_window.DrawTitleText(pFontArrus, 0, 220, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+  bank_window.DrawTitleText(pFontArrus, 0, 220, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
   switch(dialog_menu_id)
   {
     case HOUSE_DIALOGUE_MAIN:
     {
-      pColorText = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+      pColorText = Color16(0xFFu, 0xFFu, 0x9Bu);
       if ( pDialogueWindow->pCurrentPosActiveItem != 2 )
-        pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+        pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
       bank_window.DrawTitleText(pFontArrus, 0, 146, pColorText, pGlobalTXT_LocalizationStrings[60], 3);
-      pColorText = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+      pColorText = Color16(0xFFu, 0xFFu, 0x9Bu);
       if ( pDialogueWindow->pCurrentPosActiveItem != 3 )
-        pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+        pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
       bank_window.DrawTitleText(pFontArrus, 0, 176, pColorText, pGlobalTXT_LocalizationStrings[244], 3);
       break;
     }
@@ -1788,8 +1788,8 @@
       if ( window_SpeakInHouse->receives_keyboard_input_2 == WINDOW_INPUT_IN_PROGRESS)
       {
         sprintf(pTmpBuf.data(), "%s\n%s", pGlobalTXT_LocalizationStrings[60], pGlobalTXT_LocalizationStrings[112]);//"" "?"
-        bank_window.DrawTitleText(pFontArrus, 0, 146, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
-        bank_window.DrawTitleText(pFontArrus, 0, 186, TargetColor(0xFFu, 0xFFu, 0xFFu), (const char *)pKeyActionMap->pPressedKeysBuffer, 3);
+        bank_window.DrawTitleText(pFontArrus, 0, 146, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+        bank_window.DrawTitleText(pFontArrus, 0, 186, Color16(0xFFu, 0xFFu, 0xFFu), (const char *)pKeyActionMap->pPressedKeysBuffer, 3);
         bank_window.DrawFlashingInputCursor(pFontArrus->GetLineWidth((const char *)pKeyActionMap->pPressedKeysBuffer) / 2 + 80, 185, pFontArrus);
         return;
       }
@@ -1830,8 +1830,8 @@
       if ( window_SpeakInHouse->receives_keyboard_input_2 == WINDOW_INPUT_IN_PROGRESS)
       {
         sprintfex(pTmpBuf.data(), "%s\n%s", pGlobalTXT_LocalizationStrings[244], pGlobalTXT_LocalizationStrings[112]);//"" "?"
-        bank_window.DrawTitleText(pFontArrus, 0, 146, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
-        bank_window.DrawTitleText(pFontArrus, 0, 186, TargetColor(0xFFu, 0xFFu, 0xFFu), (const char *)pKeyActionMap->pPressedKeysBuffer, 3);
+        bank_window.DrawTitleText(pFontArrus, 0, 146, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+        bank_window.DrawTitleText(pFontArrus, 0, 186, Color16(0xFFu, 0xFFu, 0xFFu), (const char *)pKeyActionMap->pPressedKeysBuffer, 3);
         bank_window.DrawFlashingInputCursor(pFontArrus->GetLineWidth((const char *)pKeyActionMap->pPressedKeysBuffer) / 2 + 80, 185, pFontArrus);
         return;
       }
@@ -1930,27 +1930,27 @@
       if ( !HouseUI_CheckIfPlayerCanInteract() )
           return;
 
-      sprintf(pTopic1, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 2 ? TargetColor(0xFFu, 0xFFu, 0x9Bu) : TargetColor(0xFFu, 0xFFu, 0xFFu));
+      sprintf(pTopic1, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 2 ? Color16(0xFFu, 0xFFu, 0x9Bu) : Color16(0xFFu, 0xFFu, 0xFFu));
       sprintfex(pTmpBuf2.data(), pGlobalTXT_LocalizationStrings[178], pPriceRoom); // Rent room for %d gold
       strcat(pTopic1, pTmpBuf2.data());
       pTopic1Height = pFontArrus->CalcTextHeight(pTopic1, &dialog_window, 0, 0);
       strcat(pTopic1, "\n \n");
 
-      sprintf(pTopic2, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 3 ? TargetColor(0xFFu, 0xFFu, 0x9Bu) : TargetColor(0xFFu, 0xFFu, 0xFFu));
+      sprintf(pTopic2, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 3 ? Color16(0xFFu, 0xFFu, 0x9Bu) : Color16(0xFFu, 0xFFu, 0xFFu));
       sprintfex(pTmpBuf2.data(), pGlobalTXT_LocalizationStrings[86], // Buy food for %d days for %d gold
         (unsigned int)p2DEvents[(unsigned int)window_SpeakInHouse->ptr_1C - 1].fPriceMultiplier, pPriceFood);
       strcat(pTopic2, pTmpBuf2.data());
       pTopic2Height = pFontArrus->CalcTextHeight(pTopic2, &dialog_window, 0, 0);
       strcat(pTopic2, "\n \n");
 
-      sprintf(pTopic3, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 4 ? TargetColor(0xFFu, 0xFFu, 0x9Bu) : TargetColor(0xFFu, 0xFFu, 0xFFu));
+      sprintf(pTopic3, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 4 ? Color16(0xFFu, 0xFFu, 0x9Bu) : Color16(0xFFu, 0xFFu, 0xFFu));
       strcat(pTopic3, pGlobalTXT_LocalizationStrings[160]); // Learn Skills
       pTopic3Height = pFontArrus->CalcTextHeight(pTopic3, &dialog_window, 0, 0);
       strcat(pTopic3, "\n \n");
       pTopic4[0] = 0;
       if ( (signed int)window_SpeakInHouse->par1C >= 108 && (signed int)window_SpeakInHouse->par1C <= 120 )
       {
-        sprintf(pTopic4, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 5 ? TargetColor(0xFFu, 0xFFu, 0x9Bu) : TargetColor(0xFFu, 0xFFu, 0xFFu));
+        sprintf(pTopic4, "\f%05d", pDialogueWindow->pCurrentPosActiveItem == 5 ? Color16(0xFFu, 0xFFu, 0x9Bu) : Color16(0xFFu, 0xFFu, 0xFFu));
         strcat(pTopic4, pGlobalTXT_LocalizationStrings[611]); // Play Arcomage
         pTopic4Height = pFontArrus->CalcTextHeight(pTopic4, &dialog_window, 0, 0);
       }
@@ -2037,7 +2037,7 @@
       }
       strcpy(pTmpBuf.data(), pText);
       dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138,
-                                  TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+                                  Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
       break;
     }
     case HOUSE_DIALOGUE_TAVERN_REST:
@@ -2113,9 +2113,9 @@
             pButton->uHeight = pTextHeight;
             v54 = pTextHeight + pButton->uY - 1;
             pButton->uW = v54;
-            pColorText = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+            pColorText = Color16(0xFFu, 0xFFu, 0x9Bu);
             if ( pDialogueWindow->pCurrentPosActiveItem != i )
-              pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+              pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
             dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, pSkillNames[pButton->msg_param - 36], 3);
           }
         }
@@ -2126,7 +2126,7 @@
       strcat(pTmpBuf.data(), "\n \n");
       strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]);//    .
       pTextHeight = (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138;
-      dialog_window.DrawTitleText(pFontArrus, 0, pTextHeight, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, pTextHeight, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
       return;
     }
 
@@ -2181,9 +2181,9 @@
           pButton->uHeight = pTextHeight;
           v54 = pButton->uY + pTextHeight - 1;
           pButton->uW = v54;
-          pColorText = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+          pColorText = Color16(0xFFu, 0xFFu, 0x9Bu);
           if ( pDialogueWindow->pCurrentPosActiveItem != pItemNum )
-            pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+            pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
           dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, (const char *)pShopOptions[pNumString], 3);
           ++pNumString;
         }
@@ -2259,9 +2259,9 @@
         pButton->uHeight = pTextHeight;
         pButton->uW = pButton->uY + pTextHeight - 1;
         all_text_height = pButton->uW;
-        pTextColor = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+        pTextColor = Color16(0xFFu, 0xFFu, 0x9Bu);
         if ( pDialogueWindow->pCurrentPosActiveItem != index + 2 )
-          pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+          pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
         tample_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pShopOptions[1 * i], 3);
         i++;
         index++;
@@ -2441,9 +2441,9 @@
               pButton->uHeight = pTextHeight;
               pButton->uW = pButton->uY + pTextHeight - 1;
               all_text_height = pButton->uW;
-              pTextColor = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+              pTextColor = Color16(0xFFu, 0xFFu, 0x9Bu);
               if ( pDialogueWindow->pCurrentPosActiveItem != pCurrentItem )
-                pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+                pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
               tample_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pSkillNames[pButton->msg_param - 36], 3);
             }
             pCurrentItem++;
@@ -2456,7 +2456,7 @@
         strcat(pTmpBuf.data(), "\n \n");
         strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]);//"    ."
         pTextHeight = pFontArrus->CalcTextHeight(pTmpBuf.data(), &tample_window, 0, 0);
-        tample_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+        tample_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
       }
     }
   }
@@ -2550,9 +2550,9 @@
             pButton->uHeight = pTextHeight;
             pButton->uW = pTextHeight + pButton->uY - 1;
             v49 = pButton->uW;
-            pTextColor = TargetColor(0xE1u, 0xCDu, 0x23u);
+            pTextColor = Color16(0xE1u, 0xCDu, 0x23u);
             if ( pDialogueWindow->pCurrentPosActiveItem != i )
-              pTextColor = TargetColor(255, 255, 255);
+              pTextColor = Color16(255, 255, 255);
             training_dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pShopOptions[index], 3);
             ++index;
           }
@@ -2565,7 +2565,7 @@
       if ( !HouseUI_CheckIfPlayerCanInteract() )
       {
         v33 = pFontArrus->CalcTextHeight(pNPCTopics[122].pText, &training_dialog_window, 0, 0);
-        training_dialog_window.DrawTitleText(pFontArrus, 0, (212 - v33) / 2 + 101, TargetColor(0xE1u, 0xCDu, 0x23u), pNPCTopics[122].pText, 3);
+        training_dialog_window.DrawTitleText(pFontArrus, 0, (212 - v33) / 2 + 101, Color16(0xE1u, 0xCDu, 0x23u), pNPCTopics[122].pText, 3);
         pDialogueWindow->pNumPresenceButton = 0;
         return;
       }
@@ -2622,7 +2622,7 @@
                                                 // ""Sorry, but we are unable to train you.""
         v36 = (212 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &training_dialog_window, 0, 0)) / 2 + 101;
       }
-      training_dialog_window.DrawTitleText(pFontArrus, 0, v36, TargetColor(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
+      training_dialog_window.DrawTitleText(pFontArrus, 0, v36, Color16(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
       PlayHouseSound((unsigned int)window_SpeakInHouse->ptr_1C, (HouseSoundID)3);
       pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
       return;
@@ -2674,9 +2674,9 @@
             pButton->uHeight = pTextHeight;
             pButton->uW = pButton->uY + pTextHeight - 1;
             v19 = pButton->uY + pTextHeight - 1;
-            pTextColor = TargetColor(0xE1u, 0xCDu, 0x23u);
+            pTextColor = Color16(0xE1u, 0xCDu, 0x23u);
             if ( pDialogueWindow->pCurrentPosActiveItem != i )
-              pTextColor = TargetColor(255, 255, 255);
+              pTextColor = Color16(255, 255, 255);
             training_dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pSkillNames[pButton->msg_param - 36], 3);
           }
         }
@@ -2688,7 +2688,7 @@
         strcat(pTmpBuf.data(), "\n \n");
         strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]);// "I can offer you nothing further."
         pTextHeight = pFontArrus->CalcTextHeight(pTmpBuf.data(), &training_dialog_window, 0, 0);
-        training_dialog_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, TargetColor(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
+        training_dialog_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, Color16(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
       }
     }
   }
@@ -2731,7 +2731,7 @@
     if ( !(unsigned __int16)_449B57_test_bit((unsigned __int8 *)pPlayers[uActiveCharacter]->_achieved_awards_bits, word_4F0754[2 * (unsigned int)window_SpeakInHouse->ptr_1C]) )
     {
       pTextHeight = pFontArrus->CalcTextHeight(pNPCTopics[171].pText, &dialog_window, 0, 0);//
-      dialog_window.DrawTitleText(pFontArrus, 0, (212 - pTextHeight) / 2 + 101, TargetColor(0xFFu, 0xFFu, 0x9Bu), pNPCTopics[171].pText, 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (212 - pTextHeight) / 2 + 101, Color16(0xFFu, 0xFFu, 0x9Bu), pNPCTopics[171].pText, 3);
       pDialogueWindow->pNumPresenceButton = 0;
       return;
     }
@@ -2755,7 +2755,7 @@
       strcat(pTmpBuf.data(), "\n \n");
       strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]);//    .
       pTextHeight = pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0);
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pTextHeight) / 2 + 138, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
       return; 
     }
     sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[401], pPrice);// : %lu
@@ -2779,9 +2779,9 @@
             pButton->uHeight = pTextHeight;
             pButton->uW = pButton->uY + pTextHeight - 1;
             index = pButton->uY + pTextHeight - 1;
-            pTextColor = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+            pTextColor = Color16(0xFFu, 0xFFu, 0x9Bu);
             if ( pDialogueWindow->pCurrentPosActiveItem != i )
-              pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+              pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
             dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pSkillNames[pButton->msg_param - 36], 3);
           }
         }
@@ -2883,7 +2883,7 @@
     sprintfex(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[429], pNPC->pName, aNPCProfessionNames[pNPC->uProfession]);//^Pi[%s] %s
   else
     strcpy(pTmpBuf.data(), pNPC->pName);
-  house_window.DrawTitleText(pFontCreate, 483, 113, TargetColor(0x15u, 0x99u, 0xE9u), pTmpBuf.data(), 3);
+  house_window.DrawTitleText(pFontCreate, 483, 113, Color16(0x15u, 0x99u, 0xE9u), pTmpBuf.data(), 3);
   if ( !dword_591080 )
   {
     if ( !uDialogueType )
@@ -2935,7 +2935,7 @@
           strcpy(pButton->pButtonName, v15);
           continue;
         }
-        sprintf(pTmpBuf.data(), format_4E2D80, TargetColor(0xE1u, 0xCDu, 0x23u), pItemsTable->pItems[contract_approved].pUnidentifiedName);
+        sprintf(pTmpBuf.data(), format_4E2D80, Color16(0xE1u, 0xCDu, 0x23u), pItemsTable->pItems[contract_approved].pUnidentifiedName);
         sprintf(pTmpBuf2.data(), current_npc_text, pTmpBuf.data());
         current_npc_text = pTmpBuf2.data();
         strcpy(pButton->pButtonName, v15);
@@ -2991,7 +2991,7 @@
       case 83:
         v29 = pMonsterStats->pInfos[bountyHunting_monster_id_for_hunting].pName;
         v31 = *(int *)v29;
-        sprintfex(pTmpBuf.data(), "\f%05d%s\f%05d", TargetColor(0xFFu, 0xFFu, 0x9Bu), v31, TargetColor(0xFFu, 0xFFu, 0xFFu));
+        sprintfex(pTmpBuf.data(), "\f%05d%s\f%05d", Color16(0xFFu, 0xFFu, 0x9Bu), v31, Color16(0xFFu, 0xFFu, 0xFFu));
         sprintfex(pTmpBuf2.data(), bountyHunting_text, pTmpBuf.data(), 100 * (unsigned __int8)v29[8]);
         current_npc_text = pTmpBuf2.data();
         strcpy(pButton->pButtonName, "");
@@ -3036,9 +3036,9 @@
       pButton->uHeight = pTextHeight;
       v40 = pButton->uY + pTextHeight - 1;
       pButton->uW = v40;
-      pTextColor = TargetColor(0xE1u, 0xCDu, 0x23u);
+      pTextColor = Color16(0xE1u, 0xCDu, 0x23u);
       if ( pDialogueWindow->pCurrentPosActiveItem != i )
-        pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+        pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
       right_panel_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pButton->pButtonName, 3);
     }
   }
@@ -3069,5 +3069,5 @@
   jail_dialogue_window.uFrameWidth = 148;
   jail_dialogue_window.uFrameZ = 334;
   jail_dialogue_window.DrawTitleText(pFontArrus, 0, (310 - pFontArrus->CalcTextHeight(pGlobalTXT_LocalizationStrings[672], &jail_dialogue_window, 0, 0)) / 2 + 18,
-     TargetColor(0xFFu, 0xFFu, 0x9Bu), pGlobalTXT_LocalizationStrings[672], 3);//"           ."
+     Color16(0xFFu, 0xFFu, 0x9Bu), pGlobalTXT_LocalizationStrings[672], 3);//"           ."
 }
\ No newline at end of file
--- a/UI/UIMainMenu.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIMainMenu.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -20,8 +20,10 @@
 //----- (0041B578) --------------------------------------------------------
 void MainMenuUI_LoadFontsAndSomeStuff()
 {
-  pIcons_LOD->SetupPalettes(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
-  pPaletteManager->SetColorChannelInfo(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
+  //pIcons_LOD->SetupPalettes(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
+  pIcons_LOD->SetupPalettes(5, 6, 5);
+  //pPaletteManager->SetColorChannelInfo(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
+  pPaletteManager->SetColorChannelInfo(5, 6, 5);
   pPaletteManager->RecalculateAll();
 
   for (uint i = 0; i < 480; ++i)
@@ -244,7 +246,7 @@
   cred_texture.uHeight = pFontQuick->GetStringHeight2(pFontCChar, cred_texturet, &credit_window, 0, 1) + 2 * credit_window.uFrameHeight;
   cred_texture.uNumPixels = cred_texture.uWidth * cred_texture.uHeight;
   cred_texture.pPixels = (unsigned __int16 *)malloc(2 * cred_texture.uNumPixels);
-  fill_pixels_fast(TargetColor(0, 0xFFu, 0xFFu), cred_texture.pPixels, cred_texture.uNumPixels);
+  fill_pixels_fast(Color16(0, 0xFFu, 0xFFu), cred_texture.pPixels, cred_texture.uNumPixels);
   cred_texture._allocation_flags = 0;
 
   //    
@@ -252,7 +254,7 @@
   strncpy(pString, cred_texturet, pSize);
   pString[pSize] = 0;
   pFontQuick->_44D2FD_prolly_draw_credits_entry(pFontCChar, 0, credit_window.uFrameHeight, cred_texture.uWidth,
-    cred_texture.uHeight, TargetColor(0x70u, 0x8Fu, 0xFEu), TargetColor(0xECu, 0xE6u, 0x9Cu), pString, cred_texture.pPixels, cred_texture.uWidth);
+    cred_texture.uHeight, Color16(0x70u, 0x8Fu, 0xFEu), Color16(0xECu, 0xE6u, 0x9Cu), pString, cred_texture.pPixels, cred_texture.uWidth);
   free(pString);
 
   pWindow_MainMenu = GUIWindow::Create(0, 0, 640, 480, WINDOW_MainMenu, 0, cred_texturet);
--- a/UI/UIOptions.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIOptions.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -42,7 +42,7 @@
     else
       intensity = + 70 - 70 * time / 800;
 
-    return TargetColor(185 + intensity, 40 + intensity / 4, 40 + intensity / 4);
+    return Color16(185 + intensity, 40 + intensity / 4, 40 + intensity / 4);
   }
 
   return ui_gamemenu_keys_key_default_color;
--- a/UI/UIPartyCreation.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIPartyCreation.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -193,7 +193,7 @@
     pGUIWindow_CurrentMenu->DrawTextInRect(pFontCreate, pIntervalX + 72, pIntervalY + 12, 0, pTmpBuf.data(), 130, 0);//Race Name
 
     pTextCenter = pFontCreate->AlignText_Center(150, pText);
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + uX - 24, 291, TargetColor(0xD1, 0xBB, 0x61), pText, 0, 0, 0); // Skills
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + uX - 24, 291, Color16(0xD1, 0xBB, 0x61), pText, 0, 0, 0); // Skills
 
     uStatLevel = pParty->pPlayers[i].GetActualMight();
     sprintf(pTmpBuf.data(), "%s\r%03d%d", pGlobalTXT_LocalizationStrings[144], pX_Numbers, uStatLevel);// "Might"
@@ -234,27 +234,27 @@
     pSkillsType = pParty->pPlayers[i].GetSkillIdxByOrder(0);
     pTextCenter = pFontCreate->AlignText_Center(150, pSkillNames[pSkillsType]);
     sprintf(pTmpBuf.data(), "\t%03u%s", pTextCenter, pSkillNames[pSkillsType]);
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, uX - 24, 311, TargetColor(0xFF, 0xFF, 0xFF), pTmpBuf.data(), 0, 0, 0);
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, uX - 24, 311, Color16(0xFF, 0xFF, 0xFF), pTmpBuf.data(), 0, 0, 0);
 
     pSkillsType = pParty->pPlayers[i].GetSkillIdxByOrder(1);
     pTextCenter = pFontCreate->AlignText_Center(150, pSkillNames[pSkillsType]);
     sprintf(pTmpBuf.data(), "\t%03u%s", pTextCenter, pSkillNames[pSkillsType]);
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, uX - 24, pIntervalY + 311, TargetColor(0xFF, 0xFF, 0xFF), pTmpBuf.data(), 0, 0, 0);
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, uX - 24, pIntervalY + 311, Color16(0xFF, 0xFF, 0xFF), pTmpBuf.data(), 0, 0, 0);
 
     pSkillsType = pParty->pPlayers[i].GetSkillIdxByOrder(2);
     pTextCenter = pFontCreate->AlignText_Center(150, pSkillNames[pSkillsType]);
     sprintf(pTmpBuf.data(), "\t%03u%s", pTextCenter, pSkillNames[pSkillsType]);
-    pColorText = TargetColor(0, 0xFF, 0);
+    pColorText = Color16(0, 0xFF, 0);
     if ( (signed int)pSkillsType >= 37 )
-      pColorText = TargetColor(0, 0xF7, 0xF7);
+      pColorText = Color16(0, 0xF7, 0xF7);
     pGUIWindow_CurrentMenu->DrawText(pFontCreate, uX - 24, 2 * pIntervalY + 311, pColorText, pTmpBuf.data(), 0, 0, 0);
 
     pSkillsType = pParty->pPlayers[i].GetSkillIdxByOrder(3);
     pTextCenter = pFontCreate->AlignText_Center(150, pSkillNames[pSkillsType]);
     sprintf(pTmpBuf.data(), "\t%03u%s", pTextCenter, pSkillNames[pSkillsType]);
-    pColorText = TargetColor(0, 0xFF, 0);
+    pColorText = Color16(0, 0xFF, 0);
     if ( (signed int)pSkillsType >= 37 )
-      pColorText = TargetColor(0, 0xF7, 0xF7);
+      pColorText = Color16(0, 0xF7, 0xF7);
     pGUIWindow_CurrentMenu->DrawText(pFontCreate, uX - 24, 3 * pIntervalY + 311, pColorText, pTmpBuf.data(), 0, 0, 0);
 
     pIntervalX += 159;
@@ -268,64 +268,64 @@
 
   uClassType = pParty->pPlayers[uPlayerCreationUI_SelectedCharacter].classType;
   pTextCenter = pFontCreate->AlignText_Center(193, pText);
-  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 324, 395, TargetColor(0xD1, 0xBB, 0x61), pText, 0, 0, 0);//Classes
+  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 324, 395, Color16(0xD1, 0xBB, 0x61), pText, 0, 0, 0);//Classes
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[0]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 323, 417, pColorText, pClassNames[0], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_PALADIN )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[12]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 323, pIntervalY + 417, pColorText, pClassNames[12], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_DRUID )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[20]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 323, 2 * pIntervalY + 417, pColorText, pClassNames[20], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_CLERIC )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[24]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 388, 417, pColorText, pClassNames[24], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_DRUID)
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[28]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 388, pIntervalY + 417, pColorText, pClassNames[28], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_SORCERER )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[32]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 388, 2 * pIntervalY + 417, pColorText, pClassNames[32], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_ARCHER )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[16]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 453, 417, pColorText, pClassNames[16], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_MONK )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[8]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 453, pIntervalY + 417, pColorText, pClassNames[8], 0, 0, 0);
 
-  pColorText = TargetColor(0, 0xF7, 0xF7);
+  pColorText = Color16(0, 0xF7, 0xF7);
   if ( uClassType != PLAYER_CLASS_THEIF )
-    pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+    pColorText = Color16(0xFF, 0xFF, 0xFF);
   pTextCenter = pFontCreate->AlignText_Center(65, pClassNames[4]);
   pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 453, 2 * pIntervalY + 417, pColorText, pClassNames[4], 0, 0, 0);
 
   pTextCenter = pFontCreate->AlignText_Center(236, pGlobalTXT_LocalizationStrings[20]); // "Available Skills"
-  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 37, 395, TargetColor(0xD1, 0xBB, 0x61), pGlobalTXT_LocalizationStrings[20], 0, 0, 0);
+  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 37, 395, Color16(0xD1, 0xBB, 0x61), pGlobalTXT_LocalizationStrings[20], 0, 0, 0);
   for (uint i = 0; i < 9; ++i)
   {
     pSkillId = pParty->pPlayers[uPlayerCreationUI_SelectedCharacter].GetSkillIdxByOrder(i + 4);
@@ -351,19 +351,19 @@
     pCorrective = -10;//-5
     if ( (signed int)pLenText < 8 )//if ( (signed int)v124 > 2 )
       pCorrective = 0;
-    pColorText = TargetColor(0, 0xF7, 0xF7);
+    pColorText = Color16(0, 0xF7, 0xF7);
     if ( !pParty->pPlayers[uPlayerCreationUI_SelectedCharacter].pActiveSkills[pSkillId] )
-      pColorText = TargetColor(0xFF, 0xFF, 0xFF);
+      pColorText = Color16(0xFF, 0xFF, 0xFF);
     pTextCenter = pFontCreate->AlignText_Center(100, pText);
     pGUIWindow_CurrentMenu->DrawText(pFontCreate, 100 * (i / 3) + pTextCenter + pCorrective + 17, pIntervalY * (i % 3) + 417, pColorText, pText, 0, 0, 0);
   }
 
   pTextCenter = pFontCreate->AlignText_Center(0x5C, pGlobalTXT_LocalizationStrings[30]);// "Bonus"
-  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 533, 394, TargetColor(0xD1, 0xBB, 0x61), pGlobalTXT_LocalizationStrings[30], 0, 0, 0);
+  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 533, 394, Color16(0xD1, 0xBB, 0x61), pGlobalTXT_LocalizationStrings[30], 0, 0, 0);
   pBonusNum = PlayerCreation_GetUnspentAttributePointCount();
   sprintf(pTmpBuf.data(), "%d", pBonusNum);
   pTextCenter = pFontCreate->AlignText_Center(84, pTmpBuf.data());
-  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 530, 410, TargetColor(0xFF, 0xFF, 0xFF), pTmpBuf.data(), 0, 0, 0);
+  pGUIWindow_CurrentMenu->DrawText(pFontCreate, pTextCenter + 530, 410, Color16(0xFF, 0xFF, 0xFF), pTmpBuf.data(), 0, 0, 0);
   if ( GameUI_Footer_TimeLeft > GetTickCount() )
   {
     message_window.Hint = pGlobalTXT_LocalizationStrings[412];// "Create Party cannot be completed unless you have assigned all characters 2 extra skills and have spent all of your bonus points."
--- a/UI/UIPopup.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIPopup.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -125,6 +125,10 @@
   int v85;
   char *Str; // [sp+270h] [bp-8h]@65
 
+  int r_mask = 0xF800;
+  int g_mask = 0x7E0;
+  int b_mask = 0x1F;
+
   if (!inspect_item->uItemID)
     return;
   iteminfo_window.Hint = 0;
@@ -203,9 +207,9 @@
       pText = (char *)inspect_item->GetIdentifiedName();
     else
       pText = pItemsTable->pItems[inspect_item->uItemID].pUnidentifiedName;
-    iteminfo_window.DrawTitleText(pFontArrus, 0, 0xCu, TargetColor(0xFFu, 0xFFu, 0x9Bu), pText, 3);
+    iteminfo_window.DrawTitleText(pFontArrus, 0, 0xCu, Color16(0xFFu, 0xFFu, 0x9Bu), pText, 3);
     iteminfo_window.DrawTitleText(pFontArrus, 0x64u, ((signed int)iteminfo_window.uFrameHeight >> 1) - pFontArrus->CalcTextHeight(pGlobalTXT_LocalizationStrings[32], &iteminfo_window, 0, 0) / 2,
-                   TargetColor(0xFFu, 0x19u, 0x19u), pGlobalTXT_LocalizationStrings[32], 3); //"Broken Item"
+                   Color16(0xFFu, 0x19u, 0x19u), pGlobalTXT_LocalizationStrings[32], 3); //"Broken Item"
     pRenderer->ResetTextureClipRect();
     if ( !areWeLoadingTexture )
     {
@@ -224,9 +228,9 @@
     iteminfo_window.uFrameZ = iteminfo_window.uFrameX + iteminfo_window.uFrameWidth - 1;
     iteminfo_window.uFrameW = iteminfo_window.uFrameY + iteminfo_window.uFrameHeight - 1;
     pRenderer->DrawTextureTransparent(iteminfo_window.uFrameX + v78, v81 + iteminfo_window.uFrameY + 30, pIcons_LOD->LoadTexturePtr(inspect_item->GetIconName(), TEXTURE_16BIT_PALETTE));
-    iteminfo_window.DrawTitleText(pFontArrus, 0, 0xCu, TargetColor(0xFFu, 0xFFu, 0x9Bu), pItemsTable->pItems[inspect_item->uItemID].pUnidentifiedName, 3);
+    iteminfo_window.DrawTitleText(pFontArrus, 0, 0xCu, Color16(0xFFu, 0xFFu, 0x9Bu), pItemsTable->pItems[inspect_item->uItemID].pUnidentifiedName, 3);
     iteminfo_window.DrawTitleText(pFontArrus, 0x64u, ((signed int)iteminfo_window.uFrameHeight >> 1) - pFontArrus->CalcTextHeight(pGlobalTXT_LocalizationStrings[232], &iteminfo_window, 0, 0) / 2,
-                        TargetColor(0xFFu, 0x19u, 0x19u), pGlobalTXT_LocalizationStrings[232], 3);//"Not Identified"
+                        Color16(0xFFu, 0x19u, 0x19u), pGlobalTXT_LocalizationStrings[232], 3);//"Not Identified"
     pRenderer->ResetTextureClipRect();
     if ( !areWeLoadingTexture )
     {
@@ -314,7 +318,7 @@
                                      TEXTURE_16BIT_PALETTE)->uTextureHeight + v81 + 54;
   if ( (signed int)Str > (signed int)iteminfo_window.uFrameHeight )
     iteminfo_window.uFrameHeight = (unsigned int)Str;
-  if ( inspect_item->uAttributes & 8 && (inspect_item->uSpecEnchantmentType || inspect_item->uEnchantmentType) )
+  if ( inspect_item->uAttributes & ITEM_TEMP_BONUS && (inspect_item->uSpecEnchantmentType || inspect_item->uEnchantmentType) )
     iteminfo_window.uFrameHeight += LOBYTE(pFontComic->uFontHeight);
   v85 = 0;
   if ( pFontArrus->uFontHeight )
@@ -355,7 +359,7 @@
     iteminfo_window.DrawText(pFontSmallnum, 100, v34, 0, v28, 0, 0, 0);
   iteminfo_window.uFrameX += 12;
   iteminfo_window.uFrameWidth -= 24;
-  iteminfo_window.DrawTitleText(pFontArrus, 0, 0xCu, TargetColor(0xFFu, 0xFFu, 0x9Bu), inspect_item->GetIdentifiedName(), 3);
+  iteminfo_window.DrawTitleText(pFontArrus, 0, 0xCu, Color16(0xFFu, 0xFFu, 0x9Bu), inspect_item->GetIdentifiedName(), 3);
   iteminfo_window.uFrameWidth += 24;
   iteminfo_window.uFrameX -= 12;
   if ( v77 )
@@ -366,7 +370,7 @@
   }
   else
   {
-    if ( (inspect_item->uAttributes & 8) && (inspect_item->uSpecEnchantmentType || inspect_item->uEnchantmentType) )
+    if ( (inspect_item->uAttributes & ITEM_TEMP_BONUS) && (inspect_item->uSpecEnchantmentType || inspect_item->uEnchantmentType) )
     {
       init_summoned_item(&v67, inspect_item->uExpireTime - pParty->uTimePlayed);
       strcpy(pTmpBuf.data(), "Duration:");
@@ -393,11 +397,11 @@
     }
     sprintf(pTmpBuf.data(), "%s: %lu", pGlobalTXT_LocalizationStrings[465], inspect_item->GetValue());
     iteminfo_window.DrawText(pFontComic, 100, iteminfo_window.uFrameHeight - LOBYTE(pFontComic->uFontHeight), 0, pTmpBuf.data(), 0, 0, 0);
-    if ( BYTE1(inspect_item->uAttributes) & 1 )
+    if ( inspect_item->uAttributes & ITEM_STOLEN )
       pText = pGlobalTXT_LocalizationStrings[187]; //"Stolen"
     else
     {
-      if ( !(BYTE1(inspect_item->uAttributes) & 2) )
+      if ( !(inspect_item->uAttributes & ITEM_HARDENED) )
       {
         pRenderer->ResetTextureClipRect();
         if ( !areWeLoadingTexture )
@@ -409,7 +413,7 @@
       }
       pText = pGlobalTXT_LocalizationStrings[651]; //"Hardened"
     }
-    LOWORD(inspect_item->uAttributes) = LOWORD(pRenderer->uTargetRMask);
+    LOWORD(inspect_item->uAttributes) = r_mask;
     iteminfo_window.DrawText(pFontComic, pFontComic->GetLineWidth(pTmpBuf.data()) + 132,
           iteminfo_window.uFrameHeight - LOBYTE(pFontComic->uFontHeight), inspect_item->uAttributes, pText, 0, 0, 0);
     pRenderer->ResetTextureClipRect();
@@ -485,9 +489,8 @@
     memcpy(&pMonsterInfoUI_Doll, &pActors[uActorID], sizeof(pMonsterInfoUI_Doll));
     pMonsterInfoUI_Doll.uCurrentActionAnimation = ANIM_Bored;
     pMonsterInfoUI_Doll.uCurrentActionTime = 0;
-    v8 = rand();
-    v9 = v8 % 256 + 128;
-    pMonsterInfoUI_Doll.uCurrentActionLength = v8 % 256 + 128;
+    v9 = rand() % 256 + 128;
+    pMonsterInfoUI_Doll.uCurrentActionLength = v9;
   }
 
   if ( (signed int)pMonsterInfoUI_Doll.uCurrentActionTime > (signed __int16)v9 )
@@ -523,11 +526,11 @@
   v106.pPalette = PaletteManager::Get_Dark_or_Red_LUT(v10->uPaletteIndex, 0, 1);
   v106.sZValue = 0;
   v106.uFlags = 0;
-  pRenderer->SetRasterClipRect(0, 0, 0x27Fu, 0x1DFu);
-  pRenderer->RasterLine2D(v106.uViewportX - 1, v106.uViewportY - 1, v106.uViewportX + 129, v106.uViewportY - 1, TargetColor(0xE1u, 255, 0x9Bu));
-  pRenderer->RasterLine2D( v106.uViewportX + 129,  v106.uViewportY - 1,  v106.uViewportX + 129,    v106.uViewportW + 1, TargetColor(0xE1u, 255, 0x9Bu));
-  pRenderer->RasterLine2D(v106.uViewportX + 129, v106.uViewportW + 1, v106.uViewportX - 1, v106.uViewportW + 1, TargetColor(0xE1u, 255, 0x9Bu));
-  pRenderer->RasterLine2D(v106.uViewportX - 1, v106.uViewportW + 1, v106.uViewportX - 1, v106.uViewportY - 1, TargetColor(0xE1u, 255, 0x9Bu));
+  pRenderer->SetRasterClipRect(0, 0, 639, 479);
+  pRenderer->RasterLine2D(v106.uViewportX - 1, v106.uViewportY - 1, v106.uViewportX + 129, v106.uViewportY - 1, Color16(0xE1u, 255, 0x9Bu));//  
+  pRenderer->RasterLine2D(v106.uViewportX - 1, v106.uViewportW + 1, v106.uViewportX - 1, v106.uViewportY - 1, Color16(0xE1u, 255, 0x9Bu));//  
+  pRenderer->RasterLine2D(v106.uViewportX + 129, v106.uViewportW + 1, v106.uViewportX - 1, v106.uViewportW + 1, Color16(0xE1u, 255, 0x9Bu));//  
+  pRenderer->RasterLine2D(v106.uViewportX + 129, v106.uViewportY - 1, v106.uViewportX + 129, v106.uViewportW + 1, Color16(0xE1u, 255, 0x9Bu));//  
   if ( pRenderer->pRenderD3D )
   {
     v106.uScreenSpaceY = v115 + v106.uViewportY + pSprites_LOD->pHardwareSprites[v10->pHwSpriteIDs[0]].uBufferHeight;
@@ -568,7 +571,7 @@
     ErrD3D(pRenderer->pBackBuffer4->Blt(&v84, 0, 0, 16778240u, &Dst));
     if ( pRenderer->uTargetGBits == 5 )
     {
-      __debugbreak(); // no monster popup for r5g5b5 yet
+      __debugbreak(); // no monster popup for r5g5b5 will be
       memset(&pDesc, 0, 0x7Cu);
       pDesc.dwSize = 124;
       if ( pRenderer->LockSurface_DDraw4(pSprites_LOD->pHardwareSprites[v10->pHwSpriteIDs[0]].pTextureSurface, &pDesc, DDLOCK_WAIT))
@@ -578,7 +581,7 @@
         if (dst_y < dst_w)
         {
           v21 = dst_x;
-          v22 = &pRenderer->pTargetSurface[dst_y * pRenderer->uTargetSurfacePitch + dst_x];
+          //v22 = &pRenderer->pTargetSurface[dst_y * pRenderer->uTargetSurfacePitch + dst_x];
           ushort* _v22_2 = v22;
           v23 = i - dst_y;
           v115 = i - dst_y;
@@ -623,7 +626,7 @@
         uint num_top_scanlines_above_frame_y = i - dst_y;
         for (uint y = dst_y; y < dst_w; ++y)
         {
-          ushort* dst = &pRenderer->pTargetSurface[y * pRenderer->uTargetSurfacePitch + dst_x];
+          //ushort* dst = &pRenderer->pTargetSurface[y * pRenderer->uTargetSurfacePitch + dst_x];
 
           uint src_y = num_top_scanlines_above_frame_y + y;
           for (uint x = dst_x; x < dst_z; ++x)
@@ -633,7 +636,8 @@
             uint idx = pDesc.dwHeight * src_y / pSprites_LOD->pHardwareSprites[v10->pHwSpriteIDs[0]].uAreaHeight * (pDesc.lPitch / sizeof(short)) +
                        pDesc.dwWidth  * src_x / pSprites_LOD->pHardwareSprites[v10->pHwSpriteIDs[0]].uAreaWidth;
             uint b = src[idx] & 0x1F;
-            *dst++ = b | 2 * (src[idx] & 0xFFE0);
+            //*dst++ = b | 2 * (src[idx] & 0xFFE0);
+            pRenderer->WritePixel16(x, y, b | 2 * (src[idx] & 0xFFE0));
           }
         }
         pSprites_LOD->pHardwareSprites[v10->pHwSpriteIDs[0]].pTextureSurface->Unlock(0);
@@ -661,7 +665,7 @@
     else
       strncpy(pTmpBuf.data(), pMonsterStats->pInfos[pActors[uActorID].pMonsterInfo.uID].pName, 2000);
   }
-  window->DrawTitleText(pFontComic, 0, 0xCu, TargetColor(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
+  window->DrawTitleText(pFontComic, 0, 0xCu, Color16(0xFFu, 0xFFu, 0x9Bu), pTmpBuf.data(), 3);
   //health bar
   Actor::DrawHealthBar(&pActors[uActorID], window);
 
@@ -733,9 +737,9 @@
     for_effects = 1;
   }
 
-  window->DrawText(pFontSmallnum, 12, 196, TargetColor(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[631], 0, 0, 0);//Effects
+  window->DrawText(pFontSmallnum, 12, 196, Color16(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[631], 0, 0, 0);//Effects
   if ( !for_effects )
-    window->DrawText(pFontSmallnum, 28, LOBYTE(pFontSmallnum->uFontHeight) + 193, TargetColor(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[630], 0, 0, 0);//?
+    window->DrawText(pFontSmallnum, 28, LOBYTE(pFontSmallnum->uFontHeight) + 193, Color16(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[630], 0, 0, 0);//?
   else
   {
     pText = "";
@@ -839,24 +843,24 @@
       }
     }
     if ( pText == "" )
-      window->DrawText(pFontSmallnum, 28, pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[153], 0, 0, 0);//
+      window->DrawText(pFontSmallnum, 28, pTextHeight, Color16(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[153], 0, 0, 0);//
   }
 
   if ( normal_level )
   {
     sprintf(pTmpBuf.data(), "%s\f%05u\t100%d\n", pGlobalTXT_LocalizationStrings[108], 0, pActors[uActorID].pMonsterInfo.uHP);
-    window->DrawText(pFontSmallnum, 150, (int)v106.uViewportY, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+    window->DrawText(pFontSmallnum, 150, (int)v106.uViewportY, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
     pTextHeight = v106.uViewportY + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     sprintf(pTmpBuf.data(), "%s\f%05u\t100%d\n", pGlobalTXT_LocalizationStrings[12], 0, pActors[uActorID].pMonsterInfo.uAC);//Armor Class
   }
   else
   {
     sprintf(pTmpBuf.data(), "%s\f%05u\t100%s\n", pGlobalTXT_LocalizationStrings[108], 0, pGlobalTXT_LocalizationStrings[630]);//?
-    window->DrawText(pFontSmallnum, 150, (int)v106.uViewportY, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+    window->DrawText(pFontSmallnum, 150, (int)v106.uViewportY, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
     pTextHeight = v106.uViewportY + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     sprintf(pTmpBuf.data(), "%s\f%05u\t100%s\n", pGlobalTXT_LocalizationStrings[12], 0, (unsigned int)pGlobalTXT_LocalizationStrings[630]);//?
   }
-  window->DrawText(pFontSmallnum, 150, pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+  window->DrawText(pFontSmallnum, 150, pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
   pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 6 + LOBYTE(pFontSmallnum->uFontHeight);
 
   content[0] = pGlobalTXT_LocalizationStrings[87];
@@ -874,7 +878,7 @@
   if ( expert_level )
   {
     sprintf(pTmpBuf.data(), "%s\f%05u\t080%s\n", pGlobalTXT_LocalizationStrings[18], 0, content[pActors[uActorID].pMonsterInfo.uAttack1Type]);//Attack
-    window->DrawText(pFontSmallnum, 150, (int)pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+    window->DrawText(pFontSmallnum, 150, (int)pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
     pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     if ( pActors[uActorID].pMonsterInfo.uAttack1DamageBonus )
       sprintf(pTmpBuf.data(), "%s\f%05u\t080%dd%d+%d\n", pGlobalTXT_LocalizationStrings[53],
@@ -886,17 +890,17 @@
   else
   {
     sprintf(pTmpBuf.data(), "%s\f%05u\t080%s\n", pGlobalTXT_LocalizationStrings[18], 0, pGlobalTXT_LocalizationStrings[630]);
-    window->DrawText(pFontSmallnum, 150, (int)pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+    window->DrawText(pFontSmallnum, 150, (int)pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
     pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     sprintf(pTmpBuf.data(), "%s\f%05u\t080%s\n", pGlobalTXT_LocalizationStrings[53], 0, pGlobalTXT_LocalizationStrings[630]);
   }
-  window->DrawText(pFontSmallnum, 150, pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+  window->DrawText(pFontSmallnum, 150, pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
   pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 6 + LOBYTE(pFontSmallnum->uFontHeight);
 
   if ( !master_level )
   {
     sprintf(pTmpBuf.data(), "%s\f%05u\t080%s\n", pGlobalTXT_LocalizationStrings[628], 0, pGlobalTXT_LocalizationStrings[630]);//"Spell" "?"
-    window->DrawText(pFontSmallnum, 150, (int)pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+    window->DrawText(pFontSmallnum, 150, (int)pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
     pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
   }
   else
@@ -907,24 +911,24 @@
     if ( pActors[uActorID].pMonsterInfo.uSpell1ID )
     {
       sprintf(pTmpBuf.data(), "%s\f%05u\t070%s\n", pText, 0, pSpellStats->pInfos[pActors[uActorID].pMonsterInfo.uSpell1ID].pShortName);//"%s\f%05u\t060%s\n"
-      window->DrawText(pFontSmallnum, 150, (int)pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+      window->DrawText(pFontSmallnum, 150, (int)pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
       pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     }
     if ( pActors[uActorID].pMonsterInfo.uSpell2ID )
     {
       sprintf(pTmpBuf.data(), "\f%05u\t070%s\n", 0, pSpellStats->pInfos[pActors[uActorID].pMonsterInfo.uSpell2ID].pShortName);//"%s\f%05u\t060%s\n"
-      window->DrawText(pFontSmallnum, 150, (int)pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+      window->DrawText(pFontSmallnum, 150, (int)pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
       pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     }
     if ( !pActors[uActorID].pMonsterInfo.uSpell1ID && !pActors[uActorID].pMonsterInfo.uSpell2ID )
     {
       sprintf(pTmpBuf.data(), "%s\f%05u\t070%s\n", pGlobalTXT_LocalizationStrings[628], 0, pGlobalTXT_LocalizationStrings[153]);//"%s\f%05u\t060%s\n"
-      window->DrawText(pFontSmallnum, 150, (int)pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+      window->DrawText(pFontSmallnum, 150, (int)pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
       pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     }
   }
   pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
-  window->DrawText(pFontSmallnum, 150, pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[626], 0, 0, 0);//Immune
+  window->DrawText(pFontSmallnum, 150, pTextHeight, Color16(0xE1u, 255, 0x9Bu), pGlobalTXT_LocalizationStrings[626], 0, 0, 0);//Immune
   pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
 
   string_name[0] = pGlobalTXT_LocalizationStrings[87];//Fire
@@ -965,7 +969,7 @@
           pText = pGlobalTXT_LocalizationStrings[153];//None
       }
       sprintf(pTmpBuf.data(), "%s\f%05u\t070%s\n", string_name[i], 0, pText);
-      window->DrawText(pFontSmallnum, 170, pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+      window->DrawText(pFontSmallnum, 170, pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
       pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     }
   }
@@ -974,7 +978,7 @@
     for ( uint i = 0; i < 10; ++i )
     {
       sprintf(pTmpBuf.data(), "%s\f%05u\t070%s\n", string_name[i], 0, pGlobalTXT_LocalizationStrings[630]); // "?"
-      window->DrawText(pFontSmallnum, 170, pTextHeight, TargetColor(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
+      window->DrawText(pFontSmallnum, 170, pTextHeight, Color16(0xE1u, 255, 0x9Bu), pTmpBuf.data(), 0, 0, 0);
       pTextHeight = pTextHeight + LOBYTE(pFontSmallnum->uFontHeight) - 3;
     }
   }
@@ -1027,7 +1031,7 @@
   }
   else
   {
-    sprintf(Source, "\f%05d", TargetColor(0xFFu, 0xFFu, 0xFFu));
+    sprintf(Source, "\f%05d", Color16(0xFFu, 0xFFu, 0xFFu));
     strcat(a2, Source);
     strcat(a2, "%s: +%d");
     sprintf(static_sub_417BB5_out_string, a2, pSkillDesc[uPlayerSkillType],
@@ -1274,7 +1278,7 @@
   spell_info_window.uFrameHeight -= 12;
   spell_info_window.uFrameZ = spell_info_window.uFrameX + spell_info_window.uFrameWidth - 1;
   spell_info_window.uFrameW = spell_info_window.uFrameHeight + spell_info_window.uFrameY - 1;
-  spell_info_window.DrawTitleText(pFontArrus, 0x78u, 0xCu, TargetColor(0xFFu, 0xFFu, 0x9Bu), spell->pName, 3);
+  spell_info_window.DrawTitleText(pFontArrus, 0x78u, 0xCu, Color16(0xFFu, 0xFFu, 0x9Bu), spell->pName, 3);
   spell_info_window.DrawText(pFontSmallnum, 120, 44, 0, pTmpBuf2.data(), 0, 0, 0);
   spell_info_window.uFrameWidth = 108;
   spell_info_window.uFrameZ = spell_info_window.uFrameX + 107;
@@ -1298,7 +1302,7 @@
   unsigned int pX; // [sp+70h] [bp-8h]@3
   unsigned int pY; // [sp+74h] [bp-4h]@3
 
-  if ( pCurrentScreen == SCREEN_VIDEO )
+  if ( pCurrentScreen == SCREEN_VIDEO || GetCurrentMenuID() == MENU_MAIN )
     return;
   if ( _this )
   {
@@ -1574,7 +1578,7 @@
         popup_window.uFrameHeight -= 12;
         popup_window.uFrameZ = popup_window.uFrameX + popup_window.uFrameWidth - 1;
         popup_window.uFrameW = popup_window.uFrameY + popup_window.uFrameHeight - 1;
-        sprintf(pTmpBuf.data(), "\f%05d%s\f00000\n", TargetColor(0xFF, 0xFF, 0x9B), pStr);
+        sprintf(pTmpBuf.data(), "\f%05d%s\f00000\n", Color16(0xFF, 0xFF, 0x9B), pStr);
         popup_window.DrawTitleText(pFontCreate, 0, 0, 0, pTmpBuf.data(), 3);
         popup_window.DrawText(pFontSmallnum, 1, pFontLucida->uFontHeight, 0, pHint, 0, 0, 0);
       }
--- a/UI/UIRest.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIRest.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -128,16 +128,16 @@
     tmp_button.uWidth = 171;
     tmp_button.uHeight = 37;
     tmp_button.pParent = pButton_RestUI_WaitUntilDawn->pParent;
-    tmp_button.DrawLabel(pGlobalTXT_LocalizationStrings[183], pFontCreate, TargetColor(10, 0, 0), TargetColor(230, 214, 193));//   8 
+    tmp_button.DrawLabel(pGlobalTXT_LocalizationStrings[183], pFontCreate, Color16(10, 0, 0), Color16(230, 214, 193));//   8 
     tmp_button.pParent = 0;
 
     sprintf(pTmpBuf.data(), "\r408%d", uRestUI_FoodRequiredToRest);
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 0, 164, TargetColor(10, 0, 0), pTmpBuf.data(), 0, 0, TargetColor(230, 214, 193));
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 0, 164, Color16(10, 0, 0), pTmpBuf.data(), 0, 0, Color16(230, 214, 193));
 
-    pButton_RestUI_WaitUntilDawn->DrawLabel(pGlobalTXT_LocalizationStrings[237], pFontCreate, TargetColor(10, 0, 0), TargetColor(230, 214, 193));//  
-    pButton_RestUI_Wait1Hour->DrawLabel(pGlobalTXT_LocalizationStrings[239], pFontCreate, TargetColor(10, 0, 0), TargetColor(230, 214, 193));// 1 
-    pButton_RestUI_Wait5Minutes->DrawLabel(pGlobalTXT_LocalizationStrings[238], pFontCreate, TargetColor(10, 0, 0), TargetColor(230, 214, 193));// 5 
-    pButton_RestUI_Exit->DrawLabel(pGlobalTXT_LocalizationStrings[81], pFontCreate, TargetColor(10, 0, 0), TargetColor(230, 214, 193));// 
+    pButton_RestUI_WaitUntilDawn->DrawLabel(pGlobalTXT_LocalizationStrings[237], pFontCreate, Color16(10, 0, 0), Color16(230, 214, 193));//  
+    pButton_RestUI_Wait1Hour->DrawLabel(pGlobalTXT_LocalizationStrings[239], pFontCreate, Color16(10, 0, 0), Color16(230, 214, 193));// 1 
+    pButton_RestUI_Wait5Minutes->DrawLabel(pGlobalTXT_LocalizationStrings[238], pFontCreate, Color16(10, 0, 0), Color16(230, 214, 193));// 5 
+    pButton_RestUI_Exit->DrawLabel(pGlobalTXT_LocalizationStrings[81], pFontCreate, Color16(10, 0, 0), Color16(230, 214, 193));// 
     memset(&tmp_button, 0, sizeof(GUIButton));
     tmp_button.uX = 45;
     tmp_button.uY = 199;
@@ -149,16 +149,16 @@
     tmp_button.uHeight = 30;
 
     tmp_button.pParent = pButton_RestUI_WaitUntilDawn->pParent;
-    tmp_button.DrawLabel(pGlobalTXT_LocalizationStrings[236], pFontCreate, TargetColor(10, 0, 0), TargetColor(230, 214, 193));//  
+    tmp_button.DrawLabel(pGlobalTXT_LocalizationStrings[236], pFontCreate, Color16(10, 0, 0), Color16(230, 214, 193));//  
     tmp_button.pParent = 0;
     sprintf(pTmpBuf.data(), "%d:%02d %s", am_pm_hours, pParty->uCurrentMinute, aAMPMNames[(pParty->uCurrentHour >= 12 && pParty->uCurrentHour < 24)? 1:0]);
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 368, 168, TargetColor(10, 0, 0), pTmpBuf.data(), 0, 0, TargetColor(230, 214, 193));
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 368, 168, Color16(10, 0, 0), pTmpBuf.data(), 0, 0, Color16(230, 214, 193));
     sprintf(pTmpBuf.data(), "%s\r190%d", pGlobalTXT_LocalizationStrings[56], pParty->uDaysPlayed + 1);//
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 350, 190, TargetColor(10, 0, 0), pTmpBuf.data(), 0, 0, TargetColor(230, 214, 193));
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 350, 190, Color16(10, 0, 0), pTmpBuf.data(), 0, 0, Color16(230, 214, 193));
     sprintf(pTmpBuf.data(), "%s\r190%d", pGlobalTXT_LocalizationStrings[146], pParty->uCurrentMonth + 1);//
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 350, 222, TargetColor(10, 0, 0), pTmpBuf.data(), 0, 0, TargetColor(230, 214, 193));
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 350, 222, Color16(10, 0, 0), pTmpBuf.data(), 0, 0, Color16(230, 214, 193));
     sprintf(pTmpBuf.data(), "%s\r190%d", pGlobalTXT_LocalizationStrings[245], pParty->uCurrentYear);//
-    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 350, 254, TargetColor(10, 0, 0), pTmpBuf.data(), 0, 0, TargetColor(230, 214, 193));
+    pGUIWindow_CurrentMenu->DrawText(pFontCreate, 350, 254, Color16(10, 0, 0), pTmpBuf.data(), 0, 0, Color16(230, 214, 193));
     if ( dword_506F14 )
       Sleep6Hours();
   }
--- a/UI/UISaveLoad.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UISaveLoad.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -125,9 +125,9 @@
       if ( slot_Y >= 346 )
         break;
       if ( pGUIWindow_CurrentMenu->receives_keyboard_input_2 != WINDOW_INPUT_IN_PROGRESS || i != uLoadGameUI_SelectedSlot )
-        pGUIWindow_CurrentMenu->DrawTextInRect(pFontSmallnum, 27, slot_Y, i == uLoadGameUI_SelectedSlot ? TargetColor(0xFF, 0xFF, 0x64) : 0, pSavegameHeader[i].pName, 185, 0);
+        pGUIWindow_CurrentMenu->DrawTextInRect(pFontSmallnum, 27, slot_Y, i == uLoadGameUI_SelectedSlot ? Color16(0xFF, 0xFF, 0x64) : 0, pSavegameHeader[i].pName, 185, 0);
       else
-        pGUIWindow_CurrentMenu->DrawFlashingInputCursor(pGUIWindow_CurrentMenu->DrawTextInRect(pFontSmallnum, 27, slot_Y, i == uLoadGameUI_SelectedSlot ? TargetColor(0xFF, 0xFF, 0x64) : 0, (const char *)pKeyActionMap->pPressedKeysBuffer, 175, 1) + 27,
+        pGUIWindow_CurrentMenu->DrawFlashingInputCursor(pGUIWindow_CurrentMenu->DrawTextInRect(pFontSmallnum, 27, slot_Y, i == uLoadGameUI_SelectedSlot ? Color16(0xFF, 0xFF, 0x64) : 0, (const char *)pKeyActionMap->pPressedKeysBuffer, 175, 1) + 27,
            slot_Y, pFontSmallnum);
       slot_Y += 21;
     }
--- a/UI/UIShops.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UIShops.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -61,9 +61,9 @@
           pButton->uHeight = pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0);
           v19 = pButton->uY + pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0) - 1;
           pButton->uW = v19;
-          pColorText = TargetColor(0xE1u, 0xCDu, 0x23u);
+          pColorText = Color16(0xE1u, 0xCDu, 0x23u);
           if ( pDialogueWindow->pCurrentPosActiveItem != i )
-            pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+            pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
           dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, (const char *)pShopOptions[pNumString], 3);
           ++pNumString;
         }
@@ -106,12 +106,12 @@
             {
               pText = BuildDialogueString(pMerchantsBuyPhrases[pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_WeaponShop, (int)window_SpeakInHouse->ptr_1C, 2)],
                                        uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
             }
             else
             {
               pText = BuildDialogueString(pGlobalTXT_LocalizationStrings[181], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
             }
           }
         }
@@ -157,12 +157,12 @@
             {
               pText = BuildDialogueString(pMerchantsBuyPhrases[pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_WeaponShop, (int)window_SpeakInHouse->ptr_1C, 2)],
                                        uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
             }
             else
             {
               pText = BuildDialogueString(pGlobalTXT_LocalizationStrings[181], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+              dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
             }
           }
         }
@@ -189,7 +189,7 @@
       item = &pPlayers[uActiveCharacter]->pInventoryItemList[pItemID - 1];
       phrases_id = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_WeaponShop, (int)window_SpeakInHouse->ptr_1C, 3);
       pText = BuildDialogueString(pMerchantsSellPhrases[phrases_id], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 3, 0);
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       break;
     }
     case HOUSE_DIALOGUE_SHOP_IDENTIFY:
@@ -211,12 +211,12 @@
       {
         phrases_id = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_WeaponShop, (int)window_SpeakInHouse->ptr_1C, 4);
         pText = BuildDialogueString(pMerchantsIdentifyPhrases[phrases_id], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 4, 0);
-        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       }
       else
       {
         pText = BuildDialogueString("%24", uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 4, 0);
-        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       }
       break;
     }
@@ -238,7 +238,7 @@
       item = &pPlayers[uActiveCharacter]->pInventoryItemList[pItemID - 1];
       phrases_id = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_ArmorShop, (int)window_SpeakInHouse->ptr_1C, 5);
       pText = BuildDialogueString(pMerchantsRepairPhrases[phrases_id], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 5, 0);
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       return;
     }
     break;
@@ -263,9 +263,9 @@
         pButton->uHeight = pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0);
         v19 = pButton->uY + pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0) - 1;
         pButton->uW = v19;
-        pColorText = TargetColor(0xE1u, 0xCDu, 0x23u);
+        pColorText = Color16(0xE1u, 0xCDu, 0x23u);
         if ( pDialogueWindow->pCurrentPosActiveItem != i )
-          pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+          pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
         dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, (const char *)pShopOptions[pNumString], 3);
         ++pNumString;
         }
@@ -316,9 +316,9 @@
             pButton->uHeight = pFontArrus->CalcTextHeight(pSkillNames[pButton->msg_param - 36], &dialog_window, 0, 0);
             v19 = pButton->uY + pFontArrus->CalcTextHeight(pSkillNames[pButton->msg_param - 36], &dialog_window, 0, 0) - 1;
             pButton->uW = v19;
-            pColorText = TargetColor(0xE1u, 0xCDu, 0x23u);
+            pColorText = Color16(0xE1u, 0xCDu, 0x23u);
             if ( pDialogueWindow->pCurrentPosActiveItem != i )
-              pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+              pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
             dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, pSkillNames[pButton->msg_param - 36], 3);
           }
         }
@@ -327,7 +327,7 @@
       sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[544], pPlayers[uActiveCharacter]->pName, pClassNames[pPlayers[uActiveCharacter]->classType]);
       strcat(pTmpBuf.data(), "\n \n");
       strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]);//    .
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, Color16(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
       return;
     }
     default:
@@ -387,9 +387,9 @@
         pButton->uHeight = pFontArrus->CalcTextHeight(pShopOptions[pNumString], &dialog_window, 0, 0);
         v23 = pButton->uY + pFontArrus->CalcTextHeight(pShopOptions[pNumString], &dialog_window, 0, 0) - 1;
         pButton->uW = v23;
-        pTextColor = TargetColor(0xE1u, 0xCDu, 0x23u);
+        pTextColor = Color16(0xE1u, 0xCDu, 0x23u);
         if ( pDialogueWindow->pCurrentPosActiveItem != i )
-          pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+          pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
         dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pShopOptions[pNumString], 3);
         ++pNumString;
       }
@@ -441,12 +441,12 @@
         {
           pText = BuildDialogueString(pMerchantsBuyPhrases[pPlayers[uActiveCharacter]->SelectPhrasesTransaction(selected_item, BuildingType_ArmorShop, window_SpeakInHouse->par1C, 2)],
                                  uActiveCharacter - 1, selected_item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
         }
         else
         {
           pText = BuildDialogueString(pGlobalTXT_LocalizationStrings[181], uActiveCharacter - 1, selected_item, (char *)window_SpeakInHouse->ptr_1C, 2, 0); //"Steal %24"
-          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
         }
         return;
       }
@@ -504,12 +504,12 @@
         {
           pText = BuildDialogueString(pMerchantsBuyPhrases[pPlayers[uActiveCharacter]->SelectPhrasesTransaction(selected_item, BuildingType_ArmorShop, window_SpeakInHouse->par1C, 2)],
                  uActiveCharacter - 1, selected_item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
         }
         else
         {
           pText = BuildDialogueString(pGlobalTXT_LocalizationStrings[181], uActiveCharacter - 1, selected_item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);//"Steal %24"
-          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
         }
         return;
       }
@@ -539,9 +539,9 @@
         pButton->uHeight = pFontArrus->CalcTextHeight(pShopOptions[pNumString], &dialog_window, 0, 0);
         v23 = pButton->uY + pFontArrus->CalcTextHeight(pShopOptions[pNumString], &dialog_window, 0, 0) - 1;
         pButton->uW = v23;
-        pTextColor = TargetColor(0xE1u, 0xCDu, 0x23u);
+        pTextColor = Color16(0xE1u, 0xCDu, 0x23u);
         if ( pDialogueWindow->pCurrentPosActiveItem != i )
-          pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+          pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
         dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pShopOptions[pNumString], 3);
         ++pNumString;
       }
@@ -565,7 +565,7 @@
       selected_item = &pPlayers[uActiveCharacter]->pInventoryItemList[pPlayers[uActiveCharacter]->GetItemIDAtInventoryIndex((int *)&v153) - 1];
       pText = BuildDialogueString(pMerchantsSellPhrases[pPlayers[uActiveCharacter]->SelectPhrasesTransaction(selected_item, BuildingType_ArmorShop, window_SpeakInHouse->par1C, 3)],
               uActiveCharacter - 1, selected_item, (char *) window_SpeakInHouse->par1C, 3, 0);
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       return;
     }
     break;
@@ -588,7 +588,7 @@
             else
               pText = BuildDialogueString(pMerchantsIdentifyPhrases[pPlayers[uActiveCharacter]->SelectPhrasesTransaction(selected_item, BuildingType_ArmorShop,
                     (int)window_SpeakInHouse->ptr_1C, 4)], uActiveCharacter - 1, selected_item, (char *)window_SpeakInHouse->ptr_1C, 4, 0);
-            dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+            dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
             return;
           }
         }
@@ -613,7 +613,7 @@
       phrases_id = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(&pPlayers[uActiveCharacter]->pInventoryItemList[pPlayers[uActiveCharacter]->GetItemIDAtInventoryIndex((int *)&v153) - 1],
              BuildingType_ArmorShop, window_SpeakInHouse->par1C, 5);
       pText = BuildDialogueString(pMerchantsRepairPhrases[phrases_id], uActiveCharacter - 1, selected_item, (char *)window_SpeakInHouse->ptr_1C, 5, 0);
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       return;
     }
     break;
@@ -663,9 +663,9 @@
             pButton->uHeight = pFontArrus->CalcTextHeight(pSkillNames[pButton->msg_param - 36], &dialog_window, 0, 0);
             v23 = pButton->uY + pFontArrus->CalcTextHeight(pSkillNames[pButton->msg_param - 36], &dialog_window, 0, 0) - 1;
             pButton->uW = v23;
-            pTextColor = TargetColor(0xE1u, 0xCDu, 0x23u);
+            pTextColor = Color16(0xE1u, 0xCDu, 0x23u);
             if ( pDialogueWindow->pCurrentPosActiveItem != i )
-              pTextColor = TargetColor(0xFFu, 0xFFu, 0xFFu);
+              pTextColor = Color16(0xFFu, 0xFFu, 0xFFu);
             dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pTextColor, pSkillNames[pButton->msg_param - 36], 3);
           }
         }
@@ -674,7 +674,7 @@
       sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[544], pPlayers[uActiveCharacter]->pName, pClassNames[pPlayers[uActiveCharacter]->classType]); //"Seek knowledge elsewhere %s the %s"
       strcat(pTmpBuf.data(), "\n \n");
       strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]); //"I can offer you nothing further."
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, Color16(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
       return;
     }
     break;
@@ -733,9 +733,9 @@
           pButton->uHeight = pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0);
           v105 = pButton->uY + pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0) - 1;
           pButton->uW = v105;
-          pColorText = TargetColor(0xE1u, 0xCDu, 0x23u);
+          pColorText = Color16(0xE1u, 0xCDu, 0x23u);
           if ( pDialogueWindow->pCurrentPosActiveItem != i )
-            pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+            pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
           dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, (const char *)pShopOptions[pNumString], 3);
           ++pNumString;
         }
@@ -821,7 +821,7 @@
           }
           else
             pText = BuildDialogueString(pGlobalTXT_LocalizationStrings[181], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
           return ;
         }
       }
@@ -909,7 +909,7 @@
           }
           else
             pText = BuildDialogueString(pGlobalTXT_LocalizationStrings[181], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
-          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
           return;
         }
       }
@@ -933,7 +933,7 @@
              BuildingType_AlchemistShop, (int)window_SpeakInHouse->ptr_1C, 3);
       pText = BuildDialogueString(pMerchantsSellPhrases[v71], uActiveCharacter - 1, &pPlayers[uActiveCharacter]->pInventoryItemList[pPlayers[uActiveCharacter]->GetItemIDAtInventoryIndex((int *)&index) - 1],
              (char *)window_SpeakInHouse->ptr_1C, 3, 0);
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       return; 
     }
 
@@ -958,7 +958,7 @@
       }
       else
         pText = BuildDialogueString("%24", uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 4, 0);
-      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xFFu, 0xFFu, 0xFFu), pText, 3);
+      dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pText, &dialog_window, 0, 0)) / 2 + 138, Color16(0xFFu, 0xFFu, 0xFFu), pText, 3);
       return;
     }
 
@@ -982,9 +982,9 @@
         pButton->uHeight = pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0);
         v105 = pButton->uY + pFontArrus->CalcTextHeight((const char *)pShopOptions[pNumString], &dialog_window, 0, 0) - 1;
         pButton->uW = v105;
-        pColorText = TargetColor(0xE1u, 0xCDu, 0x23u);
+        pColorText = Color16(0xE1u, 0xCDu, 0x23u);
         if ( pDialogueWindow->pCurrentPosActiveItem != i )
-          pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+          pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
         dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, (const char *)pShopOptions[pNumString], 3);
         ++pNumString;
       }
@@ -1017,7 +1017,7 @@
         sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[544], pPlayers[uActiveCharacter]->pName, pClassNames[pPlayers[uActiveCharacter]->classType]);
         strcat(pTmpBuf.data(), "\n \n");
         strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]);
-        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, TargetColor(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
+        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, Color16(0xE1u, 0xCDu, 0x23u), pTmpBuf.data(), 3);
         return;
       }
       if ( item_num )
@@ -1045,9 +1045,9 @@
             pButton->uHeight = pFontArrus->CalcTextHeight(pSkillNames[pButton->msg_param - 36], &dialog_window, 0, 0);
             v105 = pButton->uY + pFontArrus->CalcTextHeight(pSkillNames[pButton->msg_param - 36], &dialog_window, 0, 0) - 1;
             pButton->uW = v105;
-            pColorText = TargetColor(0xE1u, 0xCDu, 0x23u);
+            pColorText = Color16(0xE1u, 0xCDu, 0x23u);
             if ( pDialogueWindow->pCurrentPosActiveItem != i )
-              pColorText = TargetColor(0xFFu, 0xFFu, 0xFFu);
+              pColorText = Color16(0xFFu, 0xFFu, 0xFFu);
             dialog_window.DrawTitleText(pFontArrus, 0, pButton->uY, pColorText, pSkillNames[pButton->msg_param - 36], 3);
           }
         }
@@ -1108,9 +1108,9 @@
       control_button->uHeight = pFontArrus->CalcTextHeight(pShopOptions[pNumString], &dialog_window, 0, 0);
       v23 = control_button->uY + control_button->uHeight - 1;
       control_button->uW = v23;
-      text_color = TargetColor(225, 205, 35);
+      text_color = Color16(225, 205, 35);
       if ( pDialogueWindow->pCurrentPosActiveItem != i )
-        text_color = TargetColor(255, 255, 255);
+        text_color = Color16(255, 255, 255);
       dialog_window.DrawTitleText(pFontArrus, 0, control_button->uY, text_color, pShopOptions[pNumString], 3);
       ++pNumString;
     }
@@ -1196,7 +1196,7 @@
           v75 = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_MagicShop, (int)window_SpeakInHouse->ptr_1C, 2);
           v30 = BuildDialogueString(pMerchantsBuyPhrases[v75], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
         }
-        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, TargetColor(255, 255, 255), v30, 3);
+        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, Color16(255, 255, 255), v30, 3);
         return;
       }
     }
@@ -1284,7 +1284,7 @@
           v75 = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_MagicShop, (int)window_SpeakInHouse->ptr_1C, 2);
           v30 = BuildDialogueString(pMerchantsBuyPhrases[v75], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 2, 0);
         }
-        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, TargetColor(255, 255, 255), v30, 3);
+        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, Color16(255, 255, 255), v30, 3);
         return;
       }
     }
@@ -1312,9 +1312,9 @@
       control_button->uHeight = pFontArrus->CalcTextHeight(pShopOptions[pSrtingNum], &dialog_window, 0, 0);
       v23 = control_button->uHeight + control_button->uY - 1;
       control_button->uW = v23;
-      text_color = TargetColor(225, 205, 35);
+      text_color = Color16(225, 205, 35);
       if ( pDialogueWindow->pCurrentPosActiveItem != i )
-        text_color = TargetColor(255, 255, 255);
+        text_color = Color16(255, 255, 255);
       dialog_window.DrawTitleText(pFontArrus, 0, control_button->uY, text_color, pShopOptions[pSrtingNum], 3);
       ++pSrtingNum;
     }
@@ -1337,7 +1337,7 @@
     item = &pPlayers[uActiveCharacter]->pInventoryItemList[pPlayers[uActiveCharacter]->GetItemIDAtInventoryIndex((int *)&v117) - 1];
     v75 = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_MagicShop, (int)window_SpeakInHouse->ptr_1C, 3);
     v30 = BuildDialogueString(pMerchantsSellPhrases[v75], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 3, 0);
-    dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, TargetColor(255, 255, 255), v30, 3);
+    dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, Color16(255, 255, 255), v30, 3);
     return;
   }
 
@@ -1355,15 +1355,15 @@
         if ( pPlayers[uActiveCharacter]->GetItemIDAtInventoryIndex((int *)&v117) )
         {
           item = &pPlayers[uActiveCharacter]->pInventoryItemList[pPlayers[uActiveCharacter]->GetItemIDAtInventoryIndex((int *)&v117) - 1];
-          if ( item->uAttributes & 1 )
+          if ( item->uAttributes & ITEM_IDENTIFIED )
           {
             dialog_window.DrawTitleText(pFontArrus, 0, (212 - pFontArrus->CalcTextHeight(BuildDialogueString("%24", uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 4, 0), &dialog_window, 0, 0)) / 2 + 101,
-               TargetColor(255, 255, 255), BuildDialogueString("%24", uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 4, 0), 3); 
+               Color16(255, 255, 255), BuildDialogueString("%24", uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 4, 0), 3); 
             return;
           }
           v75 = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(item, BuildingType_MagicShop, (int)window_SpeakInHouse->ptr_1C, 4);
           v30 = BuildDialogueString(pMerchantsIdentifyPhrases[v75], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 4, 0);
-          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, TargetColor(255, 255, 255), v30, 3);
+          dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, Color16(255, 255, 255), v30, 3);
           return;
         }
       }
@@ -1389,7 +1389,7 @@
     v75 = pPlayers[uActiveCharacter]->SelectPhrasesTransaction(&pPlayers[uActiveCharacter]->pInventoryItemList[pPlayers[uActiveCharacter]->GetItemIDAtInventoryIndex((int *)&v117) - 1],
              BuildingType_MagicShop, (int)window_SpeakInHouse->ptr_1C, 5);
     v30 = BuildDialogueString(pMerchantsRepairPhrases[v75], uActiveCharacter - 1, item, (char *)window_SpeakInHouse->ptr_1C, 5, 0);
-    dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, TargetColor(255, 255, 255), v30, 3);
+    dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(v30, &dialog_window, 0, 0)) / 2 + 138, Color16(255, 255, 255), v30, 3);
     return;
   }
 
@@ -1419,7 +1419,7 @@
                                             // "Seek knowledge elsewhere %s the %s"
         strcat(pTmpBuf.data(), "\n \n");
         strcat(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[528]);// "I can offer you nothing further."
-        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, TargetColor(225, 205, 35), pTmpBuf.data(), 3);
+        dialog_window.DrawTitleText(pFontArrus, 0, (174 - pFontArrus->CalcTextHeight(pTmpBuf.data(), &dialog_window, 0, 0)) / 2 + 138, Color16(225, 205, 35), pTmpBuf.data(), 3);
         return;
       }
       sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[401], pPrice);// "Skill Cost: %lu"
@@ -1445,9 +1445,9 @@
           control_button->uHeight = pFontArrus->CalcTextHeight(pSkillNames[control_button->msg_param - 36], &dialog_window, 0, 0);
           v23 = control_button->uY + control_button->uHeight - 1;
           control_button->uW = v23;
-          text_color = TargetColor(225, 205, 35);
+          text_color = Color16(225, 205, 35);
           if ( pDialogueWindow->pCurrentPosActiveItem != i )
-            text_color = TargetColor(255, 255, 255);
+            text_color = Color16(255, 255, 255);
           dialog_window.DrawTitleText(pFontArrus, 0, control_button->uY, text_color, pSkillNames[control_button->msg_param - 36], 3);
         }
       }
@@ -1564,7 +1564,7 @@
         {
           uPriceItemService = pPlayers[uActiveCharacter]->GetPriceIdentification(p2DEvents[(unsigned int)window_SpeakInHouse->ptr_1C - 1].fPriceMultiplier);
           item = &pPlayers[uActiveCharacter]->pInventoryItemList[pItemID - 1];
-          if ( !(item->uAttributes & 1) )
+          if ( !(item->uAttributes & ITEM_IDENTIFIED) )
           {
             if ( MerchandiseTest(item, (int)window_SpeakInHouse->ptr_1C) )
             {
@@ -1572,7 +1572,7 @@
               {
                 dword_F8B1E4 = 1;
                 Party::TakeGold(uPriceItemService);
-                item->uAttributes |= 1;
+                item->uAttributes |= ITEM_IDENTIFIED;
                 pPlayers[uActiveCharacter]->PlaySound(SPEECH_73, 0);
                 ShowStatusBarString(pGlobalTXT_LocalizationStrings[569], 2);
                 return;
@@ -1604,7 +1604,7 @@
             pPriceMultiplier = p2DEvents[(unsigned int)window_SpeakInHouse->ptr_1C - 1].fPriceMultiplier;
             ItemGen* _v = &pPlayers[uActiveCharacter]->pInventoryItemList[pItemID - 1];
             uPriceItemService = pPlayers[uActiveCharacter]->GetPriceRepair(_v->GetValue(), pPriceMultiplier);
-            if ( item->uAttributes & 2 )
+            if ( item->uAttributes & ITEM_BROKEN )
             {
               if ( MerchandiseTest(item, (int)window_SpeakInHouse->ptr_1C) )
               {
--- a/UI/UiGame.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/UI/UiGame.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -31,7 +31,7 @@
 #include "..\texts.h"
 #include "UIHouses.h"
 #include "..\BSPModel.h"
-#include "OurMath.h"
+#include "..\OurMath.h"
 #include "..\Level/Decoration.h"
 
 
@@ -230,7 +230,7 @@
           v11 = pTmpBuf.data();
           strcpy(pTmpBuf.data(), pNPC->pName);
         }
-        popup_window.DrawTitleText(pFontArrus, 0, 12, TargetColor(0xFFu, 0xFFu, 0x9Bu), v11, 3);
+        popup_window.DrawTitleText(pFontArrus, 0, 12, Color16(0xFFu, 0xFFu, 0x9Bu), v11, 3);
         popup_window.uFrameWidth -= 24;
         popup_window.uFrameZ = popup_window.uFrameX + popup_window.uFrameWidth - 1;
         popup_window.DrawText(pFontArrus, 100, 36, 0, BuildDialogueString((char *)lpsz, uActiveCharacter - 1, 0, 0, 0, 0), 0, 0, 0);
@@ -310,20 +310,24 @@
   }
   if (sDialogue_SpeakingActorNPC_ID < 0)
     v9 = 4;
-  pDialogueWindow = GUIWindow::Create(0, 0, 640, 480, WINDOW_Dialogue, v9, 0);//pNumberContacts = 1, v9 = 0; pNumberContacts = 2, v9 = 3;
-  if (pNPCInfo->Hired())
+  pDialogueWindow = GUIWindow::Create(0, 0, 640, 480, WINDOW_Dialogue, 3, 0);//pNumberContacts = 1, v9 = 0; pNumberContacts = 2, v9 = 3;
+  if (pNPCInfo->Hired() && !pNPCInfo->bHasUsedTheAbility)
   {
-    if ( !pNPCInfo->bHasUsedTheAbility )
+    if (pNPCInfo->uProfession == 10 ||    //Healer
+        pNPCInfo->uProfession == 11 ||    //Expert Healer
+        pNPCInfo->uProfession == 12 ||    //Master Healer
+        pNPCInfo->uProfession == 33 ||    //Cook
+        pNPCInfo->uProfession == 34 ||    //Chef
+        pNPCInfo->uProfession == 39 ||    //Wind Master
+        pNPCInfo->uProfession == 40 ||    //Water Master
+        pNPCInfo->uProfession == 41 ||    //Gate Master
+        pNPCInfo->uProfession == 42 ||    //Chaplain
+        pNPCInfo->uProfession == 43 ||    //Piper
+        pNPCInfo->uProfession == 52       //Fallen Wizard
+      )
     {
-      if ( pNPCInfo->uProfession >= 10 )
-      {
-        if ( pNPCInfo->uProfession <= 12 || pNPCInfo->uProfession > 32 && (pNPCInfo->uProfession <= 34 
-             || pNPCInfo->uProfession > 38 && (pNPCInfo->uProfession <= 43 || pNPCInfo->uProfession == 52)) )
-        {
-          pDialogueWindow->CreateButton(480, 250, 140, LOBYTE(pFontArrus->uFontHeight) - 3, 1, 0, UIMSG_SelectNPCDialogueOption, 9, 0, "", 0);
-          pDialogueWindow->_41D08F_set_keyboard_control_group(4, 1, 0, 1);
-        }
-      }
+      pDialogueWindow->CreateButton(480, 250, 140, LOBYTE(pFontArrus->uFontHeight) - 3, 1, 0, UIMSG_SelectNPCDialogueOption, 9, 0, "", 0);
+      pDialogueWindow->_41D08F_set_keyboard_control_group(4, 1, 0, 1);
     }
   }
 
@@ -421,7 +425,7 @@
     break;
 
     default:
-      if (uDialogueType > DIALOGUE_18 && uDialogueType < DIALOGUE_23 && !byte_5B0938[0])
+      if (uDialogueType > DIALOGUE_18 && uDialogueType < DIALOGUE_EVT_E && !byte_5B0938[0])
       {
         pInString = (char *)current_npc_text;
       }
@@ -1152,7 +1156,6 @@
   signed int v18; // eax@55
   signed int v18b;
   signed int v19; // ecx@63
-  BLVFace *pFace; // eax@69
   const char *pText; // ecx@79
   char *v28; // esi@82
   enum UIMessageType pMessageType2; // esi@110
@@ -1260,7 +1263,7 @@
       {
         if ( HIWORD(v18) < interaction_distance_limit )
         {
-          if ( uCurrentlyLoadedLevelType != LEVEL_Indoor)
+          if ( uCurrentlyLoadedLevelType == LEVEL_Outdoor)
           {
             v18b = (signed int)(unsigned __int16)v18 >> 9;
             if ( !pOutdoor->pBModels[v18b].pFaces[v19 & 0x3F].sCogTriggeredID
@@ -1284,29 +1287,31 @@
             uLastPointedObjectID = pMouse->uPointingObjectID;
             return;
           }
-          pFace = &pIndoor->pFaces[v19];
-          if ( BYTE3(pFace->uAttributes) & 6 )
+          if ( uCurrentlyLoadedLevelType == LEVEL_Indoor)
           {
-            if ( !pIndoor->pFaceExtras[pFace->uFaceExtraID].uEventID
-              || !GetEventHintString(pIndoor->pFaceExtras[pFace->uFaceExtraID].uEventID) )
+            if ( pIndoor->pFaces[v19].uAttributes & FACE_INDICATE )
             {
-              pMouse->uPointingObjectID = 0;
-              pFooterString[0] = 0;
-              bForceDrawFooter = 1;
-              uLastPointedObjectID = 0;
+              if ( !pIndoor->pFaceExtras[pIndoor->pFaces[v19].uFaceExtraID].uEventID
+               || !GetEventHintString(pIndoor->pFaceExtras[pIndoor->pFaces[v19].uFaceExtraID].uEventID) )
+              {
+                pMouse->uPointingObjectID = 0;
+                pFooterString[0] = 0;
+                bForceDrawFooter = 1;
+                uLastPointedObjectID = 0;
+                return;
+              }
+              GameUI_SetFooterString(GetEventHintString(pIndoor->pFaceExtras[pIndoor->pFaces[v19].uFaceExtraID].uEventID));
+              if ( pMouse->uPointingObjectID == 0 )
+              {
+                if ( uLastPointedObjectID != 0 )
+                {
+                  pFooterString[0] = 0;
+                  bForceDrawFooter = 1;
+                }
+              }
+              uLastPointedObjectID = pMouse->uPointingObjectID;
               return;
             }
-            GameUI_SetFooterString(GetEventHintString(pIndoor->pFaceExtras[pFace->uFaceExtraID].uEventID));
-            if ( pMouse->uPointingObjectID == 0 )
-            {
-              if ( uLastPointedObjectID != 0 )
-              {
-                pFooterString[0] = 0;
-                bForceDrawFooter = 1;
-              }
-            }
-            uLastPointedObjectID = pMouse->uPointingObjectID;
-            return;
           }
         }
         pMouse->uPointingObjectID = 0;
@@ -1818,24 +1823,24 @@
 void GameUI_DrawMinimap(unsigned int uX, unsigned int uY, unsigned int uZ, unsigned int uW, unsigned int uZoom, unsigned int bRedrawOdmMinimap)
 {
   int uHeight; // ebx@6
-  unsigned int pW; // ebx@23
+  signed int pW; // ebx@23
   int v15; // eax@23
   double v20; // st7@30
   signed int v27; // eax@37
-  unsigned __int16 *v28; // ecx@37
+  //unsigned __int16 *v28; // ecx@37
   signed int v29; // edi@40
   int pPoint_X; // edi@72
   int pPoint_Y; // ebx@72
   unsigned int lPitch; // [sp+20h] [bp-34h]@1
-  unsigned int pY; // [sp+20h] [bp-34h]@23
-  unsigned int pX; // [sp+24h] [bp-30h]@23
+  signed int pY; // [sp+20h] [bp-34h]@23
+  signed int pX; // [sp+24h] [bp-30h]@23
   signed int v70; // [sp+24h] [bp-30h]@37
   signed int uBluea; // [sp+28h] [bp-2Ch]@37
   int v73; // [sp+2Ch] [bp-28h]@30
   signed int uCenterY; // [sp+48h] [bp-Ch]@1
   signed int uCenterX; // [sp+4Ch] [bp-8h]@1
   signed int uWidth; // [sp+5Ch] [bp+8h]@30
-  unsigned int pZ; // [sp+60h] [bp+Ch]@23
+  signed int pZ; // [sp+60h] [bp+Ch]@23
   float uWb; // [sp+60h] [bp+Ch]@30
   unsigned int pColor;
 
@@ -1888,12 +1893,15 @@
       break;
       default: assert(false);
     }
+
+    static unsigned __int16 pOdmMinimap[117][137];
     assert(sizeof(pOdmMinimap) == 137 * 117 * sizeof(short));
 
     v70 = floorf(v20 * 65536.0 + 0.5f);//LODWORD(v24);
     uBluea = floorf(uWb * 65536.0 + 0.5f);//LODWORD(v25);
     v27 = uBluea >> 16;
-    v28 = &pRenderer->pTargetSurface[uX + uY * lPitch];
+    //v28 = &pRenderer->pTargetSurface[uX + uY * lPitch];
+
     if (pMapLod0 && bRedrawOdmMinimap)
     {
       assert(uWidth == 137 && uHeight == 117);
@@ -1908,6 +1916,20 @@
         for (int x = 0; x < uWidth; ++x)
         {
           //*pMinimap++ = pPal[pMapLod0Line[v29]];
+          pRenderer->WritePixel16(uX + x, uY + y, pPal[pMapLod0Line[v29]]);
+          v29 = (v70 + x * v73) >> 16;
+        }
+        uBluea += v73;
+        v27 = uBluea >> 16;
+      }
+
+      /*v29 = v70 >> 16;
+      for (int y = 0; y < uHeight; ++y)
+      {
+        uchar* pMapLod0Line = &pMapLod0[v27 * mapWidth];
+        for (int x = 0; x < uWidth; ++x)
+        {
+          //*pMinimap++ = pPal[pMapLod0Line[v29]];
           pOdmMinimap[y][x] = pPal[pMapLod0Line[v29]];
           v29 = (v70 + x * v73) >> 16;
         }
@@ -1915,17 +1937,17 @@
         v28 += 137 - uWidth;
         uBluea += v73;
         v27 = uBluea >> 16;
-      }
+      }*/
     }
 
-    for (int y = 0; y < 117; ++y)
+    /*for (int y = 0; y < 117; ++y)
     {
       for (int x = 0; x < 137; ++x)
       {
         *v28++ = pOdmMinimap[y][x];
       }
       v28 += lPitch - 137;
-    }
+    }*/
     uNumBlueFacesInBLVMinimap = 0;
   }
   else// uCurrentlyLoadedLevelType == LEVEL_Indoor
@@ -1956,7 +1978,7 @@
 LABEL_15:
       //v12 = &pIndoor->pFaces[pOutline->uFace1ID];
       if (bWizardEyeActive && uWizardEyeSkillLevel >= 3 &&
-          (pFace1->uAttributes & 0x2000 || pFace2->uAttributes & 0x2000) &&
+          (pFace1->Clickable() || pFace2->Clickable()) &&
           (pIndoor->pFaceExtras[pFace1->uFaceExtraID].uEventID || pIndoor->pFaceExtras[pFace2->uFaceExtraID].uEventID))
       {
         if (uNumBlueFacesInBLVMinimap < 49)
@@ -1967,13 +1989,15 @@
         long long _a = (uZoom * (signed __int64)pIndoor->pVertices[pOutline->uVertex1ID].x);
         uint _b = ((unsigned int)((unsigned __int64)_a >> 16) << 16);
         int _c = ((signed int)(_b - uZoom * pParty->vPosition.x) >> 16);
-        pX = uCenterX + ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pOutline->uVertex1ID].x) >> 16) << 16) - uZoom * pParty->vPosition.x) >> 16);
-        pY = uCenterY - ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pOutline->uVertex1ID].y) >> 16) << 16) - uZoom * pParty->vPosition.y) >> 16);
-        pZ = uCenterX + ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pOutline->uVertex2ID].x) >> 16) << 16) - uZoom * pParty->vPosition.x) >> 16);
-        pW = uCenterY - ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pOutline->uVertex2ID].y) >> 16) << 16) - uZoom * pParty->vPosition.y) >> 16);
+        pX = uCenterX + ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pIndoor->pMapOutlines->pOutlines[i].uVertex1ID].x) >> 16) << 16) - uZoom * pParty->vPosition.x) >> 16);
+        pY = uCenterY - ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pIndoor->pMapOutlines->pOutlines[i].uVertex1ID].y) >> 16) << 16) - uZoom * pParty->vPosition.y) >> 16);
+        pZ = uCenterX + ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pIndoor->pMapOutlines->pOutlines[i].uVertex2ID].x) >> 16) << 16) - uZoom * pParty->vPosition.x) >> 16);
+        pW = uCenterY - ((signed int)(((unsigned int)((unsigned __int64)(uZoom * (signed __int64)pIndoor->pVertices[pIndoor->pMapOutlines->pOutlines[i].uVertex2ID].y) >> 16) << 16) - uZoom * pParty->vPosition.y) >> 16);
         v15 = abs(pOutline->sZ - pParty->vPosition.z) / 8;
         if ( v15 > 100 )
           v15 = 100;
+		//if ( i == 1000 )//pY < 0 && pW > 16 )
+			//__debugbreak();
         pRenderer->RasterLine2D(pX, pY, pZ, pW, viewparams->pPalette[-v15 + 200]);
       }
     }
@@ -2214,7 +2238,7 @@
   }
   else//Green
     R = 0, G = 255, B = 0;
-  return TargetColor(R, G, B);
+  return Color16(R, G, B);
 }
 
 //----- (00417939) --------------------------------------------------------
--- a/VideoPlayer.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/VideoPlayer.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -207,69 +207,61 @@
 //----- (004C0133) --------------------------------------------------------
 bool BinkLockBuffer(_BINKBUF *_this)
 {
-  _BINKBUF *v1; // esi@1
   IDirectDrawSurface *v2; // edi@5
-  DWORD v4; // eax@8
-  DWORD v5; // eax@8
   IDirectDrawSurface4 *v6; // edi@11
-  LPVOID v7; // eax@14
 
-  v1 = _this;
+  //v1 = _this;
   if ( pVersion->pVersionInfo.dwPlatformId != VER_PLATFORM_WIN32_NT || pVersion->pVersionInfo.dwMajorVersion >= 5u )
   {
-  DDSURFACEDESC2 v8; // [sp+Ch] [bp-7Ch]@4
+    DDSURFACEDESC2 v8; // [sp+Ch] [bp-7Ch]@4
     if ( _this->pTargetDDrawSurface )
     {
-      memset(&v8, 0, 0x7Cu);
+      memset(&v8, 0, 0x7C);
       v8.dwSize = 124;
       while ( 1 )
       {
-        v6 = (IDirectDrawSurface4 *)v1->pTargetDDrawSurface;
-        if ( !v6->Lock(0, &v8, 1u, 0) )
+        v6 = (IDirectDrawSurface4 *)_this->pTargetDDrawSurface;
+        if ( !v6->Lock(0, &v8, 1, 0) )
           break;
         
         if (uBinkVersion < 0x0003000000000000)
-          BYTE3(v1->uBinkDDSurfaceType) |= 0x80u;
+          BYTE3(_this->uBinkDDSurfaceType) |= 0x80u;
         else
-          BYTE3(v1->uBinkDDSurfaceType) |= 0x04;
+          BYTE3(_this->uBinkDDSurfaceType) |= 0x04;
 
         if ( v6->Restore() )
           return 0;
       }
-      v7 = v8.lpSurface;
-      v1->pDDrawSurfaceData_ = v8.lpSurface;
-      v1->pDDrawSurfaceData = v7;
-      v5 = v8.lPitch;
-      goto LABEL_15;
+      _this->pDDrawSurfaceData_ = v8.lpSurface;
+      _this->pDDrawSurfaceData = v8.lpSurface;
+      _this->uDDrawSurfacePitch = v8.lPitch;
+      return 1;
     }
   }
   else
   {
-  DDSURFACEDESC v8; // [sp+Ch] [bp-7Ch]@4
+    DDSURFACEDESC v8; // [sp+Ch] [bp-7Ch]@4
     if ( _this->pTargetDDrawSurface )
     {
       memset(&v8.lPitch, 0, 0x6Cu);
       v8.lPitch = 108;
       while ( 1 )
       {
-        v2 = v1->pTargetDDrawSurface;
-        if ( !v2->Lock(0, (LPDDSURFACEDESC)&v8.lPitch, 1u, 0) )
+        v2 = _this->pTargetDDrawSurface;
+        if ( !v2->Lock(0, (LPDDSURFACEDESC)&v8.lPitch, 1, 0) )
           break;
         
         if (uBinkVersion < 0x0003000000000000)
           __asm int 3;
         else
-          BYTE3(v1->uBinkDDSurfaceType) |= 4u;
+          BYTE3(_this->uBinkDDSurfaceType) |= 4u;
 
         if ( v2->Restore() )
           return 0;
       }
-      v4 = (DWORD)v8.lpSurface;
-      v1->pDDrawSurfaceData_ = (void *)v8.lpSurface;
-      v1->pDDrawSurfaceData = (void *)v4;
-      v5 = v8.dwReserved;
-LABEL_15:
-      v1->uDDrawSurfacePitch = v5;
+      _this->pDDrawSurfaceData_ = v8.lpSurface;
+      _this->pDDrawSurfaceData = v8.lpSurface;
+      _this->uDDrawSurfacePitch = v8.dwReserved;
       return 1;
     }
   }
@@ -309,7 +301,7 @@
   if (!bNoVideo)
   {
     pRenderer->PresentBlackScreen();
-    PlayFullscreenMovie(MOVIE_3DOLogo, true);
+    //PlayFullscreenMovie(MOVIE_3DOLogo, true);
     //pGame->pCShow->PlayMovie(MOVIE_3DOLogo, 1);
     if ( !pVideoPlayer->bStopBeforeSchedule )
     {
@@ -458,6 +450,8 @@
   a2.dwSize = 32;
   a2.dwFlags = 64;
   pRenderer->GetTargetPixelFormat(&a2);
+  if (a2.dwRGBBitCount == 32)
+    return SMACKBUFFER565;
   if ( a2.dwRGBBitCount != 8 )
   {
     if ( a2.dwRBitMask == 0xF800 )
@@ -839,36 +833,50 @@
         pRenderer->EndScene();
       }
 }
+auto pixels = new unsigned short[640 * 480];
 
 //----- (004BF08B) --------------------------------------------------------
 void VideoPlayer::SmackUpdatePalette()
 {
-  VideoPlayer *v2; // esi@1
+  //VideoPlayer *v2; // esi@1
   unsigned __int16 *v3; // ebx@1
   unsigned int v4; // edi@1
   unsigned int v5; // eax@1
-  _SMACK *v6; // eax@1
+  //_SMACK *v6; // eax@1
+
+  Log::Warning(L"smacker");
+  //return;
 
-  v2 = this;
   pRenderer->BeginScene();
-  v3 = pRenderer->pTargetSurface;
-  v4 = pRenderer->uTargetSurfacePitch;
+
+  v3 = pixels;//pRenderer->pTargetSurface;
+  v4 = 640;//pRenderer->uTargetSurfacePitch;
   v5 = SmackCheckSurfaceFromat();
-  SmackToBuffer(v2->pSmackerMovie, 8, 8, 2 * v4, pRenderer->field_14, v3, v5);
-  v6 = v2->pSmackerMovie;
-  if ( v6->NewPalette )
+
+  SmackToBuffer(pSmackerMovie, 8, 8, 2 * v4, pRenderer->field_14, v3, v5);
+
+  
+  for (unsigned int y = 8; y < 8 + pSmackerMovie->Height; ++y)
+    for (unsigned int x = 8; x < 8 + pSmackerMovie->Width; ++x)
+    {
+      pRenderer->WritePixel16(x, y, pixels[x + y * 640]);
+    }
+  //delete [] pixels;
+
+  //v6 = pSmackerMovie;
+  if ( pSmackerMovie->NewPalette )
   {
-    SmackBufferNewPalette((long)pSmackerBuffer, (long)v6->Palette, LOWORD(v6->PalType));
+    SmackBufferNewPalette(pSmackerBuffer, pSmackerMovie->Palette, (pSmackerMovie->PalType));
     SmackColorRemapWithTrans(
-      (long)pSmackerMovie,
-      (long)pSmackerBuffer->Palette,
-      (long)pSmackerBuffer->MaxPalColors,
-      (long)pSmackerBuffer->PalType,
+      pSmackerMovie,
+      pSmackerBuffer->Palette,
+	  pSmackerBuffer->MaxPalColors,
+      pSmackerBuffer->PalType,
       1000);
   }
-  SmackDoFrame(v2->pSmackerMovie);
-  if ( v2->pSmackerMovie->FrameNum != v2->pSmackerMovie->Frames - 1 || v2->bLoopPlaying )
-    SmackNextFrame(v2->pSmackerMovie);
+  SmackDoFrame(pSmackerMovie);
+  if ( pSmackerMovie->FrameNum != pSmackerMovie->Frames - 1 || bLoopPlaying )
+    SmackNextFrame(pSmackerMovie);
   else
     Unload();
   pRenderer->EndScene();
@@ -905,10 +913,10 @@
     {
       SetFilePointer(hMagicVid, pMagicVideoHeaders[i].uFileOffset, 0, FILE_BEGIN);
 
-      if (uBinkVersion < 0x0003000000000000)
-        return BinkOpen(hMagicVid, 0x8800000);
-      else
-        return BinkOpen(hMagicVid, 0x82000000);
+	  if (uBinkVersion < 0x0003000000000000)
+		  return BinkOpen(hMagicVid, BINKNOTHREADEDIO | BINKFILEHANDLE);//0x8800000);
+	  else
+		  return BinkOpen(hMagicVid, BINKIOPROCESSOR | BINKCOPYALL);//0x82000000);
     }
 
   return nullptr;
@@ -923,7 +931,7 @@
       if ( !_stricmp(this->pMightVideoHeaders[i].pVideoName, pFilename) )
       {
         SetFilePointer(this->hMightVid, this->pMightVideoHeaders[i].uFileOffset, 0, 0);
-        return SmackOpen(this->hMightVid, 0x7140, -1);
+        return SmackOpen(this->hMightVid, SMACKTRACK2|SMACKTRACK1|SMACKFILEHANDLE|SMACKLOADEXTRA|SMACKNEEDVOLUME, -1);//0x7140,
       }
     }
   }
@@ -934,7 +942,7 @@
       if ( !_stricmp(this->pMagicVideoHeaders[i].pVideoName, pFilename) )
       {
         SetFilePointer(this->hMagicVid, this->pMagicVideoHeaders[i].uFileOffset, 0, 0);
-        return SmackOpen(this->hMagicVid, 0x7140, -1);
+        return SmackOpen(this->hMagicVid, SMACKTRACK2|SMACKTRACK1|SMACKFILEHANDLE|SMACKLOADEXTRA|SMACKNEEDVOLUME, -1);
       }
     }
   }
@@ -1128,3 +1136,14 @@
   byte_F8BC0C = 0;
   //pBinkMovie = nullptr;
 }
+
+bool MultimediaPlayer::libavcodec_initialized = false;
+
+void MultimediaPlayer::Logger(void *, int, const char *format, va_list args)
+{
+	char msg[1024];
+	vsprintf(msg, format, args);
+
+	DWORD w;
+	WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), msg, lstrlenA(msg), &w, nullptr);
+}
--- a/VideoPlayer.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/VideoPlayer.h	Thu Jan 02 09:11:28 2014 +0600
@@ -106,6 +106,669 @@
 
 void  ShowIntroVideo_and_LoadingScreen();
 
+extern "C"
+{
+#include "lib/libavcodec/avcodec.h"
+#include "lib/libavformat/avformat.h"
+#include "lib/libavutil/avutil.h"
+#include "lib/libavutil/imgutils.h"
+#include "lib/libswscale/swscale.h"
+#include "lib/libswresample/swresample.h"
+#include "lib/libavutil/opt.h"
+	//#include "libavutil/samplefmt.h"
+}
+#pragma comment(lib, "avcodec.lib")
+#pragma comment(lib, "avformat.lib")
+#pragma comment(lib, "avutil.lib")
+#pragma comment(lib, "swscale.lib")
+#pragma comment(lib, "swresample.lib")
+
+#include "lib/OpenAL/al.h"
+#include "lib/OpenAL/alc.h"
+#pragma comment(lib, "OpenAL32.lib")
+
+
+
+template<int MAX_SAMPLES_BUFFERS>
+class OpenALSoundProviderGeneric
+{
+public:
+	inline OpenALSoundProviderGeneric()
+	{
+		this->device = nullptr;
+		this->context = nullptr;
+		this->samples_current_buffer = 0;
+
+		this->samples_source_id = -1;
+		for (int i = 0; i < MAX_SAMPLES_BUFFERS; ++i)
+			samples_buffer_id[i] = -1;
+	}
+
+	inline bool Initialize()
+	{
+		auto device_names = alcGetString(nullptr, ALC_ALL_DEVICES_SPECIFIER);
+		if (!device_names)
+			device_names = alcGetString(nullptr, ALC_DEVICE_SPECIFIER);
+		if (device_names)
+		{
+			for (auto device_name = device_names; device_name[0]; device_name += strlen(device_name))
+			{
+				continue;
+			}
+		}
+
+		device = alcOpenDevice(nullptr);
+		if (!device || CheckError())
+			return false;
+
+		context = alcCreateContext(device, nullptr);
+		if (!context || CheckError())
+			return Release(), false;
+
+		alcMakeContextCurrent(context);
+
+		bool eax2 = alIsExtensionPresent("EAX2.0");
+		bool eax3 = alIsExtensionPresent("EAX3.0");
+		bool eax4 = alIsExtensionPresent("EAX4.0");
+		bool eax5 = alIsExtensionPresent("EAX5.0");
+
+		auto vendor = alGetString(AL_VERSION);
+		auto version = alGetString(AL_VERSION);
+		auto extensions = alcGetString(device, ALC_EXTENSIONS);
+
+		alGenBuffers(MAX_SAMPLES_BUFFERS, samples_buffer_id);
+		if (CheckError())
+			return Release(), false;
+
+		alGenSources(1, &samples_source_id);
+		if (CheckError())
+			return Release(), false;
+
+		float sound_pos[] = { 0.0f, 0.0f, 0.0f };
+		alSourcefv(samples_source_id, AL_POSITION, sound_pos);
+		alSourcei(samples_source_id, AL_LOOPING, AL_FALSE);
+
+		return true;
+	}
+
+	void Release()
+	{
+		if (samples_source_id != -1)
+		{
+			alDeleteSources(1, &samples_source_id);
+			samples_source_id = -1;
+		}
+
+		for (int i = 0; i < MAX_SAMPLES_BUFFERS; ++i)
+		{
+			if (samples_buffer_id[i] != -1)
+				alDeleteBuffers(1, &samples_buffer_id[i]);
+			samples_buffer_id[i] = -1;
+		}
+
+		alcMakeContextCurrent(nullptr);
+		if (context)
+		{
+			alcDestroyContext(context);
+			context = nullptr;
+		}
+		if (device)
+		{
+			alcCloseDevice(device);
+			device = nullptr;
+		}
+	}
+
+
+
+
+
+
+
+
+	void PlaySample(int num_channels, int sample_rate, int num_samples, void *samples)
+	{
+		//char msg[256];sprintf(msg, "chan %u rate %5u num %5u ptr %p\n", num_channels, sample_rate, num_samples, samples);
+		//log(msg);
+		ALenum sound_format;
+		switch (num_channels)
+		{
+		case 1: sound_format = AL_FORMAT_MONO16;    break;
+		case 2: sound_format = AL_FORMAT_STEREO16;  break;
+		default:
+			if (bool multichannel = alIsExtensionPresent("AL_EXT_MCFORMATS"))
+			{
+				switch (num_channels)
+				{
+				case 4: sound_format = alGetEnumValue("AL_FORMAT_QUAD16");  break;
+				case 6: sound_format = alGetEnumValue("AL_FORMAT_51CHN16"); break;
+				case 7: sound_format = alGetEnumValue("AL_FORMAT_61CHN16"); break;
+				case 8: sound_format = alGetEnumValue("AL_FORMAT_71CHN16"); break;
+				}
+			}
+			__debugbreak();
+		}
+
+		float listener_pos[] = { 0.0f, 0.0f, 0.0f };
+		float listener_vel[] = { 0.0f, 0.0f, 0.0f };
+		float listener_orientation[] = { 0.0f, 0.0f, -1.0f, // direction
+			0.0f, 1.0f, 0.0f }; // up vector
+		alListenerfv(AL_POSITION, listener_pos);
+		alListenerfv(AL_VELOCITY, listener_vel);
+		alListenerfv(AL_ORIENTATION, listener_orientation);
+
+		unsigned int *next_buffer = samples_buffer_id + samples_current_buffer;
+
+		alBufferData(*next_buffer, sound_format, samples, num_samples * sizeof(__int16), sample_rate);
+		CheckError();
+
+
+		int num_processed_buffers;
+		alGetSourcei(samples_source_id, AL_BUFFERS_PROCESSED, &num_processed_buffers);
+		while (num_processed_buffers)
+		{
+			unsigned int processed_buffers_id[4];
+			alSourceUnqueueBuffers(samples_source_id, min(4, num_processed_buffers), processed_buffers_id);
+			CheckError();
+			alGetSourcei(samples_source_id, AL_BUFFERS_PROCESSED, &num_processed_buffers);
+		}
+
+		int num_queued_buffers;
+		alGetSourcei(samples_source_id, AL_BUFFERS_QUEUED, &num_queued_buffers);
+		if (num_queued_buffers >= MAX_SAMPLES_BUFFERS)
+		{
+			__debugbreak();
+		}
+
+		alSourceQueueBuffers(samples_source_id, 1, next_buffer);
+		CheckError();
+
+		int status;
+		alGetSourcei(samples_source_id, AL_SOURCE_STATE, &status);
+		if (status != AL_PLAYING)
+		{
+			alSourcePlay(samples_source_id);
+			CheckError();
+		}
+
+		if (++samples_current_buffer >= MAX_SAMPLES_BUFFERS)
+			samples_current_buffer = 0;
+	}
+
+
+
+protected:
+	ALCdevice    *device;
+	ALCcontext   *context;
+	unsigned int  samples_buffer_id[MAX_SAMPLES_BUFFERS];
+	unsigned int  samples_source_id;
+	int           samples_current_buffer;
+
+
+	bool CheckError()
+	{
+		ALenum code = alcGetError(device);
+		if (code != ALC_NO_ERROR)
+		{
+			DWORD w;
+			const char *message = alcGetString(device, code);
+			WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlenA(message), &w, nullptr);
+			return true;
+		}
+		return false;
+	}
+};
+typedef OpenALSoundProviderGeneric<16> OpenALSoundProvider;
+
+
+
+void av_logger(void *, int, const char *format, va_list args);
+
+
+
+#include <memory>
+using std::tr1::shared_ptr;
+using std::tr1::make_shared;
+
+class MultimediaFrame
+{
+public:
+	typedef shared_ptr<MultimediaFrame> Ptr;
+	inline MultimediaFrame(AVMediaType type, AVPacket *packet, AVCodecContext *dec_ctx)
+	{
+		this->type = type;
+		this->f = nullptr;
+		this->p = packet;
+		this->dec_ctx = dec_ctx;
+	}
+	virtual ~MultimediaFrame() { return; }
+
+
+	AVMediaType  Type() const { return type; }
+	AVFrame     *GetAVFrame() { return f; }
+
+	virtual int   Decode() = 0;
+	virtual void *GetData() = 0;
+	virtual int   GetDataPitch() = 0;
+
+
+protected:
+	AVMediaType      type;
+	AVFrame         *f;
+	AVPacket        *p;
+	AVCodecContext  *dec_ctx;
+};
+
+
+
+class MultimediaVideoFrame : public MultimediaFrame
+{
+public:
+	inline MultimediaVideoFrame(AVMediaType type, AVPacket *packet, AVCodecContext *dec_ctx, int width, int height) :
+		MultimediaFrame(type, packet, dec_ctx)
+	{
+		this->width = width;
+		this->height = height;
+		this->rescaled_data[0] = nullptr;
+		this->rescaled_linesize[0] = 0;
+	}
+	virtual ~MultimediaVideoFrame()
+	{
+		av_freep(&rescaled_data);
+		av_frame_free(&f);
+	}
+
+	int Decode() override
+	{
+		f = avcodec_alloc_frame();
+		avcodec_get_frame_defaults(f);
+
+		volatile int done = false;
+		do
+		{
+			int ret;
+			if ((ret = avcodec_decode_video2(dec_ctx, f, (int *)&done, p)) < 0)
+				return ret;
+		} while (!done);
+		if (Rescale(f, width, height, AV_PIX_FMT_RGB32, rescaled_data, rescaled_linesize))
+			return 0;
+		else return -1;
+	}
+
+	virtual void *GetData()       { return rescaled_data[0]; }
+	virtual int   GetDataPitch()  { return rescaled_linesize[0]; }
+
+protected:
+	int      width;
+	int      height;
+	uint8_t *rescaled_data[8];
+	int      rescaled_linesize[8];
+
+	bool Rescale(AVFrame *frame, int dst_width, int dst_height, AVPixelFormat format, uint8_t **out_data, int *out_linesize)
+	{
+		if (av_image_alloc(out_data, out_linesize, dst_width, dst_height, format, 1) < 0)
+			return false;
+
+		SwsContext *converter = sws_getContext(frame->width, frame->height, (AVPixelFormat)frame->format,
+			dst_width, dst_height, format,
+			SWS_BICUBIC, nullptr, nullptr, nullptr);
+		sws_scale(converter, frame->data, frame->linesize, 0, frame->height, out_data, out_linesize);
+		sws_freeContext(converter);
+
+		return true;
+	}
+};
+
+
+
+class MultimediaAudioFrame : public MultimediaFrame
+{
+public:
+	inline MultimediaAudioFrame(AVMediaType type, AVPacket *packet, AVCodecContext *dec_ctx) :
+		MultimediaFrame(type, packet, dec_ctx)
+	{
+		this->resampled_data = nullptr;
+	}
+	virtual ~MultimediaAudioFrame()
+	{
+		av_free(resampled_data);
+		av_frame_free(&f);
+	}
+
+	int Decode() override
+	{
+		f = avcodec_alloc_frame();
+		avcodec_get_frame_defaults(f);
+
+		volatile int done = false;
+		do
+		{
+			int ret;
+			if ((ret = avcodec_decode_audio4(dec_ctx, f, (int *)&done, p)) < 0)
+				return ret;
+		} while (!done);
+		if (Resample(f, f->channel_layout, f->sample_rate,
+			f->channel_layout, f->sample_rate, AV_SAMPLE_FMT_S16, &resampled_data))
+			return 0;
+		else return -1;
+	}
+
+	virtual void *GetData()       { return resampled_data; }
+	virtual int   GetDataPitch()  { return 2 * f->nb_samples; }
+
+protected:
+	uint8_t *resampled_data;
+
+	bool Resample(AVFrame *frame,
+		int64_t src_channel_layout, int src_sample_rate,
+		int64_t dst_channel_layout, int dst_sample_rate, AVSampleFormat dst_format, uint8_t **out_data)
+	{
+		SwrContext *converter = swr_alloc();
+
+		av_opt_set_int(converter, "in_channel_layout", src_channel_layout, 0);
+		av_opt_set_int(converter, "in_sample_rate", src_sample_rate, 0);
+		av_opt_set_sample_fmt(converter, "in_sample_fmt", (AVSampleFormat)frame->format, 0);
+
+		av_opt_set_int(converter, "out_channel_layout", dst_channel_layout, 0);
+		av_opt_set_int(converter, "out_sample_rate", dst_sample_rate, 0);
+		av_opt_set_sample_fmt(converter, "out_sample_fmt", dst_format, 0);
+
+		if (swr_init(converter) < 0)
+			return false;
+
+		int dst_nb_samples;
+		int max_dst_nb_samples = dst_nb_samples = av_rescale_rnd(frame->nb_samples, dst_sample_rate, src_channel_layout, AV_ROUND_UP);
+
+		uint8_t **dst_data;
+		int       dst_linesize;
+		int dst_nb_channels = av_get_channel_layout_nb_channels(dst_channel_layout);
+		if (av_samples_alloc_array_and_samples(&dst_data, &dst_linesize, dst_nb_channels, dst_nb_samples, dst_format, 0) < 0)
+		{
+			swr_free(&converter);
+			return false;
+		}
+
+		dst_nb_samples = av_rescale_rnd(swr_get_delay(converter, src_sample_rate) + frame->nb_samples, dst_sample_rate, src_sample_rate, AV_ROUND_UP);
+		if (dst_nb_samples > max_dst_nb_samples)
+		{
+			av_free(dst_data[0]);
+			if (av_samples_alloc(dst_data, &dst_linesize, dst_nb_channels, dst_nb_samples, dst_format, 1) < 0)
+			{
+				swr_free(&converter);
+				return false;
+			}
+			max_dst_nb_samples = dst_nb_samples;
+		}
+
+
+		if (swr_convert(converter, dst_data, dst_nb_samples, (const uint8_t **)frame->data, frame->nb_samples) < 0)
+		{
+			av_free(dst_data[0]);
+			swr_free(&converter);
+			return false;
+		}
+
+		*out_data = dst_data[0];
+		return true;
+	}
+};
+
+
+template<int NUM_PRECACHED_FRAMES>
+class MovieCached
+{
+public:
+	bool Stopped() const { return stopped; }
+
+protected:
+	friend class MultimediaPlayer;
+	inline MovieCached(OpenALSoundProvider *sound_provider)
+	{
+		this->format_ctx = nullptr;
+		this->sound_provider = sound_provider;
+		this->stopped = false;
+
+		this->video_stream_idx = -1;
+		this->video_stream = nullptr;
+		this->video_stream_dec = nullptr;
+		this->video_stream_dec_ctx = nullptr;
+
+		this->audio_stream_idx = -1;
+		this->audio_stream = nullptr;
+		this->audio_stream_dec = nullptr;
+		this->audio_stream_dec_ctx = nullptr;
+	}
+
+	bool Load(const char *video_filename, int width, int height)
+	{
+		this->width = width;
+		this->height = height;
+
+		if (avformat_open_input(&format_ctx, video_filename, nullptr, nullptr) >= 0)
+		{
+			if (avformat_find_stream_info(format_ctx, nullptr) >= 0)
+			{
+				av_dump_format(format_ctx, 0, video_filename, 0);
+
+				video_stream_idx = OpenStream(AVMEDIA_TYPE_VIDEO, &video_stream, &video_stream_dec, &video_stream_dec_ctx);
+				if (video_stream_idx < 0)
+					return Release(), false;
+
+				audio_stream_idx = OpenStream(AVMEDIA_TYPE_AUDIO, &audio_stream, &audio_stream_dec, &audio_stream_dec_ctx);
+				if (audio_stream_idx < 0)
+					return Release(), false;
+
+				strcpy(movie_name, video_filename);
+				packet = new AVPacket;
+				av_init_packet(packet);
+				return true;
+			}
+		}
+		return Release(), false;
+	}
+
+	bool Release()
+	{
+		if (format_ctx)
+		{
+			avformat_free_context(format_ctx);
+			format_ctx = nullptr;
+		}
+		if (packet)
+		{
+			av_free_packet(packet);
+			delete packet;
+			packet = nullptr;
+		}
+
+		if (video_stream_idx >= 0)
+		{
+			video_stream_idx = -1;
+			video_stream = nullptr;
+			video_stream_dec = nullptr;
+			avcodec_close(video_stream_dec_ctx);
+			video_stream_dec_ctx = nullptr;
+		}
+
+		if (audio_stream_idx >= 0)
+		{
+			audio_stream_idx = -1;
+			audio_stream = nullptr;
+			audio_stream_dec = nullptr;
+			avcodec_close(audio_stream_dec_ctx);
+		}
+		return true;
+	}
+
+
+	int OpenStream(AVMediaType type, AVStream **out_stream, AVCodec **out_dec, AVCodecContext **out_dec_ctx)
+	{
+		int stream_idx = av_find_best_stream(format_ctx, type, -1, -1, nullptr, 0);
+		if (stream_idx < 0)
+			return stream_idx;
+
+		auto stream = format_ctx->streams[stream_idx];
+		auto dec_ctx = stream->codec;
+		auto dec = avcodec_find_decoder(dec_ctx->codec_id);
+		if (dec)
+		{
+			if (avcodec_open2(dec_ctx, dec, nullptr) >= 0)
+			{
+				*out_stream = stream;
+				*out_dec = dec;
+				*out_dec_ctx = dec_ctx;
+				return stream_idx;
+			}
+		}
+		return -1;
+	}
+
+
+	MultimediaFrame::Ptr GetNextFrame()
+	{
+		packet->data = nullptr;
+		packet->size = 0;
+
+		volatile int got_frame = false;
+		do
+		{
+			if (av_read_frame(format_ctx, packet) < 0)
+			{
+				stopped = true;
+				return nullptr;
+			}
+		} while (packet->stream_index != video_stream_idx &&
+			packet->stream_index != audio_stream_idx);
+
+		if (packet->stream_index == video_stream_idx)
+			return MultimediaFrame::Ptr(new MultimediaVideoFrame(AVMEDIA_TYPE_VIDEO, packet, video_stream_dec_ctx, width, height));
+		else if (packet->stream_index == audio_stream_idx)
+			return MultimediaFrame::Ptr(new MultimediaAudioFrame(AVMEDIA_TYPE_AUDIO, packet, audio_stream_dec_ctx));
+		return nullptr;
+	}
+
+
+
+	char                 movie_name[256];
+	int                  width;
+	int                  height;
+	bool                 stopped;
+	AVFormatContext     *format_ctx;
+	//AVFrame             *frame;
+	AVPacket            *packet;
+	//MultimediaFrame     *frames[NUM_PRECACHED_FRAMES];
+	OpenALSoundProvider *sound_provider;
+
+	int              video_stream_idx;
+	AVStream        *video_stream;
+	AVCodec         *video_stream_dec;
+	AVCodecContext  *video_stream_dec_ctx;
+
+	int              audio_stream_idx;
+	AVStream        *audio_stream;
+	AVCodec         *audio_stream_dec;
+	AVCodecContext  *audio_stream_dec_ctx;
+};
+typedef MovieCached<10> Movie;
+
+
+
+
+class MultimediaPlayer
+{
+public:
+	inline MultimediaPlayer()
+	{
+	}
+
+	bool Initialize()
+	{
+		if (!libavcodec_initialized)
+		{
+			av_log_set_callback(Logger);
+			avcodec_register_all();
+			av_register_all();
+
+			libavcodec_initialized = true;
+		}
+
+		sound_provider = new OpenALSoundProvider;
+		sound_provider->Initialize();
+
+		return true;
+	}
+
+
+	Movie *LoadMovie(const char *filename, int width, int height)
+	{
+		auto movie = new Movie(sound_provider);
+		if (movie)
+		{
+			if (movie->Load(filename, width, height))
+			{
+				current_movie_width = width;
+				current_movie_height = height;
+				return current_movie = movie;
+			}
+			delete movie;
+		}
+		return nullptr;
+	}
+
+
+	inline char *DoFrame()
+	{
+		if (!current_movie)
+			return nullptr;
+
+		while (true)
+		{
+			auto frame = current_movie->GetNextFrame();
+			if (!frame)
+				return nullptr;
+
+			if (frame->Type() == AVMEDIA_TYPE_AUDIO)
+			{
+				uint8_t *data;
+				if (frame->Decode() >= 0)
+				{
+					auto f = frame->GetAVFrame();
+					sound_provider->PlaySample(f->channels, f->sample_rate, f->nb_samples, frame->GetData());
+					Sleep(20);
+					continue;
+				}
+			}
+			else if (frame->Type() == AVMEDIA_TYPE_VIDEO)
+			{
+				uint8_t *dst_data[4] = { 0 };
+				int      dst_linesize[4] = { 0 };
+				if (frame->Decode() >= 0)
+				{
+					auto image = new char[current_movie_width * current_movie_height * 4];
+					memcpy(image, frame->GetData(), current_movie_height * frame->GetDataPitch());
+
+					return image;
+				}
+			}
+			return nullptr;
+		}
+	}
+
+
+
+protected:
+	static void Logger(void *, int, const char *format, va_list args);
+
+	OpenALSoundProvider *sound_provider;
+	Movie               *current_movie;
+	int                  current_movie_width;
+	int                  current_movie_height;
+
+	static bool libavcodec_initialized;
+};
+
+
+
 
 
 
--- a/Viewport.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Viewport.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -54,9 +54,9 @@
     this->uScreenWidth = br_x - tl_x + 1;
     this->uScreenHeight = br_y - tl_y + 1;
     this->uScreenCenterX = (signed int)(br_x + tl_x) /2;
-    if ( pRenderer->pRenderD3D == 0 )
-        this->uScreenCenterY = this->uScreen_BR_Y - fixpoint_mul(field_30, uScreenHeight);
-    else
+    //if ( pRenderer->pRenderD3D == 0 )
+    //    this->uScreenCenterY = this->uScreen_BR_Y - fixpoint_mul(field_30, uScreenHeight);
+    //else
         this->uScreenCenterY = (br_y + tl_y)/2;
     SetViewport(this->uScreen_TL_X, this->uScreen_TL_Y, this->uScreen_BR_X, this->uScreen_BR_Y);
     }
@@ -195,7 +195,7 @@
 void ViewingParams::InitGrayPalette()
     {
     for  (unsigned short i=0; i<256; ++i)
-        pPalette[i]=TargetColor(i, i, i);
+        pPalette[i]=Color16(i, i, i);
     }
 
 //----- (00443365) --------------------------------------------------------
@@ -487,7 +487,7 @@
         pParty->uFlags |= PARTY_FLAGS_1_FALLING;
         return;
       }
-      if ( uActiveCharacter && sub_427769_spell(pPlayers[uActiveCharacter]->uQuickSpell))
+      if ( uActiveCharacter && sub_427769_isSpellQuickCastableOnShiftClick(pPlayers[uActiveCharacter]->uQuickSpell))
         pMessageQueue_50CBD0->AddMessage(UIMSG_CastQuickSpell, 0, 0);
     }
     return;
--- a/Weather.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/Weather.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -17,174 +17,129 @@
 int Weather::DrawSnow()
 {
   unsigned __int16 *v1; // edi@1
-  __int16 *v2; // esi@2
-  int v3; // eax@2
-  signed int v4; // eax@6
-  int v5; // edx@8
-  __int16 *v6; // esi@11
-  __int16 *v7; // eax@11
-  int v8; // ecx@11
-  int v9; // eax@12
-  int v10; // ecx@16
-  int v11; // edx@18
-  Weather *v12; // eax@20
-  __int16 *v13; // esi@20
-  int v14; // eax@21
-  int v15; // eax@21
-  int v16; // edx@23
-  int v17; // eax@24
-  int v18; // edx@26
-  int v19; // ecx@27
-  int v20; // eax@27
-  char v21; // zf@27
-  unsigned int v23; // [sp+Ch] [bp-20h]@1
-  unsigned int v24; // [sp+10h] [bp-1Ch]@1
-  unsigned int v25; // [sp+14h] [bp-18h]@1
-  Weather *v26; // [sp+18h] [bp-14h]@1
-  signed int v27; // [sp+18h] [bp-14h]@20
-  unsigned int v28; // [sp+1Ch] [bp-10h]@1
-  unsigned int v29; // [sp+20h] [bp-Ch]@1
-  __int16 *v30; // [sp+24h] [bp-8h]@2
-  signed int v31; // [sp+28h] [bp-4h]@1
-  signed int v32; // [sp+28h] [bp-4h]@10
 
-  v26 = this;
-  v25 = viewparams->uScreen_BttmR_X;
-  v28 = viewparams->uScreen_topL_Y;
-  v31 = 0;
-  v1 = pRenderer->pTargetSurface;
-  v29 = viewparams->uScreen_topL_X;
-  v23 = viewparams->uScreen_BttmR_Y;
-  v24 = viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X;
-  do
+//  if (!FORCE_16_BITS)
+  //  __debugbreak(); // function expects 16bit target buffer, will fail otherwise
+  v1 = (unsigned __int16 *)pRenderer->pTargetSurface;
+  for ( uint i = 0; i < 700; ++i )
   {
-    v2 = &v26->field_0[2 * v31];
-    v30 = &v26->field_0[2 * v31 + 1];
-    *v2 += rand() % 3 + 1;
-    *v30 += rand() % 2 + 1;
-    v3 = *v2;
-    if ( v3 < (signed int)(v25 - 1) )
+    int x = 2 * i;
+    int y = 2 * i + 1;
+    this->Screen_Coord[x] += rand() % 3 + 1;
+    this->Screen_Coord[y] += rand() % 2 + 1;
+    if ( this->Screen_Coord[x] < (signed int)(viewparams->uScreen_BttmR_X - 1) )//467
     {
-      if ( v3 < (signed int)v29 )
-        *v2 = v25 - rand() % 8;
+      if ( this->Screen_Coord[x] < (signed int)viewparams->uScreen_topL_X )//8
+        this->Screen_Coord[x] = viewparams->uScreen_BttmR_X - rand() % 8;
     }
     else
-    {
-      *v2 = v29 + rand() % 8;
-    }
-    v4 = *v30;
-    if ( v4 < (signed int)v28 || v4 >= (signed int)v23 )
+      this->Screen_Coord[x] = viewparams->uScreen_topL_X + rand() % 8;
+    if ( this->Screen_Coord[y] < (signed int)viewparams->uScreen_topL_Y//8
+      || this->Screen_Coord[y] >= (signed int)viewparams->uScreen_BttmR_Y )//351
     {
-      v5 = rand() % (signed int)(v24 - 2);
-      *v30 = v28;
-      *v2 = v29 + v5;
+      this->Screen_Coord[y] = viewparams->uScreen_topL_Y;
+      this->Screen_Coord[x] = viewparams->uScreen_topL_X + (rand() % (signed int)((viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X) - 2));
     }
-    ++v31;
-    v1[*v2 + 640 * *v30] = 0xFFFFu;
+    //v1[this->Screen_Coord[2 * i] + 640 * this->Screen_Coord[2 * i + 1]] = 0xFFFFu;
+    pRenderer->WritePixel16(this->Screen_Coord[x], this->Screen_Coord[y], 0xFFFF);//snowflake - point( - )
   }
-  while ( v31 < 700 );
-  v32 = 700;
-  do
+
+  for ( uint i = 700; i < 950; ++i )
   {
-    v6 = &v26->field_0[2 * v32];
-    *v6 += rand() % 5 - 3;
-    v7 = &v26->field_0[2 * v32 + 1];
-    v8 = *v6;
-    *v7 += 4;
-    if ( v8 < (signed int)v29 )
+    int x = 2 * i;
+    int y = 2 * i + 1;
+    this->Screen_Coord[x] += rand() % 5 - 3;//x
+    this->Screen_Coord[y] += 4;//y
+    if ( this->Screen_Coord[x] < (signed int)viewparams->uScreen_topL_X )
+      this->Screen_Coord[x] = viewparams->uScreen_BttmR_X - rand() % 4 - 2;
+    if ( this->Screen_Coord[x] >= (signed int)(viewparams->uScreen_BttmR_X - 2) )
+      this->Screen_Coord[x] = rand() % 4 + viewparams->uScreen_topL_X + 2;
+    if ( this->Screen_Coord[y] < (signed int)viewparams->uScreen_topL_Y || this->Screen_Coord[y] >= (signed int)(viewparams->uScreen_BttmR_Y - 1) )
     {
-      LOWORD(v9) = v25 - rand() % 4 - 2;
-LABEL_15:
-      *v6 = v9;
-      v7 = &v26->field_0[2 * v32 + 1];
-      goto LABEL_16;
+      this->Screen_Coord[y] = viewparams->uScreen_topL_Y;
+      this->Screen_Coord[x] = viewparams->uScreen_topL_X + (rand() % (signed int)((viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X) - 2));
     }
-    if ( v8 >= (signed int)(v25 - 2) )
+	pRenderer->WritePixel16(this->Screen_Coord[x],     this->Screen_Coord[y],     0xFFFF);//x, y   )
+	pRenderer->WritePixel16(this->Screen_Coord[x] + 1, this->Screen_Coord[y],     0xFFFF);//x + 1, y
+	pRenderer->WritePixel16(this->Screen_Coord[x],     this->Screen_Coord[y] + 1, 0xFFFF);//x , y + 1
+	pRenderer->WritePixel16(this->Screen_Coord[x] + 1, this->Screen_Coord[y] + 1, 0xFFFF);//x + 1, y + 1
+
+    //v1[this->Screen_Coord[2 * i] + 640 * this->Screen_Coord[2 * i + 1]] = 0xFFFFu;
+    //v1[this->Screen_Coord[2 * i] + 640 * this->Screen_Coord[2 * i + 1] + 1] = 0xFFFFu;
+    //v1[this->Screen_Coord[2 * i] + 640 * (this->Screen_Coord[2 * i + 1] + 1)] = 0xFFFFu;
+    //v1[this->Screen_Coord[2 * i] + 640 * this->Screen_Coord[2 * i + 1] + 641] = 0xFFFFu;
+  }
+
+  for ( uint i = 0; i < 50; i++)
+  {
+    this->Screen_Coord[1901 + (i * 2)] += 8;
+    this->Screen_Coord[1901 + ((i * 2) -1)] += rand() % 11 - 5;
+    if ( this->Screen_Coord[1901 + ((i * 2) -1)] < (signed int)viewparams->uScreen_topL_X || this->Screen_Coord[1901 + ((i * 2) -1)] >= (signed int)(viewparams->uScreen_BttmR_X - 5) )
     {
-      v9 = rand() % 4 + v29 + 2;
-      goto LABEL_15;
-    }
-LABEL_16:
-    v10 = *v7;
-    if ( v10 < (signed int)v28 || v10 >= (signed int)(v23 - 1) )
-    {
-      v11 = rand() % (signed int)(v24 - 2);
-      v26->field_0[2 * v32 + 1] = v28;
-      v7 = &v26->field_0[2 * v32 + 1];
-      *v6 = v29 + v11;
+      this->Screen_Coord[1901 + (i * 2)] = viewparams->uScreen_topL_Y;
+      this->Screen_Coord[1901 + ((i * 2) -1)] = viewparams->uScreen_topL_X + (rand() % (signed int)((viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X) - 5));
     }
-    *(&v1[640 * *v7 + 1] + *v6) = 0xFFFFu;
-    *(&v1[640 * *v7 + 641] + *v6) = 0xFFFFu;
-    v1[*v6 + 640 * (*v7 + 1)] = 0xFFFFu;
-    ++v32;
-    v1[*v6 + 640 * *v7] = 0xFFFFu;
-  }
-  while ( v32 < 950 );
-  v12 = v26;
-  v27 = 50;
-  v13 = &v12->field_0[1901];
-  do
-  {
-    v14 = rand();
-    *v13 += 8;
-    *(v13 - 1) += v14 % 11 - 5;
-    v15 = *(v13 - 1);
-    if ( v15 < (signed int)v29 || v15 >= (signed int)(v25 - 5) )
-    {
-      v16 = rand() % (signed int)(v24 - 5);
-      *v13 = v28;
-      *(v13 - 1) = v29 + v16;
-    }
-    v17 = *v13;
-    if ( v17 < (signed int)v28 || v17 >= (signed int)(v23 - 5) )
+    if ( this->Screen_Coord[1901 + (i * 2)] < (signed int)viewparams->uScreen_topL_Y || this->Screen_Coord[1901 + (i * 2)] >= (signed int)(viewparams->uScreen_BttmR_Y - 5) )
     {
-      v18 = rand() % (signed int)(v24 - 5);
-      *v13 = v28;
-      *(v13 - 1) = v29 + v18;
+      this->Screen_Coord[1901 + (i * 2)] = viewparams->uScreen_topL_Y;
+      this->Screen_Coord[1901 + ((i * 2) -1)] = viewparams->uScreen_topL_X + (rand() % (signed int)((viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X) - 5));
     }
-    *(&v1[640 * *v13 + 1] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 641] + *(v13 - 1)) = 0xFFFFu;
-    v1[*(v13 - 1) + 640 * (*v13 + 1)] = 0xFFFFu;
-    v1[*(v13 - 1) + 640 * *v13] = 0xFFFFu;
-    *(&v1[640 * *v13 + 1281] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 1921] + *(v13 - 1)) = 0xFFFFu;
-    v1[*(v13 - 1) + 640 * (*v13 + 3)] = 0xFFFFu;
-    v1[*(v13 - 1) + 640 * (*v13 + 2)] = 0xFFFFu;
-    *(&v1[640 * *v13 + 3] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 643] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 642] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 2] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 1283] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 1923] + *(v13 - 1)) = 0xFFFFu;
-    *(&v1[640 * *v13 + 1922] + *(v13 - 1)) = 0xFFFFu;
-    v19 = *(v13 - 1);
-    v20 = 5 * *v13;
-    v13 += 2;
-    v21 = v27-- == 1;
-    *(&v1[128 * v20 + 1282] + v19) = 0xFFFFu;
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)], this->Screen_Coord[1901 + (i * 2)], 0xFFFF);//x, y
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)], this->Screen_Coord[1901 + (i * 2)] + 1, 0xFFFF);//x, y + 1
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)], this->Screen_Coord[1901 + (i * 2)] + 2, 0xFFFF);//x, y + 2
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)], this->Screen_Coord[1901 + (i * 2)] + 3, 0xFFFF);//x, y + 3
+
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 1, this->Screen_Coord[1901 + (i * 2)], 0xFFFF);//x + 1, y
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 1, this->Screen_Coord[1901 + (i * 2)] + 1, 0xFFFF);//x + 1, y + 1
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 1, this->Screen_Coord[1901 + (i * 2)] + 2, 0xFFFF);//x + 1, y + 2
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 1, this->Screen_Coord[1901 + (i * 2)] + 3, 0xFFFF);//x + 1, y + 3
+
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 2, this->Screen_Coord[1901 + (i * 2)], 0xFFFF);//x + 2, y
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 2, this->Screen_Coord[1901 + (i * 2)] + 1, 0xFFFF);//x + 2, y + 1
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 2, this->Screen_Coord[1901 + (i * 2)] + 2, 0xFFFF);//x + 2, y + 2
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 2, this->Screen_Coord[1901 + (i * 2)] + 3, 0xFFFF);//x + 2, y + 3
+
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 3, this->Screen_Coord[1901 + (i * 2)], 0xFFFF);//x + 3, y
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 3, this->Screen_Coord[1901 + (i * 2)] + 1, 0xFFFF);//x + 3, y + 1
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 3, this->Screen_Coord[1901 + (i * 2)] + 2, 0xFFFF);//x + 3, y + 2
+	pRenderer->WritePixel16(this->Screen_Coord[1901 + ((i * 2) -1)] + 3, this->Screen_Coord[1901 + (i * 2)] + 3, 0xFFFF);//x + 3, y + 3
+
+    //v1[this->Screen_Coord[1901 + ((i * 2) -1)] + 640 * this->Screen_Coord[1901 + (i * 2)]] = 0xFFFFu;//x, y
+    //v1[this->Screen_Coord[1901 + ((i * 2) -1)] + 640 * (this->Screen_Coord[1901 + (i * 2)] + 1)] = 0xFFFFu;//x, y + 1
+    //v1[this->Screen_Coord[1901 + ((i * 2) -1)] + 640 * (this->Screen_Coord[1901 + (i * 2)] + 2)] = 0xFFFFu;//x, y + 2
+    //v1[this->Screen_Coord[1901 + ((i * 2) -1)] + 640 * (this->Screen_Coord[1901 + (i * 2)] + 3)] = 0xFFFFu;//x, y + 3
+
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 1] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y, x + 1
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 641] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 1, x + 1
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 1281] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 2, x + 1
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 1921] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 3, x + 1
+
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 2] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y, x + 2
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 642] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 1, x + 2
+    //*(&v1[128 * (5 * this->Screen_Coord[1901 + (i * 2)]) + 1282] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 2, x + 2
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 1922] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 3, x + 2
+
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 3] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y, x + 3
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 643] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 1, x + 3
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 1283] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 2, x + 3
+    //*(&v1[640 * this->Screen_Coord[1901 + (i * 2)] + 1923] + this->Screen_Coord[1901 + ((i * 2) -1)]) = 0xFFFFu;//y + 3, x + 3
   }
-  while ( !v21 );
   return 0;
 }
 
 //----- (004C2EA0) --------------------------------------------------------
 int Weather::Initialize()
 {
-  Weather *v1; // edi@1
-  signed int v2; // esi@1
   signed int v3; // ebx@1
   signed int v4; // ebp@1
 
-  v1 = this;
-  v2 = 0;
   v3 = pViewport->uScreen_BR_X - pViewport->uScreen_TL_X - 4;
   v4 = pViewport->uScreen_BR_Y - pViewport->uScreen_TL_Y - 4;
-  do
+  for ( uint i = 0; i < 1000; i++ )
   {
-    v1->field_0[2 * v2++] = LOWORD(pViewport->uViewportTL_X) + rand() % v3;
-    *((short *)v1 + 2 * v2 - 1) = LOWORD(pViewport->uViewportTL_Y) + rand() % v4;
+    this->Screen_Coord[2 * i] = LOWORD(pViewport->uViewportTL_X) + rand() % v3;
+    this->Screen_Coord[(2 * (i + 1)) - 1] = LOWORD(pViewport->uViewportTL_Y) + rand() % v4;
   }
-  while ( v2 < 1000 );
   return 0;
 }
 
@@ -199,46 +154,23 @@
 //----- (004C2F0B) --------------------------------------------------------
 bool Weather::OnPlayerTurn(__int16 a2)
 {
-  int v3; // edx@3
-  signed int v4; // ebx@3
   unsigned int screen_width; // esi@3
-  __int16 *v6; // eax@5
-  signed int v7; // edi@5
-  unsigned int screen_x; // [sp+0h] [bp-Ch]@3
-  unsigned int screen_z_minus_4; // [sp+4h] [bp-8h]@3
-  Weather *v10; // [sp+8h] [bp-4h]@1
 
-  v10 = this;
-  if ( this->bRenderSnow != 1 )
+  if ( this->bRenderSnow != true )
     return 0;
-  HIWORD(v3) = HIWORD(viewparams->uScreen_topL_X);
-  v4 = 0;
   screen_width = viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X;
-  screen_x = viewparams->uScreen_topL_X;
-  screen_z_minus_4 = viewparams->uScreen_BttmR_X - 4;
 
-  short* _this = this->field_0;
-  while ( 1 )
+  for ( uint i = 0; i < 1000; ++i )
   {
-    v6 = &_this[2 * v4];
-    *v6 += a2;
-    LOWORD(v3) = *v6;
-    v7 = *v6;
-    if ( v7 < (signed int)screen_z_minus_4 )
+    this->Screen_Coord[2 * i] += a2;
+    if ( this->Screen_Coord[2 * i] < (signed int)viewparams->uScreen_BttmR_X - 4 )
     {
-      if ( v7 >= (signed int)screen_x )
-        goto LABEL_10;
-      v3 += screen_width;
+      if ( this->Screen_Coord[2 * i] >= (signed int)viewparams->uScreen_topL_X )
+        continue;
+      this->Screen_Coord[2 * i] += screen_width;
     }
     else
-    {
-      v3 = v3 - screen_width + 4;
-    }
-    *v6 = v3;
-LABEL_10:
-    ++v4;
-    if ( v4 >= 1000 )
-      return 1;
-    //_this = v10;
+      this->Screen_Coord[2 * i] = this->Screen_Coord[2 * i] - screen_width + 4;
   }
+  return 1;
 }
\ No newline at end of file
--- a/Weather.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/Weather.h	Thu Jan 02 09:11:28 2014 +0600
@@ -19,7 +19,7 @@
 
 
 
-  __int16 field_0[2000];
+  __int16 Screen_Coord[2000];
   int bNight;
   int bRenderSnow;
 };
--- a/_deleted.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/_deleted.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -13196,6 +13196,269 @@
   return bUserDirect3D == 0;
 }
 
+
+//----- (004A46E6) --------------------------------------------------------
+int __fastcall sr_4A46E6_draw_particle_segment(unsigned int x, signed int y, signed int _z, int a4, unsigned int lightColor)
+{
+  int v5; // eax@1
+  int z; // eax@1
+  unsigned int v7; // eax@9
+  unsigned int v8; // ecx@9
+  int v9; // eax@9
+  unsigned int v10; // eax@10
+  int *v11; // esi@10
+  int *v12; // edi@10
+  int v13; // ecx@10
+  int v14; // edx@10
+  unsigned int v15; // eax@22
+  int *v16; // esi@22
+  int *v17; // edi@22
+  int v18; // ecx@22
+  int v19; // edx@22
+  unsigned __int16 *pTarget; // [sp+Ch] [bp-8h]@9
+  int *pTargetZ; // [sp+10h] [bp-4h]@9
+  unsigned int v22; // [sp+1Ch] [bp+8h]@9
+  signed int v23; // [sp+20h] [bp+Ch]@1
+
+  v5 = a4;
+  v23 = _z >> 16;
+  z = x + v5;
+  if ( z >= (signed int)pViewport->uViewportTL_X
+    && (signed int)x <= (signed int)pViewport->uViewportBR_X
+    && y >= (signed int)pViewport->uViewportTL_Y
+    && y <= (signed int)pViewport->uViewportBR_Y )
+  {
+    if ( (signed int)x < (signed int)pViewport->uViewportTL_X )
+      x = pViewport->uViewportTL_X;
+    if ( z > (signed int)pViewport->uViewportBR_X )
+      z = pViewport->uViewportBR_X;
+    pTarget = &pRenderer->pTargetSurface[x + y * pRenderer->uTargetSurfacePitch];
+    v22 = z - x;
+    pTargetZ = &pRenderer->pActiveZBuffer[x + 640 * y];
+    v7 = lightColor >> 3;
+    v8 = lightColor & 0xF0;
+    v9 = v7 & 0x1E0000;
+    if ( pRenderer->uTargetGBits == 5 )
+    {
+      v10 = (v8 | (((unsigned __int16)(lightColor & 0xF000) | (unsigned int)v9) >> 3)) >> 4;
+      v11 = (int *)pTarget;
+      v12 = pTargetZ;
+      v13 = v22;
+      v14 = (v10 << 16) | v10;
+      z = (unsigned __int8)pTarget & 2;
+      if ( (unsigned __int8)pTarget & 2 )
+      {
+        z = (unsigned int)*pTargetZ >> 16;
+        if ( z > v23 )
+        {
+          z = v14 + ((*pTarget & 0x7BDEu) >> 1);
+          *pTarget = z;
+        }
+        v13 = v22 - 1;
+        v11 = (int *)(pTarget + 1);
+        v12 = pTargetZ + 1;
+      }
+      while ( v13 != 1 )
+      {
+        if ( v13 < 1 )
+          return z;
+        z = (unsigned int)*v12 >> 16;
+        if ( z <= v23 )
+        {
+          v13 -= 2;
+          ++v11;
+          v12 += 2;
+        }
+        else
+        {
+          v12 += 2;
+          z = v14 + ((*v11 & 0x7BDE7BDEu) >> 1);
+          v13 -= 2;
+          *v11 = z;
+          ++v11;
+        }
+      }
+      z = (unsigned int)*v12 >> 16;
+      if ( z > v23 )
+      {
+        z = v14 + ((*(short *)v11 & 0x7BDEu) >> 1);
+        *(short *)v11 = z;
+      }
+    }
+    else
+    {
+      v15 = (v8 | (((unsigned __int16)(lightColor & 0xF800) | (unsigned int)v9) >> 2)) >> 4;
+      v16 = (int *)pTarget;
+      v17 = pTargetZ;
+      v18 = v22;
+      v19 = (v15 << 16) | v15;
+      z = (unsigned __int8)pTarget & 2;
+      if ( (unsigned __int8)pTarget & 2 )
+      {
+        z = (unsigned int)*pTargetZ >> 16;
+        if ( z > v23 )
+        {
+          z = v19 + ((*pTarget & 0xF7DEu) >> 1);
+          *pTarget = z;
+        }
+        v18 = v22 - 1;
+        v16 = (int *)(pTarget + 1);
+        v17 = pTargetZ + 1;
+      }
+      while ( v18 != 1 )
+      {
+        if ( v18 < 1 )
+          return z;
+        z = (unsigned int)*v17 >> 16;
+        if ( z <= v23 )
+        {
+          v18 -= 2;
+          ++v16;
+          v17 += 2;
+        }
+        else
+        {
+          v17 += 2;
+          z = v19 + ((*v16 & 0xF7DEF7DEu) >> 1);
+          v18 -= 2;
+          *v16 = z;
+          ++v16;
+        }
+      }
+      z = (unsigned int)*v17 >> 16;
+      if ( z > v23 )
+      {
+        z = v19 + ((*(short *)v16 & 0xF7DEu) >> 1);
+        *(short *)v16 = z;
+      }
+    }
+  }
+  return z;
+}
+
+
+//----- (004A57E9) --------------------------------------------------------
+void Present_ColorKey()
+{
+  HRESULT v0; // eax@3
+  HRESULT v1; // eax@3
+  HRESULT v2; // eax@3
+  HRESULT v3; // eax@3
+  HRESULT v4; // eax@3
+  RECT a2; // [sp+4h] [bp-14h]@3
+  //CheckHRESULT_stru0 this; // [sp+14h] [bp-4h]@3
+
+  if ( !pRenderer->uNumSceneBegins )
+  {
+    if ( pRenderer->using_software_screen_buffer )
+    {
+      a2.bottom = pViewport->uViewportTL_Y;
+      a2.left = 0;
+      a2.top = 0;
+      a2.right = 640;
+      ErrD3D(pRenderer->pBackBuffer4->BltFast(0, 0, pRenderer->pColorKeySurface4, &a2, 16u));
+      a2.right = 640;
+      a2.left = 0;
+      a2.top = pViewport->uViewportBR_Y + 1;
+      a2.bottom = 480;
+      ErrD3D(pRenderer->pBackBuffer4->BltFast(
+             0,
+             pViewport->uViewportBR_Y + 1,
+             pRenderer->pColorKeySurface4,
+             &a2,
+             16u));
+      a2.right = pViewport->uViewportTL_X;
+      a2.bottom = pViewport->uViewportBR_Y + 1;
+      a2.left = 0;
+      a2.top = pViewport->uViewportTL_Y;
+      ErrD3D(pRenderer->pBackBuffer4->BltFast(
+             0,
+             pViewport->uViewportTL_Y,
+             pRenderer->pColorKeySurface4,
+             &a2,
+             16u));
+      a2.left = pViewport->uViewportBR_X;
+      a2.top = pViewport->uViewportTL_Y;
+      a2.right = 640;
+      a2.bottom = pViewport->uViewportBR_Y + 1;
+      ErrD3D(pRenderer->pBackBuffer4->BltFast(
+             pViewport->uViewportBR_X,
+             pViewport->uViewportTL_Y,
+             pRenderer->pColorKeySurface4,
+             &a2,
+             16u));
+      a2.right = pViewport->uViewportBR_X;
+      a2.bottom = pViewport->uViewportBR_Y + 1;
+      a2.left = pViewport->uViewportTL_X;
+      a2.top = pViewport->uViewportTL_Y;
+      ErrD3D(pRenderer->pBackBuffer4->BltFast(
+             pViewport->uViewportTL_X,
+             pViewport->uViewportTL_Y,
+             pRenderer->pColorKeySurface4,
+             &a2,
+             17u));
+    }
+  }
+}
+
+
+//----- (004A48E4) --------------------------------------------------------
+int Render::MakeParticleBillboardAndPush_BLV_Software(int screenSpaceX, int screenSpaceY, int z, int lightColor, int a6)
+{
+  int v6; // ecx@1
+  int v7; // ebx@1
+  int v8; // ecx@1
+  int v9; // edx@1
+  int v10; // edi@1
+  unsigned int x; // esi@1
+  int result; // eax@8
+  int v13; // [sp+Ch] [bp-10h]@1
+  int v14; // [sp+10h] [bp-Ch]@1
+  int v15; // [sp+14h] [bp-8h]@1
+  int v16; // [sp+18h] [bp-4h]@1
+  int v17; // [sp+24h] [bp+8h]@1
+  unsigned int v18; // [sp+28h] [bp+Ch]@1
+  int v19; // [sp+34h] [bp+18h]@1
+
+  v6 = screenSpaceX;
+  v7 = (a6 >> 1) + screenSpaceY;
+  v17 = 0;
+  v15 = 0;
+  v8 = (a6 >> 1) + v6;
+  v14 = (a6 >> 1) * (a6 >> 1);
+  v9 = 2 * (a6 >> 1);
+  v10 = (a6 >> 1) * ((a6 >> 1) - 1);
+  x = v8 - (a6 >> 1);
+  v16 = (a6 >> 1) + screenSpaceY - v8;
+  v19 = a6 >> 1;
+  v13 = v9;
+  v18 = v8;
+  do
+  {
+    sr_4A46E6_draw_particle_segment(x, v16 + v18, z, 2 * v19, lightColor);
+    if ( v15 )
+      sr_4A46E6_draw_particle_segment(x, v17 + v7, z, 2 * v19, lightColor);
+    v14 -= v15;
+    if ( v14 <= v10 )
+    {
+      if ( v19 != v17 )
+      {
+        sr_4A46E6_draw_particle_segment(v18, v16 + x, z, 2 * v17, lightColor);
+        sr_4A46E6_draw_particle_segment(v18, v19 + v7, z, 2 * v17, lightColor);
+      }
+      --v19;
+      v13 -= 2;
+      ++x;
+      v10 -= v13;
+    }
+    result = v17++;
+    v15 += 2;
+    --v18;
+  }
+  while ( result < v19 );
+  return result;
+}
+
 //----- (004637EB) --------------------------------------------------------
 int __stdcall aWinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
 {
@@ -14045,4 +14308,104 @@
   return v19;
 }
 
+
+//----- (0049EBF1) --------------------------------------------------------
+void Render::_stub_49EBF1()
+{
+  signed int uNumRedBits; // edx@1
+  signed int uNuGreenBits; // edi@1
+  signed int uNumBlueBits; // esi@1
+  unsigned int v4; // edx@4
+  unsigned int v5; // edi@4
+  int v6; // ebx@4
+  int v7; // edx@4
+  signed int v8; // [sp+8h] [bp-24h]@1
+  signed int v9; // [sp+Ch] [bp-20h]@1
+  signed int v10; // [sp+20h] [bp-Ch]@1
+  signed int i; // [sp+24h] [bp-8h]@2
+  signed int v12; // [sp+28h] [bp-4h]@3
+
+  v10 = 0;
+  uNumRedBits = 1 << this->uTargetRBits;
+  uNuGreenBits = 1 << this->uTargetGBits;
+  uNumBlueBits = 1 << this->uTargetBBits;
+  v9 = 1 << this->uTargetRBits;
+  v8 = 1 << this->uTargetGBits;
+  if ( uNumRedBits > 0 )
+  {
+    do
+    {
+      for ( i = 0; i < uNuGreenBits; ++i )
+      {
+        v12 = 0;
+        if ( uNumBlueBits > 0 )
+        {
+          do
+          {
+            v4 = this->uTargetBBits;
+            v5 = v4 + this->uTargetGBits;
+            v6 = (v12 >> 1) + (v10 >> 1 << v5) + (i >> 1 << this->uTargetBBits);
+            v7 = (v10 << v5) + v12++ + (i << v4);
+            this->unused_2C[v7] = v6;
+          }
+          while ( v12 < uNumBlueBits );
+          uNumRedBits = v9;
+          uNuGreenBits = v8;
+        }
+      }
+      ++v10;
+    }
+    while ( v10 < uNumRedBits );
+  }
+}
+
+
+//----- (004B0967) --------------------------------------------------------
+void BspRenderer::DrawFaceOutlines()
+{
+  signed int i; // edi@1
+  int v1; // esi@2
+  unsigned int v2; // ecx@4
+  int v3; // eax@4
+  int v4; // eax@6
+  unsigned __int16 *v5; // edx@6
+  int v6; // ecx@7
+  int v7; // esi@8
+
+  for ( i = 0; i < (signed int)pBspRenderer->num_faces; ++i )
+  {
+    v1 = pBspRenderer->faces[i].uFaceID;
+    if ( v1 >= 0 )
+    {
+      if ( v1 < (signed int)pIndoor->uNumFaces )
+      {
+        v2 = pBspRenderer->faces[i].uFaceID;
+        pBLVRenderParams->field_7C = &pBspRenderer->nodes[pBspRenderer->faces[i].uNodeID].PortalScreenData;
+        v3 = GetPortalScreenCoord(v2);
+        if ( v3 )
+        {
+          if ( PortalFrustrum(v3, &stru_F8A590, pBLVRenderParams->field_7C, v1) )
+          {
+            v4 = stru_F8A590._viewport_space_y;
+            v5 = pBLVRenderParams->pRenderTarget;
+            if ( stru_F8A590._viewport_space_y <= stru_F8A590._viewport_space_w )
+            {
+              v6 = 640 * stru_F8A590._viewport_space_y;
+              do
+              {
+                v5[v6 + stru_F8A590.viewport_left_side[v4]] = -1;
+                v7 = v6 + stru_F8A590.viewport_right_side[v4];
+                v6 += 640;
+                v5[v7] = -1;
+                ++v4;
+              }
+              while ( v4 <= stru_F8A590._viewport_space_w );
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
 */
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/EFX-Util.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,446 @@
+/*******************************************************************\
+*                                                                   *
+*  EFX-UTIL.H - EFX Utilities functions and Reverb Presets          *
+*                                                                   *
+*               File revision 1.0                                   *
+*                                                                   *
+\*******************************************************************/
+
+#ifndef EFX_UTIL_H_INCLUDED
+#define EFX_UTIL_H_INCLUDED
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#pragma pack(push, 4)
+
+#ifndef EAXVECTOR_DEFINED
+#define EAXVECTOR_DEFINED
+typedef struct _EAXVECTOR {
+	float x;
+	float y;
+	float z;
+} EAXVECTOR;
+#endif
+
+#ifndef EAXREVERBPROPERTIES_DEFINED
+#define EAXREVERBPROPERTIES_DEFINED
+typedef struct _EAXREVERBPROPERTIES
+{
+    unsigned long ulEnvironment;
+    float flEnvironmentSize;
+    float flEnvironmentDiffusion;
+    long lRoom;
+    long lRoomHF;
+    long lRoomLF;
+    float flDecayTime;
+    float flDecayHFRatio;
+    float flDecayLFRatio;
+    long lReflections;
+    float flReflectionsDelay;
+    EAXVECTOR vReflectionsPan;
+    long lReverb;
+    float flReverbDelay;
+    EAXVECTOR vReverbPan;
+    float flEchoTime;
+    float flEchoDepth;
+    float flModulationTime;
+    float flModulationDepth;
+    float flAirAbsorptionHF;
+    float flHFReference;
+    float flLFReference;
+    float flRoomRolloffFactor;
+    unsigned long ulFlags;
+} EAXREVERBPROPERTIES, *LPEAXREVERBPROPERTIES;
+#endif
+
+#ifndef EFXEAXREVERBPROPERTIES_DEFINED
+#define EFXEAXREVERBPROPERTIES_DEFINED
+typedef struct
+{
+	float flDensity;
+	float flDiffusion;
+	float flGain;
+	float flGainHF;
+	float flGainLF;
+	float flDecayTime;
+	float flDecayHFRatio;
+	float flDecayLFRatio;
+	float flReflectionsGain;
+	float flReflectionsDelay;
+	float flReflectionsPan[3];
+	float flLateReverbGain;
+	float flLateReverbDelay;
+	float flLateReverbPan[3];
+	float flEchoTime;
+	float flEchoDepth;
+	float flModulationTime;
+	float flModulationDepth;
+	float flAirAbsorptionGainHF;
+	float flHFReference;
+	float flLFReference;
+	float flRoomRolloffFactor;
+	int	iDecayHFLimit;
+} EFXEAXREVERBPROPERTIES, *LPEFXEAXREVERBPROPERTIES;
+#endif
+
+#ifndef EAXOBSTRUCTIONPROPERTIES_DEFINED
+#define EAXOBSTRUCTIONPROPERTIES_DEFINED
+typedef struct _EAXOBSTRUCTIONPROPERTIES
+{
+    long          lObstruction;
+    float         flObstructionLFRatio;
+} EAXOBSTRUCTIONPROPERTIES, *LPEAXOBSTRUCTIONPROPERTIES;
+#endif
+
+#ifndef EAXOCCLUSIONPROPERTIES_DEFINED
+#define EAXOCCLUSIONPROPERTIES_DEFINED
+typedef struct _EAXOCCLUSIONPROPERTIES
+{
+    long          lOcclusion;
+    float         flOcclusionLFRatio;
+    float         flOcclusionRoomRatio;
+    float         flOcclusionDirectRatio;
+} EAXOCCLUSIONPROPERTIES, *LPEAXOCCLUSIONPROPERTIES;
+#endif
+
+#ifndef EAXEXCLUSIONPROPERTIES_DEFINED
+#define EAXEXCLUSIONPROPERTIES_DEFINED
+typedef struct _EAXEXCLUSIONPROPERTIES
+{
+    long          lExclusion;
+    float         flExclusionLFRatio;
+} EAXEXCLUSIONPROPERTIES, *LPEAXEXCLUSIONPROPERTIES;
+#endif
+
+#ifndef EFXLOWPASSFILTER_DEFINED
+#define EFXLOWPASSFILTER_DEFINED
+typedef struct _EFXLOWPASSFILTER
+{
+	float		flGain;
+	float		flGainHF;
+} EFXLOWPASSFILTER, *LPEFXLOWPASSFILTER;
+#endif
+
+#ifdef EFXUTILDLL_EXPORTS
+ #define EFX_API __declspec(dllexport)
+#else
+ #define EFX_API
+#endif
+
+EFX_API void __cdecl ConvertReverbParameters(EAXREVERBPROPERTIES *pEAXProp, EFXEAXREVERBPROPERTIES *pEFXEAXReverb);
+EFX_API void __cdecl ConvertObstructionParameters(EAXOBSTRUCTIONPROPERTIES *pObProp, EFXLOWPASSFILTER *pDirectLowPassFilter);
+EFX_API void __cdecl ConvertExclusionParameters(EAXEXCLUSIONPROPERTIES *pExProp, EFXLOWPASSFILTER *pSendLowPassFilter);
+EFX_API void __cdecl ConvertOcclusionParameters(EAXOCCLUSIONPROPERTIES *pOcProp, EFXLOWPASSFILTER *pDirectLowPassFilter, EFXLOWPASSFILTER *pSendLowPassFilter);
+EFX_API void __cdecl AdjustEnvironmentSize(EAXREVERBPROPERTIES *pEAXProp, float flEnvironmentSize);
+
+/***********************************************************************************************\
+*
+* EAX Reverb Presets in legacy format - use ConvertReverbParameters() to convert to
+* EFX EAX Reverb Presets for use with the OpenAL Effects Extension.
+*
+************************************************************************************************/
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_GENERIC \
+	{0,		7.5f,	1.000f,	-1000,	-100,	0,		1.49f,	0.83f,	1.00f,	-2602,	0.007f,	0.00f,0.00f,0.00f,	200,	0.011f,		0.00f,0.00f,0.00f,	0.250f,	0.000f,	0.250f,	0.000f,	-5.0f,	5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_PADDEDCELL \
+	{1,		1.4f,	1.000f,	-1000,	-6000,	0,		0.17f,	0.10f,	1.00f,	-1204,	0.001f, 0.00f,0.00f,0.00f,  207,	0.002f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f,	-5.0f,	5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_ROOM \
+	{2,		1.9f,	1.000f,	-1000,	-454,	0,		0.40f,	0.83f,	1.00f,  -1646,	0.002f, 0.00f,0.00f,0.00f,	53,		0.003f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f,	-5.0f,  5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_BATHROOM \
+	{3,		1.4f,	1.000f,	-1000,  -1200,	0,		1.49f,	0.54f,	1.00f,  -370,	0.007f, 0.00f,0.00f,0.00f,	1030,	0.011f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f,	-5.0f,  5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_LIVINGROOM \
+	{4,		2.5f,	1.000f,	-1000,  -6000,	0,		0.50f,	0.10f,	1.00f,  -1376,	0.003f, 0.00f,0.00f,0.00f,	-1104,	0.004f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f,	-5.0f,  5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_STONEROOM \
+	{5,		11.6f,	1.000f,  -1000, -300,	0,		2.31f,	0.64f,	1.00f,	-711,	0.012f, 0.00f,0.00f,0.00f,	83,		0.017f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f,	-5.0f,  5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_AUDITORIUM \
+	{6,		21.6f,	1.000f,  -1000,	-476,	0,		4.32f,	0.59f,	1.00f,	-789,	0.020f, 0.00f,0.00f,0.00f,	-289,	0.030f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f,	-5.0f,  5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_CONCERTHALL \
+	{7,		19.6f,	1.000f,  -1000,	-500,	0,		3.92f,	0.70f,	1.00f,  -1230,	0.020f, 0.00f,0.00f,0.00f,  -02,	0.029f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_CAVE \
+	{8,		14.6f,	1.000f,  -1000,	0,		0,		2.91f,	1.30f,	1.00f,  -602,	0.015f, 0.00f,0.00f,0.00f,	-302,	0.022f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,	0.00f,	0x1f }
+#define REVERB_PRESET_ARENA \
+	{9,		36.2f,	1.000f,  -1000,	-698,	0,		7.24f,	0.33f,	1.00f,  -1166,	0.020f, 0.00f,0.00f,0.00f,  16,		0.030f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,	0.00f,	0x3f }
+#define REVERB_PRESET_HANGAR \
+	{10,	50.3f,	1.000f,  -1000,	-1000,	0,		10.05f, 0.23f,	1.00f,  -602,	0.020f, 0.00f,0.00f,0.00f,  198,	0.030f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_CARPETTEDHALLWAY \
+	{11,	1.9f,	1.000f,	-1000,	-4000,	0,		0.30f,	0.10f,	1.00f,  -1831,	0.002f, 0.00f,0.00f,0.00f,	-1630,	0.030f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_HALLWAY \
+	{12,	1.8f,	1.000f,	-1000,	-300,	0,		1.49f,	0.59f,	1.00f,  -1219,	0.007f, 0.00f,0.00f,0.00f,  441,	0.011f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_STONECORRIDOR \
+	{13,	13.5f,	1.000f,	-1000,	-237,	0,		2.70f,	0.79f,	1.00f,  -1214,	0.013f, 0.00f,0.00f,0.00f,  395,	0.020f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_ALLEY \
+	{14,	7.5f,	0.300f,	-1000,	-270,	0,		1.49f,	0.86f,	1.00f,  -1204,	0.007f, 0.00f,0.00f,0.00f,  -4,		0.011f,		0.00f,0.00f,0.00f,	0.125f, 0.950f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_FOREST \
+	{15,	38.0f,	0.300f,	-1000,	-3300,	0,		1.49f,	0.54f,	1.00f,  -2560,	0.162f, 0.00f,0.00f,0.00f,	-229,	0.088f,		0.00f,0.00f,0.00f,	0.125f, 1.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_CITY \
+	{16,	7.5f,	0.500f,	-1000,	-800,	0,		1.49f,	0.67f,	1.00f,  -2273,	0.007f, 0.00f,0.00f,0.00f,	-1691,	0.011f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_MOUNTAINS \
+	{17,	100.0f, 0.270f,	-1000,	-2500,	0,		1.49f,	0.21f,	1.00f,  -2780,	0.300f, 0.00f,0.00f,0.00f,	-1434,	0.100f,		0.00f,0.00f,0.00f,	0.250f, 1.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x1f }
+#define REVERB_PRESET_QUARRY \
+	{18,	17.5f,	1.000f,	-1000,	-1000,	0,		1.49f,	0.83f,	1.00f,	-10000, 0.061f, 0.00f,0.00f,0.00f,  500,	0.025f,		0.00f,0.00f,0.00f,	0.125f, 0.700f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_PLAIN \
+	{19,	42.5f,	0.210f,	-1000,	-2000,	0,		1.49f,	0.50f,	1.00f,  -2466,	0.179f, 0.00f,0.00f,0.00f,	-1926,	0.100f,		0.00f,0.00f,0.00f,	0.250f, 1.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_PARKINGLOT \
+	{20,	8.3f,	1.000f,	-1000,	0,		0,		1.65f,	1.50f,	1.00f,  -1363,	0.008f, 0.00f,0.00f,0.00f,	-1153,	0.012f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x1f }
+#define REVERB_PRESET_SEWERPIPE \
+	{21,	1.7f,	0.800f,	-1000,	-1000,	0,		2.81f,	0.14f,	1.00f,	429,	0.014f, 0.00f,0.00f,0.00f,	1023,	0.021f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_UNDERWATER \
+	{22,	1.8f,	1.000f,	-1000,  -4000,	0,		1.49f,	0.10f,	1.00f,  -449,	0.007f, 0.00f,0.00f,0.00f,	1700,	0.011f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 1.180f, 0.348f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_DRUGGED \
+	{23,	1.9f,	0.500f,	-1000,	0,		0,		8.39f,	1.39f,	1.00f,  -115,	0.002f, 0.00f,0.00f,0.00f,  985,	0.030f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 1.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x1f }
+#define REVERB_PRESET_DIZZY \
+	{24,	1.8f,	0.600f,	-1000,	-400,	0,		17.23f, 0.56f,	1.00f,  -1713,	0.020f, 0.00f,0.00f,0.00f,	-613,	0.030f,		0.00f,0.00f,0.00f,	0.250f, 1.000f, 0.810f, 0.310f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x1f }
+#define REVERB_PRESET_PSYCHOTIC \
+	{25,	1.0f,	0.500f,	-1000,	-151,	0,		7.56f,	0.91f,	1.00f,  -626,	0.020f, 0.00f,0.00f,0.00f,  774,	0.030f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 4.000f, 1.000f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x1f }
+
+
+// CASTLE PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_CASTLE_SMALLROOM \
+	{ 26,   8.3f,	0.890f,	-1000,	-800,	-2000,	1.22f,	0.83f,	0.31f,	-100,	0.022f,	0.00f,0.00f,0.00f,	600,	0.011f,		0.00f,0.00f,0.00f,	0.138f,	0.080f,	0.250f,	0.000f,	-5.0f,	5168.6f,	139.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_CASTLE_SHORTPASSAGE \
+	{ 26,   8.3f,	0.890f, -1000,  -1000,  -2000,  2.32f,	0.83f,	0.31f,	-100,	0.007f, 0.00f,0.00f,0.00f,  200,		0.023f,		0.00f,0.00f,0.00f,	0.138f, 0.080f, 0.250f, 0.000f, -5.0f,  5168.6f,	139.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_CASTLE_MEDIUMROOM \
+	{ 26,   8.3f,	0.930f, -1000,  -1100,  -2000,  2.04f,	0.83f,	0.46f,  -400,	0.022f, 0.00f,0.00f,0.00f,	400,	0.011f,		0.00f,0.00f,0.00f,	0.155f, 0.030f, 0.250f, 0.000f, -5.0f,  5168.6f,	139.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_CASTLE_LONGPASSAGE \
+	{ 26,   8.3f,	0.890f, -1000,  -800,	-2000,  3.42f,	0.83f,	0.31f,  -100,	0.007f, 0.00f,0.00f,0.00f,	300,	0.023f,		0.00f,0.00f,0.00f,	0.138f, 0.080f, 0.250f, 0.000f, -5.0f,  5168.6f,	139.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_CASTLE_LARGEROOM \
+	{ 26,   8.3f,	0.820f, -1000,  -1100,  -1800,  2.53f,	0.83f,	0.50f,  -700,	0.034f, 0.00f,0.00f,0.00f,	200,		0.016f,		0.00f,0.00f,0.00f,	0.185f, 0.070f, 0.250f, 0.000f, -5.0f,  5168.6f,	139.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_CASTLE_HALL \
+	{ 26,   8.3f,	0.810f, -1000,  -1100,  -1500,  3.14f,	0.79f,	0.62f,  -1500,	0.056f, 0.00f,0.00f,0.00f,	100,	0.024f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5168.6f,	139.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_CASTLE_CUPBOARD \
+	{ 26,   8.3f,	0.890f, -1000,  -1100,  -2000,  0.67f,	0.87f,	0.31f,  300,	0.010f,	0.00f,0.00f,0.00f,	1100,	0.007f,		0.00f,0.00f,0.00f,	0.138f, 0.080f, 0.250f, 0.000f, -5.0f,  5168.6f,	139.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_CASTLE_COURTYARD \
+	{ 26,   8.3f,	0.420f, -1000,  -700,   -1400,	2.13f,	0.61f,	0.23f,  -1300,	0.160f, 0.00f,0.00f,0.00f,	-300,	0.036f,		0.00f,0.00f,0.00f,	0.250f, 0.370f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x1f }
+#define REVERB_PRESET_CASTLE_ALCOVE \
+	{ 26,   8.3f,	0.890f,	-1000,  -600,	-2000,  1.64f,	0.87f,	0.31f,  00,	0.007f, 0.00f,0.00f,0.00f,		300,	0.034f,		0.00f,0.00f,0.00f,	0.138f, 0.080f, 0.250f, 0.000f, -5.0f,	5168.6f,	139.5f,  0.00f, 0x20 }
+
+
+// FACTORY PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_FACTORY_ALCOVE \
+	{ 26,   1.8f,	0.590f,  -1200, -200,   -600,	3.14f,	0.65f,	1.31f,  300,	0.010f, 0.00f,0.00f,0.00f,	000,	0.038f,		0.00f,0.00f,0.00f,	0.114f, 0.100f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_SHORTPASSAGE \
+	{ 26,   1.8f,	0.640f,  -1200, -200,   -600,	2.53f,	0.65f,	1.31f,  0,		0.010f, 0.00f,0.00f,0.00f,	200,	0.038f,		0.00f,0.00f,0.00f,	0.135f, 0.230f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_MEDIUMROOM \
+	{ 26,   1.9f,	0.820f,  -1200, -200,   -600,	2.76f,	0.65f,	1.31f,  -1100,	0.022f, 0.00f,0.00f,0.00f,	300,	0.023f,		0.00f,0.00f,0.00f,	0.174f, 0.070f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_LONGPASSAGE \
+	{ 26,   1.8f,	0.640f,  -1200, -200,   -600,	4.06f,	0.65f,	1.31f,  0,		0.020f, 0.00f,0.00f,0.00f,	200,	0.037f,		0.00f,0.00f,0.00f,	0.135f, 0.230f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_LARGEROOM \
+	{ 26,   1.9f,	0.750f,  -1200, -300,   -400,	4.24f,	0.51f,	1.31f,  -1500,	0.039f, 0.00f,0.00f,0.00f,	100,		0.023f,		0.00f,0.00f,0.00f,	0.231f, 0.070f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_HALL \
+	{ 26,   1.9f,	0.750f,  -1000, -300,   -400,	7.43f,	0.51f,	1.31f,  -2400,	0.073f, 0.00f,0.00f,0.00f,	-100,	0.027f,		0.00f,0.00f,0.00f,	0.250f, 0.070f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_CUPBOARD \
+	{ 26,   1.7f,	0.630f,  -1200, -200,   -600,	0.49f,	0.65f,	1.31f,  200,	0.010f, 0.00f,0.00f,0.00f,	600,	0.032f,		0.00f,0.00f,0.00f,	0.107f, 0.070f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_COURTYARD \
+	{ 26,   1.7f,	0.570f,  -1000, -1000,  -400,	2.32f,	0.29f,	0.56f,  -1300,	0.140f, 0.00f,0.00f,0.00f,	-800,	0.039f,		0.00f,0.00f,0.00f,	0.250f, 0.290f, 0.250f, 0.000f, -5.0f,  3762.6f,	362.5f,  0.00f, 0x20 }
+#define REVERB_PRESET_FACTORY_SMALLROOM \
+	{ 26,   1.8f,	0.820f,  -1000,	-200,   -600,	1.72f,	0.65f,	1.31f,  -300,	0.010f, 0.00f,0.00f,0.00f,	500,	0.024f,		0.00f,0.00f,0.00f,	0.119f, 0.070f, 0.250f, 0.000f, -5.0f,	3762.6f,	362.5f,  0.00f, 0x20 }
+
+
+// ICE PALACE PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_ICEPALACE_ALCOVE \
+	{ 26,   2.7f,	0.840f, -1000,  -500,	-1100,  2.76f,	1.46f,	0.28f,  100,	0.010f, 0.00f,0.00f,0.00f,	-100,	0.030f,		0.00f,0.00f,0.00f,	0.161f, 0.090f, 0.250f, 0.000f,	-5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_SHORTPASSAGE \
+	{ 26,   2.7f,	0.750f, -1000,  -500,	-1100,  1.79f,	1.46f,	0.28f,  -600,	0.010f, 0.00f,0.00f,0.00f,	100,		0.019f,		0.00f,0.00f,0.00f,	0.177f, 0.090f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_MEDIUMROOM \
+	{ 26,   2.7f,	0.870f, -1000,  -500,   -700,	2.22f,	1.53f,	0.32f,  -800,	0.039f, 0.00f,0.00f,0.00f,	100,	0.027f,		0.00f,0.00f,0.00f,	0.186f, 0.120f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_LONGPASSAGE \
+	{ 26,   2.7f,	0.770f, -1000,  -500,   -800,	3.01f,	1.46f,	0.28f,  -200,	0.012f, 0.00f,0.00f,0.00f,	200,	0.025f,		0.00f,0.00f,0.00f,	0.186f, 0.040f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_LARGEROOM \
+	{ 26,   2.9f,	0.810f, -1000,  -500,   -700,	3.14f,	1.53f,	0.32f,  -1200,	0.039f, 0.00f,0.00f,0.00f,	000,	0.027f,		0.00f,0.00f,0.00f,	0.214f, 0.110f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_HALL \
+	{ 26,   2.9f,	0.760f, -1000,  -700,   -500,	5.49f,	1.53f,	0.38f,  -1900,	0.054f, 0.00f,0.00f,0.00f,	-400,	0.052f,		0.00f,0.00f,0.00f,	0.226f, 0.110f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_CUPBOARD \
+	{ 26,   2.7f,	0.830f, -1000,  -600,	-1300,  0.76f,	1.53f,	0.26f,  100,	0.012f, 0.00f,0.00f,0.00f,	600,	0.016f,		0.00f,0.00f,0.00f,	0.143f, 0.080f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_COURTYARD \
+	{ 26,   2.9f,	0.590f, -1000,  -1100,  -1000,  2.04f,	1.20f,	0.38f,  -1000,	0.173f, 0.00f,0.00f,0.00f,	-1000,	0.043f,		0.00f,0.00f,0.00f,	0.235f, 0.480f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+#define REVERB_PRESET_ICEPALACE_SMALLROOM \
+	{ 26,   2.7f,	0.840f, -1000,  -500,	-1100,  1.51f,	1.53f,	0.27f,	-100,	0.010f, 0.00f,0.00f,0.00f,	300,	0.011f,		0.00f,0.00f,0.00f,	0.164f, 0.140f, 0.250f, 0.000f, -5.0f,	12428.5f,	99.6f,  0.00f,	0x20 }
+
+
+// SPACE STATION PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_SPACESTATION_ALCOVE \
+	{ 26,   1.5f,	0.780f, -1000,  -300,   -100,	1.16f,	0.81f,	0.55f,  300,	0.007f, 0.00f,0.00f,0.00f,	000,	0.018f,		0.00f,0.00f,0.00f,	0.192f, 0.210f, 0.250f, 0.000f,	-5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPACESTATION_MEDIUMROOM \
+	{ 26,   1.5f,	0.750f, -1000,  -400,   -100,	3.01f,	0.50f,	0.55f,  -800,	0.034f, 0.00f,0.00f,0.00f,	100,		0.035f,		0.00f,0.00f,0.00f,	0.209f, 0.310f, 0.250f, 0.000f,	-5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPACESTATION_SHORTPASSAGE \
+	{ 26,   1.5f,	0.870f, -1000,  -400,   -100,	3.57f,	0.50f,	0.55f,  0,		0.012f, 0.00f,0.00f,0.00f,	100,		0.016f,		0.00f,0.00f,0.00f,	0.172f, 0.200f, 0.250f, 0.000f, -5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPACESTATION_LONGPASSAGE \
+	{ 26,   1.9f,	0.820f, -1000,  -400,   -100,	4.62f,	0.62f,	0.55f,  0,		0.012f, 0.00f,0.00f,0.00f,	200,		0.031f,		0.00f,0.00f,0.00f,	0.250f, 0.230f, 0.250f, 0.000f, -5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPACESTATION_LARGEROOM \
+	{ 26,   1.8f,	0.810f, -1000,  -400,   -100,	3.89f,	0.38f,	0.61f,  -1000,	0.056f, 0.00f,0.00f,0.00f,	-100,	0.035f,		0.00f,0.00f,0.00f,	0.233f, 0.280f, 0.250f, 0.000f, -5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPACESTATION_HALL \
+	{ 26,   1.9f,	0.870f, -1000,  -400,   -100,	7.11f,	0.38f,	0.61f,  -1500,	0.100f, 0.00f,0.00f,0.00f,	-400,	0.047f,		0.00f,0.00f,0.00f,	0.250f, 0.250f, 0.250f, 0.000f, -5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPACESTATION_CUPBOARD \
+	{ 26,   1.4f,	0.560f, -1000,  -300,   -100,	0.79f,	0.81f,	0.55f,  300,	0.007f, 0.00f,0.00f,0.00f,	500,	0.018f,		0.00f,0.00f,0.00f,	0.181f, 0.310f, 0.250f, 0.000f, -5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPACESTATION_SMALLROOM \
+	{ 26,   1.5f,	0.700f, -1000,  -300,   -100,	1.72f,	0.82f,	0.55f,	-200,	0.007f, 0.00f,0.00f,0.00f,	300,	0.013f,		0.00f,0.00f,0.00f,	0.188f, 0.260f, 0.250f, 0.000f, -5.0f,  3316.1f,	458.2f,  0.00f, 0x20 }
+
+
+// WOODEN GALLEON PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_WOODEN_ALCOVE \
+	{ 26,   7.5f,	1.000f, -1000,  -1800,  -1000,  1.22f,	0.62f,	0.91f,	100,	0.012f, 0.00f,0.00f,0.00f,	-300,	0.024f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_SHORTPASSAGE \
+	{ 26,   7.5f,	1.000f, -1000,  -1800,  -1000,  1.75f,	0.50f,	0.87f,	-100,	0.012f, 0.00f,0.00f,0.00f,	-400,	0.024f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_MEDIUMROOM \
+	{ 26,   7.5f,	1.000f, -1000,  -2000,  -1100,  1.47f,	0.42f,	0.82f,	-100,	0.049f, 0.00f,0.00f,0.00f,	-100,	0.029f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_LONGPASSAGE \
+	{ 26,   7.5f,	1.000f, -1000,  -2000,  -1000,  1.99f,	0.40f,	0.79f,	000,	0.020f, 0.00f,0.00f,0.00f,	-700,	0.036f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_LARGEROOM \
+	{ 26,   7.5f,	1.000f, -1000,  -2100,  -1100,  2.65f,	0.33f,	0.82f,	-100,	0.066f, 0.00f,0.00f,0.00f,	-200,	0.049f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_HALL \
+	{ 26,   7.5f,	1.000f, -1000,  -2200,  -1100,  3.45f,	0.30f,	0.82f,	-100,	0.088f, 0.00f,0.00f,0.00f,	-200,	0.063f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_CUPBOARD \
+	{ 26,   7.5f,	1.000f, -1000,  -1700,  -1000,  0.56f,	0.46f,	0.91f,	100,	0.012f, 0.00f,0.00f,0.00f,	100,	0.028f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_SMALLROOM \
+	{ 26,   7.5f,	1.000f, -1000,  -1900,  -1000,  0.79f,	0.32f,	0.87f,	00,		0.032f, 0.00f,0.00f,0.00f,	-100,	0.029f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+#define REVERB_PRESET_WOODEN_COURTYARD \
+	{ 26,   7.5f,	0.650f, -1000,  -2200,  -1000,  1.79f,	0.35f,	0.79f,	-500,	0.123f, 0.00f,0.00f,0.00f,	-2000,	0.032f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  4705.0f,	99.6f,  0.00f,	0x3f }
+
+
+// SPORTS PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_SPORT_EMPTYSTADIUM \
+	{ 26,   7.2f,	1.000f, -1000,  -700,   -200,	6.26f,	0.51f,	1.10f,  -2400,	0.183f, 0.00f,0.00f,0.00f,	-800,	0.038f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPORT_SQUASHCOURT \
+	{ 26,   7.5f,	0.750f, -1000,  -1000,  -200,	2.22f,	0.91f,	1.16f,  -700,	0.007f, 0.00f,0.00f,0.00f,	-200,	0.011f,		0.00f,0.00f,0.00f,	0.126f, 0.190f, 0.250f, 0.000f, -5.0f,  7176.9f,	211.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPORT_SMALLSWIMMINGPOOL \
+	{ 26,  36.2f,	0.700f, -1000,  -200,   -100,	2.76f,	1.25f,	1.14f,  -400,	0.020f, 0.00f,0.00f,0.00f,	-200,	0.030f,		0.00f,0.00f,0.00f,	0.179f, 0.150f, 0.895f, 0.190f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x0 }
+#define REVERB_PRESET_SPORT_LARGESWIMMINGPOOL\
+	{ 26,  36.2f,	0.820f, -1000,  -200,   0,		5.49f,	1.31f,	1.14f,  -700,	0.039f, 0.00f,0.00f,0.00f,	-600,	0.049f,		0.00f,0.00f,0.00f,	0.222f, 0.550f, 1.159f, 0.210f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x0 }
+#define REVERB_PRESET_SPORT_GYMNASIUM \
+	{ 26,   7.5f,	0.810f, -1000,  -700,   -100,	3.14f,	1.06f,	1.35f,  -800,	0.029f, 0.00f,0.00f,0.00f,	-500,	0.045f,		0.00f,0.00f,0.00f,	0.146f, 0.140f, 0.250f, 0.000f, -5.0f,  7176.9f,	211.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPORT_FULLSTADIUM \
+	{ 26,   7.2f,	1.000f, -1000,  -2300,  -200,	5.25f,	0.17f,	0.80f,  -2000,	0.188f, 0.00f,0.00f,0.00f,	-1100,	0.038f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_SPORT_STADIUMTANNOY \
+	{ 26,   3.0f,	0.780f, -1000,   -500,   -600,	2.53f,	0.88f,	0.68f,  -1100,	0.230f, 0.00f,0.00f,0.00f,	-600,	0.063f,		0.00f,0.00f,0.00f,	0.250f, 0.200f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+
+
+// PREFAB PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_PREFAB_WORKSHOP \
+	{ 26,   1.9f,	1.000f, -1000,  -1700,  -800,	0.76f,	1.00f,	1.00f,	0,		0.012f, 0.00f,0.00f,0.00f,	100,		0.012f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x0 }
+#define REVERB_PRESET_PREFAB_SCHOOLROOM \
+	{ 26,   1.86f,	0.690f, -1000,  -400,   -600,	0.98f,	0.45f,	0.18f,  300,	0.017f, 0.00f,0.00f,0.00f,  300,	0.015f,		0.00f,0.00f,0.00f,	0.095f, 0.140f, 0.250f, 0.000f, -5.0f,  7176.9f,	211.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_PREFAB_PRACTISEROOM \
+	{ 26,   1.86f,	0.870f, -1000,  -800,   -600,	1.12f,	0.56f,	0.18f,  200,	0.010f, 0.00f,0.00f,0.00f,	300,	0.011f,		0.00f,0.00f,0.00f,	0.095f, 0.140f, 0.250f, 0.000f, -5.0f,  7176.9f,	211.2f,  0.00f, 0x20 }
+#define REVERB_PRESET_PREFAB_OUTHOUSE \
+	{ 26,  80.3f,	0.820f, -1000,  -1900,  -1600,  1.38f,	0.38f,	0.35f,	-100,	0.024f, 0.00f,0.00f,-0.00f,	-400,	0.044f,		0.00f,0.00f,0.00f,	0.121f, 0.170f, 0.250f, 0.000f, -5.0f,  2854.4f,	107.5f,  0.00f, 0x0 }
+#define REVERB_PRESET_PREFAB_CARAVAN \
+	{ 26,   8.3f,	1.000f, -1000,  -2100,  -1800,  0.43f,	1.50f,	1.00f,  0,		0.012f, 0.00f,0.00f,0.00f,	600,	0.012f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x1f }
+			// for US developers, a caravan is the same as a trailer =o)
+
+
+// DOME AND PIPE PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_DOME_TOMB \
+	{ 26,  51.8f,	0.790f, -1000,  -900,	-1300,  4.18f,	0.21f,	0.10f,  -825,	0.030f, 0.00f,0.00f,0.00f,	450,	0.022f,		0.00f,0.00f,0.00f,	0.177f, 0.190f, 0.250f, 0.000f,	-5.0f,  2854.4f,	20.0f,  0.00f,	0x0 }
+#define REVERB_PRESET_PIPE_SMALL \
+	{ 26,  50.3f,	1.000f, -1000,  -900,	-1300,  5.04f,	0.10f,	0.10f,  -600,	0.032f, 0.00f,0.00f,0.00f,	800,	0.015f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  2854.4f,	20.0f,  0.00f,	0x3f }
+#define REVERB_PRESET_DOME_SAINTPAULS \
+	{ 26,  50.3f,	0.870f, -1000,  -900,	-1300,  10.48f,	0.19f,	0.10f,  -1500,	0.090f, 0.00f,0.00f,0.00f,	200,	0.042f,		0.00f,0.00f,0.00f,	0.250f, 0.120f, 0.250f, 0.000f, -5.0f,  2854.4f,	20.0f,  0.00f,	0x3f }
+#define REVERB_PRESET_PIPE_LONGTHIN \
+	{ 26,   1.6f,	0.910f, -1000,  -700,	-1100,  9.21f,	0.18f,	0.10f,  -300,	0.010f, 0.00f,0.00f,0.00f,	-300,	0.022f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  2854.4f,	20.0f,  0.00f,	0x0 }
+#define REVERB_PRESET_PIPE_LARGE \
+	{ 26,  50.3f,	1.000f, -1000,  -900,	-1300,  8.45f,	0.10f,	0.10f,  -800,	0.046f, 0.00f,0.00f,0.00f,  400,	0.032f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  2854.4f,	20.0f,  0.00f,	0x3f }
+#define REVERB_PRESET_PIPE_RESONANT \
+	{ 26,   1.3f,	0.910f, -1000,  -700,	-1100,  6.81f,	0.18f,	0.10f,  -300,	0.010f, 0.00f,0.00f,0.00f,	00,		0.022f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,  2854.4f,	20.0f,  0.00f,	0x0 }
+
+
+// OUTDOORS PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_OUTDOORS_BACKYARD \
+	{ 26,  80.3f,	0.450f,	-1000,  -1200,  -600,	1.12f,	0.34f,	0.46f,  -700,	0.069f, 0.00f,0.00f,-0.00f,	-300,	0.023f,		0.00f,0.00f,0.00f,	0.218f, 0.340f, 0.250f, 0.000f,	-5.0f,  4399.1f,	242.9f,  0.00f, 0x0 }
+#define REVERB_PRESET_OUTDOORS_ROLLINGPLAINS \
+	{ 26,  80.3f,	0.000f,	-1000,  -3900,  -400,	2.13f,	0.21f,	0.46f,  -1500,	0.300f, 0.00f,0.00f,-0.00f,	-700,	0.019f,		0.00f,0.00f,0.00f,	0.250f, 1.000f, 0.250f, 0.000f, -5.0f,  4399.1f,	242.9f,  0.00f, 0x0 }
+#define REVERB_PRESET_OUTDOORS_DEEPCANYON \
+	{ 26,  80.3f,	0.740f,	-1000,  -1500,  -400,	3.89f,	0.21f,	0.46f,  -1000,	0.223f, 0.00f,0.00f,-0.00f,	-900,	0.019f,		0.00f,0.00f,0.00f,	0.250f, 1.000f, 0.250f, 0.000f, -5.0f,  4399.1f,	242.9f,  0.00f, 0x0 }
+#define REVERB_PRESET_OUTDOORS_CREEK \
+	{ 26,  80.3f,	0.350f,	-1000,  -1500,  -600,	2.13f,	0.21f,	0.46f,  -800,	0.115f, 0.00f,0.00f,-0.00f,	-1400,	0.031f,		0.00f,0.00f,0.00f,	0.218f, 0.340f, 0.250f, 0.000f, -5.0f,  4399.1f,	242.9f,  0.00f, 0x0 }
+#define REVERB_PRESET_OUTDOORS_VALLEY \
+	{ 26,  80.3f,	0.280f,	-1000,  -3100,	-1600,  2.88f,	0.26f,	0.35f,  -1700,	0.263f, 0.00f,0.00f,-0.00f,	-800,	0.100f,		0.00f,0.00f,0.00f,	0.250f, 0.340f, 0.250f, 0.000f, -5.0f,  2854.4f,	107.5f,  0.00f, 0x0 }
+
+
+// MOOD PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_MOOD_HEAVEN \
+	{ 26,  19.6f,	0.940f,  -1000, -200,   -700,	5.04f,	1.12f,	0.56f,  -1230,	0.020f, 0.00f,0.00f,0.00f,	200,	0.029f,		0.00f,0.00f,0.00f,	0.250f, 0.080f, 2.742f, 0.050f, -2.0f,  5000.0f,	250.0f,  0.00f, 0x3f }
+#define REVERB_PRESET_MOOD_HELL \
+	{ 26, 100.0f,	0.570f,  -1000, -900,   -700,	3.57f,	0.49f,	2.00f,	-10000, 0.020f, 0.00f,0.00f,0.00f,	300,	0.030f,		0.00f,0.00f,0.00f,	0.110f, 0.040f, 2.109f, 0.520f, -5.0f,  5000.0f,	139.5f,  0.00f, 0x40 }
+#define REVERB_PRESET_MOOD_MEMORY \
+	{ 26,   8.0f,	0.850f,  -1000, -400,   -900,	4.06f,	0.82f,	0.56f,  -2800,	0.000f, 0.00f,0.00f,0.00f,	100,	0.000f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.474f, 0.450f, -10.0f,  5000.0f,	250.0f,  0.00f, 0x0 }
+
+
+// DRIVING SIMULATION PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_DRIVING_COMMENTATOR \
+	{ 26,   3.0f,	0.000f, -1000,  -500,   -600,	2.42f,	0.88f,	0.68f,  -1400,	0.093f, 0.00f,0.00f,0.00f,	-1200,	0.017f,		0.00f,0.00f,0.00f,	0.250f, 1.000f, 0.250f, 0.000f, -10.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_DRIVING_PITGARAGE \
+	{ 26,   1.9f,	0.590f, -1000,  -300,   -500,	1.72f,	0.93f,	0.87f,  -500,	0.000f, 0.00f,0.00f,0.00f,	200,		0.016f,		0.00f,0.00f,0.00f,	0.250f, 0.110f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x0 }
+#define REVERB_PRESET_DRIVING_INCAR_RACER \
+	{ 26,   1.1f,	0.800f, -1000,   0,		-200,	0.17f,	2.00f,	0.41f,  500,	0.007f, 0.00f,0.00f,0.00f,	-300,	0.015f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,	10268.2f,	251.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_DRIVING_INCAR_SPORTS \
+	{ 26,   1.1f,	0.800f, -1000,	-400,   0,		0.17f,	0.75f,	0.41f,  0,		0.010f, 0.00f,0.00f,0.00f,	-500,	0.000f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,	10268.2f,	251.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_DRIVING_INCAR_LUXURY \
+	{ 26,   1.6f,	1.000f, -1000,	-2000,  -600,	0.13f,	0.41f,	0.46f,  -200,	0.010f, 0.00f,0.00f,0.00f,	400,	0.010f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,	10268.2f,	251.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_DRIVING_FULLGRANDSTAND \
+	{ 26,   8.3f,	1.000f, -1000,  -1100,  -400,	3.01f,	1.37f,	1.28f,  -900,	0.090f, 0.00f,0.00f,0.00f,	-1500,	0.049f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,	10420.2f,	250.0f,  0.00f, 0x1f }
+#define REVERB_PRESET_DRIVING_EMPTYGRANDSTAND \
+	{ 26,   8.3f,	1.000f, -1000,   0,		-200,	4.62f,	1.75f,	1.40f,  -1363,	0.090f, 0.00f,0.00f,0.00f,	-1200,	0.049f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.000f, -5.0f,	10420.2f,	250.0f,  0.00f, 0x1f }
+#define REVERB_PRESET_DRIVING_TUNNEL \
+	{ 26,   3.1f,	0.810f, -1000,   -800,	-100,	3.42f,	0.94f,	1.31f,  -300,	0.051f, 0.00f,0.00f,0.00f,  -300,	0.047f,		0.00f,0.00f,0.00f,	0.214f, 0.050f, 0.250f, 0.000f, -5.0f,  5000.0f,	155.3f,  0.00f, 0x20 }
+
+
+// CITY PRESETS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_CITY_STREETS \
+	{ 26,   3.0f,	0.780f, -1000,  -300,   -100,	1.79f,	1.12f,	0.91f,  -1100,	0.046f, 0.00f,0.00f,0.00f,	-1400,	0.028f,		0.00f,0.00f,0.00f,	0.250f, 0.200f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_CITY_SUBWAY \
+	{ 26,   3.0f,	0.740f, -1000,  -300,   -100,	3.01f,	1.23f,	0.91f,   -300,	0.046f, 0.00f,0.00f,0.00f,	200,	0.028f,		0.00f,0.00f,0.00f,	0.125f, 0.210f, 0.250f, 0.000f, -5.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_CITY_MUSEUM \
+	{ 26,  80.3f,	0.820f, -1000,  -1500,  -1500,  3.28f,	1.40f,	0.57f,  -1200,	0.039f, 0.00f,0.00f,-0.00f, -100,	0.034f,		0.00f,0.00f,0.00f,	0.130f, 0.170f, 0.250f, 0.000f, -5.0f,  2854.4f,	107.5f,  0.00f, 0x0 }
+#define REVERB_PRESET_CITY_LIBRARY \
+	{ 26,  80.3f,	0.820f, -1000,  -1100,  -2100,  2.76f,	0.89f,	0.41f,  -900,	0.029f, 0.00f,0.00f,-0.00f, -100,	0.020f,		0.00f,0.00f,0.00f,	0.130f, 0.170f, 0.250f, 0.000f, -5.0f,  2854.4f,	107.5f,  0.00f, 0x0 }
+#define REVERB_PRESET_CITY_UNDERPASS \
+	{ 26,   3.0f,	0.820f, -1000,  -700,   -100,	3.57f,	1.12f,	0.91f,  -800,	0.059f, 0.00f,0.00f,0.00f,	-100,	0.037f,		0.00f,0.00f,0.00f,	0.250f, 0.140f, 0.250f, 0.000f, -7.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+#define REVERB_PRESET_CITY_ABANDONED \
+	{ 26,   3.0f,	0.690f, -1000,  -200,   -100,	3.28f,	1.17f,	0.91f,  -700,	0.044f, 0.00f,0.00f,0.00f,	-1100,	0.024f,		0.00f,0.00f,0.00f,	0.250f, 0.200f, 0.250f, 0.000f, -3.0f,  5000.0f,	250.0f,  0.00f, 0x20 }
+
+
+// MISC ROOMS
+
+//	Env		Size	Diffus	Room	RoomHF	RoomLF	DecTm	DcHF	DcLF	Refl	RefDel	Ref Pan				Revb	RevDel		Rev Pan				EchTm	EchDp	ModTm	ModDp	AirAbs	HFRef		LFRef	RRlOff	FLAGS
+#define REVERB_PRESET_DUSTYROOM  \
+	{ 26,   1.8f,	0.560f,	-1000,	-200,	-300,	1.79f,	0.38f,	0.21f,	-600,	0.002f,	0.00f,0.00f,0.00f,	200,	0.006f,		0.00f,0.00f,0.00f,	0.202f, 0.050f, 0.250f, 0.000f, -10.0f,  13046.0f,	163.3f,	0.00f,	0x20 }
+#define REVERB_PRESET_CHAPEL \
+	{ 26,  19.6f,	0.840f,	-1000,  -500,	0,		4.62f,	0.64f,	1.23f,  -700,	0.032f,	0.00f,0.00f,0.00f,	-200,	0.049f,		0.00f,0.00f,0.00f,	0.250f, 0.000f, 0.250f, 0.110f, -5.0f,  5000.0f,	250.0f, 0.00f,	0x3f }
+#define REVERB_PRESET_SMALLWATERROOM \
+	{ 26,  36.2f,	0.700f, -1000,  -698,   0,		1.51f,	1.25f,	1.14f,  -100,	0.020f, 0.00f,0.00f,0.00f,	300,	0.030f,		0.00f,0.00f,0.00f,	0.179f, 0.150f, 0.895f, 0.190f, -7.0f,  5000.0f,	250.0f, 0.00f, 0x0 }
+
+
+#pragma pack(pop)
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // EFX-UTIL_H_INCLUDED
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/al.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,732 @@
+#ifndef AL_AL_H
+#define AL_AL_H
+
+
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#if defined(_WIN32) && !defined(_XBOX)
+ /* _OPENAL32LIB is deprecated */
+ #if defined(AL_BUILD_LIBRARY) || defined (_OPENAL32LIB)
+  #define AL_API __declspec(dllexport)
+ #else
+  #define AL_API __declspec(dllimport)
+ #endif
+#else
+ #define AL_API extern
+#endif
+
+#if defined(_WIN32)
+ #define AL_APIENTRY __cdecl
+#else
+ #define AL_APIENTRY
+#endif
+
+#if TARGET_OS_MAC
+ #pragma export on
+#endif
+
+/* The OPENAL, ALAPI, and ALAPIENTRY macros are deprecated, but are included for applications porting code
+   from AL 1.0 */
+#define OPENAL
+#define ALAPI AL_API
+#define ALAPIENTRY AL_APIENTRY
+
+#define AL_VERSION_1_0
+#define AL_VERSION_1_1
+
+
+/** 8-bit boolean */
+typedef char ALboolean;
+
+/** character */
+typedef char ALchar;
+
+/** signed 8-bit 2's complement integer */
+typedef char ALbyte;
+
+/** unsigned 8-bit integer */
+typedef unsigned char ALubyte;
+
+/** signed 16-bit 2's complement integer */
+typedef short ALshort;
+
+/** unsigned 16-bit integer */
+typedef unsigned short ALushort;
+
+/** signed 32-bit 2's complement integer */
+typedef int ALint;
+
+/** unsigned 32-bit integer */
+typedef unsigned int ALuint;
+
+/** non-negative 32-bit binary integer size */
+typedef int ALsizei;
+
+/** enumerated 32-bit value */
+typedef int ALenum;
+
+/** 32-bit IEEE754 floating-point */
+typedef float ALfloat;
+
+/** 64-bit IEEE754 floating-point */
+typedef double ALdouble;
+
+/** void type (for opaque pointers only) */
+typedef void ALvoid;
+
+
+/* Enumerant values begin at column 50. No tabs. */
+
+/* bad value */
+#define AL_INVALID                                -1
+
+#define AL_NONE                                   0
+
+/* Boolean False. */
+#define AL_FALSE                                  0
+
+/** Boolean True. */
+#define AL_TRUE                                   1
+
+/** Indicate Source has relative coordinates. */
+#define AL_SOURCE_RELATIVE                        0x202
+
+
+
+/**
+ * Directional source, inner cone angle, in degrees.
+ * Range:    [0-360] 
+ * Default:  360
+ */
+#define AL_CONE_INNER_ANGLE                       0x1001
+
+/**
+ * Directional source, outer cone angle, in degrees.
+ * Range:    [0-360] 
+ * Default:  360
+ */
+#define AL_CONE_OUTER_ANGLE                       0x1002
+
+/**
+ * Specify the pitch to be applied, either at source,
+ *  or on mixer results, at listener.
+ * Range:   [0.5-2.0]
+ * Default: 1.0
+ */
+#define AL_PITCH                                  0x1003
+  
+/** 
+ * Specify the current location in three dimensional space.
+ * OpenAL, like OpenGL, uses a right handed coordinate system,
+ *  where in a frontal default view X (thumb) points right, 
+ *  Y points up (index finger), and Z points towards the
+ *  viewer/camera (middle finger). 
+ * To switch from a left handed coordinate system, flip the
+ *  sign on the Z coordinate.
+ * Listener position is always in the world coordinate system.
+ */ 
+#define AL_POSITION                               0x1004
+  
+/** Specify the current direction. */
+#define AL_DIRECTION                              0x1005
+  
+/** Specify the current velocity in three dimensional space. */
+#define AL_VELOCITY                               0x1006
+
+/**
+ * Indicate whether source is looping.
+ * Type: ALboolean?
+ * Range:   [AL_TRUE, AL_FALSE]
+ * Default: FALSE.
+ */
+#define AL_LOOPING                                0x1007
+
+/**
+ * Indicate the buffer to provide sound samples. 
+ * Type: ALuint.
+ * Range: any valid Buffer id.
+ */
+#define AL_BUFFER                                 0x1009
+  
+/**
+ * Indicate the gain (volume amplification) applied. 
+ * Type:   ALfloat.
+ * Range:  ]0.0-  ]
+ * A value of 1.0 means un-attenuated/unchanged.
+ * Each division by 2 equals an attenuation of -6dB.
+ * Each multiplicaton with 2 equals an amplification of +6dB.
+ * A value of 0.0 is meaningless with respect to a logarithmic
+ *  scale; it is interpreted as zero volume - the channel
+ *  is effectively disabled.
+ */
+#define AL_GAIN                                   0x100A
+
+/*
+ * Indicate minimum source attenuation
+ * Type: ALfloat
+ * Range:  [0.0 - 1.0]
+ *
+ * Logarthmic
+ */
+#define AL_MIN_GAIN                               0x100D
+
+/**
+ * Indicate maximum source attenuation
+ * Type: ALfloat
+ * Range:  [0.0 - 1.0]
+ *
+ * Logarthmic
+ */
+#define AL_MAX_GAIN                               0x100E
+
+/**
+ * Indicate listener orientation.
+ *
+ * at/up 
+ */
+#define AL_ORIENTATION                            0x100F
+
+/**
+ * Specify the channel mask. (Creative)
+ * Type: ALuint
+ * Range: [0 - 255]
+ */
+#define AL_CHANNEL_MASK                           0x3000
+
+
+/**
+ * Source state information.
+ */
+#define AL_SOURCE_STATE                           0x1010
+#define AL_INITIAL                                0x1011
+#define AL_PLAYING                                0x1012
+#define AL_PAUSED                                 0x1013
+#define AL_STOPPED                                0x1014
+
+/**
+ * Buffer Queue params
+ */
+#define AL_BUFFERS_QUEUED                         0x1015
+#define AL_BUFFERS_PROCESSED                      0x1016
+
+/**
+ * Source buffer position information
+ */
+#define AL_SEC_OFFSET                             0x1024
+#define AL_SAMPLE_OFFSET                          0x1025
+#define AL_BYTE_OFFSET                            0x1026
+
+/*
+ * Source type (Static, Streaming or undetermined)
+ * Source is Static if a Buffer has been attached using AL_BUFFER
+ * Source is Streaming if one or more Buffers have been attached using alSourceQueueBuffers
+ * Source is undetermined when it has the NULL buffer attached
+ */
+#define AL_SOURCE_TYPE                            0x1027
+#define AL_STATIC                                 0x1028
+#define AL_STREAMING                              0x1029
+#define AL_UNDETERMINED                           0x1030
+
+/** Sound samples: format specifier. */
+#define AL_FORMAT_MONO8                           0x1100
+#define AL_FORMAT_MONO16                          0x1101
+#define AL_FORMAT_STEREO8                         0x1102
+#define AL_FORMAT_STEREO16                        0x1103
+
+/**
+ * source specific reference distance
+ * Type: ALfloat
+ * Range:  0.0 - +inf
+ *
+ * At 0.0, no distance attenuation occurs.  Default is
+ * 1.0.
+ */
+#define AL_REFERENCE_DISTANCE                     0x1020
+
+/**
+ * source specific rolloff factor
+ * Type: ALfloat
+ * Range:  0.0 - +inf
+ *
+ */
+#define AL_ROLLOFF_FACTOR                         0x1021
+
+/**
+ * Directional source, outer cone gain.
+ *
+ * Default:  0.0
+ * Range:    [0.0 - 1.0]
+ * Logarithmic
+ */
+#define AL_CONE_OUTER_GAIN                        0x1022
+
+/**
+ * Indicate distance above which sources are not
+ * attenuated using the inverse clamped distance model.
+ *
+ * Default: +inf
+ * Type: ALfloat
+ * Range:  0.0 - +inf
+ */
+#define AL_MAX_DISTANCE                           0x1023
+
+/** 
+ * Sound samples: frequency, in units of Hertz [Hz].
+ * This is the number of samples per second. Half of the
+ *  sample frequency marks the maximum significant
+ *  frequency component.
+ */
+#define AL_FREQUENCY                              0x2001
+#define AL_BITS                                   0x2002
+#define AL_CHANNELS                               0x2003
+#define AL_SIZE                                   0x2004
+
+/**
+ * Buffer state.
+ *
+ * Not supported for public use (yet).
+ */
+#define AL_UNUSED                                 0x2010
+#define AL_PENDING                                0x2011
+#define AL_PROCESSED                              0x2012
+
+
+/** Errors: No Error. */
+#define AL_NO_ERROR                               AL_FALSE
+
+/** 
+ * Invalid Name paramater passed to AL call.
+ */
+#define AL_INVALID_NAME                           0xA001
+
+/** 
+ * Invalid parameter passed to AL call.
+ */
+#define AL_ILLEGAL_ENUM                           0xA002
+#define AL_INVALID_ENUM                           0xA002
+
+/** 
+ * Invalid enum parameter value.
+ */
+#define AL_INVALID_VALUE                          0xA003
+
+/** 
+ * Illegal call.
+ */
+#define AL_ILLEGAL_COMMAND                        0xA004
+#define AL_INVALID_OPERATION                      0xA004
+
+  
+/**
+ * No mojo.
+ */
+#define AL_OUT_OF_MEMORY                          0xA005
+
+
+/** Context strings: Vendor Name. */
+#define AL_VENDOR                                 0xB001
+#define AL_VERSION                                0xB002
+#define AL_RENDERER                               0xB003
+#define AL_EXTENSIONS                             0xB004
+
+/** Global tweakage. */
+
+/**
+ * Doppler scale.  Default 1.0
+ */
+#define AL_DOPPLER_FACTOR                         0xC000
+
+/**
+ * Tweaks speed of propagation.
+ */
+#define AL_DOPPLER_VELOCITY                       0xC001
+
+/**
+ * Speed of Sound in units per second
+ */
+#define AL_SPEED_OF_SOUND                         0xC003
+
+/**
+ * Distance models
+ *
+ * used in conjunction with DistanceModel
+ *
+ * implicit: NONE, which disances distance attenuation.
+ */
+#define AL_DISTANCE_MODEL                         0xD000
+#define AL_INVERSE_DISTANCE                       0xD001
+#define AL_INVERSE_DISTANCE_CLAMPED               0xD002
+#define AL_LINEAR_DISTANCE                        0xD003
+#define AL_LINEAR_DISTANCE_CLAMPED                0xD004
+#define AL_EXPONENT_DISTANCE                      0xD005
+#define AL_EXPONENT_DISTANCE_CLAMPED              0xD006
+
+
+#if !defined(AL_NO_PROTOTYPES)
+
+/*
+ * Renderer State management
+ */
+AL_API void AL_APIENTRY alEnable( ALenum capability );
+
+AL_API void AL_APIENTRY alDisable( ALenum capability ); 
+
+AL_API ALboolean AL_APIENTRY alIsEnabled( ALenum capability ); 
+
+
+/*
+ * State retrieval
+ */
+AL_API const ALchar* AL_APIENTRY alGetString( ALenum param );
+
+AL_API void AL_APIENTRY alGetBooleanv( ALenum param, ALboolean* data );
+
+AL_API void AL_APIENTRY alGetIntegerv( ALenum param, ALint* data );
+
+AL_API void AL_APIENTRY alGetFloatv( ALenum param, ALfloat* data );
+
+AL_API void AL_APIENTRY alGetDoublev( ALenum param, ALdouble* data );
+
+AL_API ALboolean AL_APIENTRY alGetBoolean( ALenum param );
+
+AL_API ALint AL_APIENTRY alGetInteger( ALenum param );
+
+AL_API ALfloat AL_APIENTRY alGetFloat( ALenum param );
+
+AL_API ALdouble AL_APIENTRY alGetDouble( ALenum param );
+
+
+/*
+ * Error support.
+ * Obtain the most recent error generated in the AL state machine.
+ */
+AL_API ALenum AL_APIENTRY alGetError( void );
+
+
+/* 
+ * Extension support.
+ * Query for the presence of an extension, and obtain any appropriate
+ * function pointers and enum values.
+ */
+AL_API ALboolean AL_APIENTRY alIsExtensionPresent( const ALchar* extname );
+
+AL_API void* AL_APIENTRY alGetProcAddress( const ALchar* fname );
+
+AL_API ALenum AL_APIENTRY alGetEnumValue( const ALchar* ename );
+
+
+/*
+ * LISTENER
+ * Listener represents the location and orientation of the
+ * 'user' in 3D-space.
+ *
+ * Properties include: -
+ *
+ * Gain         AL_GAIN         ALfloat
+ * Position     AL_POSITION     ALfloat[3]
+ * Velocity     AL_VELOCITY     ALfloat[3]
+ * Orientation  AL_ORIENTATION  ALfloat[6] (Forward then Up vectors)
+*/
+
+/*
+ * Set Listener parameters
+ */
+AL_API void AL_APIENTRY alListenerf( ALenum param, ALfloat value );
+
+AL_API void AL_APIENTRY alListener3f( ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
+
+AL_API void AL_APIENTRY alListenerfv( ALenum param, const ALfloat* values ); 
+
+AL_API void AL_APIENTRY alListeneri( ALenum param, ALint value );
+
+AL_API void AL_APIENTRY alListener3i( ALenum param, ALint value1, ALint value2, ALint value3 );
+
+AL_API void AL_APIENTRY alListeneriv( ALenum param, const ALint* values );
+
+/*
+ * Get Listener parameters
+ */
+AL_API void AL_APIENTRY alGetListenerf( ALenum param, ALfloat* value );
+
+AL_API void AL_APIENTRY alGetListener3f( ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3 );
+
+AL_API void AL_APIENTRY alGetListenerfv( ALenum param, ALfloat* values );
+
+AL_API void AL_APIENTRY alGetListeneri( ALenum param, ALint* value );
+
+AL_API void AL_APIENTRY alGetListener3i( ALenum param, ALint *value1, ALint *value2, ALint *value3 );
+
+AL_API void AL_APIENTRY alGetListeneriv( ALenum param, ALint* values );
+
+
+/**
+ * SOURCE
+ * Sources represent individual sound objects in 3D-space.
+ * Sources take the PCM data provided in the specified Buffer,
+ * apply Source-specific modifications, and then
+ * submit them to be mixed according to spatial arrangement etc.
+ * 
+ * Properties include: -
+ *
+ * Gain                              AL_GAIN                 ALfloat
+ * Min Gain                          AL_MIN_GAIN             ALfloat
+ * Max Gain                          AL_MAX_GAIN             ALfloat
+ * Position                          AL_POSITION             ALfloat[3]
+ * Velocity                          AL_VELOCITY             ALfloat[3]
+ * Direction                         AL_DIRECTION            ALfloat[3]
+ * Head Relative Mode                AL_SOURCE_RELATIVE      ALint (AL_TRUE or AL_FALSE)
+ * Reference Distance                AL_REFERENCE_DISTANCE   ALfloat
+ * Max Distance                      AL_MAX_DISTANCE         ALfloat
+ * RollOff Factor                    AL_ROLLOFF_FACTOR       ALfloat
+ * Inner Angle                       AL_CONE_INNER_ANGLE     ALint or ALfloat
+ * Outer Angle                       AL_CONE_OUTER_ANGLE     ALint or ALfloat
+ * Cone Outer Gain                   AL_CONE_OUTER_GAIN      ALint or ALfloat
+ * Pitch                             AL_PITCH                ALfloat
+ * Looping                           AL_LOOPING              ALint (AL_TRUE or AL_FALSE)
+ * MS Offset                         AL_MSEC_OFFSET          ALint or ALfloat
+ * Byte Offset                       AL_BYTE_OFFSET          ALint or ALfloat
+ * Sample Offset                     AL_SAMPLE_OFFSET        ALint or ALfloat
+ * Attached Buffer                   AL_BUFFER               ALint
+ * State (Query only)                AL_SOURCE_STATE         ALint
+ * Buffers Queued (Query only)       AL_BUFFERS_QUEUED       ALint
+ * Buffers Processed (Query only)    AL_BUFFERS_PROCESSED    ALint
+ */
+
+/* Create Source objects */
+AL_API void AL_APIENTRY alGenSources( ALsizei n, ALuint* sources ); 
+
+/* Delete Source objects */
+AL_API void AL_APIENTRY alDeleteSources( ALsizei n, const ALuint* sources );
+
+/* Verify a handle is a valid Source */ 
+AL_API ALboolean AL_APIENTRY alIsSource( ALuint sid ); 
+
+/*
+ * Set Source parameters
+ */
+AL_API void AL_APIENTRY alSourcef( ALuint sid, ALenum param, ALfloat value ); 
+
+AL_API void AL_APIENTRY alSource3f( ALuint sid, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
+
+AL_API void AL_APIENTRY alSourcefv( ALuint sid, ALenum param, const ALfloat* values ); 
+
+AL_API void AL_APIENTRY alSourcei( ALuint sid, ALenum param, ALint value ); 
+
+AL_API void AL_APIENTRY alSource3i( ALuint sid, ALenum param, ALint value1, ALint value2, ALint value3 );
+
+AL_API void AL_APIENTRY alSourceiv( ALuint sid, ALenum param, const ALint* values );
+
+/*
+ * Get Source parameters
+ */
+AL_API void AL_APIENTRY alGetSourcef( ALuint sid, ALenum param, ALfloat* value );
+
+AL_API void AL_APIENTRY alGetSource3f( ALuint sid, ALenum param, ALfloat* value1, ALfloat* value2, ALfloat* value3);
+
+AL_API void AL_APIENTRY alGetSourcefv( ALuint sid, ALenum param, ALfloat* values );
+
+AL_API void AL_APIENTRY alGetSourcei( ALuint sid,  ALenum param, ALint* value );
+
+AL_API void AL_APIENTRY alGetSource3i( ALuint sid, ALenum param, ALint* value1, ALint* value2, ALint* value3);
+
+AL_API void AL_APIENTRY alGetSourceiv( ALuint sid,  ALenum param, ALint* values );
+
+
+/*
+ * Source vector based playback calls
+ */
+
+/* Play, replay, or resume (if paused) a list of Sources */
+AL_API void AL_APIENTRY alSourcePlayv( ALsizei ns, const ALuint *sids );
+
+/* Stop a list of Sources */
+AL_API void AL_APIENTRY alSourceStopv( ALsizei ns, const ALuint *sids );
+
+/* Rewind a list of Sources */
+AL_API void AL_APIENTRY alSourceRewindv( ALsizei ns, const ALuint *sids );
+
+/* Pause a list of Sources */
+AL_API void AL_APIENTRY alSourcePausev( ALsizei ns, const ALuint *sids );
+
+/*
+ * Source based playback calls
+ */
+
+/* Play, replay, or resume a Source */
+AL_API void AL_APIENTRY alSourcePlay( ALuint sid );
+
+/* Stop a Source */
+AL_API void AL_APIENTRY alSourceStop( ALuint sid );
+
+/* Rewind a Source (set playback postiton to beginning) */
+AL_API void AL_APIENTRY alSourceRewind( ALuint sid );
+
+/* Pause a Source */
+AL_API void AL_APIENTRY alSourcePause( ALuint sid );
+
+/*
+ * Source Queuing 
+ */
+AL_API void AL_APIENTRY alSourceQueueBuffers( ALuint sid, ALsizei numEntries, const ALuint *bids );
+
+AL_API void AL_APIENTRY alSourceUnqueueBuffers( ALuint sid, ALsizei numEntries, ALuint *bids );
+
+
+/**
+ * BUFFER
+ * Buffer objects are storage space for sample data.
+ * Buffers are referred to by Sources. One Buffer can be used
+ * by multiple Sources.
+ *
+ * Properties include: -
+ *
+ * Frequency (Query only)    AL_FREQUENCY      ALint
+ * Size (Query only)         AL_SIZE           ALint
+ * Bits (Query only)         AL_BITS           ALint
+ * Channels (Query only)     AL_CHANNELS       ALint
+ */
+
+/* Create Buffer objects */
+AL_API void AL_APIENTRY alGenBuffers( ALsizei n, ALuint* buffers );
+
+/* Delete Buffer objects */
+AL_API void AL_APIENTRY alDeleteBuffers( ALsizei n, const ALuint* buffers );
+
+/* Verify a handle is a valid Buffer */
+AL_API ALboolean AL_APIENTRY alIsBuffer( ALuint bid );
+
+/* Specify the data to be copied into a buffer */
+AL_API void AL_APIENTRY alBufferData( ALuint bid, ALenum format, const ALvoid* data, ALsizei size, ALsizei freq );
+
+/*
+ * Set Buffer parameters
+ */
+AL_API void AL_APIENTRY alBufferf( ALuint bid, ALenum param, ALfloat value );
+
+AL_API void AL_APIENTRY alBuffer3f( ALuint bid, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
+
+AL_API void AL_APIENTRY alBufferfv( ALuint bid, ALenum param, const ALfloat* values );
+
+AL_API void AL_APIENTRY alBufferi( ALuint bid, ALenum param, ALint value );
+
+AL_API void AL_APIENTRY alBuffer3i( ALuint bid, ALenum param, ALint value1, ALint value2, ALint value3 );
+
+AL_API void AL_APIENTRY alBufferiv( ALuint bid, ALenum param, const ALint* values );
+
+/*
+ * Get Buffer parameters
+ */
+AL_API void AL_APIENTRY alGetBufferf( ALuint bid, ALenum param, ALfloat* value );
+
+AL_API void AL_APIENTRY alGetBuffer3f( ALuint bid, ALenum param, ALfloat* value1, ALfloat* value2, ALfloat* value3);
+
+AL_API void AL_APIENTRY alGetBufferfv( ALuint bid, ALenum param, ALfloat* values );
+
+AL_API void AL_APIENTRY alGetBufferi( ALuint bid, ALenum param, ALint* value );
+
+AL_API void AL_APIENTRY alGetBuffer3i( ALuint bid, ALenum param, ALint* value1, ALint* value2, ALint* value3);
+
+AL_API void AL_APIENTRY alGetBufferiv( ALuint bid, ALenum param, ALint* values );
+
+
+/*
+ * Global Parameters
+ */
+AL_API void AL_APIENTRY alDopplerFactor( ALfloat value );
+
+AL_API void AL_APIENTRY alDopplerVelocity( ALfloat value );
+
+AL_API void AL_APIENTRY alSpeedOfSound( ALfloat value );
+
+AL_API void AL_APIENTRY alDistanceModel( ALenum distanceModel );
+
+#else /* AL_NO_PROTOTYPES */
+
+typedef void           (AL_APIENTRY *LPALENABLE)( ALenum capability );
+typedef void           (AL_APIENTRY *LPALDISABLE)( ALenum capability ); 
+typedef ALboolean      (AL_APIENTRY *LPALISENABLED)( ALenum capability ); 
+typedef const ALchar*  (AL_APIENTRY *LPALGETSTRING)( ALenum param );
+typedef void           (AL_APIENTRY *LPALGETBOOLEANV)( ALenum param, ALboolean* data );
+typedef void           (AL_APIENTRY *LPALGETINTEGERV)( ALenum param, ALint* data );
+typedef void           (AL_APIENTRY *LPALGETFLOATV)( ALenum param, ALfloat* data );
+typedef void           (AL_APIENTRY *LPALGETDOUBLEV)( ALenum param, ALdouble* data );
+typedef ALboolean      (AL_APIENTRY *LPALGETBOOLEAN)( ALenum param );
+typedef ALint          (AL_APIENTRY *LPALGETINTEGER)( ALenum param );
+typedef ALfloat        (AL_APIENTRY *LPALGETFLOAT)( ALenum param );
+typedef ALdouble       (AL_APIENTRY *LPALGETDOUBLE)( ALenum param );
+typedef ALenum         (AL_APIENTRY *LPALGETERROR)( void );
+typedef ALboolean      (AL_APIENTRY *LPALISEXTENSIONPRESENT)(const ALchar* extname );
+typedef void*          (AL_APIENTRY *LPALGETPROCADDRESS)( const ALchar* fname );
+typedef ALenum         (AL_APIENTRY *LPALGETENUMVALUE)( const ALchar* ename );
+typedef void           (AL_APIENTRY *LPALLISTENERF)( ALenum param, ALfloat value );
+typedef void           (AL_APIENTRY *LPALLISTENER3F)( ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
+typedef void           (AL_APIENTRY *LPALLISTENERFV)( ALenum param, const ALfloat* values );
+typedef void           (AL_APIENTRY *LPALLISTENERI)( ALenum param, ALint value );
+typedef void           (AL_APIENTRY *LPALLISTENER3I)( ALenum param, ALint value1, ALint value2, ALint value3 );
+typedef void           (AL_APIENTRY *LPALLISTENERIV)( ALenum param, const ALint* values );
+typedef void           (AL_APIENTRY *LPALGETLISTENERF)( ALenum param, ALfloat* value );
+typedef void           (AL_APIENTRY *LPALGETLISTENER3F)( ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3 );
+typedef void           (AL_APIENTRY *LPALGETLISTENERFV)( ALenum param, ALfloat* values );
+typedef void           (AL_APIENTRY *LPALGETLISTENERI)( ALenum param, ALint* value );
+typedef void           (AL_APIENTRY *LPALGETLISTENER3I)( ALenum param, ALint *value1, ALint *value2, ALint *value3 );
+typedef void           (AL_APIENTRY *LPALGETLISTENERIV)( ALenum param, ALint* values );
+typedef void           (AL_APIENTRY *LPALGENSOURCES)( ALsizei n, ALuint* sources ); 
+typedef void           (AL_APIENTRY *LPALDELETESOURCES)( ALsizei n, const ALuint* sources );
+typedef ALboolean      (AL_APIENTRY *LPALISSOURCE)( ALuint sid ); 
+typedef void           (AL_APIENTRY *LPALSOURCEF)( ALuint sid, ALenum param, ALfloat value); 
+typedef void           (AL_APIENTRY *LPALSOURCE3F)( ALuint sid, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
+typedef void           (AL_APIENTRY *LPALSOURCEFV)( ALuint sid, ALenum param, const ALfloat* values );
+typedef void           (AL_APIENTRY *LPALSOURCEI)( ALuint sid, ALenum param, ALint value); 
+typedef void           (AL_APIENTRY *LPALSOURCE3I)( ALuint sid, ALenum param, ALint value1, ALint value2, ALint value3 );
+typedef void           (AL_APIENTRY *LPALSOURCEIV)( ALuint sid, ALenum param, const ALint* values );
+typedef void           (AL_APIENTRY *LPALGETSOURCEF)( ALuint sid, ALenum param, ALfloat* value );
+typedef void           (AL_APIENTRY *LPALGETSOURCE3F)( ALuint sid, ALenum param, ALfloat* value1, ALfloat* value2, ALfloat* value3);
+typedef void           (AL_APIENTRY *LPALGETSOURCEFV)( ALuint sid, ALenum param, ALfloat* values );
+typedef void           (AL_APIENTRY *LPALGETSOURCEI)( ALuint sid, ALenum param, ALint* value );
+typedef void           (AL_APIENTRY *LPALGETSOURCE3I)( ALuint sid, ALenum param, ALint* value1, ALint* value2, ALint* value3);
+typedef void           (AL_APIENTRY *LPALGETSOURCEIV)( ALuint sid, ALenum param, ALint* values );
+typedef void           (AL_APIENTRY *LPALSOURCEPLAYV)( ALsizei ns, const ALuint *sids );
+typedef void           (AL_APIENTRY *LPALSOURCESTOPV)( ALsizei ns, const ALuint *sids );
+typedef void           (AL_APIENTRY *LPALSOURCEREWINDV)( ALsizei ns, const ALuint *sids );
+typedef void           (AL_APIENTRY *LPALSOURCEPAUSEV)( ALsizei ns, const ALuint *sids );
+typedef void           (AL_APIENTRY *LPALSOURCEPLAY)( ALuint sid );
+typedef void           (AL_APIENTRY *LPALSOURCESTOP)( ALuint sid );
+typedef void           (AL_APIENTRY *LPALSOURCEREWIND)( ALuint sid );
+typedef void           (AL_APIENTRY *LPALSOURCEPAUSE)( ALuint sid );
+typedef void           (AL_APIENTRY *LPALSOURCEQUEUEBUFFERS)(ALuint sid, ALsizei numEntries, const ALuint *bids );
+typedef void           (AL_APIENTRY *LPALSOURCEUNQUEUEBUFFERS)(ALuint sid, ALsizei numEntries, ALuint *bids );
+typedef void           (AL_APIENTRY *LPALGENBUFFERS)( ALsizei n, ALuint* buffers );
+typedef void           (AL_APIENTRY *LPALDELETEBUFFERS)( ALsizei n, const ALuint* buffers );
+typedef ALboolean      (AL_APIENTRY *LPALISBUFFER)( ALuint bid );
+typedef void           (AL_APIENTRY *LPALBUFFERDATA)( ALuint bid, ALenum format, const ALvoid* data, ALsizei size, ALsizei freq );
+typedef void           (AL_APIENTRY *LPALBUFFERF)( ALuint bid, ALenum param, ALfloat value);
+typedef void           (AL_APIENTRY *LPALBUFFER3F)( ALuint bid, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
+typedef void           (AL_APIENTRY *LPALBUFFERFV)( ALuint bid, ALenum param, const ALfloat* values );
+typedef void           (AL_APIENTRY *LPALBUFFERI)( ALuint bid, ALenum param, ALint value);
+typedef void           (AL_APIENTRY *LPALBUFFER3I)( ALuint bid, ALenum param, ALint value1, ALint value2, ALint value3 );
+typedef void           (AL_APIENTRY *LPALBUFFERIV)( ALuint bid, ALenum param, const ALint* values );
+typedef void           (AL_APIENTRY *LPALGETBUFFERF)( ALuint bid, ALenum param, ALfloat* value );
+typedef void           (AL_APIENTRY *LPALGETBUFFER3F)( ALuint bid, ALenum param, ALfloat* value1, ALfloat* value2, ALfloat* value3);
+typedef void           (AL_APIENTRY *LPALGETBUFFERFV)( ALuint bid, ALenum param, ALfloat* values );
+typedef void           (AL_APIENTRY *LPALGETBUFFERI)( ALuint bid, ALenum param, ALint* value );
+typedef void           (AL_APIENTRY *LPALGETBUFFER3I)( ALuint bid, ALenum param, ALint* value1, ALint* value2, ALint* value3);
+typedef void           (AL_APIENTRY *LPALGETBUFFERIV)( ALuint bid, ALenum param, ALint* values );
+typedef void           (AL_APIENTRY *LPALDOPPLERFACTOR)( ALfloat value );
+typedef void           (AL_APIENTRY *LPALDOPPLERVELOCITY)( ALfloat value );
+typedef void           (AL_APIENTRY *LPALSPEEDOFSOUND)( ALfloat value );
+typedef void           (AL_APIENTRY *LPALDISTANCEMODEL)( ALenum distanceModel );
+
+#endif /* AL_NO_PROTOTYPES */
+
+#if TARGET_OS_MAC
+ #pragma export off
+#endif
+
+#if defined(__cplusplus)
+}  /* extern "C" */
+#endif
+
+#endif /* AL_AL_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/alc.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,281 @@
+#ifndef AL_ALC_H
+#define AL_ALC_H
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#if defined(_WIN32) && !defined(_XBOX)
+ /* _OPENAL32LIB is deprecated */
+ #if defined(AL_BUILD_LIBRARY) || defined (_OPENAL32LIB)
+  #define ALC_API __declspec(dllexport)
+ #else
+  #define ALC_API __declspec(dllimport)
+ #endif
+#else
+ #if defined(AL_BUILD_LIBRARY) && defined(HAVE_GCC_VISIBILITY)
+  #define ALC_API __attribute__((visibility("default")))
+ #else
+  #define ALC_API extern
+ #endif
+#endif
+
+#if defined(_WIN32)
+ #define ALC_APIENTRY __cdecl
+#else
+ #define ALC_APIENTRY
+#endif
+
+#if defined(TARGET_OS_MAC) && TARGET_OS_MAC
+ #pragma export on
+#endif
+
+/*
+ * The ALCAPI, ALCAPIENTRY, and ALC_INVALID macros are deprecated, but are
+ * included for applications porting code from AL 1.0
+ */
+#define ALCAPI ALC_API
+#define ALCAPIENTRY ALC_APIENTRY
+#define ALC_INVALID 0
+
+
+#define ALC_VERSION_0_1         1
+
+typedef struct ALCdevice_struct ALCdevice;
+typedef struct ALCcontext_struct ALCcontext;
+
+
+/** 8-bit boolean */
+typedef char ALCboolean;
+
+/** character */
+typedef char ALCchar;
+
+/** signed 8-bit 2's complement integer */
+typedef char ALCbyte;
+
+/** unsigned 8-bit integer */
+typedef unsigned char ALCubyte;
+
+/** signed 16-bit 2's complement integer */
+typedef short ALCshort;
+
+/** unsigned 16-bit integer */
+typedef unsigned short ALCushort;
+
+/** signed 32-bit 2's complement integer */
+typedef int ALCint;
+
+/** unsigned 32-bit integer */
+typedef unsigned int ALCuint;
+
+/** non-negative 32-bit binary integer size */
+typedef int ALCsizei;
+
+/** enumerated 32-bit value */
+typedef int ALCenum;
+
+/** 32-bit IEEE754 floating-point */
+typedef float ALCfloat;
+
+/** 64-bit IEEE754 floating-point */
+typedef double ALCdouble;
+
+/** void type (for opaque pointers only) */
+typedef void ALCvoid;
+
+
+/* Enumerant values begin at column 50. No tabs. */
+
+/* Boolean False. */
+#define ALC_FALSE                                0
+
+/* Boolean True. */
+#define ALC_TRUE                                 1
+
+/**
+ * followed by <int> Hz
+ */
+#define ALC_FREQUENCY                            0x1007
+
+/**
+ * followed by <int> Hz
+ */
+#define ALC_REFRESH                              0x1008
+
+/**
+ * followed by AL_TRUE, AL_FALSE
+ */
+#define ALC_SYNC                                 0x1009
+
+/**
+ * followed by <int> Num of requested Mono (3D) Sources
+ */
+#define ALC_MONO_SOURCES                         0x1010
+
+/**
+ * followed by <int> Num of requested Stereo Sources
+ */
+#define ALC_STEREO_SOURCES                       0x1011
+
+/**
+ * errors
+ */
+
+/**
+ * No error
+ */
+#define ALC_NO_ERROR                             ALC_FALSE
+
+/**
+ * No device
+ */
+#define ALC_INVALID_DEVICE                       0xA001
+
+/**
+ * invalid context ID
+ */
+#define ALC_INVALID_CONTEXT                      0xA002
+
+/**
+ * bad enum
+ */
+#define ALC_INVALID_ENUM                         0xA003
+
+/**
+ * bad value
+ */
+#define ALC_INVALID_VALUE                        0xA004
+
+/**
+ * Out of memory.
+ */
+#define ALC_OUT_OF_MEMORY                        0xA005
+
+
+/**
+ * The Specifier string for default device
+ */
+#define ALC_DEFAULT_DEVICE_SPECIFIER             0x1004
+#define ALC_DEVICE_SPECIFIER                     0x1005
+#define ALC_EXTENSIONS                           0x1006
+
+#define ALC_MAJOR_VERSION                        0x1000
+#define ALC_MINOR_VERSION                        0x1001
+
+#define ALC_ATTRIBUTES_SIZE                      0x1002
+#define ALC_ALL_ATTRIBUTES                       0x1003
+
+/**
+ * ALC_ENUMERATE_ALL_EXT enums
+ */
+#define ALC_DEFAULT_ALL_DEVICES_SPECIFIER        0x1012
+#define ALC_ALL_DEVICES_SPECIFIER                0x1013
+
+/**
+ * Capture extension
+ */
+#define ALC_CAPTURE_DEVICE_SPECIFIER             0x310
+#define ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER     0x311
+#define ALC_CAPTURE_SAMPLES                      0x312
+
+
+/*
+ * Context Management
+ */
+ALC_API ALCcontext *    ALC_APIENTRY alcCreateContext( ALCdevice *device, const ALCint* attrlist );
+
+ALC_API ALCboolean      ALC_APIENTRY alcMakeContextCurrent( ALCcontext *context );
+
+ALC_API void            ALC_APIENTRY alcProcessContext( ALCcontext *context );
+
+ALC_API void            ALC_APIENTRY alcSuspendContext( ALCcontext *context );
+
+ALC_API void            ALC_APIENTRY alcDestroyContext( ALCcontext *context );
+
+ALC_API ALCcontext *    ALC_APIENTRY alcGetCurrentContext( void );
+
+ALC_API ALCdevice*      ALC_APIENTRY alcGetContextsDevice( ALCcontext *context );
+
+
+/*
+ * Device Management
+ */
+ALC_API ALCdevice *     ALC_APIENTRY alcOpenDevice( const ALCchar *devicename );
+
+ALC_API ALCboolean      ALC_APIENTRY alcCloseDevice( ALCdevice *device );
+
+
+/*
+ * Error support.
+ * Obtain the most recent Context error
+ */
+ALC_API ALCenum         ALC_APIENTRY alcGetError( ALCdevice *device );
+
+
+/* 
+ * Extension support.
+ * Query for the presence of an extension, and obtain any appropriate
+ * function pointers and enum values.
+ */
+ALC_API ALCboolean      ALC_APIENTRY alcIsExtensionPresent( ALCdevice *device, const ALCchar *extname );
+
+ALC_API void  *         ALC_APIENTRY alcGetProcAddress( ALCdevice *device, const ALCchar *funcname );
+
+ALC_API ALCenum         ALC_APIENTRY alcGetEnumValue( ALCdevice *device, const ALCchar *enumname );
+
+
+/*
+ * Query functions
+ */
+ALC_API const ALCchar * ALC_APIENTRY alcGetString( ALCdevice *device, ALCenum param );
+
+ALC_API void            ALC_APIENTRY alcGetIntegerv( ALCdevice *device, ALCenum param, ALCsizei size, ALCint *data );
+
+
+/*
+ * Capture functions
+ */
+ALC_API ALCdevice*      ALC_APIENTRY alcCaptureOpenDevice( const ALCchar *devicename, ALCuint frequency, ALCenum format, ALCsizei buffersize );
+
+ALC_API ALCboolean      ALC_APIENTRY alcCaptureCloseDevice( ALCdevice *device );
+
+ALC_API void            ALC_APIENTRY alcCaptureStart( ALCdevice *device );
+
+ALC_API void            ALC_APIENTRY alcCaptureStop( ALCdevice *device );
+
+ALC_API void            ALC_APIENTRY alcCaptureSamples( ALCdevice *device, ALCvoid *buffer, ALCsizei samples );
+
+/*
+ * Pointer-to-function types, useful for dynamically getting ALC entry points.
+ */
+typedef ALCcontext *   (ALC_APIENTRY *LPALCCREATECONTEXT) (ALCdevice *device, const ALCint *attrlist);
+typedef ALCboolean     (ALC_APIENTRY *LPALCMAKECONTEXTCURRENT)( ALCcontext *context );
+typedef void           (ALC_APIENTRY *LPALCPROCESSCONTEXT)( ALCcontext *context );
+typedef void           (ALC_APIENTRY *LPALCSUSPENDCONTEXT)( ALCcontext *context );
+typedef void           (ALC_APIENTRY *LPALCDESTROYCONTEXT)( ALCcontext *context );
+typedef ALCcontext *   (ALC_APIENTRY *LPALCGETCURRENTCONTEXT)( void );
+typedef ALCdevice *    (ALC_APIENTRY *LPALCGETCONTEXTSDEVICE)( ALCcontext *context );
+typedef ALCdevice *    (ALC_APIENTRY *LPALCOPENDEVICE)( const ALCchar *devicename );
+typedef ALCboolean     (ALC_APIENTRY *LPALCCLOSEDEVICE)( ALCdevice *device );
+typedef ALCenum        (ALC_APIENTRY *LPALCGETERROR)( ALCdevice *device );
+typedef ALCboolean     (ALC_APIENTRY *LPALCISEXTENSIONPRESENT)( ALCdevice *device, const ALCchar *extname );
+typedef void *         (ALC_APIENTRY *LPALCGETPROCADDRESS)(ALCdevice *device, const ALCchar *funcname );
+typedef ALCenum        (ALC_APIENTRY *LPALCGETENUMVALUE)(ALCdevice *device, const ALCchar *enumname );
+typedef const ALCchar* (ALC_APIENTRY *LPALCGETSTRING)( ALCdevice *device, ALCenum param );
+typedef void           (ALC_APIENTRY *LPALCGETINTEGERV)( ALCdevice *device, ALCenum param, ALCsizei size, ALCint *dest );
+typedef ALCdevice *    (ALC_APIENTRY *LPALCCAPTUREOPENDEVICE)( const ALCchar *devicename, ALCuint frequency, ALCenum format, ALCsizei buffersize );
+typedef ALCboolean     (ALC_APIENTRY *LPALCCAPTURECLOSEDEVICE)( ALCdevice *device );
+typedef void           (ALC_APIENTRY *LPALCCAPTURESTART)( ALCdevice *device );
+typedef void           (ALC_APIENTRY *LPALCCAPTURESTOP)( ALCdevice *device );
+typedef void           (ALC_APIENTRY *LPALCCAPTURESAMPLES)( ALCdevice *device, ALCvoid *buffer, ALCsizei samples );
+
+#if defined(TARGET_OS_MAC) && TARGET_OS_MAC
+ #pragma export off
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* AL_ALC_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/efx-creative.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,151 @@
+#ifndef __efxcreative_h_
+#define __efxcreative_h_
+
+/**
+ *  efx-creative.h - Environmental Audio Extensions
+ *            for OpenAL Effects Extension.
+ *
+ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * Effect object definitions to be used with alEffect functions.
+ *
+ * Effect parameter value definitions, ranges, and defaults
+ * appear farther down in this file.
+ */
+
+/* AL EAXReverb effect parameters. */
+#define AL_EAXREVERB_DENSITY                               0x0001
+#define AL_EAXREVERB_DIFFUSION                             0x0002
+#define AL_EAXREVERB_GAIN                                  0x0003
+#define AL_EAXREVERB_GAINHF                                0x0004
+#define AL_EAXREVERB_GAINLF                                0x0005
+#define AL_EAXREVERB_DECAY_TIME                            0x0006
+#define AL_EAXREVERB_DECAY_HFRATIO                         0x0007
+#define AL_EAXREVERB_DECAY_LFRATIO                         0x0008
+#define AL_EAXREVERB_REFLECTIONS_GAIN                      0x0009
+#define AL_EAXREVERB_REFLECTIONS_DELAY                     0x000A
+#define AL_EAXREVERB_REFLECTIONS_PAN                       0x000B
+#define AL_EAXREVERB_LATE_REVERB_GAIN                      0x000C
+#define AL_EAXREVERB_LATE_REVERB_DELAY                     0x000D
+#define AL_EAXREVERB_LATE_REVERB_PAN                       0x000E
+#define AL_EAXREVERB_ECHO_TIME                             0x000F
+#define AL_EAXREVERB_ECHO_DEPTH                            0x0010
+#define AL_EAXREVERB_MODULATION_TIME                       0x0011
+#define AL_EAXREVERB_MODULATION_DEPTH                      0x0012
+#define AL_EAXREVERB_AIR_ABSORPTION_GAINHF                 0x0013 
+#define AL_EAXREVERB_HFREFERENCE                           0x0014 
+#define AL_EAXREVERB_LFREFERENCE                           0x0015 
+#define AL_EAXREVERB_ROOM_ROLLOFF_FACTOR                   0x0016
+#define AL_EAXREVERB_DECAY_HFLIMIT                         0x0017
+
+/* Effect type definitions to be used with AL_EFFECT_TYPE. */
+#define AL_EFFECT_EAXREVERB                                0x8000
+
+
+
+ /**********************************************************
+ * Effect parameter structures, value definitions, ranges and defaults.
+ */
+
+/**
+ * AL reverb effect parameter ranges and defaults
+ */
+#define AL_EAXREVERB_MIN_DENSITY                           0.0f
+#define AL_EAXREVERB_MAX_DENSITY                           1.0f
+#define AL_EAXREVERB_DEFAULT_DENSITY                       1.0f
+
+#define AL_EAXREVERB_MIN_DIFFUSION                         0.0f
+#define AL_EAXREVERB_MAX_DIFFUSION                         1.0f
+#define AL_EAXREVERB_DEFAULT_DIFFUSION                     1.0f
+
+#define AL_EAXREVERB_MIN_GAIN                              0.0f
+#define AL_EAXREVERB_MAX_GAIN                              1.0f
+#define AL_EAXREVERB_DEFAULT_GAIN                          0.32f
+
+#define AL_EAXREVERB_MIN_GAINHF                            0.0f
+#define AL_EAXREVERB_MAX_GAINHF                            1.0f
+#define AL_EAXREVERB_DEFAULT_GAINHF                        0.89f
+
+#define AL_EAXREVERB_MIN_GAINLF                            0.0f
+#define AL_EAXREVERB_MAX_GAINLF                            1.0f
+#define AL_EAXREVERB_DEFAULT_GAINLF                        1.0f
+
+#define AL_EAXREVERB_MIN_DECAY_TIME                        0.1f
+#define AL_EAXREVERB_MAX_DECAY_TIME                        20.0f
+#define AL_EAXREVERB_DEFAULT_DECAY_TIME                    1.49f
+
+#define AL_EAXREVERB_MIN_DECAY_HFRATIO                     0.1f
+#define AL_EAXREVERB_MAX_DECAY_HFRATIO                     2.0f
+#define AL_EAXREVERB_DEFAULT_DECAY_HFRATIO                 0.83f
+
+#define AL_EAXREVERB_MIN_DECAY_LFRATIO                     0.1f
+#define AL_EAXREVERB_MAX_DECAY_LFRATIO                     2.0f
+#define AL_EAXREVERB_DEFAULT_DECAY_LFRATIO                 1.0f
+
+#define AL_EAXREVERB_MIN_REFLECTIONS_GAIN                  0.0f
+#define AL_EAXREVERB_MAX_REFLECTIONS_GAIN                  3.16f
+#define AL_EAXREVERB_DEFAULT_REFLECTIONS_GAIN              0.05f
+
+#define AL_EAXREVERB_MIN_REFLECTIONS_DELAY                 0.0f
+#define AL_EAXREVERB_MAX_REFLECTIONS_DELAY                 0.3f
+#define AL_EAXREVERB_DEFAULT_REFLECTIONS_DELAY             0.007f
+
+#define AL_EAXREVERB_DEFAULT_REFLECTIONS_PAN               {0.0f, 0.0f, 0.0f}
+
+#define AL_EAXREVERB_MIN_LATE_REVERB_GAIN                  0.0f
+#define AL_EAXREVERB_MAX_LATE_REVERB_GAIN                  10.0f
+#define AL_EAXREVERB_DEFAULT_LATE_REVERB_GAIN              1.26f
+
+#define AL_EAXREVERB_MIN_LATE_REVERB_DELAY                 0.0f
+#define AL_EAXREVERB_MAX_LATE_REVERB_DELAY                 0.1f
+#define AL_EAXREVERB_DEFAULT_LATE_REVERB_DELAY             0.011f
+
+#define AL_EAXREVERB_DEFAULT_LATE_REVERB_PAN               {0.0f, 0.0f, 0.0f}
+
+#define AL_EAXREVERB_MIN_ECHO_TIME                         0.075f
+#define AL_EAXREVERB_MAX_ECHO_TIME                         0.25f
+#define AL_EAXREVERB_DEFAULT_ECHO_TIME                     0.25f
+
+#define AL_EAXREVERB_MIN_ECHO_DEPTH                        0.0f
+#define AL_EAXREVERB_MAX_ECHO_DEPTH                        1.0f
+#define AL_EAXREVERB_DEFAULT_ECHO_DEPTH                    0.0f
+
+#define AL_EAXREVERB_MIN_MODULATION_TIME                   0.04f
+#define AL_EAXREVERB_MAX_MODULATION_TIME                   4.0f
+#define AL_EAXREVERB_DEFAULT_MODULATION_TIME               0.25f
+
+#define AL_EAXREVERB_MIN_MODULATION_DEPTH                  0.0f
+#define AL_EAXREVERB_MAX_MODULATION_DEPTH                  1.0f
+#define AL_EAXREVERB_DEFAULT_MODULATION_DEPTH              0.0f
+
+#define AL_EAXREVERB_MIN_AIR_ABSORPTION_GAINHF             0.892f
+#define AL_EAXREVERB_MAX_AIR_ABSORPTION_GAINHF             1.0f
+#define AL_EAXREVERB_DEFAULT_AIR_ABSORPTION_GAINHF         0.994f
+
+#define AL_EAXREVERB_MIN_HFREFERENCE                       1000.0f
+#define AL_EAXREVERB_MAX_HFREFERENCE                       20000.0f
+#define AL_EAXREVERB_DEFAULT_HFREFERENCE                   5000.0f
+
+#define AL_EAXREVERB_MIN_LFREFERENCE                       20.0f
+#define AL_EAXREVERB_MAX_LFREFERENCE                       1000.0f
+#define AL_EAXREVERB_DEFAULT_LFREFERENCE                   250.0f
+
+#define AL_EAXREVERB_MIN_ROOM_ROLLOFF_FACTOR               0.0f
+#define AL_EAXREVERB_MAX_ROOM_ROLLOFF_FACTOR               10.0f
+#define AL_EAXREVERB_DEFAULT_ROOM_ROLLOFF_FACTOR           0.0f
+
+#define AL_EAXREVERB_MIN_DECAY_HFLIMIT                     AL_FALSE
+#define AL_EAXREVERB_MAX_DECAY_HFLIMIT                     AL_TRUE
+#define AL_EAXREVERB_DEFAULT_DECAY_HFLIMIT                 AL_TRUE
+
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* __efxcreative_h_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/efx.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,737 @@
+#ifndef __efx_h_
+#define __efx_h_
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ALC_EXT_EFX_NAME                                   "ALC_EXT_EFX"
+
+/**
+ * Context definitions to be used with alcCreateContext.
+ * These values must be unique and not conflict with other 
+ * al context values.
+ */
+#define ALC_EFX_MAJOR_VERSION                              0x20001
+#define ALC_EFX_MINOR_VERSION                              0x20002
+#define ALC_MAX_AUXILIARY_SENDS                            0x20003
+
+
+
+
+/**
+ * Listener definitions to be used with alListener functions.
+ * These values must be unique and not conflict with other 
+ * al listener values.
+ */
+#define AL_METERS_PER_UNIT                                 0x20004
+
+
+
+
+/**
+ * Source definitions to be used with alSource functions.
+ * These values must be unique and not conflict with other 
+ * al source values.
+ */
+#define AL_DIRECT_FILTER                                   0x20005
+#define AL_AUXILIARY_SEND_FILTER                           0x20006
+#define AL_AIR_ABSORPTION_FACTOR                           0x20007
+#define AL_ROOM_ROLLOFF_FACTOR                             0x20008
+#define AL_CONE_OUTER_GAINHF                               0x20009
+#define AL_DIRECT_FILTER_GAINHF_AUTO                       0x2000A
+#define AL_AUXILIARY_SEND_FILTER_GAIN_AUTO                 0x2000B
+#define AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO               0x2000C
+
+
+
+
+/**
+ * Effect object definitions to be used with alEffect functions.
+ *
+ * Effect parameter value definitions, ranges, and defaults
+ * appear farther down in this file.
+ */
+
+/* Reverb Parameters */
+#define AL_REVERB_DENSITY                                  0x0001
+#define AL_REVERB_DIFFUSION                                0x0002
+#define AL_REVERB_GAIN                                     0x0003
+#define AL_REVERB_GAINHF                                   0x0004
+#define AL_REVERB_DECAY_TIME                               0x0005
+#define AL_REVERB_DECAY_HFRATIO                            0x0006
+#define AL_REVERB_REFLECTIONS_GAIN                         0x0007
+#define AL_REVERB_REFLECTIONS_DELAY                        0x0008
+#define AL_REVERB_LATE_REVERB_GAIN                         0x0009
+#define AL_REVERB_LATE_REVERB_DELAY                        0x000A
+#define AL_REVERB_AIR_ABSORPTION_GAINHF                    0x000B 
+#define AL_REVERB_ROOM_ROLLOFF_FACTOR                      0x000C
+#define AL_REVERB_DECAY_HFLIMIT                            0x000D
+
+/* Chorus Parameters */
+#define AL_CHORUS_WAVEFORM                                 0x0001
+#define	AL_CHORUS_PHASE                                    0x0002
+#define AL_CHORUS_RATE                                     0x0003
+#define AL_CHORUS_DEPTH                                    0x0004
+#define AL_CHORUS_FEEDBACK                                 0x0005
+#define AL_CHORUS_DELAY                                    0x0006
+
+/* Distortion Parameters */
+#define AL_DISTORTION_EDGE                                 0x0001
+#define AL_DISTORTION_GAIN                                 0x0002
+#define AL_DISTORTION_LOWPASS_CUTOFF                       0x0003
+#define AL_DISTORTION_EQCENTER                             0x0004
+#define AL_DISTORTION_EQBANDWIDTH                          0x0005
+
+/* Echo Parameters */
+#define AL_ECHO_DELAY                                      0x0001
+#define AL_ECHO_LRDELAY                                    0x0002
+#define AL_ECHO_DAMPING                                    0x0003
+#define AL_ECHO_FEEDBACK                                   0x0004
+#define AL_ECHO_SPREAD                                     0x0005
+
+/* Flanger Parameters */
+#define AL_FLANGER_WAVEFORM                                0x0001
+#define AL_FLANGER_PHASE                                   0x0002
+#define AL_FLANGER_RATE                                    0x0003
+#define AL_FLANGER_DEPTH                                   0x0004
+#define AL_FLANGER_FEEDBACK                                0x0005
+#define AL_FLANGER_DELAY                                   0x0006
+
+/* Frequencyshifter Parameters */
+#define AL_FREQUENCY_SHIFTER_FREQUENCY                     0x0001
+#define AL_FREQUENCY_SHIFTER_LEFT_DIRECTION                0x0002
+#define AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION               0x0003
+
+/* Vocalmorpher Parameters */
+#define AL_VOCAL_MORPHER_PHONEMEA                          0x0001
+#define AL_VOCAL_MORPHER_PHONEMEA_COARSE_TUNING            0x0002
+#define AL_VOCAL_MORPHER_PHONEMEB                          0x0003
+#define AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING            0x0004
+#define AL_VOCAL_MORPHER_WAVEFORM                          0x0005
+#define AL_VOCAL_MORPHER_RATE                              0x0006
+
+/* Pitchshifter Parameters */
+#define AL_PITCH_SHIFTER_COARSE_TUNE                       0x0001
+#define AL_PITCH_SHIFTER_FINE_TUNE                         0x0002
+
+/* Ringmodulator Parameters */
+#define AL_RING_MODULATOR_FREQUENCY                        0x0001
+#define AL_RING_MODULATOR_HIGHPASS_CUTOFF                  0x0002
+#define AL_RING_MODULATOR_WAVEFORM                         0x0003
+
+/* Autowah Parameters */
+#define AL_AUTOWAH_ATTACK_TIME                             0x0001
+#define AL_AUTOWAH_RELEASE_TIME                            0x0002
+#define AL_AUTOWAH_RESONANCE                               0x0003
+#define AL_AUTOWAH_PEAK_GAIN                               0x0004
+
+/* Compressor Parameters */
+#define AL_COMPRESSOR_ONOFF                                0x0001
+
+/* Equalizer Parameters */
+#define AL_EQUALIZER_LOW_GAIN                              0x0001
+#define AL_EQUALIZER_LOW_CUTOFF                            0x0002
+#define AL_EQUALIZER_MID1_GAIN                             0x0003
+#define AL_EQUALIZER_MID1_CENTER                           0x0004
+#define AL_EQUALIZER_MID1_WIDTH                            0x0005
+#define AL_EQUALIZER_MID2_GAIN                             0x0006
+#define AL_EQUALIZER_MID2_CENTER                           0x0007
+#define AL_EQUALIZER_MID2_WIDTH                            0x0008
+#define AL_EQUALIZER_HIGH_GAIN                             0x0009
+#define AL_EQUALIZER_HIGH_CUTOFF                           0x000A
+
+/* Effect type */
+#define AL_EFFECT_FIRST_PARAMETER                          0x0000
+#define AL_EFFECT_LAST_PARAMETER                           0x8000
+#define AL_EFFECT_TYPE                                     0x8001
+
+/* Effect type definitions to be used with AL_EFFECT_TYPE. */
+#define AL_EFFECT_NULL                                     0x0000  /* Can also be used as an Effect Object ID */
+#define AL_EFFECT_REVERB                                   0x0001
+#define AL_EFFECT_CHORUS                                   0x0002
+#define AL_EFFECT_DISTORTION                               0x0003
+#define AL_EFFECT_ECHO                                     0x0004
+#define AL_EFFECT_FLANGER                                  0x0005
+#define AL_EFFECT_FREQUENCY_SHIFTER                        0x0006
+#define AL_EFFECT_VOCAL_MORPHER                            0x0007
+#define AL_EFFECT_PITCH_SHIFTER                            0x0008
+#define AL_EFFECT_RING_MODULATOR                           0x0009
+#define AL_EFFECT_AUTOWAH                                  0x000A
+#define AL_EFFECT_COMPRESSOR                               0x000B
+#define AL_EFFECT_EQUALIZER                                0x000C
+
+/**
+ * Auxiliary Slot object definitions to be used with alAuxiliaryEffectSlot functions.
+ */
+#define AL_EFFECTSLOT_EFFECT                               0x0001
+#define AL_EFFECTSLOT_GAIN                                 0x0002
+#define AL_EFFECTSLOT_AUXILIARY_SEND_AUTO                  0x0003
+
+/**
+ * Value to be used as an Auxiliary Slot ID to disable a source send..
+ */
+#define AL_EFFECTSLOT_NULL                                 0x0000
+
+
+
+/**
+ * Filter object definitions to be used with alFilter functions.
+ */
+
+/* Lowpass parameters. */
+#define AL_LOWPASS_GAIN                                    0x0001
+#define AL_LOWPASS_GAINHF                                  0x0002
+
+/* Highpass Parameters */
+#define AL_HIGHPASS_GAIN                                   0x0001
+#define AL_HIGHPASS_GAINLF                                 0x0002
+
+/* Bandpass Parameters */
+#define AL_BANDPASS_GAIN                                   0x0001
+#define AL_BANDPASS_GAINLF                                 0x0002
+#define AL_BANDPASS_GAINHF                                 0x0003
+
+/* Filter type */
+#define AL_FILTER_FIRST_PARAMETER                          0x0000
+#define AL_FILTER_LAST_PARAMETER                           0x8000
+#define AL_FILTER_TYPE                                     0x8001
+
+/* Filter type definitions to be used with AL_FILTER_TYPE. */
+#define AL_FILTER_NULL                                     0x0000  /* Can also be used as a Filter Object ID */
+#define	AL_FILTER_LOWPASS                                  0x0001
+#define AL_FILTER_HIGHPASS                                 0x0002
+#define AL_FILTER_BANDPASS                                 0x0003
+
+
+/**
+ * Effect object functions.
+ */
+
+/* Create Effect objects. */
+typedef void (__cdecl *LPALGENEFFECTS)( ALsizei n, ALuint* effects );
+
+/* Delete Effect objects. */
+typedef void (__cdecl *LPALDELETEEFFECTS)( ALsizei n, ALuint* effects );
+
+/* Verify a handle is a valid Effect. */ 
+typedef ALboolean (__cdecl *LPALISEFFECT)( ALuint eid );
+
+/* Set an integer parameter for an Effect object. */
+typedef void (__cdecl *LPALEFFECTI)( ALuint eid, ALenum param, ALint value); 
+typedef void (__cdecl *LPALEFFECTIV)( ALuint eid, ALenum param, ALint* values ); 
+
+/* Set a floating point parameter for an Effect object. */
+typedef void (__cdecl *LPALEFFECTF)( ALuint eid, ALenum param, ALfloat value); 
+typedef void (__cdecl *LPALEFFECTFV)( ALuint eid, ALenum param, ALfloat* values ); 
+
+/* Get an integer parameter for an Effect object. */
+typedef void (__cdecl *LPALGETEFFECTI)( ALuint eid, ALenum pname, ALint* value );
+typedef void (__cdecl *LPALGETEFFECTIV)( ALuint eid, ALenum pname, ALint* values );
+
+/* Get a floating point parameter for an Effect object. */
+typedef void (__cdecl *LPALGETEFFECTF)( ALuint eid, ALenum pname, ALfloat* value );
+typedef void (__cdecl *LPALGETEFFECTFV)( ALuint eid, ALenum pname, ALfloat* values );
+
+
+/**
+ * Filter object functions
+ */
+
+/* Create Filter objects. */
+typedef void (__cdecl *LPALGENFILTERS)( ALsizei n, ALuint* filters ); 
+
+/* Delete Filter objects. */
+typedef void (__cdecl *LPALDELETEFILTERS)( ALsizei n, ALuint* filters );
+
+/* Verify a handle is a valid Filter. */ 
+typedef ALboolean (__cdecl *LPALISFILTER)( ALuint fid );
+
+/* Set an integer parameter for a Filter object. */
+typedef void (__cdecl *LPALFILTERI)( ALuint fid, ALenum param, ALint value ); 
+typedef void (__cdecl *LPALFILTERIV)( ALuint fid, ALenum param, ALint* values ); 
+
+/* Set a floating point parameter for an Filter object. */
+typedef void (__cdecl *LPALFILTERF)( ALuint fid, ALenum param, ALfloat value); 
+typedef void (__cdecl *LPALFILTERFV)( ALuint fid, ALenum param, ALfloat* values ); 
+
+/* Get an integer parameter for a Filter object. */
+typedef void (__cdecl *LPALGETFILTERI)( ALuint fid, ALenum pname, ALint* value );
+typedef void (__cdecl *LPALGETFILTERIV)( ALuint fid, ALenum pname, ALint* values );
+
+/* Get a floating point parameter for a Filter object. */
+typedef void (__cdecl *LPALGETFILTERF)( ALuint fid, ALenum pname, ALfloat* value );
+typedef void (__cdecl *LPALGETFILTERFV)( ALuint fid, ALenum pname, ALfloat* values );
+
+
+/**
+ * Auxiliary Slot object functions
+ */
+
+/* Create Auxiliary Slot objects. */
+typedef void (__cdecl *LPALGENAUXILIARYEFFECTSLOTS)( ALsizei n, ALuint* slots ); 
+
+/* Delete Auxiliary Slot objects. */
+typedef void (__cdecl *LPALDELETEAUXILIARYEFFECTSLOTS)( ALsizei n, ALuint* slots );
+
+/* Verify a handle is a valid Auxiliary Slot. */ 
+typedef ALboolean (__cdecl *LPALISAUXILIARYEFFECTSLOT)( ALuint slot ); 
+
+/* Set an integer parameter for a Auxiliary Slot object. */
+typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTI)( ALuint asid, ALenum param, ALint value ); 
+typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTIV)( ALuint asid, ALenum param, ALint* values ); 
+
+/* Set a floating point parameter for an Auxiliary Slot object. */
+typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTF)( ALuint asid, ALenum param, ALfloat value ); 
+typedef void (__cdecl *LPALAUXILIARYEFFECTSLOTFV)( ALuint asid, ALenum param, ALfloat* values ); 
+
+/* Get an integer parameter for a Auxiliary Slot object. */
+typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTI)( ALuint asid, ALenum pname, ALint* value );
+typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTIV)( ALuint asid, ALenum pname, ALint* values );
+
+/* Get a floating point parameter for a Auxiliary Slot object. */
+typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTF)( ALuint asid, ALenum pname, ALfloat* value );
+typedef void (__cdecl *LPALGETAUXILIARYEFFECTSLOTFV)( ALuint asid, ALenum pname, ALfloat* values );
+
+
+
+
+/**********************************************************
+ * Filter ranges and defaults.
+ */
+
+/**
+ * Lowpass filter
+ */
+
+#define LOWPASS_MIN_GAIN                                   0.0f
+#define LOWPASS_MAX_GAIN                                   1.0f
+#define LOWPASS_DEFAULT_GAIN                               1.0f
+
+#define LOWPASS_MIN_GAINHF                                 0.0f
+#define LOWPASS_MAX_GAINHF                                 1.0f
+#define LOWPASS_DEFAULT_GAINHF                             1.0f
+
+/**
+ * Highpass filter
+ */
+
+#define HIGHPASS_MIN_GAIN                                  0.0f
+#define HIGHPASS_MAX_GAIN                                  1.0f
+#define HIGHPASS_DEFAULT_GAIN                              1.0f
+
+#define HIGHPASS_MIN_GAINLF                                0.0f
+#define HIGHPASS_MAX_GAINLF                                1.0f
+#define HIGHPASS_DEFAULT_GAINLF                            1.0f
+
+/**
+ * Bandpass filter
+ */
+
+#define BANDPASS_MIN_GAIN                                  0.0f
+#define BANDPASS_MAX_GAIN                                  1.0f
+#define BANDPASS_DEFAULT_GAIN                              1.0f
+
+#define BANDPASS_MIN_GAINHF                                0.0f
+#define BANDPASS_MAX_GAINHF                                1.0f
+#define BANDPASS_DEFAULT_GAINHF                            1.0f
+
+#define BANDPASS_MIN_GAINLF                                0.0f
+#define BANDPASS_MAX_GAINLF                                1.0f
+#define BANDPASS_DEFAULT_GAINLF                            1.0f
+
+
+
+
+ /**********************************************************
+ * Effect parameter structures, value definitions, ranges and defaults.
+ */
+
+/**
+ * AL reverb effect parameter ranges and defaults
+ */
+#define AL_REVERB_MIN_DENSITY                              0.0f
+#define AL_REVERB_MAX_DENSITY                              1.0f
+#define AL_REVERB_DEFAULT_DENSITY                          1.0f
+
+#define AL_REVERB_MIN_DIFFUSION                            0.0f
+#define AL_REVERB_MAX_DIFFUSION                            1.0f
+#define AL_REVERB_DEFAULT_DIFFUSION                        1.0f
+
+#define AL_REVERB_MIN_GAIN                                 0.0f
+#define AL_REVERB_MAX_GAIN                                 1.0f
+#define AL_REVERB_DEFAULT_GAIN                             0.32f
+
+#define AL_REVERB_MIN_GAINHF                               0.0f
+#define AL_REVERB_MAX_GAINHF                               1.0f
+#define AL_REVERB_DEFAULT_GAINHF                           0.89f
+
+#define AL_REVERB_MIN_DECAY_TIME                           0.1f
+#define AL_REVERB_MAX_DECAY_TIME                           20.0f
+#define AL_REVERB_DEFAULT_DECAY_TIME                       1.49f
+
+#define AL_REVERB_MIN_DECAY_HFRATIO                        0.1f
+#define AL_REVERB_MAX_DECAY_HFRATIO                        2.0f
+#define AL_REVERB_DEFAULT_DECAY_HFRATIO                    0.83f
+
+#define AL_REVERB_MIN_REFLECTIONS_GAIN                     0.0f
+#define AL_REVERB_MAX_REFLECTIONS_GAIN                     3.16f
+#define AL_REVERB_DEFAULT_REFLECTIONS_GAIN                 0.05f
+
+#define AL_REVERB_MIN_REFLECTIONS_DELAY                    0.0f
+#define AL_REVERB_MAX_REFLECTIONS_DELAY                    0.3f
+#define AL_REVERB_DEFAULT_REFLECTIONS_DELAY                0.007f
+
+#define AL_REVERB_MIN_LATE_REVERB_GAIN                     0.0f
+#define AL_REVERB_MAX_LATE_REVERB_GAIN                     10.0f
+#define AL_REVERB_DEFAULT_LATE_REVERB_GAIN                 1.26f
+
+#define AL_REVERB_MIN_LATE_REVERB_DELAY                    0.0f
+#define AL_REVERB_MAX_LATE_REVERB_DELAY                    0.1f
+#define AL_REVERB_DEFAULT_LATE_REVERB_DELAY                0.011f
+
+#define AL_REVERB_MIN_AIR_ABSORPTION_GAINHF                0.892f
+#define AL_REVERB_MAX_AIR_ABSORPTION_GAINHF                1.0f
+#define AL_REVERB_DEFAULT_AIR_ABSORPTION_GAINHF            0.994f
+
+#define AL_REVERB_MIN_ROOM_ROLLOFF_FACTOR                  0.0f
+#define AL_REVERB_MAX_ROOM_ROLLOFF_FACTOR                  10.0f
+#define AL_REVERB_DEFAULT_ROOM_ROLLOFF_FACTOR              0.0f
+
+#define AL_REVERB_MIN_DECAY_HFLIMIT                        AL_FALSE
+#define AL_REVERB_MAX_DECAY_HFLIMIT                        AL_TRUE
+#define AL_REVERB_DEFAULT_DECAY_HFLIMIT                    AL_TRUE
+
+/**
+ * AL chorus effect parameter ranges and defaults
+ */
+#define AL_CHORUS_MIN_WAVEFORM                             0
+#define AL_CHORUS_MAX_WAVEFORM                             1
+#define AL_CHORUS_DEFAULT_WAVEFORM                         1
+
+#define AL_CHORUS_WAVEFORM_SINUSOID                        0
+#define AL_CHORUS_WAVEFORM_TRIANGLE                        1
+
+#define AL_CHORUS_MIN_PHASE                                (-180)
+#define AL_CHORUS_MAX_PHASE                                180
+#define AL_CHORUS_DEFAULT_PHASE                            90
+
+#define AL_CHORUS_MIN_RATE                                 0.0f
+#define AL_CHORUS_MAX_RATE                                 10.0f
+#define AL_CHORUS_DEFAULT_RATE                             1.1f
+
+#define AL_CHORUS_MIN_DEPTH                                0.0f
+#define AL_CHORUS_MAX_DEPTH                                1.0f
+#define AL_CHORUS_DEFAULT_DEPTH                            0.1f
+
+#define AL_CHORUS_MIN_FEEDBACK                             (-1.0f)
+#define AL_CHORUS_MAX_FEEDBACK                             1.0f
+#define AL_CHORUS_DEFAULT_FEEDBACK                         0.25f
+
+#define AL_CHORUS_MIN_DELAY                                0.0f
+#define AL_CHORUS_MAX_DELAY                                0.016f
+#define AL_CHORUS_DEFAULT_DELAY                            0.016f
+
+/**
+ * AL distortion effect parameter ranges and defaults
+ */
+#define AL_DISTORTION_MIN_EDGE                             0.0f
+#define AL_DISTORTION_MAX_EDGE                             1.0f
+#define AL_DISTORTION_DEFAULT_EDGE                         0.2f
+
+#define AL_DISTORTION_MIN_GAIN                             0.01f
+#define AL_DISTORTION_MAX_GAIN                             1.0f
+#define AL_DISTORTION_DEFAULT_GAIN                         0.05f
+
+#define AL_DISTORTION_MIN_LOWPASS_CUTOFF                   80.0f
+#define AL_DISTORTION_MAX_LOWPASS_CUTOFF                   24000.0f
+#define AL_DISTORTION_DEFAULT_LOWPASS_CUTOFF               8000.0f
+
+#define AL_DISTORTION_MIN_EQCENTER                         80.0f
+#define AL_DISTORTION_MAX_EQCENTER                         24000.0f
+#define AL_DISTORTION_DEFAULT_EQCENTER                     3600.0f
+
+#define AL_DISTORTION_MIN_EQBANDWIDTH                      80.0f
+#define AL_DISTORTION_MAX_EQBANDWIDTH                      24000.0f
+#define AL_DISTORTION_DEFAULT_EQBANDWIDTH                  3600.0f
+
+/**
+ * AL echo effect parameter ranges and defaults
+ */
+#define AL_ECHO_MIN_DELAY                                  0.0f
+#define AL_ECHO_MAX_DELAY                                  0.207f
+#define AL_ECHO_DEFAULT_DELAY                              0.1f
+
+#define AL_ECHO_MIN_LRDELAY                                0.0f
+#define AL_ECHO_MAX_LRDELAY                                0.404f
+#define AL_ECHO_DEFAULT_LRDELAY                            0.1f
+
+#define AL_ECHO_MIN_DAMPING                                0.0f
+#define AL_ECHO_MAX_DAMPING                                0.99f
+#define AL_ECHO_DEFAULT_DAMPING                            0.5f
+
+#define AL_ECHO_MIN_FEEDBACK                               0.0f
+#define AL_ECHO_MAX_FEEDBACK                               1.0f
+#define AL_ECHO_DEFAULT_FEEDBACK                           0.5f
+
+#define AL_ECHO_MIN_SPREAD                                 (-1.0f)
+#define AL_ECHO_MAX_SPREAD                                 1.0f
+#define AL_ECHO_DEFAULT_SPREAD                             (-1.0f)
+
+/**
+ * AL flanger effect parameter ranges and defaults
+ */
+#define AL_FLANGER_MIN_WAVEFORM                            0
+#define AL_FLANGER_MAX_WAVEFORM                            1
+#define AL_FLANGER_DEFAULT_WAVEFORM                        1
+
+#define AL_FLANGER_WAVEFORM_SINUSOID                       0
+#define AL_FLANGER_WAVEFORM_TRIANGLE                       1
+
+#define AL_FLANGER_MIN_PHASE                               (-180)
+#define AL_FLANGER_MAX_PHASE                               180
+#define AL_FLANGER_DEFAULT_PHASE                           0
+
+#define AL_FLANGER_MIN_RATE                                0.0f
+#define AL_FLANGER_MAX_RATE                                10.0f
+#define AL_FLANGER_DEFAULT_RATE                            0.27f
+
+#define AL_FLANGER_MIN_DEPTH                               0.0f
+#define AL_FLANGER_MAX_DEPTH                               1.0f
+#define AL_FLANGER_DEFAULT_DEPTH                           1.0f
+
+#define AL_FLANGER_MIN_FEEDBACK                            (-1.0f)
+#define AL_FLANGER_MAX_FEEDBACK                            1.0f
+#define AL_FLANGER_DEFAULT_FEEDBACK                        (-0.5f)
+
+#define AL_FLANGER_MIN_DELAY                               0.0f
+#define AL_FLANGER_MAX_DELAY                               0.004f
+#define AL_FLANGER_DEFAULT_DELAY                           0.002f
+
+/**
+ * AL frequency shifter effect parameter ranges and defaults
+ */
+#define AL_FREQUENCY_SHIFTER_MIN_FREQUENCY                 0.0f
+#define AL_FREQUENCY_SHIFTER_MAX_FREQUENCY                 24000.0f
+#define AL_FREQUENCY_SHIFTER_DEFAULT_FREQUENCY             0.0f
+
+#define AL_FREQUENCY_SHIFTER_MIN_LEFT_DIRECTION            0
+#define AL_FREQUENCY_SHIFTER_MAX_LEFT_DIRECTION            2
+#define AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION        0
+
+#define AL_FREQUENCY_SHIFTER_MIN_RIGHT_DIRECTION           0
+#define AL_FREQUENCY_SHIFTER_MAX_RIGHT_DIRECTION           2
+#define AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION       0
+
+#define AL_FREQUENCY_SHIFTER_DIRECTION_DOWN                0
+#define AL_FREQUENCY_SHIFTER_DIRECTION_UP                  1
+#define AL_FREQUENCY_SHIFTER_DIRECTION_OFF                 2
+
+/**
+ * AL vocal morpher effect parameter ranges and defaults
+ */
+#define AL_VOCAL_MORPHER_MIN_PHONEMEA                      0
+#define AL_VOCAL_MORPHER_MAX_PHONEMEA                      29
+#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEA                  0
+
+#define AL_VOCAL_MORPHER_MIN_PHONEMEA_COARSE_TUNING	       (-24)
+#define AL_VOCAL_MORPHER_MAX_PHONEMEA_COARSE_TUNING	       24
+#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEA_COARSE_TUNING    0
+
+#define AL_VOCAL_MORPHER_MIN_PHONEMEB                      0
+#define AL_VOCAL_MORPHER_MAX_PHONEMEB                      29
+#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEB                  10
+
+#define AL_VOCAL_MORPHER_PHONEME_A                         0
+#define AL_VOCAL_MORPHER_PHONEME_E                         1
+#define AL_VOCAL_MORPHER_PHONEME_I                         2
+#define AL_VOCAL_MORPHER_PHONEME_O                         3
+#define AL_VOCAL_MORPHER_PHONEME_U                         4
+#define AL_VOCAL_MORPHER_PHONEME_AA                        5
+#define AL_VOCAL_MORPHER_PHONEME_AE                        6
+#define AL_VOCAL_MORPHER_PHONEME_AH                        7
+#define AL_VOCAL_MORPHER_PHONEME_AO                        8
+#define AL_VOCAL_MORPHER_PHONEME_EH                        9
+#define AL_VOCAL_MORPHER_PHONEME_ER                        10
+#define AL_VOCAL_MORPHER_PHONEME_IH                        11
+#define AL_VOCAL_MORPHER_PHONEME_IY                        12
+#define AL_VOCAL_MORPHER_PHONEME_UH                        13
+#define AL_VOCAL_MORPHER_PHONEME_UW                        14
+#define AL_VOCAL_MORPHER_PHONEME_B                         15
+#define AL_VOCAL_MORPHER_PHONEME_D                         16
+#define AL_VOCAL_MORPHER_PHONEME_F                         17
+#define AL_VOCAL_MORPHER_PHONEME_G                         18
+#define AL_VOCAL_MORPHER_PHONEME_J                         19
+#define AL_VOCAL_MORPHER_PHONEME_K                         20
+#define AL_VOCAL_MORPHER_PHONEME_L                         21
+#define AL_VOCAL_MORPHER_PHONEME_M                         22
+#define AL_VOCAL_MORPHER_PHONEME_N                         23
+#define AL_VOCAL_MORPHER_PHONEME_P                         24
+#define AL_VOCAL_MORPHER_PHONEME_R                         25
+#define AL_VOCAL_MORPHER_PHONEME_S                         26
+#define AL_VOCAL_MORPHER_PHONEME_T                         27
+#define AL_VOCAL_MORPHER_PHONEME_V                         28
+#define AL_VOCAL_MORPHER_PHONEME_Z                         29
+
+#define AL_VOCAL_MORPHER_MIN_PHONEMEB_COARSE_TUNING        (-24)
+#define AL_VOCAL_MORPHER_MAX_PHONEMEB_COARSE_TUNING        24
+#define AL_VOCAL_MORPHER_DEFAULT_PHONEMEB_COARSE_TUNING    0
+
+#define AL_VOCAL_MORPHER_MIN_WAVEFORM                      0
+#define AL_VOCAL_MORPHER_MAX_WAVEFORM                      2
+#define AL_VOCAL_MORPHER_DEFAULT_WAVEFORM                  0
+
+#define AL_VOCAL_MORPHER_WAVEFORM_SINUSOID                 0
+#define AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE                 1
+#define AL_VOCAL_MORPHER_WAVEFORM_SAWTOOTH                 2
+
+#define AL_VOCAL_MORPHER_MIN_RATE                          0.0f
+#define AL_VOCAL_MORPHER_MAX_RATE                          10.0f
+#define AL_VOCAL_MORPHER_DEFAULT_RATE                      1.41f
+
+/**
+ * AL pitch shifter effect parameter ranges and defaults
+ */
+#define AL_PITCH_SHIFTER_MIN_COARSE_TUNE                   (-12)
+#define AL_PITCH_SHIFTER_MAX_COARSE_TUNE                   12
+#define AL_PITCH_SHIFTER_DEFAULT_COARSE_TUNE               12
+
+#define AL_PITCH_SHIFTER_MIN_FINE_TUNE                     (-50)
+#define AL_PITCH_SHIFTER_MAX_FINE_TUNE                     50
+#define AL_PITCH_SHIFTER_DEFAULT_FINE_TUNE                 0
+
+/**
+ * AL ring modulator effect parameter ranges and defaults
+ */
+#define AL_RING_MODULATOR_MIN_FREQUENCY                    0.0f
+#define AL_RING_MODULATOR_MAX_FREQUENCY                    8000.0f
+#define AL_RING_MODULATOR_DEFAULT_FREQUENCY                440.0f
+
+#define AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF              0.0f
+#define AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF              24000.0f
+#define AL_RING_MODULATOR_DEFAULT_HIGHPASS_CUTOFF          800.0f
+
+#define AL_RING_MODULATOR_MIN_WAVEFORM                     0
+#define AL_RING_MODULATOR_MAX_WAVEFORM                     2
+#define AL_RING_MODULATOR_DEFAULT_WAVEFORM                 0
+
+#define AL_RING_MODULATOR_SINUSOID                         0
+#define AL_RING_MODULATOR_SAWTOOTH                         1
+#define AL_RING_MODULATOR_SQUARE                           2
+
+/**
+ * AL autowah effect parameter ranges and defaults
+ */
+#define AL_AUTOWAH_MIN_ATTACK_TIME                         0.0001f
+#define AL_AUTOWAH_MAX_ATTACK_TIME                         1.0f
+#define AL_AUTOWAH_DEFAULT_ATTACK_TIME                     0.06f
+
+#define AL_AUTOWAH_MIN_RELEASE_TIME                        0.0001f
+#define AL_AUTOWAH_MAX_RELEASE_TIME                        1.0f
+#define AL_AUTOWAH_DEFAULT_RELEASE_TIME                    0.06f
+
+#define AL_AUTOWAH_MIN_RESONANCE                           2.0f
+#define AL_AUTOWAH_MAX_RESONANCE                           1000.0f
+#define AL_AUTOWAH_DEFAULT_RESONANCE                       1000.0f
+	
+#define AL_AUTOWAH_MIN_PEAK_GAIN                           0.00003f
+#define AL_AUTOWAH_MAX_PEAK_GAIN                           31621.0f
+#define AL_AUTOWAH_DEFAULT_PEAK_GAIN                       11.22f
+
+/**
+ * AL compressor effect parameter ranges and defaults
+ */
+#define AL_COMPRESSOR_MIN_ONOFF                            0
+#define AL_COMPRESSOR_MAX_ONOFF                            1
+#define AL_COMPRESSOR_DEFAULT_ONOFF                        1
+
+/**
+ * AL equalizer effect parameter ranges and defaults
+ */
+#define AL_EQUALIZER_MIN_LOW_GAIN                          0.126f
+#define AL_EQUALIZER_MAX_LOW_GAIN                          7.943f
+#define AL_EQUALIZER_DEFAULT_LOW_GAIN                      1.0f
+
+#define AL_EQUALIZER_MIN_LOW_CUTOFF                        50.0f
+#define AL_EQUALIZER_MAX_LOW_CUTOFF                        800.0f
+#define AL_EQUALIZER_DEFAULT_LOW_CUTOFF                    200.0f
+
+#define AL_EQUALIZER_MIN_MID1_GAIN                         0.126f
+#define AL_EQUALIZER_MAX_MID1_GAIN                         7.943f
+#define AL_EQUALIZER_DEFAULT_MID1_GAIN                     1.0f
+
+#define AL_EQUALIZER_MIN_MID1_CENTER                       200.0f
+#define AL_EQUALIZER_MAX_MID1_CENTER                       3000.0f
+#define AL_EQUALIZER_DEFAULT_MID1_CENTER                   500.0f
+
+#define AL_EQUALIZER_MIN_MID1_WIDTH                        0.01f
+#define AL_EQUALIZER_MAX_MID1_WIDTH                        1.0f
+#define AL_EQUALIZER_DEFAULT_MID1_WIDTH                    1.0f
+
+#define AL_EQUALIZER_MIN_MID2_GAIN                         0.126f
+#define AL_EQUALIZER_MAX_MID2_GAIN                         7.943f
+#define AL_EQUALIZER_DEFAULT_MID2_GAIN                     1.0f
+
+#define AL_EQUALIZER_MIN_MID2_CENTER                       1000.0f
+#define AL_EQUALIZER_MAX_MID2_CENTER                       8000.0f
+#define AL_EQUALIZER_DEFAULT_MID2_CENTER                   3000.0f
+
+#define AL_EQUALIZER_MIN_MID2_WIDTH                        0.01f
+#define AL_EQUALIZER_MAX_MID2_WIDTH                        1.0f
+#define AL_EQUALIZER_DEFAULT_MID2_WIDTH                    1.0f
+
+#define AL_EQUALIZER_MIN_HIGH_GAIN                         0.126f
+#define AL_EQUALIZER_MAX_HIGH_GAIN                         7.943f
+#define AL_EQUALIZER_DEFAULT_HIGH_GAIN                     1.0f
+
+#define AL_EQUALIZER_MIN_HIGH_CUTOFF                       4000.0f
+#define AL_EQUALIZER_MAX_HIGH_CUTOFF                       16000.0f
+#define AL_EQUALIZER_DEFAULT_HIGH_CUTOFF                   6000.0f
+
+
+
+
+/**********************************************************
+ * Source parameter value definitions, ranges and defaults.
+ */
+#define AL_MIN_AIR_ABSORPTION_FACTOR                       0.0f
+#define AL_MAX_AIR_ABSORPTION_FACTOR                       10.0f
+#define AL_DEFAULT_AIR_ABSORPTION_FACTOR                   0.0f
+
+#define AL_MIN_ROOM_ROLLOFF_FACTOR                         0.0f
+#define AL_MAX_ROOM_ROLLOFF_FACTOR                         10.0f
+#define AL_DEFAULT_ROOM_ROLLOFF_FACTOR                     0.0f
+
+#define AL_MIN_CONE_OUTER_GAINHF                           0.0f
+#define AL_MAX_CONE_OUTER_GAINHF                           1.0f
+#define AL_DEFAULT_CONE_OUTER_GAINHF                       1.0f
+
+#define AL_MIN_DIRECT_FILTER_GAINHF_AUTO                   AL_FALSE
+#define AL_MAX_DIRECT_FILTER_GAINHF_AUTO                   AL_TRUE
+#define AL_DEFAULT_DIRECT_FILTER_GAINHF_AUTO               AL_TRUE
+
+#define AL_MIN_AUXILIARY_SEND_FILTER_GAIN_AUTO             AL_FALSE
+#define AL_MAX_AUXILIARY_SEND_FILTER_GAIN_AUTO             AL_TRUE
+#define AL_DEFAULT_AUXILIARY_SEND_FILTER_GAIN_AUTO         AL_TRUE
+
+#define AL_MIN_AUXILIARY_SEND_FILTER_GAINHF_AUTO           AL_FALSE
+#define AL_MAX_AUXILIARY_SEND_FILTER_GAINHF_AUTO           AL_TRUE
+#define AL_DEFAULT_AUXILIARY_SEND_FILTER_GAINHF_AUTO       AL_TRUE
+
+
+
+
+/**********************************************************
+ * Listener parameter value definitions, ranges and defaults.
+ */
+#define AL_MIN_METERS_PER_UNIT                             FLT_MIN
+#define AL_MAX_METERS_PER_UNIT                             FLT_MAX
+#define AL_DEFAULT_METERS_PER_UNIT                         1.0f
+
+
+#ifdef __cplusplus
+}  /* extern "C" */
+#endif
+
+#endif /* __efx_h_ */
Binary file lib/OpenAL/lib/OpenAL/OpenAL32.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/avcodec-55.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,263 @@
+EXPORTS
+    audio_resample
+    audio_resample_close
+    av_audio_convert
+    av_audio_convert_alloc
+    av_audio_convert_free
+    av_audio_resample_init
+    av_bitstream_filter_close
+    av_bitstream_filter_filter
+    av_bitstream_filter_init
+    av_bitstream_filter_next
+    av_codec_get_codec_descriptor
+    av_codec_get_lowres
+    av_codec_get_pkt_timebase
+    av_codec_is_decoder
+    av_codec_is_encoder
+    av_codec_next
+    av_codec_set_codec_descriptor
+    av_codec_set_lowres
+    av_codec_set_pkt_timebase
+    av_copy_packet
+    av_copy_packet_side_data
+    av_dct_calc
+    av_dct_end
+    av_dct_init
+    av_destruct_packet
+    av_dup_packet
+    av_fast_malloc
+    av_fast_padded_malloc
+    av_fast_padded_mallocz
+    av_fast_realloc
+    av_fft_calc
+    av_fft_end
+    av_fft_init
+    av_fft_permute
+    av_free_packet
+    av_get_audio_frame_duration
+    av_get_bits_per_sample
+    av_get_codec_tag_string
+    av_get_exact_bits_per_sample
+    av_get_pcm_codec
+    av_get_profile_name
+    av_grow_packet
+    av_hwaccel_next
+    av_imdct_calc
+    av_imdct_half
+    av_init_packet
+    av_lockmgr_register
+    av_log_ask_for_sample
+    av_log_missing_feature
+    av_mdct_calc
+    av_mdct_end
+    av_mdct_init
+    av_new_packet
+    av_packet_from_data
+    av_packet_get_side_data
+    av_packet_merge_side_data
+    av_packet_new_side_data
+    av_packet_shrink_side_data
+    av_packet_split_side_data
+    av_parser_change
+    av_parser_close
+    av_parser_init
+    av_parser_next
+    av_parser_parse2
+    av_picture_copy
+    av_picture_crop
+    av_picture_pad
+    av_rdft_calc
+    av_rdft_end
+    av_rdft_init
+    av_register_bitstream_filter
+    av_register_codec_parser
+    av_register_hwaccel
+    av_resample
+    av_resample_close
+    av_resample_compensate
+    av_resample_init
+    av_shrink_packet
+    av_xiphlacing
+    available_bits
+    avcodec_align_dimensions
+    avcodec_align_dimensions2
+    avcodec_alloc_context3
+    avcodec_alloc_frame
+    avcodec_close
+    avcodec_configuration
+    avcodec_copy_context
+    avcodec_decode_audio3
+    avcodec_decode_audio4
+    avcodec_decode_subtitle2
+    avcodec_decode_video2
+    avcodec_default_execute
+    avcodec_default_execute2
+    avcodec_default_get_buffer
+    avcodec_default_get_buffer2
+    avcodec_default_get_format
+    avcodec_default_reget_buffer
+    avcodec_default_release_buffer
+    avcodec_descriptor_get
+    avcodec_descriptor_get_by_name
+    avcodec_descriptor_next
+    avcodec_encode_audio
+    avcodec_encode_audio2
+    avcodec_encode_subtitle
+    avcodec_encode_video
+    avcodec_encode_video2
+    avcodec_fill_audio_frame
+    avcodec_find_best_pix_fmt2
+    avcodec_find_best_pix_fmt_of_2
+    avcodec_find_best_pix_fmt_of_list
+    avcodec_find_decoder
+    avcodec_find_decoder_by_name
+    avcodec_find_encoder
+    avcodec_find_encoder_by_name
+    avcodec_flush_buffers
+    avcodec_free_frame
+    avcodec_get_chroma_sub_sample
+    avcodec_get_class
+    avcodec_get_context_defaults3
+    avcodec_get_edge_width
+    avcodec_get_frame_class
+    avcodec_get_frame_defaults
+    avcodec_get_name
+    avcodec_get_pix_fmt_loss
+    avcodec_get_subtitle_rect_class
+    avcodec_get_type
+    avcodec_is_open
+    avcodec_license
+    avcodec_open2
+    avcodec_pix_fmt_to_codec_tag
+    avcodec_register
+    avcodec_register_all
+    avcodec_set_dimensions
+    avcodec_string
+    avcodec_version
+    aver_isf_history
+    avpicture_alloc
+    avpicture_deinterlace
+    avpicture_fill
+    avpicture_free
+    avpicture_get_size
+    avpicture_layout
+    avpriv_aac_parse_header
+    avpriv_ac3_channel_layout_tab DATA
+    avpriv_ac3_parse_header
+    avpriv_adx_decode_header
+    avpriv_align_put_bits
+    avpriv_bprint_to_extradata
+    avpriv_color_frame
+    avpriv_copy_bits
+    avpriv_copy_pce_data
+    avpriv_dca_sample_rates DATA
+    avpriv_dirac_parse_sequence_header
+    avpriv_dnxhd_get_frame_size
+    avpriv_dsputil_init
+    avpriv_dv_codec_profile
+    avpriv_dv_frame_profile
+    avpriv_dv_frame_profile2
+    avpriv_find_pix_fmt
+    avpriv_find_start_code
+    avpriv_flac_is_extradata_valid
+    avpriv_flac_parse_block_header
+    avpriv_flac_parse_streaminfo
+    avpriv_h264_has_num_reorder_frames
+    avpriv_lock_avformat
+    avpriv_mjpeg_bits_ac_chrominance DATA
+    avpriv_mjpeg_bits_ac_luminance DATA
+    avpriv_mjpeg_bits_dc_chrominance DATA
+    avpriv_mjpeg_bits_dc_luminance DATA
+    avpriv_mjpeg_val_ac_chrominance DATA
+    avpriv_mjpeg_val_ac_luminance DATA
+    avpriv_mjpeg_val_dc DATA
+    avpriv_mpa_bitrate_tab DATA
+    avpriv_mpa_decode_header
+    avpriv_mpa_freq_tab DATA
+    avpriv_mpeg4audio_get_config
+    avpriv_mpeg4audio_sample_rates DATA
+    avpriv_mpegaudio_decode_header
+    avpriv_put_string
+    avpriv_split_xiph_headers
+    avpriv_tak_parse_streaminfo
+    avpriv_toupper4
+    avpriv_unlock_avformat
+    avpriv_vorbis_parse_extradata
+    avpriv_vorbis_parse_frame
+    avpriv_vorbis_parse_reset
+    avsubtitle_free
+    dsputil_init
+    ff_aanscales DATA
+    ff_dct32_fixed
+    ff_dct32_float
+    ff_dct32_float_avx DATA
+    ff_dct32_float_sse DATA
+    ff_dct32_float_sse2 DATA
+    ff_dct_common_init
+    ff_dct_encode_init
+    ff_dct_encode_init_x86
+    ff_dct_end
+    ff_dct_init
+    ff_dct_init_x86
+    ff_dct_quantize_c
+    ff_dnxhd_cid_table DATA
+    ff_dnxhd_get_cid_table
+    ff_dsputil_init
+    ff_faandct
+    ff_faandct248
+    ff_faanidct
+    ff_faanidct_add
+    ff_faanidct_put
+    ff_fdct248_islow_10
+    ff_fdct248_islow_8
+    ff_fdct_ifast
+    ff_fdct_ifast248
+    ff_fdct_mmx
+    ff_fdct_mmxext
+    ff_fdct_sse2
+    ff_fft_calc_3dnow DATA
+    ff_fft_calc_3dnowext DATA
+    ff_fft_calc_avx DATA
+    ff_fft_calc_sse DATA
+    ff_fft_end
+    ff_fft_end_fixed
+    ff_fft_init
+    ff_fft_init_fixed
+    ff_fft_init_x86
+    ff_fft_permute_sse DATA
+    ff_idct_xvid_mmx
+    ff_idct_xvid_mmx_add
+    ff_idct_xvid_mmx_put
+    ff_idct_xvid_mmxext
+    ff_idct_xvid_mmxext_add
+    ff_idct_xvid_mmxext_put
+    ff_idct_xvid_sse2
+    ff_idct_xvid_sse2_add
+    ff_idct_xvid_sse2_put
+    ff_jpeg_fdct_islow_10
+    ff_jpeg_fdct_islow_8
+    ff_mdct_calc_c
+    ff_mdct_calc_c_fixed
+    ff_mdct_calcw_c
+    ff_mdct_end
+    ff_mdct_end_fixed
+    ff_mdct_init
+    ff_mdct_init_fixed
+    ff_mdct_win_fixed DATA
+    ff_mdct_win_float DATA
+    ff_raw_pix_fmt_tags DATA
+    ff_rdft_end
+    ff_rdft_init
+    ff_simple_idct248_put
+    ff_simple_idct44_add
+    ff_simple_idct48_add
+    ff_simple_idct84_add
+    ff_simple_idct_10
+    ff_simple_idct_8
+    ff_simple_idct_add_10
+    ff_simple_idct_add_8
+    ff_simple_idct_add_mmx
+    ff_simple_idct_mmx
+    ff_simple_idct_put_10
+    ff_simple_idct_put_8
+    ff_simple_idct_put_mmx
Binary file lib/OpenAL/lib/x86/avcodec.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/avdevice-55.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,5 @@
+EXPORTS
+    avdevice_configuration
+    avdevice_license
+    avdevice_register_all
+    avdevice_version
Binary file lib/OpenAL/lib/x86/avdevice.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/avfilter-3.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,240 @@
+EXPORTS
+    av_abuffersink_params_alloc
+    av_buffersink_get_buffer_ref
+    av_buffersink_get_frame
+    av_buffersink_get_frame_flags
+    av_buffersink_get_frame_rate
+    av_buffersink_get_samples
+    av_buffersink_params_alloc
+    av_buffersink_poll_frame
+    av_buffersink_read
+    av_buffersink_read_samples
+    av_buffersink_set_frame_size
+    av_buffersrc_add_frame
+    av_buffersrc_add_frame_flags
+    av_buffersrc_add_ref
+    av_buffersrc_buffer
+    av_buffersrc_get_nb_failed_requests
+    av_buffersrc_write_frame
+    av_filter_next
+    avfilter_add_matrix
+    avfilter_af_aconvert DATA
+    avfilter_af_afade DATA
+    avfilter_af_afifo DATA
+    avfilter_af_aformat DATA
+    avfilter_af_ainterleave DATA
+    avfilter_af_allpass DATA
+    avfilter_af_amerge DATA
+    avfilter_af_amix DATA
+    avfilter_af_anull DATA
+    avfilter_af_apad DATA
+    avfilter_af_aperms DATA
+    avfilter_af_aphaser DATA
+    avfilter_af_aresample DATA
+    avfilter_af_aselect DATA
+    avfilter_af_asendcmd DATA
+    avfilter_af_asetnsamples DATA
+    avfilter_af_asetpts DATA
+    avfilter_af_asetrate DATA
+    avfilter_af_asettb DATA
+    avfilter_af_ashowinfo DATA
+    avfilter_af_asplit DATA
+    avfilter_af_astats DATA
+    avfilter_af_astreamsync DATA
+    avfilter_af_atempo DATA
+    avfilter_af_atrim DATA
+    avfilter_af_bandpass DATA
+    avfilter_af_bandreject DATA
+    avfilter_af_bass DATA
+    avfilter_af_biquad DATA
+    avfilter_af_channelmap DATA
+    avfilter_af_channelsplit DATA
+    avfilter_af_earwax DATA
+    avfilter_af_ebur128 DATA
+    avfilter_af_equalizer DATA
+    avfilter_af_highpass DATA
+    avfilter_af_join DATA
+    avfilter_af_lowpass DATA
+    avfilter_af_pan DATA
+    avfilter_af_silencedetect DATA
+    avfilter_af_treble DATA
+    avfilter_af_volume DATA
+    avfilter_af_volumedetect DATA
+    avfilter_all_channel_layouts DATA
+    avfilter_asink_abuffer DATA
+    avfilter_asink_anullsink DATA
+    avfilter_asink_ffabuffersink DATA
+    avfilter_asrc_abuffer DATA
+    avfilter_asrc_aevalsrc DATA
+    avfilter_asrc_anullsrc DATA
+    avfilter_asrc_sine DATA
+    avfilter_avf_avectorscope DATA
+    avfilter_avf_concat DATA
+    avfilter_avf_showspectrum DATA
+    avfilter_avf_showwaves DATA
+    avfilter_avsrc_amovie DATA
+    avfilter_avsrc_movie DATA
+    avfilter_config_links
+    avfilter_configuration
+    avfilter_copy_buf_props
+    avfilter_copy_buffer_ref_props
+    avfilter_copy_frame_props
+    avfilter_fill_frame_from_audio_buffer_ref
+    avfilter_fill_frame_from_buffer_ref
+    avfilter_fill_frame_from_video_buffer_ref
+    avfilter_free
+    avfilter_get_audio_buffer_ref_from_arrays
+    avfilter_get_audio_buffer_ref_from_arrays_channels
+    avfilter_get_audio_buffer_ref_from_frame
+    avfilter_get_buffer_ref_from_frame
+    avfilter_get_by_name
+    avfilter_get_class
+    avfilter_get_matrix
+    avfilter_get_video_buffer_ref_from_arrays
+    avfilter_get_video_buffer_ref_from_frame
+    avfilter_graph_add_filter
+    avfilter_graph_alloc
+    avfilter_graph_alloc_filter
+    avfilter_graph_config
+    avfilter_graph_create_filter
+    avfilter_graph_dump
+    avfilter_graph_free
+    avfilter_graph_get_filter
+    avfilter_graph_parse
+    avfilter_graph_parse2
+    avfilter_graph_queue_command
+    avfilter_graph_request_oldest
+    avfilter_graph_send_command
+    avfilter_graph_set_auto_convert
+    avfilter_init_dict
+    avfilter_init_filter
+    avfilter_init_str
+    avfilter_inout_alloc
+    avfilter_inout_free
+    avfilter_insert_filter
+    avfilter_license
+    avfilter_link
+    avfilter_link_free
+    avfilter_link_get_channels
+    avfilter_link_set_closed
+    avfilter_make_format64_list
+    avfilter_mul_matrix
+    avfilter_next
+    avfilter_open
+    avfilter_pad_count
+    avfilter_pad_get_name
+    avfilter_pad_get_type
+    avfilter_process_command
+    avfilter_ref_buffer
+    avfilter_ref_get_channels
+    avfilter_register
+    avfilter_register_all
+    avfilter_sub_matrix
+    avfilter_transform
+    avfilter_uninit
+    avfilter_unref_buffer
+    avfilter_unref_bufferp
+    avfilter_version
+    avfilter_vf_alphaextract DATA
+    avfilter_vf_alphamerge DATA
+    avfilter_vf_ass DATA
+    avfilter_vf_bbox DATA
+    avfilter_vf_blackdetect DATA
+    avfilter_vf_blackframe DATA
+    avfilter_vf_blend DATA
+    avfilter_vf_boxblur DATA
+    avfilter_vf_colorbalance DATA
+    avfilter_vf_colorchannelmixer DATA
+    avfilter_vf_colormatrix DATA
+    avfilter_vf_copy DATA
+    avfilter_vf_crop DATA
+    avfilter_vf_cropdetect DATA
+    avfilter_vf_curves DATA
+    avfilter_vf_dctdnoiz DATA
+    avfilter_vf_decimate DATA
+    avfilter_vf_delogo DATA
+    avfilter_vf_deshake DATA
+    avfilter_vf_drawbox DATA
+    avfilter_vf_drawgrid DATA
+    avfilter_vf_drawtext DATA
+    avfilter_vf_edgedetect DATA
+    avfilter_vf_extractplanes DATA
+    avfilter_vf_fade DATA
+    avfilter_vf_field DATA
+    avfilter_vf_fieldmatch DATA
+    avfilter_vf_fieldorder DATA
+    avfilter_vf_fifo DATA
+    avfilter_vf_format DATA
+    avfilter_vf_fps DATA
+    avfilter_vf_framestep DATA
+    avfilter_vf_frei0r DATA
+    avfilter_vf_geq DATA
+    avfilter_vf_gradfun DATA
+    avfilter_vf_hflip DATA
+    avfilter_vf_histeq DATA
+    avfilter_vf_histogram DATA
+    avfilter_vf_hqdn3d DATA
+    avfilter_vf_hue DATA
+    avfilter_vf_idet DATA
+    avfilter_vf_il DATA
+    avfilter_vf_interlace DATA
+    avfilter_vf_interleave DATA
+    avfilter_vf_kerndeint DATA
+    avfilter_vf_lut DATA
+    avfilter_vf_lut3d DATA
+    avfilter_vf_lutrgb DATA
+    avfilter_vf_lutyuv DATA
+    avfilter_vf_mp DATA
+    avfilter_vf_mpdecimate DATA
+    avfilter_vf_negate DATA
+    avfilter_vf_noformat DATA
+    avfilter_vf_noise DATA
+    avfilter_vf_null DATA
+    avfilter_vf_overlay DATA
+    avfilter_vf_owdenoise DATA
+    avfilter_vf_pad DATA
+    avfilter_vf_perms DATA
+    avfilter_vf_pixdesctest DATA
+    avfilter_vf_pp DATA
+    avfilter_vf_removelogo DATA
+    avfilter_vf_scale DATA
+    avfilter_vf_select DATA
+    avfilter_vf_sendcmd DATA
+    avfilter_vf_separatefields DATA
+    avfilter_vf_setdar DATA
+    avfilter_vf_setfield DATA
+    avfilter_vf_setpts DATA
+    avfilter_vf_setsar DATA
+    avfilter_vf_settb DATA
+    avfilter_vf_showinfo DATA
+    avfilter_vf_smartblur DATA
+    avfilter_vf_split DATA
+    avfilter_vf_stereo3d DATA
+    avfilter_vf_subtitles DATA
+    avfilter_vf_super2xsai DATA
+    avfilter_vf_swapuv DATA
+    avfilter_vf_telecine DATA
+    avfilter_vf_thumbnail DATA
+    avfilter_vf_tile DATA
+    avfilter_vf_tinterlace DATA
+    avfilter_vf_transpose DATA
+    avfilter_vf_trim DATA
+    avfilter_vf_unsharp DATA
+    avfilter_vf_vflip DATA
+    avfilter_vf_yadif DATA
+    avfilter_vsink_buffer DATA
+    avfilter_vsink_ffbuffersink DATA
+    avfilter_vsink_nullsink DATA
+    avfilter_vsrc_buffer DATA
+    avfilter_vsrc_cellauto DATA
+    avfilter_vsrc_color DATA
+    avfilter_vsrc_frei0r_src DATA
+    avfilter_vsrc_life DATA
+    avfilter_vsrc_mandelbrot DATA
+    avfilter_vsrc_mptestsrc DATA
+    avfilter_vsrc_nullsrc DATA
+    avfilter_vsrc_rgbtestsrc DATA
+    avfilter_vsrc_smptebars DATA
+    avfilter_vsrc_smptehdbars DATA
+    avfilter_vsrc_testsrc DATA
+    ff_default_query_formats
Binary file lib/OpenAL/lib/x86/avfilter.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/avformat-55.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,144 @@
+EXPORTS
+    av_add_index_entry
+    av_append_packet
+    av_close_input_file
+    av_codec_get_id
+    av_codec_get_tag
+    av_codec_get_tag2
+    av_convert_lang_to
+    av_demuxer_open
+    av_dump_format
+    av_filename_number_test
+    av_find_best_stream
+    av_find_default_stream_index
+    av_find_input_format
+    av_find_program_from_stream
+    av_find_stream_info
+    av_fmt_ctx_get_duration_estimation_method
+    av_get_frame_filename
+    av_get_output_timestamp
+    av_get_packet
+    av_guess_codec
+    av_guess_format
+    av_guess_frame_rate
+    av_guess_sample_aspect_ratio
+    av_hex_dump
+    av_hex_dump_log
+    av_iformat_next
+    av_index_search_timestamp
+    av_interleaved_write_frame
+    av_match_ext
+    av_new_program
+    av_new_stream
+    av_oformat_next
+    av_pkt_dump2
+    av_pkt_dump_log2
+    av_probe_input_buffer
+    av_probe_input_format
+    av_probe_input_format2
+    av_probe_input_format3
+    av_read_frame
+    av_read_packet
+    av_read_pause
+    av_read_play
+    av_register_all
+    av_register_input_format
+    av_register_output_format
+    av_register_rdt_dynamic_payload_handlers
+    av_register_rtp_dynamic_payload_handlers
+    av_sdp_create
+    av_seek_frame
+    av_set_pts_info
+    av_stream_get_r_frame_rate
+    av_stream_set_r_frame_rate
+    av_url_split
+    av_write_frame
+    av_write_trailer
+    avformat_alloc_context
+    avformat_alloc_output_context
+    avformat_alloc_output_context2
+    avformat_close_input
+    avformat_configuration
+    avformat_find_stream_info
+    avformat_free_context
+    avformat_get_class
+    avformat_get_riff_audio_tags
+    avformat_get_riff_video_tags
+    avformat_license
+    avformat_match_stream_specifier
+    avformat_network_deinit
+    avformat_network_init
+    avformat_new_stream
+    avformat_open_input
+    avformat_query_codec
+    avformat_queue_attached_pictures
+    avformat_seek_file
+    avformat_version
+    avformat_write_header
+    avio_alloc_context
+    avio_check
+    avio_close
+    avio_close_dyn_buf
+    avio_closep
+    avio_enum_protocols
+    avio_flush
+    avio_get_str
+    avio_get_str16be
+    avio_get_str16le
+    avio_open
+    avio_open2
+    avio_open_dyn_buf
+    avio_pause
+    avio_printf
+    avio_put_str
+    avio_put_str16le
+    avio_r8
+    avio_rb16
+    avio_rb24
+    avio_rb32
+    avio_rb64
+    avio_read
+    avio_rl16
+    avio_rl24
+    avio_rl32
+    avio_rl64
+    avio_seek
+    avio_seek_time
+    avio_size
+    avio_skip
+    avio_w8
+    avio_wb16
+    avio_wb24
+    avio_wb32
+    avio_wb64
+    avio_wl16
+    avio_wl24
+    avio_wl32
+    avio_wl64
+    avio_write
+    avpriv_dv_get_packet
+    avpriv_dv_init_demux
+    avpriv_dv_produce_packet
+    avpriv_new_chapter
+    avpriv_set_pts_info
+    ff_codec_get_id
+    ff_inet_aton
+    ff_mpegts_parse_close
+    ff_mpegts_parse_open
+    ff_mpegts_parse_packet
+    ff_rtp_get_local_rtcp_port
+    ff_rtp_get_local_rtp_port
+    ff_rtsp_parse_line
+    ff_socket_nonblock
+    ffio_open_dyn_packet_buf
+    ffio_set_buf_size
+    ffurl_close
+    ffurl_open
+    ffurl_protocol_next
+    ffurl_read_complete
+    ffurl_seek
+    ffurl_size
+    ffurl_write
+    get_crc_table
+    get_extension
+    url_feof
Binary file lib/OpenAL/lib/x86/avformat.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/avutil-52.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,387 @@
+EXPORTS
+    av_add_q
+    av_adler32_update
+    av_aes_alloc
+    av_aes_crypt
+    av_aes_init
+    av_aes_size DATA
+    av_asprintf
+    av_audio_fifo_alloc
+    av_audio_fifo_drain
+    av_audio_fifo_free
+    av_audio_fifo_read
+    av_audio_fifo_realloc
+    av_audio_fifo_reset
+    av_audio_fifo_size
+    av_audio_fifo_space
+    av_audio_fifo_write
+    av_base64_decode
+    av_base64_encode
+    av_basename
+    av_blowfish_crypt
+    av_blowfish_crypt_ecb
+    av_blowfish_init
+    av_bmg_get
+    av_bprint_channel_layout
+    av_bprint_chars
+    av_bprint_clear
+    av_bprint_escape
+    av_bprint_finalize
+    av_bprint_get_buffer
+    av_bprint_init
+    av_bprint_init_for_buffer
+    av_bprint_strftime
+    av_bprintf
+    av_buffer_alloc
+    av_buffer_allocz
+    av_buffer_create
+    av_buffer_default_free
+    av_buffer_get_opaque
+    av_buffer_get_ref_count
+    av_buffer_is_writable
+    av_buffer_make_writable
+    av_buffer_pool_get
+    av_buffer_pool_init
+    av_buffer_pool_uninit
+    av_buffer_realloc
+    av_buffer_ref
+    av_buffer_unref
+    av_calloc
+    av_channel_layout_extract_channel
+    av_compare_mod
+    av_compare_ts
+    av_crc
+    av_crc_get_table
+    av_crc_init
+    av_ctz
+    av_d2q
+    av_d2str
+    av_dbl2ext
+    av_dbl2int
+    av_default_get_category
+    av_default_item_name
+    av_des_crypt
+    av_des_init
+    av_des_mac
+    av_dict_copy
+    av_dict_count
+    av_dict_free
+    av_dict_get
+    av_dict_parse_string
+    av_dict_set
+    av_dirname
+    av_div_q
+    av_dynarray2_add
+    av_dynarray_add
+    av_escape
+    av_evaluate_lls
+    av_expr_eval
+    av_expr_free
+    av_expr_parse
+    av_expr_parse_and_eval
+    av_ext2dbl
+    av_fifo_alloc
+    av_fifo_drain
+    av_fifo_free
+    av_fifo_generic_read
+    av_fifo_generic_write
+    av_fifo_grow
+    av_fifo_realloc2
+    av_fifo_reset
+    av_fifo_size
+    av_fifo_space
+    av_file_map
+    av_file_unmap
+    av_find_info_tag
+    av_find_nearest_q_idx
+    av_find_opt
+    av_flt2int
+    av_force_cpu_flags
+    av_frame_alloc
+    av_frame_clone
+    av_frame_copy_props
+    av_frame_free
+    av_frame_get_best_effort_timestamp
+    av_frame_get_buffer
+    av_frame_get_channel_layout
+    av_frame_get_channels
+    av_frame_get_decode_error_flags
+    av_frame_get_metadata
+    av_frame_get_pkt_duration
+    av_frame_get_pkt_pos
+    av_frame_get_pkt_size
+    av_frame_get_plane_buffer
+    av_frame_get_qp_table
+    av_frame_get_sample_rate
+    av_frame_get_side_data
+    av_frame_is_writable
+    av_frame_make_writable
+    av_frame_move_ref
+    av_frame_new_side_data
+    av_frame_ref
+    av_frame_set_best_effort_timestamp
+    av_frame_set_channel_layout
+    av_frame_set_channels
+    av_frame_set_decode_error_flags
+    av_frame_set_metadata
+    av_frame_set_pkt_duration
+    av_frame_set_pkt_pos
+    av_frame_set_pkt_size
+    av_frame_set_qp_table
+    av_frame_set_sample_rate
+    av_frame_unref
+    av_free
+    av_freep
+    av_gcd
+    av_get_alt_sample_fmt
+    av_get_bits_per_pixel
+    av_get_bits_per_sample_fmt
+    av_get_bytes_per_sample
+    av_get_channel_description
+    av_get_channel_layout
+    av_get_channel_layout_channel_index
+    av_get_channel_layout_nb_channels
+    av_get_channel_layout_string
+    av_get_channel_name
+    av_get_cpu_flags
+    av_get_default_channel_layout
+    av_get_double
+    av_get_int
+    av_get_media_type_string
+    av_get_packed_sample_fmt
+    av_get_padded_bits_per_pixel
+    av_get_picture_type_char
+    av_get_pix_fmt
+    av_get_pix_fmt_name
+    av_get_pix_fmt_string
+    av_get_planar_sample_fmt
+    av_get_q
+    av_get_random_seed
+    av_get_sample_fmt
+    av_get_sample_fmt_name
+    av_get_sample_fmt_string
+    av_get_standard_channel_layout
+    av_get_string
+    av_get_token
+    av_gettime
+    av_hash_alloc
+    av_hash_final
+    av_hash_freep
+    av_hash_get_name
+    av_hash_get_size
+    av_hash_init
+    av_hash_names
+    av_hash_update
+    av_hmac_alloc
+    av_hmac_calc
+    av_hmac_final
+    av_hmac_free
+    av_hmac_init
+    av_hmac_update
+    av_image_alloc
+    av_image_check_size
+    av_image_copy
+    av_image_copy_plane
+    av_image_copy_to_buffer
+    av_image_fill_arrays
+    av_image_fill_linesizes
+    av_image_fill_max_pixsteps
+    av_image_fill_pointers
+    av_image_get_buffer_size
+    av_image_get_linesize
+    av_init_lls
+    av_int2dbl
+    av_int2flt
+    av_int_list_length_for_size
+    av_isdigit
+    av_isgraph
+    av_isspace
+    av_isxdigit
+    av_lfg_init
+    av_log
+    av_log2
+    av_log2_16bit
+    av_log_default_callback
+    av_log_format_line
+    av_log_get_level
+    av_log_set_callback
+    av_log_set_flags
+    av_log_set_level
+    av_lzo1x_decode
+    av_malloc
+    av_mallocz
+    av_max_alloc
+    av_md5_alloc
+    av_md5_final
+    av_md5_init
+    av_md5_size DATA
+    av_md5_sum
+    av_md5_update
+    av_memcpy_backptr
+    av_memdup
+    av_mul_q
+    av_murmur3_alloc
+    av_murmur3_final
+    av_murmur3_init
+    av_murmur3_init_seeded
+    av_murmur3_update
+    av_nearer_q
+    av_next_option
+    av_opt_child_class_next
+    av_opt_child_next
+    av_opt_eval_double
+    av_opt_eval_flags
+    av_opt_eval_float
+    av_opt_eval_int
+    av_opt_eval_int64
+    av_opt_eval_q
+    av_opt_find
+    av_opt_find2
+    av_opt_flag_is_set
+    av_opt_free
+    av_opt_freep_ranges
+    av_opt_get
+    av_opt_get_double
+    av_opt_get_image_size
+    av_opt_get_int
+    av_opt_get_key_value
+    av_opt_get_pixel_fmt
+    av_opt_get_q
+    av_opt_get_sample_fmt
+    av_opt_get_video_rate
+    av_opt_next
+    av_opt_ptr
+    av_opt_query_ranges
+    av_opt_query_ranges_default
+    av_opt_set
+    av_opt_set_bin
+    av_opt_set_defaults
+    av_opt_set_defaults2
+    av_opt_set_dict
+    av_opt_set_double
+    av_opt_set_from_string
+    av_opt_set_image_size
+    av_opt_set_int
+    av_opt_set_pixel_fmt
+    av_opt_set_q
+    av_opt_set_sample_fmt
+    av_opt_set_video_rate
+    av_opt_show2
+    av_parse_color
+    av_parse_cpu_caps
+    av_parse_cpu_flags
+    av_parse_ratio
+    av_parse_time
+    av_parse_video_rate
+    av_parse_video_size
+    av_pix_fmt_count_planes
+    av_pix_fmt_desc_get
+    av_pix_fmt_desc_get_id
+    av_pix_fmt_desc_next
+    av_pix_fmt_descriptors DATA
+    av_pix_fmt_get_chroma_sub_sample
+    av_pix_fmt_swap_endianness
+    av_rc4_crypt
+    av_rc4_init
+    av_read_image_line
+    av_realloc
+    av_realloc_f
+    av_reduce
+    av_rescale
+    av_rescale_delta
+    av_rescale_q
+    av_rescale_q_rnd
+    av_rescale_rnd
+    av_reverse DATA
+    av_sample_fmt_is_planar
+    av_samples_alloc
+    av_samples_alloc_array_and_samples
+    av_samples_copy
+    av_samples_fill_arrays
+    av_samples_get_buffer_size
+    av_samples_set_silence
+    av_set_cpu_flags_mask
+    av_set_double
+    av_set_int
+    av_set_options_string
+    av_set_q
+    av_set_string3
+    av_sha_alloc
+    av_sha_final
+    av_sha_init
+    av_sha_size DATA
+    av_sha_update
+    av_small_strptime
+    av_solve_lls
+    av_strcasecmp
+    av_strdup
+    av_strerror
+    av_stristart
+    av_stristr
+    av_strlcat
+    av_strlcatf
+    av_strlcpy
+    av_strncasecmp
+    av_strnstr
+    av_strstart
+    av_strtod
+    av_strtok
+    av_sub_q
+    av_tempfile
+    av_timecode_adjust_ntsc_framenum2
+    av_timecode_check_frame_rate
+    av_timecode_get_smpte_from_framenum
+    av_timecode_init
+    av_timecode_init_from_string
+    av_timecode_make_mpeg_tc_string
+    av_timecode_make_smpte_tc_string
+    av_timecode_make_string
+    av_timegm
+    av_tree_destroy
+    av_tree_enumerate
+    av_tree_find
+    av_tree_insert
+    av_tree_node_alloc
+    av_tree_node_size DATA
+    av_update_lls
+    av_usleep
+    av_vlog
+    av_write_image_line
+    av_xtea_crypt
+    av_xtea_init
+    avpriv_cga_font DATA
+    avpriv_emms_yasm DATA
+    avpriv_evaluate_lls
+    avpriv_float_dsp_init
+    avpriv_frame_get_metadatap
+    avpriv_init_lls
+    avpriv_report_missing_feature
+    avpriv_request_sample
+    avpriv_scalarproduct_float_c
+    avpriv_set_systematic_pal2
+    avpriv_solve_lls
+    avpriv_update_lls
+    avpriv_vga16_font DATA
+    avutil_configuration
+    avutil_license
+    avutil_version
+    ff_butterflies_float_sse DATA
+    ff_check_pixfmt_descriptors
+    ff_cpu_cpuid DATA
+    ff_cpu_cpuid_test DATA
+    ff_cpu_xgetbv DATA
+    ff_float_dsp_init_x86
+    ff_get_cpu_flags_x86
+    ff_log2_tab DATA
+    ff_scalarproduct_float_sse DATA
+    ff_vector_dmul_scalar_avx DATA
+    ff_vector_dmul_scalar_sse2 DATA
+    ff_vector_fmac_scalar_avx DATA
+    ff_vector_fmac_scalar_sse DATA
+    ff_vector_fmul_add_avx DATA
+    ff_vector_fmul_add_sse DATA
+    ff_vector_fmul_avx DATA
+    ff_vector_fmul_reverse_avx DATA
+    ff_vector_fmul_reverse_sse DATA
+    ff_vector_fmul_scalar_sse DATA
+    ff_vector_fmul_sse DATA
Binary file lib/OpenAL/lib/x86/avutil.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/postproc-52.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,10 @@
+EXPORTS
+    postproc_configuration
+    postproc_license
+    postproc_version
+    pp_free_context
+    pp_free_mode
+    pp_get_context
+    pp_get_mode_by_name_and_quality
+    pp_help DATA
+    pp_postprocess
Binary file lib/OpenAL/lib/x86/postproc.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/swresample-0.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,105 @@
+EXPORTS
+    ff_float_to_int16_a_sse2 DATA
+    ff_float_to_int16_u_sse2 DATA
+    ff_float_to_int32_a_sse2 DATA
+    ff_float_to_int32_u_sse2 DATA
+    ff_int16_to_float_a_sse2 DATA
+    ff_int16_to_float_u_sse2 DATA
+    ff_int16_to_int32_a_mmx DATA
+    ff_int16_to_int32_a_sse2 DATA
+    ff_int16_to_int32_u_mmx DATA
+    ff_int16_to_int32_u_sse2 DATA
+    ff_int32_to_float_a_avx DATA
+    ff_int32_to_float_a_sse2 DATA
+    ff_int32_to_float_u_avx DATA
+    ff_int32_to_float_u_sse2 DATA
+    ff_int32_to_int16_a_mmx DATA
+    ff_int32_to_int16_a_sse2 DATA
+    ff_int32_to_int16_u_mmx DATA
+    ff_int32_to_int16_u_sse2 DATA
+    ff_log2_tab DATA
+    ff_mix_1_1_a_float_avx DATA
+    ff_mix_1_1_a_float_sse DATA
+    ff_mix_1_1_a_int16_mmx DATA
+    ff_mix_1_1_a_int16_sse2 DATA
+    ff_mix_1_1_u_float_avx DATA
+    ff_mix_1_1_u_float_sse DATA
+    ff_mix_1_1_u_int16_mmx DATA
+    ff_mix_1_1_u_int16_sse2 DATA
+    ff_mix_2_1_a_float_avx DATA
+    ff_mix_2_1_a_float_sse DATA
+    ff_mix_2_1_a_int16_mmx DATA
+    ff_mix_2_1_a_int16_sse2 DATA
+    ff_mix_2_1_u_float_avx DATA
+    ff_mix_2_1_u_float_sse DATA
+    ff_mix_2_1_u_int16_mmx DATA
+    ff_mix_2_1_u_int16_sse2 DATA
+    ff_pack_2ch_float_to_int16_a_sse2 DATA
+    ff_pack_2ch_float_to_int16_u_sse2 DATA
+    ff_pack_2ch_float_to_int32_a_sse2 DATA
+    ff_pack_2ch_float_to_int32_u_sse2 DATA
+    ff_pack_2ch_int16_to_float_a_sse2 DATA
+    ff_pack_2ch_int16_to_float_u_sse2 DATA
+    ff_pack_2ch_int16_to_int16_a_sse2 DATA
+    ff_pack_2ch_int16_to_int16_u_sse2 DATA
+    ff_pack_2ch_int16_to_int32_a_sse2 DATA
+    ff_pack_2ch_int16_to_int32_u_sse2 DATA
+    ff_pack_2ch_int32_to_float_a_sse2 DATA
+    ff_pack_2ch_int32_to_float_u_sse2 DATA
+    ff_pack_2ch_int32_to_int16_a_sse2 DATA
+    ff_pack_2ch_int32_to_int16_u_sse2 DATA
+    ff_pack_2ch_int32_to_int32_a_sse2 DATA
+    ff_pack_2ch_int32_to_int32_u_sse2 DATA
+    ff_pack_6ch_float_to_float_a_avx DATA
+    ff_pack_6ch_float_to_float_a_mmx DATA
+    ff_pack_6ch_float_to_float_a_sse4 DATA
+    ff_pack_6ch_float_to_float_u_avx DATA
+    ff_pack_6ch_float_to_float_u_mmx DATA
+    ff_pack_6ch_float_to_float_u_sse4 DATA
+    ff_pack_6ch_float_to_int32_a_avx DATA
+    ff_pack_6ch_float_to_int32_a_sse4 DATA
+    ff_pack_6ch_float_to_int32_u_avx DATA
+    ff_pack_6ch_float_to_int32_u_sse4 DATA
+    ff_pack_6ch_int32_to_float_a_avx DATA
+    ff_pack_6ch_int32_to_float_a_sse4 DATA
+    ff_pack_6ch_int32_to_float_u_avx DATA
+    ff_pack_6ch_int32_to_float_u_sse4 DATA
+    ff_resample_int16_rounder DATA
+    ff_unpack_2ch_float_to_int16_a_sse2 DATA
+    ff_unpack_2ch_float_to_int16_u_sse2 DATA
+    ff_unpack_2ch_float_to_int32_a_sse2 DATA
+    ff_unpack_2ch_float_to_int32_u_sse2 DATA
+    ff_unpack_2ch_int16_to_float_a_sse2 DATA
+    ff_unpack_2ch_int16_to_float_a_ssse3 DATA
+    ff_unpack_2ch_int16_to_float_u_sse2 DATA
+    ff_unpack_2ch_int16_to_float_u_ssse3 DATA
+    ff_unpack_2ch_int16_to_int16_a_sse2 DATA
+    ff_unpack_2ch_int16_to_int16_a_ssse3 DATA
+    ff_unpack_2ch_int16_to_int16_u_sse2 DATA
+    ff_unpack_2ch_int16_to_int16_u_ssse3 DATA
+    ff_unpack_2ch_int16_to_int32_a_sse2 DATA
+    ff_unpack_2ch_int16_to_int32_a_ssse3 DATA
+    ff_unpack_2ch_int16_to_int32_u_sse2 DATA
+    ff_unpack_2ch_int16_to_int32_u_ssse3 DATA
+    ff_unpack_2ch_int32_to_float_a_sse2 DATA
+    ff_unpack_2ch_int32_to_float_u_sse2 DATA
+    ff_unpack_2ch_int32_to_int16_a_sse2 DATA
+    ff_unpack_2ch_int32_to_int16_u_sse2 DATA
+    ff_unpack_2ch_int32_to_int32_a_sse2 DATA
+    ff_unpack_2ch_int32_to_int32_u_sse2 DATA
+    swr_alloc
+    swr_alloc_set_opts
+    swr_convert
+    swr_drop_output
+    swr_free
+    swr_get_class
+    swr_get_delay
+    swr_init
+    swr_inject_silence
+    swr_next_pts
+    swr_set_channel_mapping
+    swr_set_compensation
+    swr_set_matrix
+    swresample_configuration
+    swresample_license
+    swresample_version
Binary file lib/OpenAL/lib/x86/swresample.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/lib/x86/swscale-2.def	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,37 @@
+EXPORTS
+    sws_addVec
+    sws_allocVec
+    sws_alloc_context
+    sws_cloneVec
+    sws_context_class DATA
+    sws_convVec
+    sws_convertPalette8ToPacked24
+    sws_convertPalette8ToPacked32
+    sws_format_name
+    sws_freeContext
+    sws_freeFilter
+    sws_freeVec
+    sws_getCachedContext
+    sws_getCoefficients
+    sws_getColorspaceDetails
+    sws_getConstVec
+    sws_getContext
+    sws_getDefaultFilter
+    sws_getGaussianVec
+    sws_getIdentityVec
+    sws_get_class
+    sws_init_context
+    sws_isSupportedEndiannessConversion
+    sws_isSupportedInput
+    sws_isSupportedOutput
+    sws_normalizeVec
+    sws_printVec2
+    sws_rgb2rgb_init
+    sws_scale
+    sws_scaleVec
+    sws_setColorspaceDetails
+    sws_shiftVec
+    sws_subVec
+    swscale_configuration
+    swscale_license
+    swscale_version
Binary file lib/OpenAL/lib/x86/swscale.lib has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/OpenAL/xram.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,94 @@
+#include <al.h>
+
+// X-RAM Function pointer definitions
+typedef ALboolean (__cdecl *EAXSetBufferMode)(ALsizei n, ALuint *buffers, ALint value);
+typedef ALenum    (__cdecl *EAXGetBufferMode)(ALuint buffer, ALint *value);
+
+//////////////////////////////////////////////////////////////////////////////
+// Query for X-RAM extension
+//
+// if (alIsExtensionPresent("EAX-RAM") == AL_TRUE)
+//		X-RAM Extension found
+//  
+//////////////////////////////////////////////////////////////////////////////
+
+
+//////////////////////////////////////////////////////////////////////////////
+// X-RAM enum names
+//
+// "AL_EAX_RAM_SIZE"
+// "AL_EAX_RAM_FREE"
+// "AL_STORAGE_AUTOMATIC"
+// "AL_STORAGE_HARDWARE"
+// "AL_STORAGE_ACCESSIBLE"
+//
+// Query enum values using alGetEnumValue, for example
+// 
+// long lRamSizeEnum = alGetEnumValue("AL_EAX_RAM_SIZE")
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Query total amount of X-RAM
+//
+// long lTotalSize = alGetInteger(alGetEnumValue("AL_EAX_RAM_SIZE")
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Query free X-RAM available
+//
+// long lFreeSize = alGetInteger(alGetEnumValue("AL_EAX_RAM_FREE")
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Query X-RAM Function pointers
+// 
+// Use typedefs defined above to get the X-RAM function pointers using
+// alGetProcAddress
+//
+// EAXSetBufferMode eaxSetBufferMode;
+// EAXGetBufferMode eaxGetBufferMode;
+//
+// eaxSetBufferMode = (EAXSetBufferMode)alGetProcAddress("EAXSetBufferMode");
+// eaxGetBufferMode = (EAXGetBufferMode)alGetProcAddress("EAXGetBufferMode");
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Force an Open AL Buffer into X-RAM (good for non-streaming buffers)
+//
+// ALuint uiBuffer;
+// alGenBuffers(1, &uiBuffer);
+// eaxSetBufferMode(1, &uiBuffer, alGetEnumValue("AL_STORAGE_HARDWARE"));
+// alBufferData(...);
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Force an Open AL Buffer into 'accessible' (currently host) RAM (good for streaming buffers)
+//
+// ALuint uiBuffer;
+// alGenBuffers(1, &uiBuffer);
+// eaxSetBufferMode(1, &uiBuffer, alGetEnumValue("AL_STORAGE_ACCESSIBLE"));
+// alBufferData(...);
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Put an Open AL Buffer into X-RAM if memory is available, otherwise use
+// host RAM.  This is the default mode.
+//
+// ALuint uiBuffer;
+// alGenBuffers(1, &uiBuffer);
+// eaxSetBufferMode(1, &uiBuffer, alGetEnumValue("AL_STORAGE_AUTOMATIC"));
+// alBufferData(...);
+//
+//////////////////////////////////////////////////////////////////////////////
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/avcodec.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,4768 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AVCODEC_H
+#define AVCODEC_AVCODEC_H
+
+/**
+ * @file
+ * @ingroup libavc
+ * Libavcodec external API header
+ */
+
+#include <errno.h>
+#include "../libavutil/samplefmt.h"
+#include "../libavutil/avutil.h"
+#include "../libavutil/buffer.h"
+#include "../libavutil/cpu.h"
+#include "../libavutil/channel_layout.h"
+#include "../libavutil/dict.h"
+#include "../libavutil/frame.h"
+#include "../libavutil/log.h"
+#include "../libavutil/pixfmt.h"
+#include "../libavutil/rational.h"
+
+#include "../libavcodec/version.h"
+/**
+ * @defgroup libavc Encoding/Decoding Library
+ * @{
+ *
+ * @defgroup lavc_decoding Decoding
+ * @{
+ * @}
+ *
+ * @defgroup lavc_encoding Encoding
+ * @{
+ * @}
+ *
+ * @defgroup lavc_codec Codecs
+ * @{
+ * @defgroup lavc_codec_native Native Codecs
+ * @{
+ * @}
+ * @defgroup lavc_codec_wrappers External library wrappers
+ * @{
+ * @}
+ * @defgroup lavc_codec_hwaccel Hardware Accelerators bridge
+ * @{
+ * @}
+ * @}
+ * @defgroup lavc_internal Internal
+ * @{
+ * @}
+ * @}
+ *
+ */
+
+/**
+ * @defgroup lavc_core Core functions/structures.
+ * @ingroup libavc
+ *
+ * Basic definitions, functions for querying libavcodec capabilities,
+ * allocating core structures, etc.
+ * @{
+ */
+
+
+/**
+ * Identify the syntax and semantics of the bitstream.
+ * The principle is roughly:
+ * Two decoders with the same ID can decode the same streams.
+ * Two encoders with the same ID can encode compatible streams.
+ * There may be slight deviations from the principle due to implementation
+ * details.
+ *
+ * If you add a codec ID to this list, add it so that
+ * 1. no value of a existing codec ID changes (that would break ABI),
+ * 2. Give it a value which when taken as ASCII is recognized uniquely by a human as this specific codec.
+ *    This ensures that 2 forks can independently add AVCodecIDs without producing conflicts.
+ *
+ * After adding new codec IDs, do not forget to add an entry to the codec
+ * descriptor list and bump libavcodec minor version.
+ */
+enum AVCodecID {
+    AV_CODEC_ID_NONE,
+
+    /* video codecs */
+    AV_CODEC_ID_MPEG1VIDEO,
+    AV_CODEC_ID_MPEG2VIDEO, ///< preferred ID for MPEG-1/2 video decoding
+    AV_CODEC_ID_MPEG2VIDEO_XVMC,
+    AV_CODEC_ID_H261,
+    AV_CODEC_ID_H263,
+    AV_CODEC_ID_RV10,
+    AV_CODEC_ID_RV20,
+    AV_CODEC_ID_MJPEG,
+    AV_CODEC_ID_MJPEGB,
+    AV_CODEC_ID_LJPEG,
+    AV_CODEC_ID_SP5X,
+    AV_CODEC_ID_JPEGLS,
+    AV_CODEC_ID_MPEG4,
+    AV_CODEC_ID_RAWVIDEO,
+    AV_CODEC_ID_MSMPEG4V1,
+    AV_CODEC_ID_MSMPEG4V2,
+    AV_CODEC_ID_MSMPEG4V3,
+    AV_CODEC_ID_WMV1,
+    AV_CODEC_ID_WMV2,
+    AV_CODEC_ID_H263P,
+    AV_CODEC_ID_H263I,
+    AV_CODEC_ID_FLV1,
+    AV_CODEC_ID_SVQ1,
+    AV_CODEC_ID_SVQ3,
+    AV_CODEC_ID_DVVIDEO,
+    AV_CODEC_ID_HUFFYUV,
+    AV_CODEC_ID_CYUV,
+    AV_CODEC_ID_H264,
+    AV_CODEC_ID_INDEO3,
+    AV_CODEC_ID_VP3,
+    AV_CODEC_ID_THEORA,
+    AV_CODEC_ID_ASV1,
+    AV_CODEC_ID_ASV2,
+    AV_CODEC_ID_FFV1,
+    AV_CODEC_ID_4XM,
+    AV_CODEC_ID_VCR1,
+    AV_CODEC_ID_CLJR,
+    AV_CODEC_ID_MDEC,
+    AV_CODEC_ID_ROQ,
+    AV_CODEC_ID_INTERPLAY_VIDEO,
+    AV_CODEC_ID_XAN_WC3,
+    AV_CODEC_ID_XAN_WC4,
+    AV_CODEC_ID_RPZA,
+    AV_CODEC_ID_CINEPAK,
+    AV_CODEC_ID_WS_VQA,
+    AV_CODEC_ID_MSRLE,
+    AV_CODEC_ID_MSVIDEO1,
+    AV_CODEC_ID_IDCIN,
+    AV_CODEC_ID_8BPS,
+    AV_CODEC_ID_SMC,
+    AV_CODEC_ID_FLIC,
+    AV_CODEC_ID_TRUEMOTION1,
+    AV_CODEC_ID_VMDVIDEO,
+    AV_CODEC_ID_MSZH,
+    AV_CODEC_ID_ZLIB,
+    AV_CODEC_ID_QTRLE,
+    AV_CODEC_ID_TSCC,
+    AV_CODEC_ID_ULTI,
+    AV_CODEC_ID_QDRAW,
+    AV_CODEC_ID_VIXL,
+    AV_CODEC_ID_QPEG,
+    AV_CODEC_ID_PNG,
+    AV_CODEC_ID_PPM,
+    AV_CODEC_ID_PBM,
+    AV_CODEC_ID_PGM,
+    AV_CODEC_ID_PGMYUV,
+    AV_CODEC_ID_PAM,
+    AV_CODEC_ID_FFVHUFF,
+    AV_CODEC_ID_RV30,
+    AV_CODEC_ID_RV40,
+    AV_CODEC_ID_VC1,
+    AV_CODEC_ID_WMV3,
+    AV_CODEC_ID_LOCO,
+    AV_CODEC_ID_WNV1,
+    AV_CODEC_ID_AASC,
+    AV_CODEC_ID_INDEO2,
+    AV_CODEC_ID_FRAPS,
+    AV_CODEC_ID_TRUEMOTION2,
+    AV_CODEC_ID_BMP,
+    AV_CODEC_ID_CSCD,
+    AV_CODEC_ID_MMVIDEO,
+    AV_CODEC_ID_ZMBV,
+    AV_CODEC_ID_AVS,
+    AV_CODEC_ID_SMACKVIDEO,
+    AV_CODEC_ID_NUV,
+    AV_CODEC_ID_KMVC,
+    AV_CODEC_ID_FLASHSV,
+    AV_CODEC_ID_CAVS,
+    AV_CODEC_ID_JPEG2000,
+    AV_CODEC_ID_VMNC,
+    AV_CODEC_ID_VP5,
+    AV_CODEC_ID_VP6,
+    AV_CODEC_ID_VP6F,
+    AV_CODEC_ID_TARGA,
+    AV_CODEC_ID_DSICINVIDEO,
+    AV_CODEC_ID_TIERTEXSEQVIDEO,
+    AV_CODEC_ID_TIFF,
+    AV_CODEC_ID_GIF,
+    AV_CODEC_ID_DXA,
+    AV_CODEC_ID_DNXHD,
+    AV_CODEC_ID_THP,
+    AV_CODEC_ID_SGI,
+    AV_CODEC_ID_C93,
+    AV_CODEC_ID_BETHSOFTVID,
+    AV_CODEC_ID_PTX,
+    AV_CODEC_ID_TXD,
+    AV_CODEC_ID_VP6A,
+    AV_CODEC_ID_AMV,
+    AV_CODEC_ID_VB,
+    AV_CODEC_ID_PCX,
+    AV_CODEC_ID_SUNRAST,
+    AV_CODEC_ID_INDEO4,
+    AV_CODEC_ID_INDEO5,
+    AV_CODEC_ID_MIMIC,
+    AV_CODEC_ID_RL2,
+    AV_CODEC_ID_ESCAPE124,
+    AV_CODEC_ID_DIRAC,
+    AV_CODEC_ID_BFI,
+    AV_CODEC_ID_CMV,
+    AV_CODEC_ID_MOTIONPIXELS,
+    AV_CODEC_ID_TGV,
+    AV_CODEC_ID_TGQ,
+    AV_CODEC_ID_TQI,
+    AV_CODEC_ID_AURA,
+    AV_CODEC_ID_AURA2,
+    AV_CODEC_ID_V210X,
+    AV_CODEC_ID_TMV,
+    AV_CODEC_ID_V210,
+    AV_CODEC_ID_DPX,
+    AV_CODEC_ID_MAD,
+    AV_CODEC_ID_FRWU,
+    AV_CODEC_ID_FLASHSV2,
+    AV_CODEC_ID_CDGRAPHICS,
+    AV_CODEC_ID_R210,
+    AV_CODEC_ID_ANM,
+    AV_CODEC_ID_BINKVIDEO,
+    AV_CODEC_ID_IFF_ILBM,
+    AV_CODEC_ID_IFF_BYTERUN1,
+    AV_CODEC_ID_KGV1,
+    AV_CODEC_ID_YOP,
+    AV_CODEC_ID_VP8,
+    AV_CODEC_ID_PICTOR,
+    AV_CODEC_ID_ANSI,
+    AV_CODEC_ID_A64_MULTI,
+    AV_CODEC_ID_A64_MULTI5,
+    AV_CODEC_ID_R10K,
+    AV_CODEC_ID_MXPEG,
+    AV_CODEC_ID_LAGARITH,
+    AV_CODEC_ID_PRORES,
+    AV_CODEC_ID_JV,
+    AV_CODEC_ID_DFA,
+    AV_CODEC_ID_WMV3IMAGE,
+    AV_CODEC_ID_VC1IMAGE,
+    AV_CODEC_ID_UTVIDEO,
+    AV_CODEC_ID_BMV_VIDEO,
+    AV_CODEC_ID_VBLE,
+    AV_CODEC_ID_DXTORY,
+    AV_CODEC_ID_V410,
+    AV_CODEC_ID_XWD,
+    AV_CODEC_ID_CDXL,
+    AV_CODEC_ID_XBM,
+    AV_CODEC_ID_ZEROCODEC,
+    AV_CODEC_ID_MSS1,
+    AV_CODEC_ID_MSA1,
+    AV_CODEC_ID_TSCC2,
+    AV_CODEC_ID_MTS2,
+    AV_CODEC_ID_CLLC,
+    AV_CODEC_ID_MSS2,
+    AV_CODEC_ID_VP9,
+    AV_CODEC_ID_AIC,
+    AV_CODEC_ID_ESCAPE130_DEPRECATED,
+
+    AV_CODEC_ID_BRENDER_PIX= MKBETAG('B','P','I','X'),
+    AV_CODEC_ID_Y41P       = MKBETAG('Y','4','1','P'),
+    AV_CODEC_ID_ESCAPE130  = MKBETAG('E','1','3','0'),
+    AV_CODEC_ID_EXR        = MKBETAG('0','E','X','R'),
+    AV_CODEC_ID_AVRP       = MKBETAG('A','V','R','P'),
+
+    AV_CODEC_ID_012V       = MKBETAG('0','1','2','V'),
+    AV_CODEC_ID_G2M        = MKBETAG( 0 ,'G','2','M'),
+    AV_CODEC_ID_AVUI       = MKBETAG('A','V','U','I'),
+    AV_CODEC_ID_AYUV       = MKBETAG('A','Y','U','V'),
+    AV_CODEC_ID_TARGA_Y216 = MKBETAG('T','2','1','6'),
+    AV_CODEC_ID_V308       = MKBETAG('V','3','0','8'),
+    AV_CODEC_ID_V408       = MKBETAG('V','4','0','8'),
+    AV_CODEC_ID_YUV4       = MKBETAG('Y','U','V','4'),
+    AV_CODEC_ID_SANM       = MKBETAG('S','A','N','M'),
+    AV_CODEC_ID_PAF_VIDEO  = MKBETAG('P','A','F','V'),
+    AV_CODEC_ID_AVRN       = MKBETAG('A','V','R','n'),
+    AV_CODEC_ID_CPIA       = MKBETAG('C','P','I','A'),
+    AV_CODEC_ID_XFACE      = MKBETAG('X','F','A','C'),
+    AV_CODEC_ID_SGIRLE     = MKBETAG('S','G','I','R'),
+    AV_CODEC_ID_MVC1       = MKBETAG('M','V','C','1'),
+    AV_CODEC_ID_MVC2       = MKBETAG('M','V','C','2'),
+    AV_CODEC_ID_SNOW       = MKBETAG('S','N','O','W'),
+    AV_CODEC_ID_WEBP       = MKBETAG('W','E','B','P'),
+    AV_CODEC_ID_SMVJPEG    = MKBETAG('S','M','V','J'),
+
+    /* various PCM "codecs" */
+    AV_CODEC_ID_FIRST_AUDIO = 0x10000,     ///< A dummy id pointing at the start of audio codecs
+    AV_CODEC_ID_PCM_S16LE = 0x10000,
+    AV_CODEC_ID_PCM_S16BE,
+    AV_CODEC_ID_PCM_U16LE,
+    AV_CODEC_ID_PCM_U16BE,
+    AV_CODEC_ID_PCM_S8,
+    AV_CODEC_ID_PCM_U8,
+    AV_CODEC_ID_PCM_MULAW,
+    AV_CODEC_ID_PCM_ALAW,
+    AV_CODEC_ID_PCM_S32LE,
+    AV_CODEC_ID_PCM_S32BE,
+    AV_CODEC_ID_PCM_U32LE,
+    AV_CODEC_ID_PCM_U32BE,
+    AV_CODEC_ID_PCM_S24LE,
+    AV_CODEC_ID_PCM_S24BE,
+    AV_CODEC_ID_PCM_U24LE,
+    AV_CODEC_ID_PCM_U24BE,
+    AV_CODEC_ID_PCM_S24DAUD,
+    AV_CODEC_ID_PCM_ZORK,
+    AV_CODEC_ID_PCM_S16LE_PLANAR,
+    AV_CODEC_ID_PCM_DVD,
+    AV_CODEC_ID_PCM_F32BE,
+    AV_CODEC_ID_PCM_F32LE,
+    AV_CODEC_ID_PCM_F64BE,
+    AV_CODEC_ID_PCM_F64LE,
+    AV_CODEC_ID_PCM_BLURAY,
+    AV_CODEC_ID_PCM_LXF,
+    AV_CODEC_ID_S302M,
+    AV_CODEC_ID_PCM_S8_PLANAR,
+    AV_CODEC_ID_PCM_S24LE_PLANAR = MKBETAG(24,'P','S','P'),
+    AV_CODEC_ID_PCM_S32LE_PLANAR = MKBETAG(32,'P','S','P'),
+    AV_CODEC_ID_PCM_S16BE_PLANAR = MKBETAG('P','S','P',16),
+
+    /* various ADPCM codecs */
+    AV_CODEC_ID_ADPCM_IMA_QT = 0x11000,
+    AV_CODEC_ID_ADPCM_IMA_WAV,
+    AV_CODEC_ID_ADPCM_IMA_DK3,
+    AV_CODEC_ID_ADPCM_IMA_DK4,
+    AV_CODEC_ID_ADPCM_IMA_WS,
+    AV_CODEC_ID_ADPCM_IMA_SMJPEG,
+    AV_CODEC_ID_ADPCM_MS,
+    AV_CODEC_ID_ADPCM_4XM,
+    AV_CODEC_ID_ADPCM_XA,
+    AV_CODEC_ID_ADPCM_ADX,
+    AV_CODEC_ID_ADPCM_EA,
+    AV_CODEC_ID_ADPCM_G726,
+    AV_CODEC_ID_ADPCM_CT,
+    AV_CODEC_ID_ADPCM_SWF,
+    AV_CODEC_ID_ADPCM_YAMAHA,
+    AV_CODEC_ID_ADPCM_SBPRO_4,
+    AV_CODEC_ID_ADPCM_SBPRO_3,
+    AV_CODEC_ID_ADPCM_SBPRO_2,
+    AV_CODEC_ID_ADPCM_THP,
+    AV_CODEC_ID_ADPCM_IMA_AMV,
+    AV_CODEC_ID_ADPCM_EA_R1,
+    AV_CODEC_ID_ADPCM_EA_R3,
+    AV_CODEC_ID_ADPCM_EA_R2,
+    AV_CODEC_ID_ADPCM_IMA_EA_SEAD,
+    AV_CODEC_ID_ADPCM_IMA_EA_EACS,
+    AV_CODEC_ID_ADPCM_EA_XAS,
+    AV_CODEC_ID_ADPCM_EA_MAXIS_XA,
+    AV_CODEC_ID_ADPCM_IMA_ISS,
+    AV_CODEC_ID_ADPCM_G722,
+    AV_CODEC_ID_ADPCM_IMA_APC,
+    AV_CODEC_ID_VIMA       = MKBETAG('V','I','M','A'),
+    AV_CODEC_ID_ADPCM_AFC  = MKBETAG('A','F','C',' '),
+    AV_CODEC_ID_ADPCM_IMA_OKI = MKBETAG('O','K','I',' '),
+    AV_CODEC_ID_ADPCM_DTK  = MKBETAG('D','T','K',' '),
+    AV_CODEC_ID_ADPCM_IMA_RAD = MKBETAG('R','A','D',' '),
+
+    /* AMR */
+    AV_CODEC_ID_AMR_NB = 0x12000,
+    AV_CODEC_ID_AMR_WB,
+
+    /* RealAudio codecs*/
+    AV_CODEC_ID_RA_144 = 0x13000,
+    AV_CODEC_ID_RA_288,
+
+    /* various DPCM codecs */
+    AV_CODEC_ID_ROQ_DPCM = 0x14000,
+    AV_CODEC_ID_INTERPLAY_DPCM,
+    AV_CODEC_ID_XAN_DPCM,
+    AV_CODEC_ID_SOL_DPCM,
+
+    /* audio codecs */
+    AV_CODEC_ID_MP2 = 0x15000,
+    AV_CODEC_ID_MP3, ///< preferred ID for decoding MPEG audio layer 1, 2 or 3
+    AV_CODEC_ID_AAC,
+    AV_CODEC_ID_AC3,
+    AV_CODEC_ID_DTS,
+    AV_CODEC_ID_VORBIS,
+    AV_CODEC_ID_DVAUDIO,
+    AV_CODEC_ID_WMAV1,
+    AV_CODEC_ID_WMAV2,
+    AV_CODEC_ID_MACE3,
+    AV_CODEC_ID_MACE6,
+    AV_CODEC_ID_VMDAUDIO,
+    AV_CODEC_ID_FLAC,
+    AV_CODEC_ID_MP3ADU,
+    AV_CODEC_ID_MP3ON4,
+    AV_CODEC_ID_SHORTEN,
+    AV_CODEC_ID_ALAC,
+    AV_CODEC_ID_WESTWOOD_SND1,
+    AV_CODEC_ID_GSM, ///< as in Berlin toast format
+    AV_CODEC_ID_QDM2,
+    AV_CODEC_ID_COOK,
+    AV_CODEC_ID_TRUESPEECH,
+    AV_CODEC_ID_TTA,
+    AV_CODEC_ID_SMACKAUDIO,
+    AV_CODEC_ID_QCELP,
+    AV_CODEC_ID_WAVPACK,
+    AV_CODEC_ID_DSICINAUDIO,
+    AV_CODEC_ID_IMC,
+    AV_CODEC_ID_MUSEPACK7,
+    AV_CODEC_ID_MLP,
+    AV_CODEC_ID_GSM_MS, /* as found in WAV */
+    AV_CODEC_ID_ATRAC3,
+    AV_CODEC_ID_VOXWARE,
+    AV_CODEC_ID_APE,
+    AV_CODEC_ID_NELLYMOSER,
+    AV_CODEC_ID_MUSEPACK8,
+    AV_CODEC_ID_SPEEX,
+    AV_CODEC_ID_WMAVOICE,
+    AV_CODEC_ID_WMAPRO,
+    AV_CODEC_ID_WMALOSSLESS,
+    AV_CODEC_ID_ATRAC3P,
+    AV_CODEC_ID_EAC3,
+    AV_CODEC_ID_SIPR,
+    AV_CODEC_ID_MP1,
+    AV_CODEC_ID_TWINVQ,
+    AV_CODEC_ID_TRUEHD,
+    AV_CODEC_ID_MP4ALS,
+    AV_CODEC_ID_ATRAC1,
+    AV_CODEC_ID_BINKAUDIO_RDFT,
+    AV_CODEC_ID_BINKAUDIO_DCT,
+    AV_CODEC_ID_AAC_LATM,
+    AV_CODEC_ID_QDMC,
+    AV_CODEC_ID_CELT,
+    AV_CODEC_ID_G723_1,
+    AV_CODEC_ID_G729,
+    AV_CODEC_ID_8SVX_EXP,
+    AV_CODEC_ID_8SVX_FIB,
+    AV_CODEC_ID_BMV_AUDIO,
+    AV_CODEC_ID_RALF,
+    AV_CODEC_ID_IAC,
+    AV_CODEC_ID_ILBC,
+    AV_CODEC_ID_OPUS_DEPRECATED,
+    AV_CODEC_ID_COMFORT_NOISE,
+    AV_CODEC_ID_TAK_DEPRECATED,
+    AV_CODEC_ID_FFWAVESYNTH = MKBETAG('F','F','W','S'),
+    AV_CODEC_ID_SONIC       = MKBETAG('S','O','N','C'),
+    AV_CODEC_ID_SONIC_LS    = MKBETAG('S','O','N','L'),
+    AV_CODEC_ID_PAF_AUDIO   = MKBETAG('P','A','F','A'),
+    AV_CODEC_ID_OPUS        = MKBETAG('O','P','U','S'),
+    AV_CODEC_ID_TAK         = MKBETAG('t','B','a','K'),
+    AV_CODEC_ID_EVRC        = MKBETAG('s','e','v','c'),
+    AV_CODEC_ID_SMV         = MKBETAG('s','s','m','v'),
+
+    /* subtitle codecs */
+    AV_CODEC_ID_FIRST_SUBTITLE = 0x17000,          ///< A dummy ID pointing at the start of subtitle codecs.
+    AV_CODEC_ID_DVD_SUBTITLE = 0x17000,
+    AV_CODEC_ID_DVB_SUBTITLE,
+    AV_CODEC_ID_TEXT,  ///< raw UTF-8 text
+    AV_CODEC_ID_XSUB,
+    AV_CODEC_ID_SSA,
+    AV_CODEC_ID_MOV_TEXT,
+    AV_CODEC_ID_HDMV_PGS_SUBTITLE,
+    AV_CODEC_ID_DVB_TELETEXT,
+    AV_CODEC_ID_SRT,
+    AV_CODEC_ID_MICRODVD   = MKBETAG('m','D','V','D'),
+    AV_CODEC_ID_EIA_608    = MKBETAG('c','6','0','8'),
+    AV_CODEC_ID_JACOSUB    = MKBETAG('J','S','U','B'),
+    AV_CODEC_ID_SAMI       = MKBETAG('S','A','M','I'),
+    AV_CODEC_ID_REALTEXT   = MKBETAG('R','T','X','T'),
+    AV_CODEC_ID_SUBVIEWER1 = MKBETAG('S','b','V','1'),
+    AV_CODEC_ID_SUBVIEWER  = MKBETAG('S','u','b','V'),
+    AV_CODEC_ID_SUBRIP     = MKBETAG('S','R','i','p'),
+    AV_CODEC_ID_WEBVTT     = MKBETAG('W','V','T','T'),
+    AV_CODEC_ID_MPL2       = MKBETAG('M','P','L','2'),
+    AV_CODEC_ID_VPLAYER    = MKBETAG('V','P','l','r'),
+    AV_CODEC_ID_PJS        = MKBETAG('P','h','J','S'),
+    AV_CODEC_ID_ASS        = MKBETAG('A','S','S',' '),  ///< ASS as defined in Matroska
+
+    /* other specific kind of codecs (generally used for attachments) */
+    AV_CODEC_ID_FIRST_UNKNOWN = 0x18000,           ///< A dummy ID pointing at the start of various fake codecs.
+    AV_CODEC_ID_TTF = 0x18000,
+    AV_CODEC_ID_BINTEXT    = MKBETAG('B','T','X','T'),
+    AV_CODEC_ID_XBIN       = MKBETAG('X','B','I','N'),
+    AV_CODEC_ID_IDF        = MKBETAG( 0 ,'I','D','F'),
+    AV_CODEC_ID_OTF        = MKBETAG( 0 ,'O','T','F'),
+    AV_CODEC_ID_SMPTE_KLV  = MKBETAG('K','L','V','A'),
+    AV_CODEC_ID_DVD_NAV    = MKBETAG('D','N','A','V'),
+
+
+    AV_CODEC_ID_PROBE = 0x19000, ///< codec_id is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it
+
+    AV_CODEC_ID_MPEG2TS = 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS
+                                * stream (only used by libavformat) */
+    AV_CODEC_ID_MPEG4SYSTEMS = 0x20001, /**< _FAKE_ codec to indicate a MPEG-4 Systems
+                                * stream (only used by libavformat) */
+    AV_CODEC_ID_FFMETADATA = 0x21000,   ///< Dummy codec for streams containing only metadata information.
+
+#if FF_API_CODEC_ID
+#include "old_codec_ids.h"
+#endif
+};
+
+/**
+ * This struct describes the properties of a single codec described by an
+ * AVCodecID.
+ * @see avcodec_get_descriptor()
+ */
+typedef struct AVCodecDescriptor {
+    enum AVCodecID     id;
+    enum AVMediaType type;
+    /**
+     * Name of the codec described by this descriptor. It is non-empty and
+     * unique for each codec descriptor. It should contain alphanumeric
+     * characters and '_' only.
+     */
+    const char      *name;
+    /**
+     * A more descriptive name for this codec. May be NULL.
+     */
+    const char *long_name;
+    /**
+     * Codec properties, a combination of AV_CODEC_PROP_* flags.
+     */
+    int             props;
+} AVCodecDescriptor;
+
+/**
+ * Codec uses only intra compression.
+ * Video codecs only.
+ */
+#define AV_CODEC_PROP_INTRA_ONLY    (1 << 0)
+/**
+ * Codec supports lossy compression. Audio and video codecs only.
+ * @note a codec may support both lossy and lossless
+ * compression modes
+ */
+#define AV_CODEC_PROP_LOSSY         (1 << 1)
+/**
+ * Codec supports lossless compression. Audio and video codecs only.
+ */
+#define AV_CODEC_PROP_LOSSLESS      (1 << 2)
+/**
+ * Subtitle codec is bitmap based
+ * Decoded AVSubtitle data can be read from the AVSubtitleRect->pict field.
+ */
+#define AV_CODEC_PROP_BITMAP_SUB    (1 << 16)
+/**
+ * Subtitle codec is text based.
+ * Decoded AVSubtitle data can be read from the AVSubtitleRect->ass field.
+ */
+#define AV_CODEC_PROP_TEXT_SUB      (1 << 17)
+
+/**
+ * @ingroup lavc_decoding
+ * Required number of additionally allocated bytes at the end of the input bitstream for decoding.
+ * This is mainly needed because some optimized bitstream readers read
+ * 32 or 64 bit at once and could read over the end.<br>
+ * Note: If the first 23 bits of the additional bytes are not 0, then damaged
+ * MPEG bitstreams could cause overread and segfault.
+ */
+#define FF_INPUT_BUFFER_PADDING_SIZE 16
+
+/**
+ * @ingroup lavc_encoding
+ * minimum encoding buffer size
+ * Used to avoid some checks during header writing.
+ */
+#define FF_MIN_BUFFER_SIZE 16384
+
+
+/**
+ * @ingroup lavc_encoding
+ * motion estimation type.
+ */
+enum Motion_Est_ID {
+    ME_ZERO = 1,    ///< no search, that is use 0,0 vector whenever one is needed
+    ME_FULL,
+    ME_LOG,
+    ME_PHODS,
+    ME_EPZS,        ///< enhanced predictive zonal search
+    ME_X1,          ///< reserved for experiments
+    ME_HEX,         ///< hexagon based search
+    ME_UMH,         ///< uneven multi-hexagon search
+    ME_TESA,        ///< transformed exhaustive search algorithm
+    ME_ITER=50,     ///< iterative search
+};
+
+/**
+ * @ingroup lavc_decoding
+ */
+enum AVDiscard{
+    /* We leave some space between them for extensions (drop some
+     * keyframes for intra-only or drop just some bidir frames). */
+    AVDISCARD_NONE    =-16, ///< discard nothing
+    AVDISCARD_DEFAULT =  0, ///< discard useless packets like 0 size packets in avi
+    AVDISCARD_NONREF  =  8, ///< discard all non reference
+    AVDISCARD_BIDIR   = 16, ///< discard all bidirectional frames
+    AVDISCARD_NONKEY  = 32, ///< discard all frames except keyframes
+    AVDISCARD_ALL     = 48, ///< discard all
+};
+
+enum AVColorPrimaries{
+    AVCOL_PRI_BT709       = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B
+    AVCOL_PRI_UNSPECIFIED = 2,
+    AVCOL_PRI_BT470M      = 4,
+    AVCOL_PRI_BT470BG     = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM
+    AVCOL_PRI_SMPTE170M   = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
+    AVCOL_PRI_SMPTE240M   = 7, ///< functionally identical to above
+    AVCOL_PRI_FILM        = 8,
+    AVCOL_PRI_NB             , ///< Not part of ABI
+};
+
+enum AVColorTransferCharacteristic{
+    AVCOL_TRC_BT709       = 1, ///< also ITU-R BT1361
+    AVCOL_TRC_UNSPECIFIED = 2,
+    AVCOL_TRC_GAMMA22     = 4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
+    AVCOL_TRC_GAMMA28     = 5, ///< also ITU-R BT470BG
+    AVCOL_TRC_SMPTE240M   = 7,
+    AVCOL_TRC_NB             , ///< Not part of ABI
+};
+
+enum AVColorSpace{
+    AVCOL_SPC_RGB         = 0,
+    AVCOL_SPC_BT709       = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
+    AVCOL_SPC_UNSPECIFIED = 2,
+    AVCOL_SPC_FCC         = 4,
+    AVCOL_SPC_BT470BG     = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
+    AVCOL_SPC_SMPTE170M   = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above
+    AVCOL_SPC_SMPTE240M   = 7,
+    AVCOL_SPC_YCOCG       = 8, ///< Used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16
+    AVCOL_SPC_NB             , ///< Not part of ABI
+};
+#define AVCOL_SPC_YCGCO AVCOL_SPC_YCOCG
+
+enum AVColorRange{
+    AVCOL_RANGE_UNSPECIFIED = 0,
+    AVCOL_RANGE_MPEG        = 1, ///< the normal 219*2^(n-8) "MPEG" YUV ranges
+    AVCOL_RANGE_JPEG        = 2, ///< the normal     2^n-1   "JPEG" YUV ranges
+    AVCOL_RANGE_NB             , ///< Not part of ABI
+};
+
+/**
+ *  X   X      3 4 X      X are luma samples,
+ *             1 2        1-6 are possible chroma positions
+ *  X   X      5 6 X      0 is undefined/unknown position
+ */
+enum AVChromaLocation{
+    AVCHROMA_LOC_UNSPECIFIED = 0,
+    AVCHROMA_LOC_LEFT        = 1, ///< mpeg2/4, h264 default
+    AVCHROMA_LOC_CENTER      = 2, ///< mpeg1, jpeg, h263
+    AVCHROMA_LOC_TOPLEFT     = 3, ///< DV
+    AVCHROMA_LOC_TOP         = 4,
+    AVCHROMA_LOC_BOTTOMLEFT  = 5,
+    AVCHROMA_LOC_BOTTOM      = 6,
+    AVCHROMA_LOC_NB             , ///< Not part of ABI
+};
+
+enum AVAudioServiceType {
+    AV_AUDIO_SERVICE_TYPE_MAIN              = 0,
+    AV_AUDIO_SERVICE_TYPE_EFFECTS           = 1,
+    AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED = 2,
+    AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED  = 3,
+    AV_AUDIO_SERVICE_TYPE_DIALOGUE          = 4,
+    AV_AUDIO_SERVICE_TYPE_COMMENTARY        = 5,
+    AV_AUDIO_SERVICE_TYPE_EMERGENCY         = 6,
+    AV_AUDIO_SERVICE_TYPE_VOICE_OVER        = 7,
+    AV_AUDIO_SERVICE_TYPE_KARAOKE           = 8,
+    AV_AUDIO_SERVICE_TYPE_NB                   , ///< Not part of ABI
+};
+
+/**
+ * @ingroup lavc_encoding
+ */
+typedef struct RcOverride{
+    int start_frame;
+    int end_frame;
+    int qscale; // If this is 0 then quality_factor will be used instead.
+    float quality_factor;
+} RcOverride;
+
+#define FF_MAX_B_FRAMES 16
+
+/* encoding support
+   These flags can be passed in AVCodecContext.flags before initialization.
+   Note: Not everything is supported yet.
+*/
+
+/**
+ * Allow decoders to produce frames with data planes that are not aligned
+ * to CPU requirements (e.g. due to cropping).
+ */
+#define CODEC_FLAG_UNALIGNED 0x0001
+#define CODEC_FLAG_QSCALE 0x0002  ///< Use fixed qscale.
+#define CODEC_FLAG_4MV    0x0004  ///< 4 MV per MB allowed / advanced prediction for H.263.
+#define CODEC_FLAG_QPEL   0x0010  ///< Use qpel MC.
+#define CODEC_FLAG_GMC    0x0020  ///< Use GMC.
+#define CODEC_FLAG_MV0    0x0040  ///< Always try a MB with MV=<0,0>.
+/**
+ * The parent program guarantees that the input for B-frames containing
+ * streams is not written to for at least s->max_b_frames+1 frames, if
+ * this is not set the input will be copied.
+ */
+#define CODEC_FLAG_INPUT_PRESERVED 0x0100
+#define CODEC_FLAG_PASS1           0x0200   ///< Use internal 2pass ratecontrol in first pass mode.
+#define CODEC_FLAG_PASS2           0x0400   ///< Use internal 2pass ratecontrol in second pass mode.
+#define CODEC_FLAG_GRAY            0x2000   ///< Only decode/encode grayscale.
+#define CODEC_FLAG_EMU_EDGE        0x4000   ///< Don't draw edges.
+#define CODEC_FLAG_PSNR            0x8000   ///< error[?] variables will be set during encoding.
+#define CODEC_FLAG_TRUNCATED       0x00010000 /** Input bitstream might be truncated at a random
+                                                  location instead of only at frame boundaries. */
+#define CODEC_FLAG_NORMALIZE_AQP  0x00020000 ///< Normalize adaptive quantization.
+#define CODEC_FLAG_INTERLACED_DCT 0x00040000 ///< Use interlaced DCT.
+#define CODEC_FLAG_LOW_DELAY      0x00080000 ///< Force low delay.
+#define CODEC_FLAG_GLOBAL_HEADER  0x00400000 ///< Place global headers in extradata instead of every keyframe.
+#define CODEC_FLAG_BITEXACT       0x00800000 ///< Use only bitexact stuff (except (I)DCT).
+/* Fx : Flag for h263+ extra options */
+#define CODEC_FLAG_AC_PRED        0x01000000 ///< H.263 advanced intra coding / MPEG-4 AC prediction
+#define CODEC_FLAG_LOOP_FILTER    0x00000800 ///< loop filter
+#define CODEC_FLAG_INTERLACED_ME  0x20000000 ///< interlaced motion estimation
+#define CODEC_FLAG_CLOSED_GOP     0x80000000
+#define CODEC_FLAG2_FAST          0x00000001 ///< Allow non spec compliant speedup tricks.
+#define CODEC_FLAG2_NO_OUTPUT     0x00000004 ///< Skip bitstream encoding.
+#define CODEC_FLAG2_LOCAL_HEADER  0x00000008 ///< Place global headers at every keyframe instead of in extradata.
+#define CODEC_FLAG2_DROP_FRAME_TIMECODE 0x00002000 ///< timecode is in drop frame format. DEPRECATED!!!!
+#define CODEC_FLAG2_IGNORE_CROP   0x00010000 ///< Discard cropping information from SPS.
+
+#define CODEC_FLAG2_CHUNKS        0x00008000 ///< Input bitstream might be truncated at a packet boundaries instead of only at frame boundaries.
+#define CODEC_FLAG2_SHOW_ALL      0x00400000 ///< Show all frames before the first keyframe
+
+/* Unsupported options :
+ *              Syntax Arithmetic coding (SAC)
+ *              Reference Picture Selection
+ *              Independent Segment Decoding */
+/* /Fx */
+/* codec capabilities */
+
+#define CODEC_CAP_DRAW_HORIZ_BAND 0x0001 ///< Decoder can use draw_horiz_band callback.
+/**
+ * Codec uses get_buffer() for allocating buffers and supports custom allocators.
+ * If not set, it might not use get_buffer() at all or use operations that
+ * assume the buffer was allocated by avcodec_default_get_buffer.
+ */
+#define CODEC_CAP_DR1             0x0002
+#define CODEC_CAP_TRUNCATED       0x0008
+/* Codec can export data for HW decoding (XvMC). */
+#define CODEC_CAP_HWACCEL         0x0010
+/**
+ * Encoder or decoder requires flushing with NULL input at the end in order to
+ * give the complete and correct output.
+ *
+ * NOTE: If this flag is not set, the codec is guaranteed to never be fed with
+ *       with NULL data. The user can still send NULL data to the public encode
+ *       or decode function, but libavcodec will not pass it along to the codec
+ *       unless this flag is set.
+ *
+ * Decoders:
+ * The decoder has a non-zero delay and needs to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to get the delayed data until the decoder no longer
+ * returns frames.
+ *
+ * Encoders:
+ * The encoder needs to be fed with NULL data at the end of encoding until the
+ * encoder no longer returns data.
+ *
+ * NOTE: For encoders implementing the AVCodec.encode2() function, setting this
+ *       flag also means that the encoder must set the pts and duration for
+ *       each output packet. If this flag is not set, the pts and duration will
+ *       be determined by libavcodec from the input frame.
+ */
+#define CODEC_CAP_DELAY           0x0020
+/**
+ * Codec can be fed a final frame with a smaller size.
+ * This can be used to prevent truncation of the last audio samples.
+ */
+#define CODEC_CAP_SMALL_LAST_FRAME 0x0040
+/**
+ * Codec can export data for HW decoding (VDPAU).
+ */
+#define CODEC_CAP_HWACCEL_VDPAU    0x0080
+/**
+ * Codec can output multiple frames per AVPacket
+ * Normally demuxers return one frame at a time, demuxers which do not do
+ * are connected to a parser to split what they return into proper frames.
+ * This flag is reserved to the very rare category of codecs which have a
+ * bitstream that cannot be split into frames without timeconsuming
+ * operations like full decoding. Demuxers carring such bitstreams thus
+ * may return multiple frames in a packet. This has many disadvantages like
+ * prohibiting stream copy in many cases thus it should only be considered
+ * as a last resort.
+ */
+#define CODEC_CAP_SUBFRAMES        0x0100
+/**
+ * Codec is experimental and is thus avoided in favor of non experimental
+ * encoders
+ */
+#define CODEC_CAP_EXPERIMENTAL     0x0200
+/**
+ * Codec should fill in channel configuration and samplerate instead of container
+ */
+#define CODEC_CAP_CHANNEL_CONF     0x0400
+
+/**
+ * Codec is able to deal with negative linesizes
+ */
+#define CODEC_CAP_NEG_LINESIZES    0x0800
+
+/**
+ * Codec supports frame-level multithreading.
+ */
+#define CODEC_CAP_FRAME_THREADS    0x1000
+/**
+ * Codec supports slice-based (or partition-based) multithreading.
+ */
+#define CODEC_CAP_SLICE_THREADS    0x2000
+/**
+ * Codec supports changed parameters at any point.
+ */
+#define CODEC_CAP_PARAM_CHANGE     0x4000
+/**
+ * Codec supports avctx->thread_count == 0 (auto).
+ */
+#define CODEC_CAP_AUTO_THREADS     0x8000
+/**
+ * Audio encoder supports receiving a different number of samples in each call.
+ */
+#define CODEC_CAP_VARIABLE_FRAME_SIZE 0x10000
+/**
+ * Codec is intra only.
+ */
+#define CODEC_CAP_INTRA_ONLY       0x40000000
+/**
+ * Codec is lossless.
+ */
+#define CODEC_CAP_LOSSLESS         0x80000000
+
+//The following defines may change, don't expect compatibility if you use them.
+#define MB_TYPE_INTRA4x4   0x0001
+#define MB_TYPE_INTRA16x16 0x0002 //FIXME H.264-specific
+#define MB_TYPE_INTRA_PCM  0x0004 //FIXME H.264-specific
+#define MB_TYPE_16x16      0x0008
+#define MB_TYPE_16x8       0x0010
+#define MB_TYPE_8x16       0x0020
+#define MB_TYPE_8x8        0x0040
+#define MB_TYPE_INTERLACED 0x0080
+#define MB_TYPE_DIRECT2    0x0100 //FIXME
+#define MB_TYPE_ACPRED     0x0200
+#define MB_TYPE_GMC        0x0400
+#define MB_TYPE_SKIP       0x0800
+#define MB_TYPE_P0L0       0x1000
+#define MB_TYPE_P1L0       0x2000
+#define MB_TYPE_P0L1       0x4000
+#define MB_TYPE_P1L1       0x8000
+#define MB_TYPE_L0         (MB_TYPE_P0L0 | MB_TYPE_P1L0)
+#define MB_TYPE_L1         (MB_TYPE_P0L1 | MB_TYPE_P1L1)
+#define MB_TYPE_L0L1       (MB_TYPE_L0   | MB_TYPE_L1)
+#define MB_TYPE_QUANT      0x00010000
+#define MB_TYPE_CBP        0x00020000
+//Note bits 24-31 are reserved for codec specific use (h264 ref0, mpeg1 0mv, ...)
+
+/**
+ * Pan Scan area.
+ * This specifies the area which should be displayed.
+ * Note there may be multiple such areas for one frame.
+ */
+typedef struct AVPanScan{
+    /**
+     * id
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int id;
+
+    /**
+     * width and height in 1/16 pel
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int width;
+    int height;
+
+    /**
+     * position of the top left corner in 1/16 pel for up to 3 fields/frames
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int16_t position[3][2];
+}AVPanScan;
+
+#define FF_QSCALE_TYPE_MPEG1 0
+#define FF_QSCALE_TYPE_MPEG2 1
+#define FF_QSCALE_TYPE_H264  2
+#define FF_QSCALE_TYPE_VP56  3
+
+#if FF_API_GET_BUFFER
+#define FF_BUFFER_TYPE_INTERNAL 1
+#define FF_BUFFER_TYPE_USER     2 ///< direct rendering buffers (image is (de)allocated by user)
+#define FF_BUFFER_TYPE_SHARED   4 ///< Buffer from somewhere else; don't deallocate image (data/base), all other tables are not shared.
+#define FF_BUFFER_TYPE_COPY     8 ///< Just a (modified) copy of some other buffer, don't deallocate anything.
+
+#define FF_BUFFER_HINTS_VALID    0x01 // Buffer hints value is meaningful (if 0 ignore).
+#define FF_BUFFER_HINTS_READABLE 0x02 // Codec will read from buffer.
+#define FF_BUFFER_HINTS_PRESERVE 0x04 // User must not alter buffer content.
+#define FF_BUFFER_HINTS_REUSABLE 0x08 // Codec will reuse the buffer (update).
+#endif
+
+/**
+ * The decoder will keep a reference to the frame and may reuse it later.
+ */
+#define AV_GET_BUFFER_FLAG_REF (1 << 0)
+
+/**
+ * @defgroup lavc_packet AVPacket
+ *
+ * Types and functions for working with AVPacket.
+ * @{
+ */
+enum AVPacketSideDataType {
+    AV_PKT_DATA_PALETTE,
+    AV_PKT_DATA_NEW_EXTRADATA,
+
+    /**
+     * An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows:
+     * @code
+     * u32le param_flags
+     * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT)
+     *     s32le channel_count
+     * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT)
+     *     u64le channel_layout
+     * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE)
+     *     s32le sample_rate
+     * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS)
+     *     s32le width
+     *     s32le height
+     * @endcode
+     */
+    AV_PKT_DATA_PARAM_CHANGE,
+
+    /**
+     * An AV_PKT_DATA_H263_MB_INFO side data packet contains a number of
+     * structures with info about macroblocks relevant to splitting the
+     * packet into smaller packets on macroblock edges (e.g. as for RFC 2190).
+     * That is, it does not necessarily contain info about all macroblocks,
+     * as long as the distance between macroblocks in the info is smaller
+     * than the target payload size.
+     * Each MB info structure is 12 bytes, and is laid out as follows:
+     * @code
+     * u32le bit offset from the start of the packet
+     * u8    current quantizer at the start of the macroblock
+     * u8    GOB number
+     * u16le macroblock address within the GOB
+     * u8    horizontal MV predictor
+     * u8    vertical MV predictor
+     * u8    horizontal MV predictor for block number 3
+     * u8    vertical MV predictor for block number 3
+     * @endcode
+     */
+    AV_PKT_DATA_H263_MB_INFO,
+
+    /**
+     * Recommmends skipping the specified number of samples
+     * @code
+     * u32le number of samples to skip from start of this packet
+     * u32le number of samples to skip from end of this packet
+     * u8    reason for start skip
+     * u8    reason for end   skip (0=padding silence, 1=convergence)
+     * @endcode
+     */
+    AV_PKT_DATA_SKIP_SAMPLES=70,
+
+    /**
+     * An AV_PKT_DATA_JP_DUALMONO side data packet indicates that
+     * the packet may contain "dual mono" audio specific to Japanese DTV
+     * and if it is true, recommends only the selected channel to be used.
+     * @code
+     * u8    selected channels (0=mail/left, 1=sub/right, 2=both)
+     * @endcode
+     */
+    AV_PKT_DATA_JP_DUALMONO,
+
+    /**
+     * A list of zero terminated key/value strings. There is no end marker for
+     * the list, so it is required to rely on the side data size to stop.
+     */
+    AV_PKT_DATA_STRINGS_METADATA,
+
+    /**
+     * Subtitle event position
+     * @code
+     * u32le x1
+     * u32le y1
+     * u32le x2
+     * u32le y2
+     * @endcode
+     */
+    AV_PKT_DATA_SUBTITLE_POSITION,
+
+    /**
+     * Data found in BlockAdditional element of matroska container. There is
+     * no end marker for the data, so it is required to rely on the side data
+     * size to recognize the end. 8 byte id (as found in BlockAddId) followed
+     * by data.
+     */
+    AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
+};
+
+/**
+ * This structure stores compressed data. It is typically exported by demuxers
+ * and then passed as input to decoders, or received as output from encoders and
+ * then passed to muxers.
+ *
+ * For video, it should typically contain one compressed frame. For audio it may
+ * contain several compressed frames.
+ *
+ * AVPacket is one of the few structs in FFmpeg, whose size is a part of public
+ * ABI. Thus it may be allocated on stack and no new fields can be added to it
+ * without libavcodec and libavformat major bump.
+ *
+ * The semantics of data ownership depends on the buf or destruct (deprecated)
+ * fields. If either is set, the packet data is dynamically allocated and is
+ * valid indefinitely until av_free_packet() is called (which in turn calls
+ * av_buffer_unref()/the destruct callback to free the data). If neither is set,
+ * the packet data is typically backed by some static buffer somewhere and is
+ * only valid for a limited time (e.g. until the next read call when demuxing).
+ *
+ * The side data is always allocated with av_malloc() and is freed in
+ * av_free_packet().
+ */
+typedef struct AVPacket {
+    /**
+     * A reference to the reference-counted buffer where the packet data is
+     * stored.
+     * May be NULL, then the packet data is not reference-counted.
+     */
+    AVBufferRef *buf;
+    /**
+     * Presentation timestamp in AVStream->time_base units; the time at which
+     * the decompressed packet will be presented to the user.
+     * Can be AV_NOPTS_VALUE if it is not stored in the file.
+     * pts MUST be larger or equal to dts as presentation cannot happen before
+     * decompression, unless one wants to view hex dumps. Some formats misuse
+     * the terms dts and pts/cts to mean something different. Such timestamps
+     * must be converted to true pts/dts before they are stored in AVPacket.
+     */
+    int64_t pts;
+    /**
+     * Decompression timestamp in AVStream->time_base units; the time at which
+     * the packet is decompressed.
+     * Can be AV_NOPTS_VALUE if it is not stored in the file.
+     */
+    int64_t dts;
+    uint8_t *data;
+    int   size;
+    int   stream_index;
+    /**
+     * A combination of AV_PKT_FLAG values
+     */
+    int   flags;
+    /**
+     * Additional packet data that can be provided by the container.
+     * Packet can contain several types of side information.
+     */
+    struct {
+        uint8_t *data;
+        int      size;
+        enum AVPacketSideDataType type;
+    } *side_data;
+    int side_data_elems;
+
+    /**
+     * Duration of this packet in AVStream->time_base units, 0 if unknown.
+     * Equals next_pts - this_pts in presentation order.
+     */
+    int   duration;
+#if FF_API_DESTRUCT_PACKET
+    attribute_deprecated
+    void  (*destruct)(struct AVPacket *);
+    attribute_deprecated
+    void  *priv;
+#endif
+    int64_t pos;                            ///< byte position in stream, -1 if unknown
+
+    /**
+     * Time difference in AVStream->time_base units from the pts of this
+     * packet to the point at which the output from the decoder has converged
+     * independent from the availability of previous frames. That is, the
+     * frames are virtually identical no matter if decoding started from
+     * the very first frame or from this keyframe.
+     * Is AV_NOPTS_VALUE if unknown.
+     * This field is not the display duration of the current packet.
+     * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY
+     * set.
+     *
+     * The purpose of this field is to allow seeking in streams that have no
+     * keyframes in the conventional sense. It corresponds to the
+     * recovery point SEI in H.264 and match_time_delta in NUT. It is also
+     * essential for some types of subtitle streams to ensure that all
+     * subtitles are correctly displayed after seeking.
+     */
+    int64_t convergence_duration;
+} AVPacket;
+#define AV_PKT_FLAG_KEY     0x0001 ///< The packet contains a keyframe
+#define AV_PKT_FLAG_CORRUPT 0x0002 ///< The packet content is corrupted
+
+enum AVSideDataParamChangeFlags {
+    AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT  = 0x0001,
+    AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT = 0x0002,
+    AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE    = 0x0004,
+    AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS     = 0x0008,
+};
+/**
+ * @}
+ */
+
+struct AVCodecInternal;
+
+enum AVFieldOrder {
+    AV_FIELD_UNKNOWN,
+    AV_FIELD_PROGRESSIVE,
+    AV_FIELD_TT,          //< Top coded_first, top displayed first
+    AV_FIELD_BB,          //< Bottom coded first, bottom displayed first
+    AV_FIELD_TB,          //< Top coded first, bottom displayed first
+    AV_FIELD_BT,          //< Bottom coded first, top displayed first
+};
+
+/**
+ * main external API structure.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * Please use AVOptions (av_opt* / av_set/get*()) to access these fields from user
+ * applications.
+ * sizeof(AVCodecContext) must not be used outside libav*.
+ */
+typedef struct AVCodecContext {
+    /**
+     * information on struct for av_log
+     * - set by avcodec_alloc_context3
+     */
+    const AVClass *av_class;
+    int log_level_offset;
+
+    enum AVMediaType codec_type; /* see AVMEDIA_TYPE_xxx */
+    const struct AVCodec  *codec;
+    char             codec_name[32];
+    enum AVCodecID     codec_id; /* see AV_CODEC_ID_xxx */
+
+    /**
+     * fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
+     * This is used to work around some encoder bugs.
+     * A demuxer should set this to what is stored in the field used to identify the codec.
+     * If there are multiple such fields in a container then the demuxer should choose the one
+     * which maximizes the information about the used codec.
+     * If the codec tag field in a container is larger than 32 bits then the demuxer should
+     * remap the longer ID to 32 bits with a table or other structure. Alternatively a new
+     * extra_codec_tag + size could be added but for this a clear advantage must be demonstrated
+     * first.
+     * - encoding: Set by user, if not then the default based on codec_id will be used.
+     * - decoding: Set by user, will be converted to uppercase by libavcodec during init.
+     */
+    unsigned int codec_tag;
+
+    /**
+     * fourcc from the AVI stream header (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
+     * This is used to work around some encoder bugs.
+     * - encoding: unused
+     * - decoding: Set by user, will be converted to uppercase by libavcodec during init.
+     */
+    unsigned int stream_codec_tag;
+
+    void *priv_data;
+
+    /**
+     * Private context used for internal data.
+     *
+     * Unlike priv_data, this is not codec-specific. It is used in general
+     * libavcodec functions.
+     */
+    struct AVCodecInternal *internal;
+
+    /**
+     * Private data of the user, can be used to carry app specific stuff.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    void *opaque;
+
+    /**
+     * the average bitrate
+     * - encoding: Set by user; unused for constant quantizer encoding.
+     * - decoding: Set by libavcodec. 0 or some bitrate if this info is available in the stream.
+     */
+    int bit_rate;
+
+    /**
+     * number of bits the bitstream is allowed to diverge from the reference.
+     *           the reference can be CBR (for CBR pass1) or VBR (for pass2)
+     * - encoding: Set by user; unused for constant quantizer encoding.
+     * - decoding: unused
+     */
+    int bit_rate_tolerance;
+
+    /**
+     * Global quality for codecs which cannot change it per frame.
+     * This should be proportional to MPEG-1/2/4 qscale.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int global_quality;
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int compression_level;
+#define FF_COMPRESSION_DEFAULT -1
+
+    /**
+     * CODEC_FLAG_*.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int flags;
+
+    /**
+     * CODEC_FLAG2_*
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int flags2;
+
+    /**
+     * some codecs need / can use extradata like Huffman tables.
+     * mjpeg: Huffman tables
+     * rv10: additional flags
+     * mpeg4: global headers (they can be in the bitstream or here)
+     * The allocated memory should be FF_INPUT_BUFFER_PADDING_SIZE bytes larger
+     * than extradata_size to avoid prolems if it is read with the bitstream reader.
+     * The bytewise contents of extradata must not depend on the architecture or CPU endianness.
+     * - encoding: Set/allocated/freed by libavcodec.
+     * - decoding: Set/allocated/freed by user.
+     */
+    uint8_t *extradata;
+    int extradata_size;
+
+    /**
+     * This is the fundamental unit of time (in seconds) in terms
+     * of which frame timestamps are represented. For fixed-fps content,
+     * timebase should be 1/framerate and timestamp increments should be
+     * identically 1.
+     * - encoding: MUST be set by user.
+     * - decoding: Set by libavcodec.
+     */
+    AVRational time_base;
+
+    /**
+     * For some codecs, the time base is closer to the field rate than the frame rate.
+     * Most notably, H.264 and MPEG-2 specify time_base as half of frame duration
+     * if no telecine is used ...
+     *
+     * Set to time_base ticks per frame. Default 1, e.g., H.264/MPEG-2 set it to 2.
+     */
+    int ticks_per_frame;
+
+    /**
+     * Codec delay.
+     *
+     * Encoding: Number of frames delay there will be from the encoder input to
+     *           the decoder output. (we assume the decoder matches the spec)
+     * Decoding: Number of frames delay in addition to what a standard decoder
+     *           as specified in the spec would produce.
+     *
+     * Video:
+     *   Number of frames the decoded output will be delayed relative to the
+     *   encoded input.
+     *
+     * Audio:
+     *   For encoding, this is the number of "priming" samples added to the
+     *   beginning of the stream. The decoded output will be delayed by this
+     *   many samples relative to the input to the encoder. Note that this
+     *   field is purely informational and does not directly affect the pts
+     *   output by the encoder, which should always be based on the actual
+     *   presentation time, including any delay.
+     *   For decoding, this is the number of samples the decoder needs to
+     *   output before the decoder's output is valid. When seeking, you should
+     *   start decoding this many samples prior to your desired seek point.
+     *
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int delay;
+
+
+    /* video only */
+    /**
+     * picture width / height.
+     * - encoding: MUST be set by user.
+     * - decoding: May be set by the user before opening the decoder if known e.g.
+     *             from the container. Some decoders will require the dimensions
+     *             to be set by the caller. During decoding, the decoder may
+     *             overwrite those values as required.
+     */
+    int width, height;
+
+    /**
+     * Bitstream width / height, may be different from width/height e.g. when
+     * the decoded frame is cropped before being output or lowres is enabled.
+     * - encoding: unused
+     * - decoding: May be set by the user before opening the decoder if known
+     *             e.g. from the container. During decoding, the decoder may
+     *             overwrite those values as required.
+     */
+    int coded_width, coded_height;
+
+#define FF_ASPECT_EXTENDED 15
+
+    /**
+     * the number of pictures in a group of pictures, or 0 for intra_only
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int gop_size;
+
+    /**
+     * Pixel format, see AV_PIX_FMT_xxx.
+     * May be set by the demuxer if known from headers.
+     * May be overridden by the decoder if it knows better.
+     * - encoding: Set by user.
+     * - decoding: Set by user if known, overridden by libavcodec if known
+     */
+    enum AVPixelFormat pix_fmt;
+
+    /**
+     * Motion estimation algorithm used for video coding.
+     * 1 (zero), 2 (full), 3 (log), 4 (phods), 5 (epzs), 6 (x1), 7 (hex),
+     * 8 (umh), 9 (iter), 10 (tesa) [7, 8, 10 are x264 specific, 9 is snow specific]
+     * - encoding: MUST be set by user.
+     * - decoding: unused
+     */
+    int me_method;
+
+    /**
+     * If non NULL, 'draw_horiz_band' is called by the libavcodec
+     * decoder to draw a horizontal band. It improves cache usage. Not
+     * all codecs can do that. You must check the codec capabilities
+     * beforehand.
+     * When multithreading is used, it may be called from multiple threads
+     * at the same time; threads might draw different parts of the same AVFrame,
+     * or multiple AVFrames, and there is no guarantee that slices will be drawn
+     * in order.
+     * The function is also used by hardware acceleration APIs.
+     * It is called at least once during frame decoding to pass
+     * the data needed for hardware render.
+     * In that mode instead of pixel data, AVFrame points to
+     * a structure specific to the acceleration API. The application
+     * reads the structure and can change some fields to indicate progress
+     * or mark state.
+     * - encoding: unused
+     * - decoding: Set by user.
+     * @param height the height of the slice
+     * @param y the y position of the slice
+     * @param type 1->top field, 2->bottom field, 3->frame
+     * @param offset offset into the AVFrame.data from which the slice should be read
+     */
+    void (*draw_horiz_band)(struct AVCodecContext *s,
+                            const AVFrame *src, int offset[AV_NUM_DATA_POINTERS],
+                            int y, int type, int height);
+
+    /**
+     * callback to negotiate the pixelFormat
+     * @param fmt is the list of formats which are supported by the codec,
+     * it is terminated by -1 as 0 is a valid format, the formats are ordered by quality.
+     * The first is always the native one.
+     * @return the chosen format
+     * - encoding: unused
+     * - decoding: Set by user, if not set the native format will be chosen.
+     */
+    enum AVPixelFormat (*get_format)(struct AVCodecContext *s, const enum AVPixelFormat * fmt);
+
+    /**
+     * maximum number of B-frames between non-B-frames
+     * Note: The output will be delayed by max_b_frames+1 relative to the input.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int max_b_frames;
+
+    /**
+     * qscale factor between IP and B-frames
+     * If > 0 then the last P-frame quantizer will be used (q= lastp_q*factor+offset).
+     * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset).
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float b_quant_factor;
+
+    /** obsolete FIXME remove */
+    int rc_strategy;
+#define FF_RC_STRATEGY_XVID 1
+
+    int b_frame_strategy;
+
+    /**
+     * qscale offset between IP and B-frames
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float b_quant_offset;
+
+    /**
+     * Size of the frame reordering buffer in the decoder.
+     * For MPEG-2 it is 1 IPB or 0 low delay IP.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int has_b_frames;
+
+    /**
+     * 0-> h263 quant 1-> mpeg quant
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mpeg_quant;
+
+    /**
+     * qscale factor between P and I-frames
+     * If > 0 then the last p frame quantizer will be used (q= lastp_q*factor+offset).
+     * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset).
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float i_quant_factor;
+
+    /**
+     * qscale offset between P and I-frames
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float i_quant_offset;
+
+    /**
+     * luminance masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float lumi_masking;
+
+    /**
+     * temporary complexity masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float temporal_cplx_masking;
+
+    /**
+     * spatial complexity masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float spatial_cplx_masking;
+
+    /**
+     * p block masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float p_masking;
+
+    /**
+     * darkness masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float dark_masking;
+
+    /**
+     * slice count
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by user (or 0).
+     */
+    int slice_count;
+    /**
+     * prediction method (needed for huffyuv)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+     int prediction_method;
+#define FF_PRED_LEFT   0
+#define FF_PRED_PLANE  1
+#define FF_PRED_MEDIAN 2
+
+    /**
+     * slice offsets in the frame in bytes
+     * - encoding: Set/allocated by libavcodec.
+     * - decoding: Set/allocated by user (or NULL).
+     */
+    int *slice_offset;
+
+    /**
+     * sample aspect ratio (0 if unknown)
+     * That is the width of a pixel divided by the height of the pixel.
+     * Numerator and denominator must be relatively prime and smaller than 256 for some video standards.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    AVRational sample_aspect_ratio;
+
+    /**
+     * motion estimation comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_cmp;
+    /**
+     * subpixel motion estimation comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_sub_cmp;
+    /**
+     * macroblock comparison function (not supported yet)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_cmp;
+    /**
+     * interlaced DCT comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int ildct_cmp;
+#define FF_CMP_SAD    0
+#define FF_CMP_SSE    1
+#define FF_CMP_SATD   2
+#define FF_CMP_DCT    3
+#define FF_CMP_PSNR   4
+#define FF_CMP_BIT    5
+#define FF_CMP_RD     6
+#define FF_CMP_ZERO   7
+#define FF_CMP_VSAD   8
+#define FF_CMP_VSSE   9
+#define FF_CMP_NSSE   10
+#define FF_CMP_W53    11
+#define FF_CMP_W97    12
+#define FF_CMP_DCTMAX 13
+#define FF_CMP_DCT264 14
+#define FF_CMP_CHROMA 256
+
+    /**
+     * ME diamond size & shape
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int dia_size;
+
+    /**
+     * amount of previous MV predictors (2a+1 x 2a+1 square)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int last_predictor_count;
+
+    /**
+     * prepass for motion estimation
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int pre_me;
+
+    /**
+     * motion estimation prepass comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_pre_cmp;
+
+    /**
+     * ME prepass diamond size & shape
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int pre_dia_size;
+
+    /**
+     * subpel ME quality
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_subpel_quality;
+
+    /**
+     * DTG active format information (additional aspect ratio
+     * information only used in DVB MPEG-2 transport streams)
+     * 0 if not set.
+     *
+     * - encoding: unused
+     * - decoding: Set by decoder.
+     */
+    int dtg_active_format;
+#define FF_DTG_AFD_SAME         8
+#define FF_DTG_AFD_4_3          9
+#define FF_DTG_AFD_16_9         10
+#define FF_DTG_AFD_14_9         11
+#define FF_DTG_AFD_4_3_SP_14_9  13
+#define FF_DTG_AFD_16_9_SP_14_9 14
+#define FF_DTG_AFD_SP_4_3       15
+
+    /**
+     * maximum motion estimation search range in subpel units
+     * If 0 then no limit.
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_range;
+
+    /**
+     * intra quantizer bias
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int intra_quant_bias;
+#define FF_DEFAULT_QUANT_BIAS 999999
+
+    /**
+     * inter quantizer bias
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int inter_quant_bias;
+
+    /**
+     * slice flags
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int slice_flags;
+#define SLICE_FLAG_CODED_ORDER    0x0001 ///< draw_horiz_band() is called in coded order instead of display
+#define SLICE_FLAG_ALLOW_FIELD    0x0002 ///< allow draw_horiz_band() with field slices (MPEG2 field pics)
+#define SLICE_FLAG_ALLOW_PLANE    0x0004 ///< allow draw_horiz_band() with 1 component at a time (SVQ1)
+
+    /**
+     * XVideo Motion Acceleration
+     * - encoding: forbidden
+     * - decoding: set by decoder
+     */
+    int xvmc_acceleration;
+
+    /**
+     * macroblock decision mode
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_decision;
+#define FF_MB_DECISION_SIMPLE 0        ///< uses mb_cmp
+#define FF_MB_DECISION_BITS   1        ///< chooses the one which needs the fewest bits
+#define FF_MB_DECISION_RD     2        ///< rate distortion
+
+    /**
+     * custom intra quantization matrix
+     * - encoding: Set by user, can be NULL.
+     * - decoding: Set by libavcodec.
+     */
+    uint16_t *intra_matrix;
+
+    /**
+     * custom inter quantization matrix
+     * - encoding: Set by user, can be NULL.
+     * - decoding: Set by libavcodec.
+     */
+    uint16_t *inter_matrix;
+
+    /**
+     * scene change detection threshold
+     * 0 is default, larger means fewer detected scene changes.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int scenechange_threshold;
+
+    /**
+     * noise reduction strength
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int noise_reduction;
+
+    /**
+     * Motion estimation threshold below which no motion estimation is
+     * performed, but instead the user specified motion vectors are used.
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_threshold;
+
+    /**
+     * Macroblock threshold below which the user specified macroblock types will be used.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_threshold;
+
+    /**
+     * precision of the intra DC coefficient - 8
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int intra_dc_precision;
+
+    /**
+     * Number of macroblock rows at the top which are skipped.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int skip_top;
+
+    /**
+     * Number of macroblock rows at the bottom which are skipped.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int skip_bottom;
+
+    /**
+     * Border processing masking, raises the quantizer for mbs on the borders
+     * of the picture.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float border_masking;
+
+    /**
+     * minimum MB lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_lmin;
+
+    /**
+     * maximum MB lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_lmax;
+
+    /**
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_penalty_compensation;
+
+    /**
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int bidir_refine;
+
+    /**
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int brd_scale;
+
+    /**
+     * minimum GOP size
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int keyint_min;
+
+    /**
+     * number of reference frames
+     * - encoding: Set by user.
+     * - decoding: Set by lavc.
+     */
+    int refs;
+
+    /**
+     * chroma qp offset from luma
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int chromaoffset;
+
+    /**
+     * Multiplied by qscale for each frame and added to scene_change_score.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int scenechange_factor;
+
+    /**
+     *
+     * Note: Value depends upon the compare function used for fullpel ME.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mv0_threshold;
+
+    /**
+     * Adjust sensitivity of b_frame_strategy 1.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int b_sensitivity;
+
+    /**
+     * Chromaticity coordinates of the source primaries.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorPrimaries color_primaries;
+
+    /**
+     * Color Transfer Characteristic.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorTransferCharacteristic color_trc;
+
+    /**
+     * YUV colorspace type.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorSpace colorspace;
+
+    /**
+     * MPEG vs JPEG YUV range.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorRange color_range;
+
+    /**
+     * This defines the location of chroma samples.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVChromaLocation chroma_sample_location;
+
+    /**
+     * Number of slices.
+     * Indicates number of picture subdivisions. Used for parallelized
+     * decoding.
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    int slices;
+
+    /** Field order
+     * - encoding: set by libavcodec
+     * - decoding: Set by user.
+     */
+    enum AVFieldOrder field_order;
+
+    /* audio only */
+    int sample_rate; ///< samples per second
+    int channels;    ///< number of audio channels
+
+    /**
+     * audio sample format
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    enum AVSampleFormat sample_fmt;  ///< sample format
+
+    /* The following data should not be initialized. */
+    /**
+     * Number of samples per channel in an audio frame.
+     *
+     * - encoding: set by libavcodec in avcodec_open2(). Each submitted frame
+     *   except the last must contain exactly frame_size samples per channel.
+     *   May be 0 when the codec has CODEC_CAP_VARIABLE_FRAME_SIZE set, then the
+     *   frame size is not restricted.
+     * - decoding: may be set by some decoders to indicate constant frame size
+     */
+    int frame_size;
+
+    /**
+     * Frame counter, set by libavcodec.
+     *
+     * - decoding: total number of frames returned from the decoder so far.
+     * - encoding: total number of frames passed to the encoder so far.
+     *
+     *   @note the counter is not incremented if encoding/decoding resulted in
+     *   an error.
+     */
+    int frame_number;
+
+    /**
+     * number of bytes per packet if constant and known or 0
+     * Used by some WAV based audio codecs.
+     */
+    int block_align;
+
+    /**
+     * Audio cutoff bandwidth (0 means "automatic")
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int cutoff;
+
+#if FF_API_REQUEST_CHANNELS
+    /**
+     * Decoder should decode to this many channels if it can (0 for default)
+     * - encoding: unused
+     * - decoding: Set by user.
+     * @deprecated Deprecated in favor of request_channel_layout.
+     */
+    int request_channels;
+#endif
+
+    /**
+     * Audio channel layout.
+     * - encoding: set by user.
+     * - decoding: set by user, may be overwritten by libavcodec.
+     */
+    uint64_t channel_layout;
+
+    /**
+     * Request decoder to use this channel layout if it can (0 for default)
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    uint64_t request_channel_layout;
+
+    /**
+     * Type of service that the audio stream conveys.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    enum AVAudioServiceType audio_service_type;
+
+    /**
+     * desired sample format
+     * - encoding: Not used.
+     * - decoding: Set by user.
+     * Decoder will decode to this format if it can.
+     */
+    enum AVSampleFormat request_sample_fmt;
+
+#if FF_API_GET_BUFFER
+    /**
+     * Called at the beginning of each frame to get a buffer for it.
+     *
+     * The function will set AVFrame.data[], AVFrame.linesize[].
+     * AVFrame.extended_data[] must also be set, but it should be the same as
+     * AVFrame.data[] except for planar audio with more channels than can fit
+     * in AVFrame.data[]. In that case, AVFrame.data[] shall still contain as
+     * many data pointers as it can hold.
+     *
+     * if CODEC_CAP_DR1 is not set then get_buffer() must call
+     * avcodec_default_get_buffer() instead of providing buffers allocated by
+     * some other means.
+     *
+     * AVFrame.data[] should be 32- or 16-byte-aligned unless the CPU doesn't
+     * need it. avcodec_default_get_buffer() aligns the output buffer properly,
+     * but if get_buffer() is overridden then alignment considerations should
+     * be taken into account.
+     *
+     * @see avcodec_default_get_buffer()
+     *
+     * Video:
+     *
+     * If pic.reference is set then the frame will be read later by libavcodec.
+     * avcodec_align_dimensions2() should be used to find the required width and
+     * height, as they normally need to be rounded up to the next multiple of 16.
+     *
+     * If frame multithreading is used and thread_safe_callbacks is set,
+     * it may be called from a different thread, but not from more than one at
+     * once. Does not need to be reentrant.
+     *
+     * @see release_buffer(), reget_buffer()
+     * @see avcodec_align_dimensions2()
+     *
+     * Audio:
+     *
+     * Decoders request a buffer of a particular size by setting
+     * AVFrame.nb_samples prior to calling get_buffer(). The decoder may,
+     * however, utilize only part of the buffer by setting AVFrame.nb_samples
+     * to a smaller value in the output frame.
+     *
+     * Decoders cannot use the buffer after returning from
+     * avcodec_decode_audio4(), so they will not call release_buffer(), as it
+     * is assumed to be released immediately upon return. In some rare cases,
+     * a decoder may need to call get_buffer() more than once in a single
+     * call to avcodec_decode_audio4(). In that case, when get_buffer() is
+     * called again after it has already been called once, the previously
+     * acquired buffer is assumed to be released at that time and may not be
+     * reused by the decoder.
+     *
+     * As a convenience, av_samples_get_buffer_size() and
+     * av_samples_fill_arrays() in libavutil may be used by custom get_buffer()
+     * functions to find the required data size and to fill data pointers and
+     * linesize. In AVFrame.linesize, only linesize[0] may be set for audio
+     * since all planes must be the same size.
+     *
+     * @see av_samples_get_buffer_size(), av_samples_fill_arrays()
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec, user can override.
+     *
+     * @deprecated use get_buffer2()
+     */
+    attribute_deprecated
+    int (*get_buffer)(struct AVCodecContext *c, AVFrame *pic);
+
+    /**
+     * Called to release buffers which were allocated with get_buffer.
+     * A released buffer can be reused in get_buffer().
+     * pic.data[*] must be set to NULL.
+     * May be called from a different thread if frame multithreading is used,
+     * but not by more than one thread at once, so does not need to be reentrant.
+     * - encoding: unused
+     * - decoding: Set by libavcodec, user can override.
+     *
+     * @deprecated custom freeing callbacks should be set from get_buffer2()
+     */
+    attribute_deprecated
+    void (*release_buffer)(struct AVCodecContext *c, AVFrame *pic);
+
+    /**
+     * Called at the beginning of a frame to get cr buffer for it.
+     * Buffer type (size, hints) must be the same. libavcodec won't check it.
+     * libavcodec will pass previous buffer in pic, function should return
+     * same buffer or new buffer with old frame "painted" into it.
+     * If pic.data[0] == NULL must behave like get_buffer().
+     * if CODEC_CAP_DR1 is not set then reget_buffer() must call
+     * avcodec_default_reget_buffer() instead of providing buffers allocated by
+     * some other means.
+     * - encoding: unused
+     * - decoding: Set by libavcodec, user can override.
+     */
+    attribute_deprecated
+    int (*reget_buffer)(struct AVCodecContext *c, AVFrame *pic);
+#endif
+
+    /**
+     * This callback is called at the beginning of each frame to get data
+     * buffer(s) for it. There may be one contiguous buffer for all the data or
+     * there may be a buffer per each data plane or anything in between. What
+     * this means is, you may set however many entries in buf[] you feel necessary.
+     * Each buffer must be reference-counted using the AVBuffer API (see description
+     * of buf[] below).
+     *
+     * The following fields will be set in the frame before this callback is
+     * called:
+     * - format
+     * - width, height (video only)
+     * - sample_rate, channel_layout, nb_samples (audio only)
+     * Their values may differ from the corresponding values in
+     * AVCodecContext. This callback must use the frame values, not the codec
+     * context values, to calculate the required buffer size.
+     *
+     * This callback must fill the following fields in the frame:
+     * - data[]
+     * - linesize[]
+     * - extended_data:
+     *   * if the data is planar audio with more than 8 channels, then this
+     *     callback must allocate and fill extended_data to contain all pointers
+     *     to all data planes. data[] must hold as many pointers as it can.
+     *     extended_data must be allocated with av_malloc() and will be freed in
+     *     av_frame_unref().
+     *   * otherwise exended_data must point to data
+     * - buf[] must contain one or more pointers to AVBufferRef structures. Each of
+     *   the frame's data and extended_data pointers must be contained in these. That
+     *   is, one AVBufferRef for each allocated chunk of memory, not necessarily one
+     *   AVBufferRef per data[] entry. See: av_buffer_create(), av_buffer_alloc(),
+     *   and av_buffer_ref().
+     * - extended_buf and nb_extended_buf must be allocated with av_malloc() by
+     *   this callback and filled with the extra buffers if there are more
+     *   buffers than buf[] can hold. extended_buf will be freed in
+     *   av_frame_unref().
+     *
+     * If CODEC_CAP_DR1 is not set then get_buffer2() must call
+     * avcodec_default_get_buffer2() instead of providing buffers allocated by
+     * some other means.
+     *
+     * Each data plane must be aligned to the maximum required by the target
+     * CPU.
+     *
+     * @see avcodec_default_get_buffer2()
+     *
+     * Video:
+     *
+     * If AV_GET_BUFFER_FLAG_REF is set in flags then the frame may be reused
+     * (read and/or written to if it is writable) later by libavcodec.
+     *
+     * If CODEC_FLAG_EMU_EDGE is not set in s->flags, the buffer must contain an
+     * edge of the size returned by avcodec_get_edge_width() on all sides.
+     *
+     * avcodec_align_dimensions2() should be used to find the required width and
+     * height, as they normally need to be rounded up to the next multiple of 16.
+     *
+     * If frame multithreading is used and thread_safe_callbacks is set,
+     * this callback may be called from a different thread, but not from more
+     * than one at once. Does not need to be reentrant.
+     *
+     * @see avcodec_align_dimensions2()
+     *
+     * Audio:
+     *
+     * Decoders request a buffer of a particular size by setting
+     * AVFrame.nb_samples prior to calling get_buffer2(). The decoder may,
+     * however, utilize only part of the buffer by setting AVFrame.nb_samples
+     * to a smaller value in the output frame.
+     *
+     * As a convenience, av_samples_get_buffer_size() and
+     * av_samples_fill_arrays() in libavutil may be used by custom get_buffer2()
+     * functions to find the required data size and to fill data pointers and
+     * linesize. In AVFrame.linesize, only linesize[0] may be set for audio
+     * since all planes must be the same size.
+     *
+     * @see av_samples_get_buffer_size(), av_samples_fill_arrays()
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec, user can override.
+     */
+    int (*get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags);
+
+    /**
+     * If non-zero, the decoded audio and video frames returned from
+     * avcodec_decode_video2() and avcodec_decode_audio4() are reference-counted
+     * and are valid indefinitely. The caller must free them with
+     * av_frame_unref() when they are not needed anymore.
+     * Otherwise, the decoded frames must not be freed by the caller and are
+     * only valid until the next decode call.
+     *
+     * - encoding: unused
+     * - decoding: set by the caller before avcodec_open2().
+     */
+    int refcounted_frames;
+
+    /* - encoding parameters */
+    float qcompress;  ///< amount of qscale change between easy & hard scenes (0.0-1.0)
+    float qblur;      ///< amount of qscale smoothing over time (0.0-1.0)
+
+    /**
+     * minimum quantizer
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int qmin;
+
+    /**
+     * maximum quantizer
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int qmax;
+
+    /**
+     * maximum quantizer difference between frames
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int max_qdiff;
+
+    /**
+     * ratecontrol qmin qmax limiting method
+     * 0-> clipping, 1-> use a nice continuous function to limit qscale wthin qmin/qmax.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float rc_qsquish;
+
+    float rc_qmod_amp;
+    int rc_qmod_freq;
+
+    /**
+     * decoder bitstream buffer size
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_buffer_size;
+
+    /**
+     * ratecontrol override, see RcOverride
+     * - encoding: Allocated/set/freed by user.
+     * - decoding: unused
+     */
+    int rc_override_count;
+    RcOverride *rc_override;
+
+    /**
+     * rate control equation
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    const char *rc_eq;
+
+    /**
+     * maximum bitrate
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_max_rate;
+
+    /**
+     * minimum bitrate
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_min_rate;
+
+    float rc_buffer_aggressivity;
+
+    /**
+     * initial complexity for pass1 ratecontrol
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float rc_initial_cplx;
+
+    /**
+     * Ratecontrol attempt to use, at maximum, <value> of what can be used without an underflow.
+     * - encoding: Set by user.
+     * - decoding: unused.
+     */
+    float rc_max_available_vbv_use;
+
+    /**
+     * Ratecontrol attempt to use, at least, <value> times the amount needed to prevent a vbv overflow.
+     * - encoding: Set by user.
+     * - decoding: unused.
+     */
+    float rc_min_vbv_overflow_use;
+
+    /**
+     * Number of bits which should be loaded into the rc buffer before decoding starts.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_initial_buffer_occupancy;
+
+#define FF_CODER_TYPE_VLC       0
+#define FF_CODER_TYPE_AC        1
+#define FF_CODER_TYPE_RAW       2
+#define FF_CODER_TYPE_RLE       3
+#define FF_CODER_TYPE_DEFLATE   4
+    /**
+     * coder type
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int coder_type;
+
+    /**
+     * context model
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int context_model;
+
+    /**
+     * minimum Lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int lmin;
+
+    /**
+     * maximum Lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int lmax;
+
+    /**
+     * frame skip threshold
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_threshold;
+
+    /**
+     * frame skip factor
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_factor;
+
+    /**
+     * frame skip exponent
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_exp;
+
+    /**
+     * frame skip comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_cmp;
+
+    /**
+     * trellis RD quantization
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int trellis;
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int min_prediction_order;
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int max_prediction_order;
+
+    /**
+     * GOP timecode frame start number
+     * - encoding: Set by user, in non drop frame format
+     * - decoding: Set by libavcodec (timecode in the 25 bits format, -1 if unset)
+     */
+    int64_t timecode_frame_start;
+
+    /* The RTP callback: This function is called    */
+    /* every time the encoder has a packet to send. */
+    /* It depends on the encoder if the data starts */
+    /* with a Start Code (it should). H.263 does.   */
+    /* mb_nb contains the number of macroblocks     */
+    /* encoded in the RTP payload.                  */
+    void (*rtp_callback)(struct AVCodecContext *avctx, void *data, int size, int mb_nb);
+
+    int rtp_payload_size;   /* The size of the RTP payload: the coder will  */
+                            /* do its best to deliver a chunk with size     */
+                            /* below rtp_payload_size, the chunk will start */
+                            /* with a start code on some codecs like H.263. */
+                            /* This doesn't take account of any particular  */
+                            /* headers inside the transmitted RTP payload.  */
+
+    /* statistics, used for 2-pass encoding */
+    int mv_bits;
+    int header_bits;
+    int i_tex_bits;
+    int p_tex_bits;
+    int i_count;
+    int p_count;
+    int skip_count;
+    int misc_bits;
+
+    /**
+     * number of bits used for the previously encoded frame
+     * - encoding: Set by libavcodec.
+     * - decoding: unused
+     */
+    int frame_bits;
+
+    /**
+     * pass1 encoding statistics output buffer
+     * - encoding: Set by libavcodec.
+     * - decoding: unused
+     */
+    char *stats_out;
+
+    /**
+     * pass2 encoding statistics input buffer
+     * Concatenated stuff from stats_out of pass1 should be placed here.
+     * - encoding: Allocated/set/freed by user.
+     * - decoding: unused
+     */
+    char *stats_in;
+
+    /**
+     * Work around bugs in encoders which sometimes cannot be detected automatically.
+     * - encoding: Set by user
+     * - decoding: Set by user
+     */
+    int workaround_bugs;
+#define FF_BUG_AUTODETECT       1  ///< autodetection
+#define FF_BUG_OLD_MSMPEG4      2
+#define FF_BUG_XVID_ILACE       4
+#define FF_BUG_UMP4             8
+#define FF_BUG_NO_PADDING       16
+#define FF_BUG_AMV              32
+#define FF_BUG_AC_VLC           0  ///< Will be removed, libavcodec can now handle these non-compliant files by default.
+#define FF_BUG_QPEL_CHROMA      64
+#define FF_BUG_STD_QPEL         128
+#define FF_BUG_QPEL_CHROMA2     256
+#define FF_BUG_DIRECT_BLOCKSIZE 512
+#define FF_BUG_EDGE             1024
+#define FF_BUG_HPEL_CHROMA      2048
+#define FF_BUG_DC_CLIP          4096
+#define FF_BUG_MS               8192 ///< Work around various bugs in Microsoft's broken decoders.
+#define FF_BUG_TRUNCATED       16384
+
+    /**
+     * strictly follow the standard (MPEG4, ...).
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     * Setting this to STRICT or higher means the encoder and decoder will
+     * generally do stupid things, whereas setting it to unofficial or lower
+     * will mean the encoder might produce output that is not supported by all
+     * spec-compliant decoders. Decoders don't differentiate between normal,
+     * unofficial and experimental (that is, they always try to decode things
+     * when they can) unless they are explicitly asked to behave stupidly
+     * (=strictly conform to the specs)
+     */
+    int strict_std_compliance;
+#define FF_COMPLIANCE_VERY_STRICT   2 ///< Strictly conform to an older more strict version of the spec or reference software.
+#define FF_COMPLIANCE_STRICT        1 ///< Strictly conform to all the things in the spec no matter what consequences.
+#define FF_COMPLIANCE_NORMAL        0
+#define FF_COMPLIANCE_UNOFFICIAL   -1 ///< Allow unofficial extensions
+#define FF_COMPLIANCE_EXPERIMENTAL -2 ///< Allow nonstandardized experimental things.
+
+    /**
+     * error concealment flags
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int error_concealment;
+#define FF_EC_GUESS_MVS   1
+#define FF_EC_DEBLOCK     2
+
+    /**
+     * debug
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int debug;
+#define FF_DEBUG_PICT_INFO   1
+#define FF_DEBUG_RC          2
+#define FF_DEBUG_BITSTREAM   4
+#define FF_DEBUG_MB_TYPE     8
+#define FF_DEBUG_QP          16
+#define FF_DEBUG_MV          32
+#define FF_DEBUG_DCT_COEFF   0x00000040
+#define FF_DEBUG_SKIP        0x00000080
+#define FF_DEBUG_STARTCODE   0x00000100
+#define FF_DEBUG_PTS         0x00000200
+#define FF_DEBUG_ER          0x00000400
+#define FF_DEBUG_MMCO        0x00000800
+#define FF_DEBUG_BUGS        0x00001000
+#define FF_DEBUG_VIS_QP      0x00002000
+#define FF_DEBUG_VIS_MB_TYPE 0x00004000
+#define FF_DEBUG_BUFFERS     0x00008000
+#define FF_DEBUG_THREADS     0x00010000
+
+    /**
+     * debug
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int debug_mv;
+#define FF_DEBUG_VIS_MV_P_FOR  0x00000001 //visualize forward predicted MVs of P frames
+#define FF_DEBUG_VIS_MV_B_FOR  0x00000002 //visualize forward predicted MVs of B frames
+#define FF_DEBUG_VIS_MV_B_BACK 0x00000004 //visualize backward predicted MVs of B frames
+
+    /**
+     * Error recognition; may misdetect some more or less valid parts as errors.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int err_recognition;
+#define AV_EF_CRCCHECK  (1<<0)
+#define AV_EF_BITSTREAM (1<<1)
+#define AV_EF_BUFFER    (1<<2)
+#define AV_EF_EXPLODE   (1<<3)
+
+#define AV_EF_CAREFUL    (1<<16)
+#define AV_EF_COMPLIANT  (1<<17)
+#define AV_EF_AGGRESSIVE (1<<18)
+
+
+    /**
+     * opaque 64bit number (generally a PTS) that will be reordered and
+     * output in AVFrame.reordered_opaque
+     * @deprecated in favor of pkt_pts
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int64_t reordered_opaque;
+
+    /**
+     * Hardware accelerator in use
+     * - encoding: unused.
+     * - decoding: Set by libavcodec
+     */
+    struct AVHWAccel *hwaccel;
+
+    /**
+     * Hardware accelerator context.
+     * For some hardware accelerators, a global context needs to be
+     * provided by the user. In that case, this holds display-dependent
+     * data FFmpeg cannot instantiate itself. Please refer to the
+     * FFmpeg HW accelerator documentation to know how to fill this
+     * is. e.g. for VA API, this is a struct vaapi_context.
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    void *hwaccel_context;
+
+    /**
+     * error
+     * - encoding: Set by libavcodec if flags&CODEC_FLAG_PSNR.
+     * - decoding: unused
+     */
+    uint64_t error[AV_NUM_DATA_POINTERS];
+
+    /**
+     * DCT algorithm, see FF_DCT_* below
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int dct_algo;
+#define FF_DCT_AUTO    0
+#define FF_DCT_FASTINT 1
+#define FF_DCT_INT     2
+#define FF_DCT_MMX     3
+#define FF_DCT_ALTIVEC 5
+#define FF_DCT_FAAN    6
+
+    /**
+     * IDCT algorithm, see FF_IDCT_* below.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int idct_algo;
+#define FF_IDCT_AUTO          0
+#define FF_IDCT_INT           1
+#define FF_IDCT_SIMPLE        2
+#define FF_IDCT_SIMPLEMMX     3
+#define FF_IDCT_ARM           7
+#define FF_IDCT_ALTIVEC       8
+#define FF_IDCT_SH4           9
+#define FF_IDCT_SIMPLEARM     10
+#define FF_IDCT_IPP           13
+#define FF_IDCT_XVIDMMX       14
+#define FF_IDCT_SIMPLEARMV5TE 16
+#define FF_IDCT_SIMPLEARMV6   17
+#define FF_IDCT_SIMPLEVIS     18
+#define FF_IDCT_FAAN          20
+#define FF_IDCT_SIMPLENEON    22
+#define FF_IDCT_SIMPLEALPHA   23
+
+    /**
+     * bits per sample/pixel from the demuxer (needed for huffyuv).
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by user.
+     */
+     int bits_per_coded_sample;
+
+    /**
+     * Bits per sample/pixel of internal libavcodec pixel/sample format.
+     * - encoding: set by user.
+     * - decoding: set by libavcodec.
+     */
+    int bits_per_raw_sample;
+
+#if FF_API_LOWRES
+    /**
+     * low resolution decoding, 1-> 1/2 size, 2->1/4 size
+     * - encoding: unused
+     * - decoding: Set by user.
+     * Code outside libavcodec should access this field using:
+     * av_codec_{get,set}_lowres(avctx)
+     */
+     int lowres;
+#endif
+
+    /**
+     * the picture in the bitstream
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    AVFrame *coded_frame;
+
+    /**
+     * thread count
+     * is used to decide how many independent tasks should be passed to execute()
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int thread_count;
+
+    /**
+     * Which multithreading methods to use.
+     * Use of FF_THREAD_FRAME will increase decoding delay by one frame per thread,
+     * so clients which cannot provide future frames should not use it.
+     *
+     * - encoding: Set by user, otherwise the default is used.
+     * - decoding: Set by user, otherwise the default is used.
+     */
+    int thread_type;
+#define FF_THREAD_FRAME   1 ///< Decode more than one frame at once
+#define FF_THREAD_SLICE   2 ///< Decode more than one part of a single frame at once
+
+    /**
+     * Which multithreading methods are in use by the codec.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int active_thread_type;
+
+    /**
+     * Set by the client if its custom get_buffer() callback can be called
+     * synchronously from another thread, which allows faster multithreaded decoding.
+     * draw_horiz_band() will be called from other threads regardless of this setting.
+     * Ignored if the default get_buffer() is used.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int thread_safe_callbacks;
+
+    /**
+     * The codec may call this to execute several independent things.
+     * It will return only after finishing all tasks.
+     * The user may replace this with some multithreaded implementation,
+     * the default implementation will execute the parts serially.
+     * @param count the number of things to execute
+     * - encoding: Set by libavcodec, user can override.
+     * - decoding: Set by libavcodec, user can override.
+     */
+    int (*execute)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg), void *arg2, int *ret, int count, int size);
+
+    /**
+     * The codec may call this to execute several independent things.
+     * It will return only after finishing all tasks.
+     * The user may replace this with some multithreaded implementation,
+     * the default implementation will execute the parts serially.
+     * Also see avcodec_thread_init and e.g. the --enable-pthread configure option.
+     * @param c context passed also to func
+     * @param count the number of things to execute
+     * @param arg2 argument passed unchanged to func
+     * @param ret return values of executed functions, must have space for "count" values. May be NULL.
+     * @param func function that will be called count times, with jobnr from 0 to count-1.
+     *             threadnr will be in the range 0 to c->thread_count-1 < MAX_THREADS and so that no
+     *             two instances of func executing at the same time will have the same threadnr.
+     * @return always 0 currently, but code should handle a future improvement where when any call to func
+     *         returns < 0 no further calls to func may be done and < 0 is returned.
+     * - encoding: Set by libavcodec, user can override.
+     * - decoding: Set by libavcodec, user can override.
+     */
+    int (*execute2)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg, int jobnr, int threadnr), void *arg2, int *ret, int count);
+
+    /**
+     * thread opaque
+     * Can be used by execute() to store some per AVCodecContext stuff.
+     * - encoding: set by execute()
+     * - decoding: set by execute()
+     */
+    void *thread_opaque;
+
+    /**
+     * noise vs. sse weight for the nsse comparsion function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+     int nsse_weight;
+
+    /**
+     * profile
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+     int profile;
+#define FF_PROFILE_UNKNOWN -99
+#define FF_PROFILE_RESERVED -100
+
+#define FF_PROFILE_AAC_MAIN 0
+#define FF_PROFILE_AAC_LOW  1
+#define FF_PROFILE_AAC_SSR  2
+#define FF_PROFILE_AAC_LTP  3
+#define FF_PROFILE_AAC_HE   4
+#define FF_PROFILE_AAC_HE_V2 28
+#define FF_PROFILE_AAC_LD   22
+#define FF_PROFILE_AAC_ELD  38
+
+#define FF_PROFILE_DTS         20
+#define FF_PROFILE_DTS_ES      30
+#define FF_PROFILE_DTS_96_24   40
+#define FF_PROFILE_DTS_HD_HRA  50
+#define FF_PROFILE_DTS_HD_MA   60
+
+#define FF_PROFILE_MPEG2_422    0
+#define FF_PROFILE_MPEG2_HIGH   1
+#define FF_PROFILE_MPEG2_SS     2
+#define FF_PROFILE_MPEG2_SNR_SCALABLE  3
+#define FF_PROFILE_MPEG2_MAIN   4
+#define FF_PROFILE_MPEG2_SIMPLE 5
+
+#define FF_PROFILE_H264_CONSTRAINED  (1<<9)  // 8+1; constraint_set1_flag
+#define FF_PROFILE_H264_INTRA        (1<<11) // 8+3; constraint_set3_flag
+
+#define FF_PROFILE_H264_BASELINE             66
+#define FF_PROFILE_H264_CONSTRAINED_BASELINE (66|FF_PROFILE_H264_CONSTRAINED)
+#define FF_PROFILE_H264_MAIN                 77
+#define FF_PROFILE_H264_EXTENDED             88
+#define FF_PROFILE_H264_HIGH                 100
+#define FF_PROFILE_H264_HIGH_10              110
+#define FF_PROFILE_H264_HIGH_10_INTRA        (110|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_HIGH_422             122
+#define FF_PROFILE_H264_HIGH_422_INTRA       (122|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_HIGH_444             144
+#define FF_PROFILE_H264_HIGH_444_PREDICTIVE  244
+#define FF_PROFILE_H264_HIGH_444_INTRA       (244|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_CAVLC_444            44
+
+#define FF_PROFILE_VC1_SIMPLE   0
+#define FF_PROFILE_VC1_MAIN     1
+#define FF_PROFILE_VC1_COMPLEX  2
+#define FF_PROFILE_VC1_ADVANCED 3
+
+#define FF_PROFILE_MPEG4_SIMPLE                     0
+#define FF_PROFILE_MPEG4_SIMPLE_SCALABLE            1
+#define FF_PROFILE_MPEG4_CORE                       2
+#define FF_PROFILE_MPEG4_MAIN                       3
+#define FF_PROFILE_MPEG4_N_BIT                      4
+#define FF_PROFILE_MPEG4_SCALABLE_TEXTURE           5
+#define FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION      6
+#define FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE     7
+#define FF_PROFILE_MPEG4_HYBRID                     8
+#define FF_PROFILE_MPEG4_ADVANCED_REAL_TIME         9
+#define FF_PROFILE_MPEG4_CORE_SCALABLE             10
+#define FF_PROFILE_MPEG4_ADVANCED_CODING           11
+#define FF_PROFILE_MPEG4_ADVANCED_CORE             12
+#define FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE 13
+#define FF_PROFILE_MPEG4_SIMPLE_STUDIO             14
+#define FF_PROFILE_MPEG4_ADVANCED_SIMPLE           15
+
+#define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0   0
+#define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1   1
+#define FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION  2
+#define FF_PROFILE_JPEG2000_DCINEMA_2K              3
+#define FF_PROFILE_JPEG2000_DCINEMA_4K              4
+
+    /**
+     * level
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+     int level;
+#define FF_LEVEL_UNKNOWN -99
+
+    /**
+     * Skip loop filtering for selected frames.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    enum AVDiscard skip_loop_filter;
+
+    /**
+     * Skip IDCT/dequantization for selected frames.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    enum AVDiscard skip_idct;
+
+    /**
+     * Skip decoding for selected frames.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    enum AVDiscard skip_frame;
+
+    /**
+     * Header containing style information for text subtitles.
+     * For SUBTITLE_ASS subtitle type, it should contain the whole ASS
+     * [Script Info] and [V4+ Styles] section, plus the [Events] line and
+     * the Format line following. It shouldn't include any Dialogue line.
+     * - encoding: Set/allocated/freed by user (before avcodec_open2())
+     * - decoding: Set/allocated/freed by libavcodec (by avcodec_open2())
+     */
+    uint8_t *subtitle_header;
+    int subtitle_header_size;
+
+    /**
+     * Simulates errors in the bitstream to test error concealment.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int error_rate;
+
+    /**
+     * Current packet as passed into the decoder, to avoid having
+     * to pass the packet into every function. Currently only valid
+     * inside lavc and get/release_buffer callbacks.
+     * - decoding: set by avcodec_decode_*, read by get_buffer() for setting pkt_pts
+     * - encoding: unused
+     */
+    AVPacket *pkt;
+
+    /**
+     * VBV delay coded in the last frame (in periods of a 27 MHz clock).
+     * Used for compliant TS muxing.
+     * - encoding: Set by libavcodec.
+     * - decoding: unused.
+     */
+    uint64_t vbv_delay;
+
+    /**
+     * Timebase in which pkt_dts/pts and AVPacket.dts/pts are.
+     * Code outside libavcodec should access this field using:
+     * av_codec_{get,set}_pkt_timebase(avctx)
+     * - encoding unused.
+     * - decodimg set by user
+     */
+    AVRational pkt_timebase;
+
+    /**
+     * AVCodecDescriptor
+     * Code outside libavcodec should access this field using:
+     * av_codec_{get,set}_codec_descriptor(avctx)
+     * - encoding: unused.
+     * - decoding: set by libavcodec.
+     */
+    const AVCodecDescriptor *codec_descriptor;
+
+#if !FF_API_LOWRES
+    /**
+     * low resolution decoding, 1-> 1/2 size, 2->1/4 size
+     * - encoding: unused
+     * - decoding: Set by user.
+     * Code outside libavcodec should access this field using:
+     * av_codec_{get,set}_lowres(avctx)
+     */
+     int lowres;
+#endif
+
+    /**
+     * Current statistics for PTS correction.
+     * - decoding: maintained and used by libavcodec, not intended to be used by user apps
+     * - encoding: unused
+     */
+    int64_t pts_correction_num_faulty_pts; /// Number of incorrect PTS values so far
+    int64_t pts_correction_num_faulty_dts; /// Number of incorrect DTS values so far
+    int64_t pts_correction_last_pts;       /// PTS of the last frame
+    int64_t pts_correction_last_dts;       /// DTS of the last frame
+
+    /**
+     * Character encoding of the input subtitles file.
+     * - decoding: set by user
+     * - encoding: unused
+     */
+    char *sub_charenc;
+
+    /**
+     * Subtitles character encoding mode. Formats or codecs might be adjusting
+     * this setting (if they are doing the conversion themselves for instance).
+     * - decoding: set by libavcodec
+     * - encoding: unused
+     */
+    int sub_charenc_mode;
+#define FF_SUB_CHARENC_MODE_DO_NOTHING  -1  ///< do nothing (demuxer outputs a stream supposed to be already in UTF-8, or the codec is bitmap for instance)
+#define FF_SUB_CHARENC_MODE_AUTOMATIC    0  ///< libavcodec will select the mode itself
+#define FF_SUB_CHARENC_MODE_PRE_DECODER  1  ///< the AVPacket data needs to be recoded to UTF-8 before being fed to the decoder, requires iconv
+
+} AVCodecContext;
+
+AVRational av_codec_get_pkt_timebase         (const AVCodecContext *avctx);
+void       av_codec_set_pkt_timebase         (AVCodecContext *avctx, AVRational val);
+
+const AVCodecDescriptor *av_codec_get_codec_descriptor(const AVCodecContext *avctx);
+void                     av_codec_set_codec_descriptor(AVCodecContext *avctx, const AVCodecDescriptor *desc);
+
+int  av_codec_get_lowres(const AVCodecContext *avctx);
+void av_codec_set_lowres(AVCodecContext *avctx, int val);
+
+/**
+ * AVProfile.
+ */
+typedef struct AVProfile {
+    int profile;
+    const char *name; ///< short name for the profile
+} AVProfile;
+
+typedef struct AVCodecDefault AVCodecDefault;
+
+struct AVSubtitle;
+
+/**
+ * AVCodec.
+ */
+typedef struct AVCodec {
+    /**
+     * Name of the codec implementation.
+     * The name is globally unique among encoders and among decoders (but an
+     * encoder and a decoder can share the same name).
+     * This is the primary way to find a codec from the user perspective.
+     */
+    const char *name;
+    /**
+     * Descriptive name for the codec, meant to be more human readable than name.
+     * You should use the NULL_IF_CONFIG_SMALL() macro to define it.
+     */
+    const char *long_name;
+    enum AVMediaType type;
+    enum AVCodecID id;
+    /**
+     * Codec capabilities.
+     * see CODEC_CAP_*
+     */
+    int capabilities;
+    const AVRational *supported_framerates; ///< array of supported framerates, or NULL if any, array is terminated by {0,0}
+    const enum AVPixelFormat *pix_fmts;     ///< array of supported pixel formats, or NULL if unknown, array is terminated by -1
+    const int *supported_samplerates;       ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0
+    const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1
+    const uint64_t *channel_layouts;         ///< array of support channel layouts, or NULL if unknown. array is terminated by 0
+    uint8_t max_lowres;                     ///< maximum value for lowres supported by the decoder
+    const AVClass *priv_class;              ///< AVClass for the private context
+    const AVProfile *profiles;              ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN}
+
+    /*****************************************************************
+     * No fields below this line are part of the public API. They
+     * may not be used outside of libavcodec and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+    int priv_data_size;
+    struct AVCodec *next;
+    /**
+     * @name Frame-level threading support functions
+     * @{
+     */
+    /**
+     * If defined, called on thread contexts when they are created.
+     * If the codec allocates writable tables in init(), re-allocate them here.
+     * priv_data will be set to a copy of the original.
+     */
+    int (*init_thread_copy)(AVCodecContext *);
+    /**
+     * Copy necessary context variables from a previous thread context to the current one.
+     * If not defined, the next thread will start automatically; otherwise, the codec
+     * must call ff_thread_finish_setup().
+     *
+     * dst and src will (rarely) point to the same context, in which case memcpy should be skipped.
+     */
+    int (*update_thread_context)(AVCodecContext *dst, const AVCodecContext *src);
+    /** @} */
+
+    /**
+     * Private codec-specific defaults.
+     */
+    const AVCodecDefault *defaults;
+
+    /**
+     * Initialize codec static data, called from avcodec_register().
+     */
+    void (*init_static_data)(struct AVCodec *codec);
+
+    int (*init)(AVCodecContext *);
+    int (*encode_sub)(AVCodecContext *, uint8_t *buf, int buf_size,
+                      const struct AVSubtitle *sub);
+    /**
+     * Encode data to an AVPacket.
+     *
+     * @param      avctx          codec context
+     * @param      avpkt          output AVPacket (may contain a user-provided buffer)
+     * @param[in]  frame          AVFrame containing the raw data to be encoded
+     * @param[out] got_packet_ptr encoder sets to 0 or 1 to indicate that a
+     *                            non-empty packet was returned in avpkt.
+     * @return 0 on success, negative error code on failure
+     */
+    int (*encode2)(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame,
+                   int *got_packet_ptr);
+    int (*decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt);
+    int (*close)(AVCodecContext *);
+    /**
+     * Flush buffers.
+     * Will be called when seeking
+     */
+    void (*flush)(AVCodecContext *);
+} AVCodec;
+
+/**
+ * AVHWAccel.
+ */
+typedef struct AVHWAccel {
+    /**
+     * Name of the hardware accelerated codec.
+     * The name is globally unique among encoders and among decoders (but an
+     * encoder and a decoder can share the same name).
+     */
+    const char *name;
+
+    /**
+     * Type of codec implemented by the hardware accelerator.
+     *
+     * See AVMEDIA_TYPE_xxx
+     */
+    enum AVMediaType type;
+
+    /**
+     * Codec implemented by the hardware accelerator.
+     *
+     * See AV_CODEC_ID_xxx
+     */
+    enum AVCodecID id;
+
+    /**
+     * Supported pixel format.
+     *
+     * Only hardware accelerated formats are supported here.
+     */
+    enum AVPixelFormat pix_fmt;
+
+    /**
+     * Hardware accelerated codec capabilities.
+     * see FF_HWACCEL_CODEC_CAP_*
+     */
+    int capabilities;
+
+    struct AVHWAccel *next;
+
+    /**
+     * Called at the beginning of each frame or field picture.
+     *
+     * Meaningful frame information (codec specific) is guaranteed to
+     * be parsed at this point. This function is mandatory.
+     *
+     * Note that buf can be NULL along with buf_size set to 0.
+     * Otherwise, this means the whole frame is available at this point.
+     *
+     * @param avctx the codec context
+     * @param buf the frame data buffer base
+     * @param buf_size the size of the frame in bytes
+     * @return zero if successful, a negative value otherwise
+     */
+    int (*start_frame)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size);
+
+    /**
+     * Callback for each slice.
+     *
+     * Meaningful slice information (codec specific) is guaranteed to
+     * be parsed at this point. This function is mandatory.
+     *
+     * @param avctx the codec context
+     * @param buf the slice data buffer base
+     * @param buf_size the size of the slice in bytes
+     * @return zero if successful, a negative value otherwise
+     */
+    int (*decode_slice)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size);
+
+    /**
+     * Called at the end of each frame or field picture.
+     *
+     * The whole picture is parsed at this point and can now be sent
+     * to the hardware accelerator. This function is mandatory.
+     *
+     * @param avctx the codec context
+     * @return zero if successful, a negative value otherwise
+     */
+    int (*end_frame)(AVCodecContext *avctx);
+
+    /**
+     * Size of HW accelerator private data.
+     *
+     * Private data is allocated with av_mallocz() before
+     * AVCodecContext.get_buffer() and deallocated after
+     * AVCodecContext.release_buffer().
+     */
+    int priv_data_size;
+} AVHWAccel;
+
+/**
+ * @defgroup lavc_picture AVPicture
+ *
+ * Functions for working with AVPicture
+ * @{
+ */
+
+/**
+ * four components are given, that's all.
+ * the last component is alpha
+ */
+typedef struct AVPicture {
+    uint8_t *data[AV_NUM_DATA_POINTERS];
+    int linesize[AV_NUM_DATA_POINTERS];     ///< number of bytes per line
+} AVPicture;
+
+/**
+ * @}
+ */
+
+enum AVSubtitleType {
+    SUBTITLE_NONE,
+
+    SUBTITLE_BITMAP,                ///< A bitmap, pict will be set
+
+    /**
+     * Plain text, the text field must be set by the decoder and is
+     * authoritative. ass and pict fields may contain approximations.
+     */
+    SUBTITLE_TEXT,
+
+    /**
+     * Formatted text, the ass field must be set by the decoder and is
+     * authoritative. pict and text fields may contain approximations.
+     */
+    SUBTITLE_ASS,
+};
+
+#define AV_SUBTITLE_FLAG_FORCED 0x00000001
+
+typedef struct AVSubtitleRect {
+    int x;         ///< top left corner  of pict, undefined when pict is not set
+    int y;         ///< top left corner  of pict, undefined when pict is not set
+    int w;         ///< width            of pict, undefined when pict is not set
+    int h;         ///< height           of pict, undefined when pict is not set
+    int nb_colors; ///< number of colors in pict, undefined when pict is not set
+
+    /**
+     * data+linesize for the bitmap of this subtitle.
+     * can be set for text/ass as well once they where rendered
+     */
+    AVPicture pict;
+    enum AVSubtitleType type;
+
+    char *text;                     ///< 0 terminated plain UTF-8 text
+
+    /**
+     * 0 terminated ASS/SSA compatible event line.
+     * The presentation of this is unaffected by the other values in this
+     * struct.
+     */
+    char *ass;
+
+    int flags;
+} AVSubtitleRect;
+
+typedef struct AVSubtitle {
+    uint16_t format; /* 0 = graphics */
+    uint32_t start_display_time; /* relative to packet pts, in ms */
+    uint32_t end_display_time; /* relative to packet pts, in ms */
+    unsigned num_rects;
+    AVSubtitleRect **rects;
+    int64_t pts;    ///< Same as packet pts, in AV_TIME_BASE
+} AVSubtitle;
+
+/**
+ * If c is NULL, returns the first registered codec,
+ * if c is non-NULL, returns the next registered codec after c,
+ * or NULL if c is the last one.
+ */
+AVCodec *av_codec_next(const AVCodec *c);
+
+/**
+ * Return the LIBAVCODEC_VERSION_INT constant.
+ */
+unsigned avcodec_version(void);
+
+/**
+ * Return the libavcodec build-time configuration.
+ */
+const char *avcodec_configuration(void);
+
+/**
+ * Return the libavcodec license.
+ */
+const char *avcodec_license(void);
+
+/**
+ * Register the codec codec and initialize libavcodec.
+ *
+ * @warning either this function or avcodec_register_all() must be called
+ * before any other libavcodec functions.
+ *
+ * @see avcodec_register_all()
+ */
+void avcodec_register(AVCodec *codec);
+
+/**
+ * Register all the codecs, parsers and bitstream filters which were enabled at
+ * configuration time. If you do not call this function you can select exactly
+ * which formats you want to support, by using the individual registration
+ * functions.
+ *
+ * @see avcodec_register
+ * @see av_register_codec_parser
+ * @see av_register_bitstream_filter
+ */
+void avcodec_register_all(void);
+
+
+#if FF_API_ALLOC_CONTEXT
+/**
+ * Allocate an AVCodecContext and set its fields to default values.  The
+ * resulting struct can be deallocated by simply calling av_free().
+ *
+ * @return An AVCodecContext filled with default values or NULL on failure.
+ * @see avcodec_get_context_defaults
+ *
+ * @deprecated use avcodec_alloc_context3()
+ */
+attribute_deprecated
+AVCodecContext *avcodec_alloc_context(void);
+
+/** THIS FUNCTION IS NOT YET PART OF THE PUBLIC API!
+ *  we WILL change its arguments and name a few times! */
+attribute_deprecated
+AVCodecContext *avcodec_alloc_context2(enum AVMediaType);
+
+/**
+ * Set the fields of the given AVCodecContext to default values.
+ *
+ * @param s The AVCodecContext of which the fields should be set to default values.
+ * @deprecated use avcodec_get_context_defaults3
+ */
+attribute_deprecated
+void avcodec_get_context_defaults(AVCodecContext *s);
+
+/** THIS FUNCTION IS NOT YET PART OF THE PUBLIC API!
+ *  we WILL change its arguments and name a few times! */
+attribute_deprecated
+void avcodec_get_context_defaults2(AVCodecContext *s, enum AVMediaType);
+#endif
+
+/**
+ * Allocate an AVCodecContext and set its fields to default values.  The
+ * resulting struct can be deallocated by calling avcodec_close() on it followed
+ * by av_free().
+ *
+ * @param codec if non-NULL, allocate private data and initialize defaults
+ *              for the given codec. It is illegal to then call avcodec_open2()
+ *              with a different codec.
+ *              If NULL, then the codec-specific defaults won't be initialized,
+ *              which may result in suboptimal default settings (this is
+ *              important mainly for encoders, e.g. libx264).
+ *
+ * @return An AVCodecContext filled with default values or NULL on failure.
+ * @see avcodec_get_context_defaults
+ */
+AVCodecContext *avcodec_alloc_context3(const AVCodec *codec);
+
+/**
+ * Set the fields of the given AVCodecContext to default values corresponding
+ * to the given codec (defaults may be codec-dependent).
+ *
+ * Do not call this function if a non-NULL codec has been passed
+ * to avcodec_alloc_context3() that allocated this AVCodecContext.
+ * If codec is non-NULL, it is illegal to call avcodec_open2() with a
+ * different codec on this AVCodecContext.
+ */
+int avcodec_get_context_defaults3(AVCodecContext *s, const AVCodec *codec);
+
+/**
+ * Get the AVClass for AVCodecContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avcodec_get_class(void);
+
+/**
+ * Get the AVClass for AVFrame. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avcodec_get_frame_class(void);
+
+/**
+ * Get the AVClass for AVSubtitleRect. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avcodec_get_subtitle_rect_class(void);
+
+/**
+ * Copy the settings of the source AVCodecContext into the destination
+ * AVCodecContext. The resulting destination codec context will be
+ * unopened, i.e. you are required to call avcodec_open2() before you
+ * can use this AVCodecContext to decode/encode video/audio data.
+ *
+ * @param dest target codec context, should be initialized with
+ *             avcodec_alloc_context3(), but otherwise uninitialized
+ * @param src source codec context
+ * @return AVERROR() on error (e.g. memory allocation error), 0 on success
+ */
+int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src);
+
+/**
+ * Allocate an AVFrame and set its fields to default values.  The resulting
+ * struct must be freed using avcodec_free_frame().
+ *
+ * @return An AVFrame filled with default values or NULL on failure.
+ * @see avcodec_get_frame_defaults
+ */
+AVFrame *avcodec_alloc_frame(void);
+
+/**
+ * Set the fields of the given AVFrame to default values.
+ *
+ * @param frame The AVFrame of which the fields should be set to default values.
+ */
+void avcodec_get_frame_defaults(AVFrame *frame);
+
+/**
+ * Free the frame and any dynamically allocated objects in it,
+ * e.g. extended_data.
+ *
+ * @param frame frame to be freed. The pointer will be set to NULL.
+ *
+ * @warning this function does NOT free the data buffers themselves
+ * (it does not know how, since they might have been allocated with
+ *  a custom get_buffer()).
+ */
+void avcodec_free_frame(AVFrame **frame);
+
+#if FF_API_AVCODEC_OPEN
+/**
+ * Initialize the AVCodecContext to use the given AVCodec. Prior to using this
+ * function the context has to be allocated.
+ *
+ * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(),
+ * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for
+ * retrieving a codec.
+ *
+ * @warning This function is not thread safe!
+ *
+ * @code
+ * avcodec_register_all();
+ * codec = avcodec_find_decoder(AV_CODEC_ID_H264);
+ * if (!codec)
+ *     exit(1);
+ *
+ * context = avcodec_alloc_context3(codec);
+ *
+ * if (avcodec_open(context, codec) < 0)
+ *     exit(1);
+ * @endcode
+ *
+ * @param avctx The context which will be set up to use the given codec.
+ * @param codec The codec to use within the context.
+ * @return zero on success, a negative value on error
+ * @see avcodec_alloc_context3, avcodec_find_decoder, avcodec_find_encoder, avcodec_close
+ *
+ * @deprecated use avcodec_open2
+ */
+attribute_deprecated
+int avcodec_open(AVCodecContext *avctx, AVCodec *codec);
+#endif
+
+/**
+ * Initialize the AVCodecContext to use the given AVCodec. Prior to using this
+ * function the context has to be allocated with avcodec_alloc_context3().
+ *
+ * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(),
+ * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for
+ * retrieving a codec.
+ *
+ * @warning This function is not thread safe!
+ *
+ * @code
+ * avcodec_register_all();
+ * av_dict_set(&opts, "b", "2.5M", 0);
+ * codec = avcodec_find_decoder(AV_CODEC_ID_H264);
+ * if (!codec)
+ *     exit(1);
+ *
+ * context = avcodec_alloc_context3(codec);
+ *
+ * if (avcodec_open2(context, codec, opts) < 0)
+ *     exit(1);
+ * @endcode
+ *
+ * @param avctx The context to initialize.
+ * @param codec The codec to open this context for. If a non-NULL codec has been
+ *              previously passed to avcodec_alloc_context3() or
+ *              avcodec_get_context_defaults3() for this context, then this
+ *              parameter MUST be either NULL or equal to the previously passed
+ *              codec.
+ * @param options A dictionary filled with AVCodecContext and codec-private options.
+ *                On return this object will be filled with options that were not found.
+ *
+ * @return zero on success, a negative value on error
+ * @see avcodec_alloc_context3(), avcodec_find_decoder(), avcodec_find_encoder(),
+ *      av_dict_set(), av_opt_find().
+ */
+int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options);
+
+/**
+ * Close a given AVCodecContext and free all the data associated with it
+ * (but not the AVCodecContext itself).
+ *
+ * Calling this function on an AVCodecContext that hasn't been opened will free
+ * the codec-specific data allocated in avcodec_alloc_context3() /
+ * avcodec_get_context_defaults3() with a non-NULL codec. Subsequent calls will
+ * do nothing.
+ */
+int avcodec_close(AVCodecContext *avctx);
+
+/**
+ * Free all allocated data in the given subtitle struct.
+ *
+ * @param sub AVSubtitle to free.
+ */
+void avsubtitle_free(AVSubtitle *sub);
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavc_packet
+ * @{
+ */
+
+#if FF_API_DESTRUCT_PACKET
+/**
+ * Default packet destructor.
+ * @deprecated use the AVBuffer API instead
+ */
+attribute_deprecated
+void av_destruct_packet(AVPacket *pkt);
+#endif
+
+/**
+ * Initialize optional fields of a packet with default values.
+ *
+ * Note, this does not touch the data and size members, which have to be
+ * initialized separately.
+ *
+ * @param pkt packet
+ */
+void av_init_packet(AVPacket *pkt);
+
+/**
+ * Allocate the payload of a packet and initialize its fields with
+ * default values.
+ *
+ * @param pkt packet
+ * @param size wanted payload size
+ * @return 0 if OK, AVERROR_xxx otherwise
+ */
+int av_new_packet(AVPacket *pkt, int size);
+
+/**
+ * Reduce packet size, correctly zeroing padding
+ *
+ * @param pkt packet
+ * @param size new size
+ */
+void av_shrink_packet(AVPacket *pkt, int size);
+
+/**
+ * Increase packet size, correctly zeroing padding
+ *
+ * @param pkt packet
+ * @param grow_by number of bytes by which to increase the size of the packet
+ */
+int av_grow_packet(AVPacket *pkt, int grow_by);
+
+/**
+ * Initialize a reference-counted packet from av_malloc()ed data.
+ *
+ * @param pkt packet to be initialized. This function will set the data, size,
+ *        buf and destruct fields, all others are left untouched.
+ * @param data Data allocated by av_malloc() to be used as packet data. If this
+ *        function returns successfully, the data is owned by the underlying AVBuffer.
+ *        The caller may not access the data through other means.
+ * @param size size of data in bytes, without the padding. I.e. the full buffer
+ *        size is assumed to be size + FF_INPUT_BUFFER_PADDING_SIZE.
+ *
+ * @return 0 on success, a negative AVERROR on error
+ */
+int av_packet_from_data(AVPacket *pkt, uint8_t *data, int size);
+
+/**
+ * @warning This is a hack - the packet memory allocation stuff is broken. The
+ * packet is allocated if it was not really allocated.
+ */
+int av_dup_packet(AVPacket *pkt);
+
+/**
+ * Copy packet, including contents
+ *
+ * @return 0 on success, negative AVERROR on fail
+ */
+int av_copy_packet(AVPacket *dst, AVPacket *src);
+
+/**
+ * Copy packet side data
+ *
+ * @return 0 on success, negative AVERROR on fail
+ */
+int av_copy_packet_side_data(AVPacket *dst, AVPacket *src);
+
+/**
+ * Free a packet.
+ *
+ * @param pkt packet to free
+ */
+void av_free_packet(AVPacket *pkt);
+
+/**
+ * Allocate new information of a packet.
+ *
+ * @param pkt packet
+ * @param type side information type
+ * @param size side information size
+ * @return pointer to fresh allocated data or NULL otherwise
+ */
+uint8_t* av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int size);
+
+/**
+ * Shrink the already allocated side data buffer
+ *
+ * @param pkt packet
+ * @param type side information type
+ * @param size new side information size
+ * @return 0 on success, < 0 on failure
+ */
+int av_packet_shrink_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                               int size);
+
+/**
+ * Get side information from packet.
+ *
+ * @param pkt packet
+ * @param type desired side information type
+ * @param size pointer for side information size to store (optional)
+ * @return pointer to data if present or NULL otherwise
+ */
+uint8_t* av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int *size);
+
+int av_packet_merge_side_data(AVPacket *pkt);
+
+int av_packet_split_side_data(AVPacket *pkt);
+
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavc_decoding
+ * @{
+ */
+
+/**
+ * Find a registered decoder with a matching codec ID.
+ *
+ * @param id AVCodecID of the requested decoder
+ * @return A decoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_decoder(enum AVCodecID id);
+
+/**
+ * Find a registered decoder with the specified name.
+ *
+ * @param name name of the requested decoder
+ * @return A decoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_decoder_by_name(const char *name);
+
+#if FF_API_GET_BUFFER
+attribute_deprecated int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic);
+attribute_deprecated void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic);
+attribute_deprecated int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic);
+#endif
+
+/**
+ * The default callback for AVCodecContext.get_buffer2(). It is made public so
+ * it can be called by custom get_buffer2() implementations for decoders without
+ * CODEC_CAP_DR1 set.
+ */
+int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags);
+
+/**
+ * Return the amount of padding in pixels which the get_buffer callback must
+ * provide around the edge of the image for codecs which do not have the
+ * CODEC_FLAG_EMU_EDGE flag.
+ *
+ * @return Required padding in pixels.
+ */
+unsigned avcodec_get_edge_width(void);
+
+/**
+ * Modify width and height values so that they will result in a memory
+ * buffer that is acceptable for the codec if you do not use any horizontal
+ * padding.
+ *
+ * May only be used if a codec with CODEC_CAP_DR1 has been opened.
+ * If CODEC_FLAG_EMU_EDGE is not set, the dimensions must have been increased
+ * according to avcodec_get_edge_width() before.
+ */
+void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height);
+
+/**
+ * Modify width and height values so that they will result in a memory
+ * buffer that is acceptable for the codec if you also ensure that all
+ * line sizes are a multiple of the respective linesize_align[i].
+ *
+ * May only be used if a codec with CODEC_CAP_DR1 has been opened.
+ * If CODEC_FLAG_EMU_EDGE is not set, the dimensions must have been increased
+ * according to avcodec_get_edge_width() before.
+ */
+void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
+                               int linesize_align[AV_NUM_DATA_POINTERS]);
+
+#if FF_API_OLD_DECODE_AUDIO
+/**
+ * Wrapper function which calls avcodec_decode_audio4.
+ *
+ * @deprecated Use avcodec_decode_audio4 instead.
+ *
+ * Decode the audio frame of size avpkt->size from avpkt->data into samples.
+ * Some decoders may support multiple frames in a single AVPacket, such
+ * decoders would then just decode the first frame. In this case,
+ * avcodec_decode_audio3 has to be called again with an AVPacket that contains
+ * the remaining data in order to decode the second frame etc.
+ * If no frame
+ * could be outputted, frame_size_ptr is zero. Otherwise, it is the
+ * decompressed frame size in bytes.
+ *
+ * @warning You must set frame_size_ptr to the allocated size of the
+ * output buffer before calling avcodec_decode_audio3().
+ *
+ * @warning The input buffer must be FF_INPUT_BUFFER_PADDING_SIZE larger than
+ * the actual read bytes because some optimized bitstream readers read 32 or 64
+ * bits at once and could read over the end.
+ *
+ * @warning The end of the input buffer avpkt->data should be set to 0 to ensure that
+ * no overreading happens for damaged MPEG streams.
+ *
+ * @warning You must not provide a custom get_buffer() when using
+ * avcodec_decode_audio3().  Doing so will override it with
+ * avcodec_default_get_buffer.  Use avcodec_decode_audio4() instead,
+ * which does allow the application to provide a custom get_buffer().
+ *
+ * @note You might have to align the input buffer avpkt->data and output buffer
+ * samples. The alignment requirements depend on the CPU: On some CPUs it isn't
+ * necessary at all, on others it won't work at all if not aligned and on others
+ * it will work but it will have an impact on performance.
+ *
+ * In practice, avpkt->data should have 4 byte alignment at minimum and
+ * samples should be 16 byte aligned unless the CPU doesn't need it
+ * (AltiVec and SSE do).
+ *
+ * @note Codecs which have the CODEC_CAP_DELAY capability set have a delay
+ * between input and output, these need to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to return the remaining frames.
+ *
+ * @param avctx the codec context
+ * @param[out] samples the output buffer, sample type in avctx->sample_fmt
+ *                     If the sample format is planar, each channel plane will
+ *                     be the same size, with no padding between channels.
+ * @param[in,out] frame_size_ptr the output buffer size in bytes
+ * @param[in] avpkt The input AVPacket containing the input buffer.
+ *            You can create such packet with av_init_packet() and by then setting
+ *            data and size, some decoders might in addition need other fields.
+ *            All decoders are designed to use the least fields possible though.
+ * @return On error a negative value is returned, otherwise the number of bytes
+ * used or zero if no frame data was decompressed (used) from the input AVPacket.
+ */
+attribute_deprecated int avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
+                         int *frame_size_ptr,
+                         AVPacket *avpkt);
+#endif
+
+/**
+ * Decode the audio frame of size avpkt->size from avpkt->data into frame.
+ *
+ * Some decoders may support multiple frames in a single AVPacket. Such
+ * decoders would then just decode the first frame. In this case,
+ * avcodec_decode_audio4 has to be called again with an AVPacket containing
+ * the remaining data in order to decode the second frame, etc...
+ * Even if no frames are returned, the packet needs to be fed to the decoder
+ * with remaining data until it is completely consumed or an error occurs.
+ *
+ * @warning The input buffer, avpkt->data must be FF_INPUT_BUFFER_PADDING_SIZE
+ *          larger than the actual read bytes because some optimized bitstream
+ *          readers read 32 or 64 bits at once and could read over the end.
+ *
+ * @note You might have to align the input buffer. The alignment requirements
+ *       depend on the CPU and the decoder.
+ *
+ * @param      avctx the codec context
+ * @param[out] frame The AVFrame in which to store decoded audio samples.
+ *                   The decoder will allocate a buffer for the decoded frame by
+ *                   calling the AVCodecContext.get_buffer2() callback.
+ *                   When AVCodecContext.refcounted_frames is set to 1, the frame is
+ *                   reference counted and the returned reference belongs to the
+ *                   caller. The caller must release the frame using av_frame_unref()
+ *                   when the frame is no longer needed. The caller may safely write
+ *                   to the frame if av_frame_is_writable() returns 1.
+ *                   When AVCodecContext.refcounted_frames is set to 0, the returned
+ *                   reference belongs to the decoder and is valid only until the
+ *                   next call to this function or until closing the decoder.
+ *                   The caller may not write to it.
+ * @param[out] got_frame_ptr Zero if no frame could be decoded, otherwise it is
+ *                           non-zero.
+ * @param[in]  avpkt The input AVPacket containing the input buffer.
+ *                   At least avpkt->data and avpkt->size should be set. Some
+ *                   decoders might also require additional fields to be set.
+ * @return A negative error code is returned if an error occurred during
+ *         decoding, otherwise the number of bytes consumed from the input
+ *         AVPacket is returned.
+ */
+int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame,
+                          int *got_frame_ptr, const AVPacket *avpkt);
+
+/**
+ * Decode the video frame of size avpkt->size from avpkt->data into picture.
+ * Some decoders may support multiple frames in a single AVPacket, such
+ * decoders would then just decode the first frame.
+ *
+ * @warning The input buffer must be FF_INPUT_BUFFER_PADDING_SIZE larger than
+ * the actual read bytes because some optimized bitstream readers read 32 or 64
+ * bits at once and could read over the end.
+ *
+ * @warning The end of the input buffer buf should be set to 0 to ensure that
+ * no overreading happens for damaged MPEG streams.
+ *
+ * @note You might have to align the input buffer avpkt->data.
+ * The alignment requirements depend on the CPU: on some CPUs it isn't
+ * necessary at all, on others it won't work at all if not aligned and on others
+ * it will work but it will have an impact on performance.
+ *
+ * In practice, avpkt->data should have 4 byte alignment at minimum.
+ *
+ * @note Codecs which have the CODEC_CAP_DELAY capability set have a delay
+ * between input and output, these need to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to return the remaining frames.
+ *
+ * @param avctx the codec context
+ * @param[out] picture The AVFrame in which the decoded video frame will be stored.
+ *             Use av_frame_alloc() to get an AVFrame. The codec will
+ *             allocate memory for the actual bitmap by calling the
+ *             AVCodecContext.get_buffer2() callback.
+ *             When AVCodecContext.refcounted_frames is set to 1, the frame is
+ *             reference counted and the returned reference belongs to the
+ *             caller. The caller must release the frame using av_frame_unref()
+ *             when the frame is no longer needed. The caller may safely write
+ *             to the frame if av_frame_is_writable() returns 1.
+ *             When AVCodecContext.refcounted_frames is set to 0, the returned
+ *             reference belongs to the decoder and is valid only until the
+ *             next call to this function or until closing the decoder. The
+ *             caller may not write to it.
+ *
+ * @param[in] avpkt The input AVpacket containing the input buffer.
+ *            You can create such packet with av_init_packet() and by then setting
+ *            data and size, some decoders might in addition need other fields like
+ *            flags&AV_PKT_FLAG_KEY. All decoders are designed to use the least
+ *            fields possible.
+ * @param[in,out] got_picture_ptr Zero if no frame could be decompressed, otherwise, it is nonzero.
+ * @return On error a negative value is returned, otherwise the number of bytes
+ * used or zero if no frame could be decompressed.
+ */
+int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
+                         int *got_picture_ptr,
+                         const AVPacket *avpkt);
+
+/**
+ * Decode a subtitle message.
+ * Return a negative value on error, otherwise return the number of bytes used.
+ * If no subtitle could be decompressed, got_sub_ptr is zero.
+ * Otherwise, the subtitle is stored in *sub.
+ * Note that CODEC_CAP_DR1 is not available for subtitle codecs. This is for
+ * simplicity, because the performance difference is expect to be negligible
+ * and reusing a get_buffer written for video codecs would probably perform badly
+ * due to a potentially very different allocation pattern.
+ *
+ * @param avctx the codec context
+ * @param[out] sub The AVSubtitle in which the decoded subtitle will be stored, must be
+                   freed with avsubtitle_free if *got_sub_ptr is set.
+ * @param[in,out] got_sub_ptr Zero if no subtitle could be decompressed, otherwise, it is nonzero.
+ * @param[in] avpkt The input AVPacket containing the input buffer.
+ */
+int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
+                            int *got_sub_ptr,
+                            AVPacket *avpkt);
+
+/**
+ * @defgroup lavc_parsing Frame parsing
+ * @{
+ */
+
+typedef struct AVCodecParserContext {
+    void *priv_data;
+    struct AVCodecParser *parser;
+    int64_t frame_offset; /* offset of the current frame */
+    int64_t cur_offset; /* current offset
+                           (incremented by each av_parser_parse()) */
+    int64_t next_frame_offset; /* offset of the next frame */
+    /* video info */
+    int pict_type; /* XXX: Put it back in AVCodecContext. */
+    /**
+     * This field is used for proper frame duration computation in lavf.
+     * It signals, how much longer the frame duration of the current frame
+     * is compared to normal frame duration.
+     *
+     * frame_duration = (1 + repeat_pict) * time_base
+     *
+     * It is used by codecs like H.264 to display telecined material.
+     */
+    int repeat_pict; /* XXX: Put it back in AVCodecContext. */
+    int64_t pts;     /* pts of the current frame */
+    int64_t dts;     /* dts of the current frame */
+
+    /* private data */
+    int64_t last_pts;
+    int64_t last_dts;
+    int fetch_timestamp;
+
+#define AV_PARSER_PTS_NB 4
+    int cur_frame_start_index;
+    int64_t cur_frame_offset[AV_PARSER_PTS_NB];
+    int64_t cur_frame_pts[AV_PARSER_PTS_NB];
+    int64_t cur_frame_dts[AV_PARSER_PTS_NB];
+
+    int flags;
+#define PARSER_FLAG_COMPLETE_FRAMES           0x0001
+#define PARSER_FLAG_ONCE                      0x0002
+/// Set if the parser has a valid file offset
+#define PARSER_FLAG_FETCHED_OFFSET            0x0004
+#define PARSER_FLAG_USE_CODEC_TS              0x1000
+
+    int64_t offset;      ///< byte offset from starting packet start
+    int64_t cur_frame_end[AV_PARSER_PTS_NB];
+
+    /**
+     * Set by parser to 1 for key frames and 0 for non-key frames.
+     * It is initialized to -1, so if the parser doesn't set this flag,
+     * old-style fallback using AV_PICTURE_TYPE_I picture type as key frames
+     * will be used.
+     */
+    int key_frame;
+
+    /**
+     * Time difference in stream time base units from the pts of this
+     * packet to the point at which the output from the decoder has converged
+     * independent from the availability of previous frames. That is, the
+     * frames are virtually identical no matter if decoding started from
+     * the very first frame or from this keyframe.
+     * Is AV_NOPTS_VALUE if unknown.
+     * This field is not the display duration of the current frame.
+     * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY
+     * set.
+     *
+     * The purpose of this field is to allow seeking in streams that have no
+     * keyframes in the conventional sense. It corresponds to the
+     * recovery point SEI in H.264 and match_time_delta in NUT. It is also
+     * essential for some types of subtitle streams to ensure that all
+     * subtitles are correctly displayed after seeking.
+     */
+    int64_t convergence_duration;
+
+    // Timestamp generation support:
+    /**
+     * Synchronization point for start of timestamp generation.
+     *
+     * Set to >0 for sync point, 0 for no sync point and <0 for undefined
+     * (default).
+     *
+     * For example, this corresponds to presence of H.264 buffering period
+     * SEI message.
+     */
+    int dts_sync_point;
+
+    /**
+     * Offset of the current timestamp against last timestamp sync point in
+     * units of AVCodecContext.time_base.
+     *
+     * Set to INT_MIN when dts_sync_point unused. Otherwise, it must
+     * contain a valid timestamp offset.
+     *
+     * Note that the timestamp of sync point has usually a nonzero
+     * dts_ref_dts_delta, which refers to the previous sync point. Offset of
+     * the next frame after timestamp sync point will be usually 1.
+     *
+     * For example, this corresponds to H.264 cpb_removal_delay.
+     */
+    int dts_ref_dts_delta;
+
+    /**
+     * Presentation delay of current frame in units of AVCodecContext.time_base.
+     *
+     * Set to INT_MIN when dts_sync_point unused. Otherwise, it must
+     * contain valid non-negative timestamp delta (presentation time of a frame
+     * must not lie in the past).
+     *
+     * This delay represents the difference between decoding and presentation
+     * time of the frame.
+     *
+     * For example, this corresponds to H.264 dpb_output_delay.
+     */
+    int pts_dts_delta;
+
+    /**
+     * Position of the packet in file.
+     *
+     * Analogous to cur_frame_pts/dts
+     */
+    int64_t cur_frame_pos[AV_PARSER_PTS_NB];
+
+    /**
+     * Byte position of currently parsed frame in stream.
+     */
+    int64_t pos;
+
+    /**
+     * Previous frame byte position.
+     */
+    int64_t last_pos;
+
+    /**
+     * Duration of the current frame.
+     * For audio, this is in units of 1 / AVCodecContext.sample_rate.
+     * For all other types, this is in units of AVCodecContext.time_base.
+     */
+    int duration;
+
+    enum AVFieldOrder field_order;
+} AVCodecParserContext;
+
+typedef struct AVCodecParser {
+    int codec_ids[5]; /* several codec IDs are permitted */
+    int priv_data_size;
+    int (*parser_init)(AVCodecParserContext *s);
+    int (*parser_parse)(AVCodecParserContext *s,
+                        AVCodecContext *avctx,
+                        const uint8_t **poutbuf, int *poutbuf_size,
+                        const uint8_t *buf, int buf_size);
+    void (*parser_close)(AVCodecParserContext *s);
+    int (*split)(AVCodecContext *avctx, const uint8_t *buf, int buf_size);
+    struct AVCodecParser *next;
+} AVCodecParser;
+
+AVCodecParser *av_parser_next(AVCodecParser *c);
+
+void av_register_codec_parser(AVCodecParser *parser);
+AVCodecParserContext *av_parser_init(int codec_id);
+
+/**
+ * Parse a packet.
+ *
+ * @param s             parser context.
+ * @param avctx         codec context.
+ * @param poutbuf       set to pointer to parsed buffer or NULL if not yet finished.
+ * @param poutbuf_size  set to size of parsed buffer or zero if not yet finished.
+ * @param buf           input buffer.
+ * @param buf_size      input length, to signal EOF, this should be 0 (so that the last frame can be output).
+ * @param pts           input presentation timestamp.
+ * @param dts           input decoding timestamp.
+ * @param pos           input byte position in stream.
+ * @return the number of bytes of the input bitstream used.
+ *
+ * Example:
+ * @code
+ *   while(in_len){
+ *       len = av_parser_parse2(myparser, AVCodecContext, &data, &size,
+ *                                        in_data, in_len,
+ *                                        pts, dts, pos);
+ *       in_data += len;
+ *       in_len  -= len;
+ *
+ *       if(size)
+ *          decode_frame(data, size);
+ *   }
+ * @endcode
+ */
+int av_parser_parse2(AVCodecParserContext *s,
+                     AVCodecContext *avctx,
+                     uint8_t **poutbuf, int *poutbuf_size,
+                     const uint8_t *buf, int buf_size,
+                     int64_t pts, int64_t dts,
+                     int64_t pos);
+
+/**
+ * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed
+ * @deprecated use AVBitStreamFilter
+ */
+int av_parser_change(AVCodecParserContext *s,
+                     AVCodecContext *avctx,
+                     uint8_t **poutbuf, int *poutbuf_size,
+                     const uint8_t *buf, int buf_size, int keyframe);
+void av_parser_close(AVCodecParserContext *s);
+
+/**
+ * @}
+ * @}
+ */
+
+/**
+ * @addtogroup lavc_encoding
+ * @{
+ */
+
+/**
+ * Find a registered encoder with a matching codec ID.
+ *
+ * @param id AVCodecID of the requested encoder
+ * @return An encoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_encoder(enum AVCodecID id);
+
+/**
+ * Find a registered encoder with the specified name.
+ *
+ * @param name name of the requested encoder
+ * @return An encoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_encoder_by_name(const char *name);
+
+#if FF_API_OLD_ENCODE_AUDIO
+/**
+ * Encode an audio frame from samples into buf.
+ *
+ * @deprecated Use avcodec_encode_audio2 instead.
+ *
+ * @note The output buffer should be at least FF_MIN_BUFFER_SIZE bytes large.
+ * However, for codecs with avctx->frame_size equal to 0 (e.g. PCM) the user
+ * will know how much space is needed because it depends on the value passed
+ * in buf_size as described below. In that case a lower value can be used.
+ *
+ * @param avctx the codec context
+ * @param[out] buf the output buffer
+ * @param[in] buf_size the output buffer size
+ * @param[in] samples the input buffer containing the samples
+ * The number of samples read from this buffer is frame_size*channels,
+ * both of which are defined in avctx.
+ * For codecs which have avctx->frame_size equal to 0 (e.g. PCM) the number of
+ * samples read from samples is equal to:
+ * buf_size * 8 / (avctx->channels * av_get_bits_per_sample(avctx->codec_id))
+ * This also implies that av_get_bits_per_sample() must not return 0 for these
+ * codecs.
+ * @return On error a negative value is returned, on success zero or the number
+ * of bytes used to encode the data read from the input buffer.
+ */
+int attribute_deprecated avcodec_encode_audio(AVCodecContext *avctx,
+                                              uint8_t *buf, int buf_size,
+                                              const short *samples);
+#endif
+
+/**
+ * Encode a frame of audio.
+ *
+ * Takes input samples from frame and writes the next output packet, if
+ * available, to avpkt. The output packet does not necessarily contain data for
+ * the most recent frame, as encoders can delay, split, and combine input frames
+ * internally as needed.
+ *
+ * @param avctx     codec context
+ * @param avpkt     output AVPacket.
+ *                  The user can supply an output buffer by setting
+ *                  avpkt->data and avpkt->size prior to calling the
+ *                  function, but if the size of the user-provided data is not
+ *                  large enough, encoding will fail. If avpkt->data and
+ *                  avpkt->size are set, avpkt->destruct must also be set. All
+ *                  other AVPacket fields will be reset by the encoder using
+ *                  av_init_packet(). If avpkt->data is NULL, the encoder will
+ *                  allocate it. The encoder will set avpkt->size to the size
+ *                  of the output packet.
+ *
+ *                  If this function fails or produces no output, avpkt will be
+ *                  freed using av_free_packet() (i.e. avpkt->destruct will be
+ *                  called to free the user supplied buffer).
+ * @param[in] frame AVFrame containing the raw audio data to be encoded.
+ *                  May be NULL when flushing an encoder that has the
+ *                  CODEC_CAP_DELAY capability set.
+ *                  If CODEC_CAP_VARIABLE_FRAME_SIZE is set, then each frame
+ *                  can have any number of samples.
+ *                  If it is not set, frame->nb_samples must be equal to
+ *                  avctx->frame_size for all frames except the last.
+ *                  The final frame may be smaller than avctx->frame_size.
+ * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the
+ *                            output packet is non-empty, and to 0 if it is
+ *                            empty. If the function returns an error, the
+ *                            packet can be assumed to be invalid, and the
+ *                            value of got_packet_ptr is undefined and should
+ *                            not be used.
+ * @return          0 on success, negative error code on failure
+ */
+int avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt,
+                          const AVFrame *frame, int *got_packet_ptr);
+
+#if FF_API_OLD_ENCODE_VIDEO
+/**
+ * @deprecated use avcodec_encode_video2() instead.
+ *
+ * Encode a video frame from pict into buf.
+ * The input picture should be
+ * stored using a specific format, namely avctx.pix_fmt.
+ *
+ * @param avctx the codec context
+ * @param[out] buf the output buffer for the bitstream of encoded frame
+ * @param[in] buf_size the size of the output buffer in bytes
+ * @param[in] pict the input picture to encode
+ * @return On error a negative value is returned, on success zero or the number
+ * of bytes used from the output buffer.
+ */
+attribute_deprecated
+int avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
+                         const AVFrame *pict);
+#endif
+
+/**
+ * Encode a frame of video.
+ *
+ * Takes input raw video data from frame and writes the next output packet, if
+ * available, to avpkt. The output packet does not necessarily contain data for
+ * the most recent frame, as encoders can delay and reorder input frames
+ * internally as needed.
+ *
+ * @param avctx     codec context
+ * @param avpkt     output AVPacket.
+ *                  The user can supply an output buffer by setting
+ *                  avpkt->data and avpkt->size prior to calling the
+ *                  function, but if the size of the user-provided data is not
+ *                  large enough, encoding will fail. All other AVPacket fields
+ *                  will be reset by the encoder using av_init_packet(). If
+ *                  avpkt->data is NULL, the encoder will allocate it.
+ *                  The encoder will set avpkt->size to the size of the
+ *                  output packet. The returned data (if any) belongs to the
+ *                  caller, he is responsible for freeing it.
+ *
+ *                  If this function fails or produces no output, avpkt will be
+ *                  freed using av_free_packet() (i.e. avpkt->destruct will be
+ *                  called to free the user supplied buffer).
+ * @param[in] frame AVFrame containing the raw video data to be encoded.
+ *                  May be NULL when flushing an encoder that has the
+ *                  CODEC_CAP_DELAY capability set.
+ * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the
+ *                            output packet is non-empty, and to 0 if it is
+ *                            empty. If the function returns an error, the
+ *                            packet can be assumed to be invalid, and the
+ *                            value of got_packet_ptr is undefined and should
+ *                            not be used.
+ * @return          0 on success, negative error code on failure
+ */
+int avcodec_encode_video2(AVCodecContext *avctx, AVPacket *avpkt,
+                          const AVFrame *frame, int *got_packet_ptr);
+
+int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
+                            const AVSubtitle *sub);
+
+
+/**
+ * @}
+ */
+
+#if FF_API_AVCODEC_RESAMPLE
+/**
+ * @defgroup lavc_resample Audio resampling
+ * @ingroup libavc
+ * @deprecated use libswresample instead
+ *
+ * @{
+ */
+struct ReSampleContext;
+struct AVResampleContext;
+
+typedef struct ReSampleContext ReSampleContext;
+
+/**
+ *  Initialize audio resampling context.
+ *
+ * @param output_channels  number of output channels
+ * @param input_channels   number of input channels
+ * @param output_rate      output sample rate
+ * @param input_rate       input sample rate
+ * @param sample_fmt_out   requested output sample format
+ * @param sample_fmt_in    input sample format
+ * @param filter_length    length of each FIR filter in the filterbank relative to the cutoff frequency
+ * @param log2_phase_count log2 of the number of entries in the polyphase filterbank
+ * @param linear           if 1 then the used FIR filter will be linearly interpolated
+                           between the 2 closest, if 0 the closest will be used
+ * @param cutoff           cutoff frequency, 1.0 corresponds to half the output sampling rate
+ * @return allocated ReSampleContext, NULL if error occurred
+ */
+attribute_deprecated
+ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
+                                        int output_rate, int input_rate,
+                                        enum AVSampleFormat sample_fmt_out,
+                                        enum AVSampleFormat sample_fmt_in,
+                                        int filter_length, int log2_phase_count,
+                                        int linear, double cutoff);
+
+attribute_deprecated
+int audio_resample(ReSampleContext *s, short *output, short *input, int nb_samples);
+
+/**
+ * Free resample context.
+ *
+ * @param s a non-NULL pointer to a resample context previously
+ *          created with av_audio_resample_init()
+ */
+attribute_deprecated
+void audio_resample_close(ReSampleContext *s);
+
+
+/**
+ * Initialize an audio resampler.
+ * Note, if either rate is not an integer then simply scale both rates up so they are.
+ * @param filter_length length of each FIR filter in the filterbank relative to the cutoff freq
+ * @param log2_phase_count log2 of the number of entries in the polyphase filterbank
+ * @param linear If 1 then the used FIR filter will be linearly interpolated
+                 between the 2 closest, if 0 the closest will be used
+ * @param cutoff cutoff frequency, 1.0 corresponds to half the output sampling rate
+ */
+attribute_deprecated
+struct AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_length, int log2_phase_count, int linear, double cutoff);
+
+/**
+ * Resample an array of samples using a previously configured context.
+ * @param src an array of unconsumed samples
+ * @param consumed the number of samples of src which have been consumed are returned here
+ * @param src_size the number of unconsumed samples available
+ * @param dst_size the amount of space in samples available in dst
+ * @param update_ctx If this is 0 then the context will not be modified, that way several channels can be resampled with the same context.
+ * @return the number of samples written in dst or -1 if an error occurred
+ */
+attribute_deprecated
+int av_resample(struct AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx);
+
+
+/**
+ * Compensate samplerate/timestamp drift. The compensation is done by changing
+ * the resampler parameters, so no audible clicks or similar distortions occur
+ * @param compensation_distance distance in output samples over which the compensation should be performed
+ * @param sample_delta number of output samples which should be output less
+ *
+ * example: av_resample_compensate(c, 10, 500)
+ * here instead of 510 samples only 500 samples would be output
+ *
+ * note, due to rounding the actual compensation might be slightly different,
+ * especially if the compensation_distance is large and the in_rate used during init is small
+ */
+attribute_deprecated
+void av_resample_compensate(struct AVResampleContext *c, int sample_delta, int compensation_distance);
+attribute_deprecated
+void av_resample_close(struct AVResampleContext *c);
+
+/**
+ * @}
+ */
+#endif
+
+/**
+ * @addtogroup lavc_picture
+ * @{
+ */
+
+/**
+ * Allocate memory for a picture.  Call avpicture_free() to free it.
+ *
+ * @see avpicture_fill()
+ *
+ * @param picture the picture to be filled in
+ * @param pix_fmt the format of the picture
+ * @param width the width of the picture
+ * @param height the height of the picture
+ * @return zero if successful, a negative value if not
+ */
+int avpicture_alloc(AVPicture *picture, enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * Free a picture previously allocated by avpicture_alloc().
+ * The data buffer used by the AVPicture is freed, but the AVPicture structure
+ * itself is not.
+ *
+ * @param picture the AVPicture to be freed
+ */
+void avpicture_free(AVPicture *picture);
+
+/**
+ * Fill in the AVPicture fields, always assume a linesize alignment of
+ * 1.
+ *
+ * @see av_image_fill_arrays()
+ */
+int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
+                   enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * Copy pixel data from an AVPicture into a buffer, always assume a
+ * linesize alignment of 1.
+ *
+ * @see av_image_copy_to_buffer()
+ */
+int avpicture_layout(const AVPicture* src, enum AVPixelFormat pix_fmt,
+                     int width, int height,
+                     unsigned char *dest, int dest_size);
+
+/**
+ * Calculate the size in bytes that a picture of the given width and height
+ * would occupy if stored in the given picture format.
+ * Always assume a linesize alignment of 1.
+ *
+ * @see av_image_get_buffer_size().
+ */
+int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
+
+#if FF_API_DEINTERLACE
+/**
+ *  deinterlace - if not supported return -1
+ *
+ * @deprecated - use yadif (in libavfilter) instead
+ */
+attribute_deprecated
+int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
+                          enum AVPixelFormat pix_fmt, int width, int height);
+#endif
+/**
+ * Copy image src to dst. Wraps av_image_copy().
+ */
+void av_picture_copy(AVPicture *dst, const AVPicture *src,
+                     enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * Crop image top and left side.
+ */
+int av_picture_crop(AVPicture *dst, const AVPicture *src,
+                    enum AVPixelFormat pix_fmt, int top_band, int left_band);
+
+/**
+ * Pad image.
+ */
+int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width, enum AVPixelFormat pix_fmt,
+            int padtop, int padbottom, int padleft, int padright, int *color);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavc_misc Utility functions
+ * @ingroup libavc
+ *
+ * Miscellaneous utility functions related to both encoding and decoding
+ * (or neither).
+ * @{
+ */
+
+/**
+ * @defgroup lavc_misc_pixfmt Pixel formats
+ *
+ * Functions for working with pixel formats.
+ * @{
+ */
+
+/**
+ * Utility function to access log2_chroma_w log2_chroma_h from
+ * the pixel format AVPixFmtDescriptor.
+ *
+ * This function asserts that pix_fmt is valid. See av_pix_fmt_get_chroma_sub_sample
+ * for one that returns a failure code and continues in case of invalid
+ * pix_fmts.
+ *
+ * @param[in]  pix_fmt the pixel format
+ * @param[out] h_shift store log2_chroma_w
+ * @param[out] v_shift store log2_chroma_h
+ *
+ * @see av_pix_fmt_get_chroma_sub_sample
+ */
+
+void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift);
+
+/**
+ * Return a value representing the fourCC code associated to the
+ * pixel format pix_fmt, or 0 if no associated fourCC code can be
+ * found.
+ */
+unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat pix_fmt);
+
+#define FF_LOSS_RESOLUTION  0x0001 /**< loss due to resolution change */
+#define FF_LOSS_DEPTH       0x0002 /**< loss due to color depth change */
+#define FF_LOSS_COLORSPACE  0x0004 /**< loss due to color space conversion */
+#define FF_LOSS_ALPHA       0x0008 /**< loss of alpha bits */
+#define FF_LOSS_COLORQUANT  0x0010 /**< loss due to color quantization */
+#define FF_LOSS_CHROMA      0x0020 /**< loss of chroma (e.g. RGB to gray conversion) */
+
+/**
+ * Compute what kind of losses will occur when converting from one specific
+ * pixel format to another.
+ * When converting from one pixel format to another, information loss may occur.
+ * For example, when converting from RGB24 to GRAY, the color information will
+ * be lost. Similarly, other losses occur when converting from some formats to
+ * other formats. These losses can involve loss of chroma, but also loss of
+ * resolution, loss of color depth, loss due to the color space conversion, loss
+ * of the alpha bits or loss due to color quantization.
+ * avcodec_get_fix_fmt_loss() informs you about the various types of losses
+ * which will occur when converting from one pixel format to another.
+ *
+ * @param[in] dst_pix_fmt destination pixel format
+ * @param[in] src_pix_fmt source pixel format
+ * @param[in] has_alpha Whether the source pixel format alpha channel is used.
+ * @return Combination of flags informing you what kind of losses will occur
+ * (maximum loss for an invalid dst_pix_fmt).
+ */
+int avcodec_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt, enum AVPixelFormat src_pix_fmt,
+                             int has_alpha);
+
+/**
+ * Find the best pixel format to convert to given a certain source pixel
+ * format.  When converting from one pixel format to another, information loss
+ * may occur.  For example, when converting from RGB24 to GRAY, the color
+ * information will be lost. Similarly, other losses occur when converting from
+ * some formats to other formats. avcodec_find_best_pix_fmt_of_2() searches which of
+ * the given pixel formats should be used to suffer the least amount of loss.
+ * The pixel formats from which it chooses one, are determined by the
+ * pix_fmt_list parameter.
+ *
+ *
+ * @param[in] pix_fmt_list AV_PIX_FMT_NONE terminated array of pixel formats to choose from
+ * @param[in] src_pix_fmt source pixel format
+ * @param[in] has_alpha Whether the source pixel format alpha channel is used.
+ * @param[out] loss_ptr Combination of flags informing you what kind of losses will occur.
+ * @return The best pixel format to convert to or -1 if none was found.
+ */
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(enum AVPixelFormat *pix_fmt_list,
+                                            enum AVPixelFormat src_pix_fmt,
+                                            int has_alpha, int *loss_ptr);
+
+/**
+ * Find the best pixel format to convert to given a certain source pixel
+ * format and a selection of two destination pixel formats. When converting from
+ * one pixel format to another, information loss may occur.  For example, when converting
+ * from RGB24 to GRAY, the color information will be lost. Similarly, other losses occur when
+ * converting from some formats to other formats. avcodec_find_best_pix_fmt_of_2() selects which of
+ * the given pixel formats should be used to suffer the least amount of loss.
+ *
+ * If one of the destination formats is AV_PIX_FMT_NONE the other pixel format (if valid) will be
+ * returned.
+ *
+ * @code
+ * src_pix_fmt = AV_PIX_FMT_YUV420P;
+ * dst_pix_fmt1= AV_PIX_FMT_RGB24;
+ * dst_pix_fmt2= AV_PIX_FMT_GRAY8;
+ * dst_pix_fmt3= AV_PIX_FMT_RGB8;
+ * loss= FF_LOSS_CHROMA; // don't care about chroma loss, so chroma loss will be ignored.
+ * dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt1, dst_pix_fmt2, src_pix_fmt, alpha, &loss);
+ * dst_pix_fmt = avcodec_find_best_pix_fmt_of_2(dst_pix_fmt, dst_pix_fmt3, src_pix_fmt, alpha, &loss);
+ * @endcode
+ *
+ * @param[in] dst_pix_fmt1 One of the two destination pixel formats to choose from
+ * @param[in] dst_pix_fmt2 The other of the two destination pixel formats to choose from
+ * @param[in] src_pix_fmt Source pixel format
+ * @param[in] has_alpha Whether the source pixel format alpha channel is used.
+ * @param[in, out] loss_ptr Combination of loss flags. In: selects which of the losses to ignore, i.e.
+ *                               NULL or value of zero means we care about all losses. Out: the loss
+ *                               that occurs when converting from src to selected dst pixel format.
+ * @return The best pixel format to convert to or -1 if none was found.
+ */
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+                                            enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
+
+attribute_deprecated
+#if AV_HAVE_INCOMPATIBLE_FORK_ABI
+enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat *pix_fmt_list,
+                                              enum AVPixelFormat src_pix_fmt,
+                                              int has_alpha, int *loss_ptr);
+#else
+enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+                                            enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
+#endif
+
+
+enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat * fmt);
+
+/**
+ * @}
+ */
+
+void avcodec_set_dimensions(AVCodecContext *s, int width, int height);
+
+/**
+ * Put a string representing the codec tag codec_tag in buf.
+ *
+ * @param buf_size size in bytes of buf
+ * @return the length of the string that would have been generated if
+ * enough space had been available, excluding the trailing null
+ */
+size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag);
+
+void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode);
+
+/**
+ * Return a name for the specified profile, if available.
+ *
+ * @param codec the codec that is searched for the given profile
+ * @param profile the profile value for which a name is requested
+ * @return A name for the profile if found, NULL otherwise.
+ */
+const char *av_get_profile_name(const AVCodec *codec, int profile);
+
+int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size);
+int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int, int),void *arg, int *ret, int count);
+//FIXME func typedef
+
+/**
+ * Fill AVFrame audio data and linesize pointers.
+ *
+ * The buffer buf must be a preallocated buffer with a size big enough
+ * to contain the specified samples amount. The filled AVFrame data
+ * pointers will point to this buffer.
+ *
+ * AVFrame extended_data channel pointers are allocated if necessary for
+ * planar audio.
+ *
+ * @param frame       the AVFrame
+ *                    frame->nb_samples must be set prior to calling the
+ *                    function. This function fills in frame->data,
+ *                    frame->extended_data, frame->linesize[0].
+ * @param nb_channels channel count
+ * @param sample_fmt  sample format
+ * @param buf         buffer to use for frame data
+ * @param buf_size    size of buffer
+ * @param align       plane size sample alignment (0 = default)
+ * @return            >=0 on success, negative error code on failure
+ * @todo return the size in bytes required to store the samples in
+ * case of success, at the next libavutil bump
+ */
+int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
+                             enum AVSampleFormat sample_fmt, const uint8_t *buf,
+                             int buf_size, int align);
+
+/**
+ * Flush buffers, should be called when seeking or when switching to a different stream.
+ */
+void avcodec_flush_buffers(AVCodecContext *avctx);
+
+/**
+ * Return codec bits per sample.
+ *
+ * @param[in] codec_id the codec
+ * @return Number of bits per sample or zero if unknown for the given codec.
+ */
+int av_get_bits_per_sample(enum AVCodecID codec_id);
+
+/**
+ * Return the PCM codec associated with a sample format.
+ * @param be  endianness, 0 for little, 1 for big,
+ *            -1 (or anything else) for native
+ * @return  AV_CODEC_ID_PCM_* or AV_CODEC_ID_NONE
+ */
+enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be);
+
+/**
+ * Return codec bits per sample.
+ * Only return non-zero if the bits per sample is exactly correct, not an
+ * approximation.
+ *
+ * @param[in] codec_id the codec
+ * @return Number of bits per sample or zero if unknown for the given codec.
+ */
+int av_get_exact_bits_per_sample(enum AVCodecID codec_id);
+
+/**
+ * Return audio frame duration.
+ *
+ * @param avctx        codec context
+ * @param frame_bytes  size of the frame, or 0 if unknown
+ * @return             frame duration, in samples, if known. 0 if not able to
+ *                     determine.
+ */
+int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes);
+
+
+typedef struct AVBitStreamFilterContext {
+    void *priv_data;
+    struct AVBitStreamFilter *filter;
+    AVCodecParserContext *parser;
+    struct AVBitStreamFilterContext *next;
+} AVBitStreamFilterContext;
+
+
+typedef struct AVBitStreamFilter {
+    const char *name;
+    int priv_data_size;
+    int (*filter)(AVBitStreamFilterContext *bsfc,
+                  AVCodecContext *avctx, const char *args,
+                  uint8_t **poutbuf, int *poutbuf_size,
+                  const uint8_t *buf, int buf_size, int keyframe);
+    void (*close)(AVBitStreamFilterContext *bsfc);
+    struct AVBitStreamFilter *next;
+} AVBitStreamFilter;
+
+void av_register_bitstream_filter(AVBitStreamFilter *bsf);
+AVBitStreamFilterContext *av_bitstream_filter_init(const char *name);
+int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc,
+                               AVCodecContext *avctx, const char *args,
+                               uint8_t **poutbuf, int *poutbuf_size,
+                               const uint8_t *buf, int buf_size, int keyframe);
+void av_bitstream_filter_close(AVBitStreamFilterContext *bsf);
+
+AVBitStreamFilter *av_bitstream_filter_next(AVBitStreamFilter *f);
+
+/* memory */
+
+/**
+ * Reallocate the given block if it is not large enough, otherwise do nothing.
+ *
+ * @see av_realloc
+ */
+void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Allocate a buffer, reusing the given one if large enough.
+ *
+ * Contrary to av_fast_realloc the current buffer contents might not be
+ * preserved and on error the old buffer is freed, thus no special
+ * handling to avoid memleaks is necessary.
+ *
+ * @param ptr pointer to pointer to already allocated buffer, overwritten with pointer to new buffer
+ * @param size size of the buffer *ptr points to
+ * @param min_size minimum size of *ptr buffer after returning, *ptr will be NULL and
+ *                 *size 0 if an error occurred.
+ */
+void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Same behaviour av_fast_malloc but the buffer has additional
+ * FF_INPUT_BUFFER_PADDING_SIZE at the end which will will always be 0.
+ *
+ * In addition the whole buffer will initially and after resizes
+ * be 0-initialized so that no uninitialized data will ever appear.
+ */
+void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Same behaviour av_fast_padded_malloc except that buffer will always
+ * be 0-initialized after call.
+ */
+void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Encode extradata length to a buffer. Used by xiph codecs.
+ *
+ * @param s buffer to write to; must be at least (v/255+1) bytes long
+ * @param v size of extradata in bytes
+ * @return number of bytes written to the buffer.
+ */
+unsigned int av_xiphlacing(unsigned char *s, unsigned int v);
+
+#if FF_API_MISSING_SAMPLE
+/**
+ * Log a generic warning message about a missing feature. This function is
+ * intended to be used internally by FFmpeg (libavcodec, libavformat, etc.)
+ * only, and would normally not be used by applications.
+ * @param[in] avc a pointer to an arbitrary struct of which the first field is
+ * a pointer to an AVClass struct
+ * @param[in] feature string containing the name of the missing feature
+ * @param[in] want_sample indicates if samples are wanted which exhibit this feature.
+ * If want_sample is non-zero, additional verbage will be added to the log
+ * message which tells the user how to report samples to the development
+ * mailing list.
+ * @deprecated Use avpriv_report_missing_feature() instead.
+ */
+attribute_deprecated
+void av_log_missing_feature(void *avc, const char *feature, int want_sample);
+
+/**
+ * Log a generic warning message asking for a sample. This function is
+ * intended to be used internally by FFmpeg (libavcodec, libavformat, etc.)
+ * only, and would normally not be used by applications.
+ * @param[in] avc a pointer to an arbitrary struct of which the first field is
+ * a pointer to an AVClass struct
+ * @param[in] msg string containing an optional message, or NULL if no message
+ * @deprecated Use avpriv_request_sample() instead.
+ */
+attribute_deprecated
+void av_log_ask_for_sample(void *avc, const char *msg, ...) av_printf_format(2, 3);
+#endif /* FF_API_MISSING_SAMPLE */
+
+/**
+ * Register the hardware accelerator hwaccel.
+ */
+void av_register_hwaccel(AVHWAccel *hwaccel);
+
+/**
+ * If hwaccel is NULL, returns the first registered hardware accelerator,
+ * if hwaccel is non-NULL, returns the next registered hardware accelerator
+ * after hwaccel, or NULL if hwaccel is the last one.
+ */
+AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel);
+
+
+/**
+ * Lock operation used by lockmgr
+ */
+enum AVLockOp {
+  AV_LOCK_CREATE,  ///< Create a mutex
+  AV_LOCK_OBTAIN,  ///< Lock the mutex
+  AV_LOCK_RELEASE, ///< Unlock the mutex
+  AV_LOCK_DESTROY, ///< Free mutex resources
+};
+
+/**
+ * Register a user provided lock manager supporting the operations
+ * specified by AVLockOp. mutex points to a (void *) where the
+ * lockmgr should store/get a pointer to a user allocated mutex. It's
+ * NULL upon AV_LOCK_CREATE and != NULL for all other ops.
+ *
+ * @param cb User defined callback. Note: FFmpeg may invoke calls to this
+ *           callback during the call to av_lockmgr_register().
+ *           Thus, the application must be prepared to handle that.
+ *           If cb is set to NULL the lockmgr will be unregistered.
+ *           Also note that during unregistration the previously registered
+ *           lockmgr callback may also be invoked.
+ */
+int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op));
+
+/**
+ * Get the type of the given codec.
+ */
+enum AVMediaType avcodec_get_type(enum AVCodecID codec_id);
+
+/**
+ * Get the name of a codec.
+ * @return  a static string identifying the codec; never NULL
+ */
+const char *avcodec_get_name(enum AVCodecID id);
+
+/**
+ * @return a positive value if s is open (i.e. avcodec_open2() was called on it
+ * with no corresponding avcodec_close()), 0 otherwise.
+ */
+int avcodec_is_open(AVCodecContext *s);
+
+/**
+ * @return a non-zero number if codec is an encoder, zero otherwise
+ */
+int av_codec_is_encoder(const AVCodec *codec);
+
+/**
+ * @return a non-zero number if codec is a decoder, zero otherwise
+ */
+int av_codec_is_decoder(const AVCodec *codec);
+
+/**
+ * @return descriptor for given codec ID or NULL if no descriptor exists.
+ */
+const AVCodecDescriptor *avcodec_descriptor_get(enum AVCodecID id);
+
+/**
+ * Iterate over all codec descriptors known to libavcodec.
+ *
+ * @param prev previous descriptor. NULL to get the first descriptor.
+ *
+ * @return next descriptor or NULL after the last descriptor
+ */
+const AVCodecDescriptor *avcodec_descriptor_next(const AVCodecDescriptor *prev);
+
+/**
+ * @return codec descriptor with the given name or NULL if no such descriptor
+ *         exists.
+ */
+const AVCodecDescriptor *avcodec_descriptor_get_by_name(const char *name);
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_AVCODEC_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/avfft.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,116 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AVFFT_H
+#define AVCODEC_AVFFT_H
+
+/**
+ * @file
+ * @ingroup lavc_fft
+ * FFT functions
+ */
+
+/**
+ * @defgroup lavc_fft FFT functions
+ * @ingroup lavc_misc
+ *
+ * @{
+ */
+
+typedef float FFTSample;
+
+typedef struct FFTComplex {
+    FFTSample re, im;
+} FFTComplex;
+
+typedef struct FFTContext FFTContext;
+
+/**
+ * Set up a complex FFT.
+ * @param nbits           log2 of the length of the input array
+ * @param inverse         if 0 perform the forward transform, if 1 perform the inverse
+ */
+FFTContext *av_fft_init(int nbits, int inverse);
+
+/**
+ * Do the permutation needed BEFORE calling ff_fft_calc().
+ */
+void av_fft_permute(FFTContext *s, FFTComplex *z);
+
+/**
+ * Do a complex FFT with the parameters defined in av_fft_init(). The
+ * input data must be permuted before. No 1.0/sqrt(n) normalization is done.
+ */
+void av_fft_calc(FFTContext *s, FFTComplex *z);
+
+void av_fft_end(FFTContext *s);
+
+FFTContext *av_mdct_init(int nbits, int inverse, double scale);
+void av_imdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_imdct_half(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_mdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_mdct_end(FFTContext *s);
+
+/* Real Discrete Fourier Transform */
+
+enum RDFTransformType {
+    DFT_R2C,
+    IDFT_C2R,
+    IDFT_R2C,
+    DFT_C2R,
+};
+
+typedef struct RDFTContext RDFTContext;
+
+/**
+ * Set up a real FFT.
+ * @param nbits           log2 of the length of the input array
+ * @param trans           the type of transform
+ */
+RDFTContext *av_rdft_init(int nbits, enum RDFTransformType trans);
+void av_rdft_calc(RDFTContext *s, FFTSample *data);
+void av_rdft_end(RDFTContext *s);
+
+/* Discrete Cosine Transform */
+
+typedef struct DCTContext DCTContext;
+
+enum DCTTransformType {
+    DCT_II = 0,
+    DCT_III,
+    DCT_I,
+    DST_I,
+};
+
+/**
+ * Set up DCT.
+ * @param nbits           size of the input array:
+ *                        (1 << nbits)     for DCT-II, DCT-III and DST-I
+ *                        (1 << nbits) + 1 for DCT-I
+ *
+ * @note the first element of the input of DST-I is ignored
+ */
+DCTContext *av_dct_init(int nbits, enum DCTTransformType type);
+void av_dct_calc(DCTContext *s, FFTSample *data);
+void av_dct_end (DCTContext *s);
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_AVFFT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/dxva2.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,95 @@
+/*
+ * DXVA2 HW acceleration
+ *
+ * copyright (c) 2009 Laurent Aimar
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_DXVA_H
+#define AVCODEC_DXVA_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_dxva2
+ * Public libavcodec DXVA2 header.
+ */
+
+#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600
+#undef _WIN32_WINNT
+#endif
+
+#if !defined(_WIN32_WINNT)
+#define _WIN32_WINNT 0x0600
+#endif
+
+#include <stdint.h>
+#include <d3d9.h>
+#include <dxva2api.h>
+
+/**
+ * @defgroup lavc_codec_hwaccel_dxva2 DXVA2
+ * @ingroup lavc_codec_hwaccel
+ *
+ * @{
+ */
+
+#define FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG 1 ///< Work around for DXVA2 and old UVD/UVD+ ATI video cards
+
+/**
+ * This structure is used to provides the necessary configurations and data
+ * to the DXVA2 FFmpeg HWAccel implementation.
+ *
+ * The application must make it available as AVCodecContext.hwaccel_context.
+ */
+struct dxva_context {
+    /**
+     * DXVA2 decoder object
+     */
+    IDirectXVideoDecoder *decoder;
+
+    /**
+     * DXVA2 configuration used to create the decoder
+     */
+    const DXVA2_ConfigPictureDecode *cfg;
+
+    /**
+     * The number of surface in the surface array
+     */
+    unsigned surface_count;
+
+    /**
+     * The array of Direct3D surfaces used to create the decoder
+     */
+    LPDIRECT3DSURFACE9 *surface;
+
+    /**
+     * A bit field configuring the workarounds needed for using the decoder
+     */
+    uint64_t workaround;
+
+    /**
+     * Private to the FFmpeg AVHWAccel implementation
+     */
+    unsigned report_id;
+};
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_DXVA_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/old_codec_ids.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,397 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_OLD_CODEC_IDS_H
+#define AVCODEC_OLD_CODEC_IDS_H
+
+#include "../libavutil/common.h"
+
+/*
+ * This header exists to prevent new codec IDs from being accidentally added to
+ * the deprecated list.
+ * Do not include it directly. It will be removed on next major bump
+ *
+ * Do not add new items to this list. Use the AVCodecID enum instead.
+ */
+
+    CODEC_ID_NONE = AV_CODEC_ID_NONE,
+
+    /* video codecs */
+    CODEC_ID_MPEG1VIDEO,
+    CODEC_ID_MPEG2VIDEO, ///< preferred ID for MPEG-1/2 video decoding
+    CODEC_ID_MPEG2VIDEO_XVMC,
+    CODEC_ID_H261,
+    CODEC_ID_H263,
+    CODEC_ID_RV10,
+    CODEC_ID_RV20,
+    CODEC_ID_MJPEG,
+    CODEC_ID_MJPEGB,
+    CODEC_ID_LJPEG,
+    CODEC_ID_SP5X,
+    CODEC_ID_JPEGLS,
+    CODEC_ID_MPEG4,
+    CODEC_ID_RAWVIDEO,
+    CODEC_ID_MSMPEG4V1,
+    CODEC_ID_MSMPEG4V2,
+    CODEC_ID_MSMPEG4V3,
+    CODEC_ID_WMV1,
+    CODEC_ID_WMV2,
+    CODEC_ID_H263P,
+    CODEC_ID_H263I,
+    CODEC_ID_FLV1,
+    CODEC_ID_SVQ1,
+    CODEC_ID_SVQ3,
+    CODEC_ID_DVVIDEO,
+    CODEC_ID_HUFFYUV,
+    CODEC_ID_CYUV,
+    CODEC_ID_H264,
+    CODEC_ID_INDEO3,
+    CODEC_ID_VP3,
+    CODEC_ID_THEORA,
+    CODEC_ID_ASV1,
+    CODEC_ID_ASV2,
+    CODEC_ID_FFV1,
+    CODEC_ID_4XM,
+    CODEC_ID_VCR1,
+    CODEC_ID_CLJR,
+    CODEC_ID_MDEC,
+    CODEC_ID_ROQ,
+    CODEC_ID_INTERPLAY_VIDEO,
+    CODEC_ID_XAN_WC3,
+    CODEC_ID_XAN_WC4,
+    CODEC_ID_RPZA,
+    CODEC_ID_CINEPAK,
+    CODEC_ID_WS_VQA,
+    CODEC_ID_MSRLE,
+    CODEC_ID_MSVIDEO1,
+    CODEC_ID_IDCIN,
+    CODEC_ID_8BPS,
+    CODEC_ID_SMC,
+    CODEC_ID_FLIC,
+    CODEC_ID_TRUEMOTION1,
+    CODEC_ID_VMDVIDEO,
+    CODEC_ID_MSZH,
+    CODEC_ID_ZLIB,
+    CODEC_ID_QTRLE,
+    CODEC_ID_TSCC,
+    CODEC_ID_ULTI,
+    CODEC_ID_QDRAW,
+    CODEC_ID_VIXL,
+    CODEC_ID_QPEG,
+    CODEC_ID_PNG,
+    CODEC_ID_PPM,
+    CODEC_ID_PBM,
+    CODEC_ID_PGM,
+    CODEC_ID_PGMYUV,
+    CODEC_ID_PAM,
+    CODEC_ID_FFVHUFF,
+    CODEC_ID_RV30,
+    CODEC_ID_RV40,
+    CODEC_ID_VC1,
+    CODEC_ID_WMV3,
+    CODEC_ID_LOCO,
+    CODEC_ID_WNV1,
+    CODEC_ID_AASC,
+    CODEC_ID_INDEO2,
+    CODEC_ID_FRAPS,
+    CODEC_ID_TRUEMOTION2,
+    CODEC_ID_BMP,
+    CODEC_ID_CSCD,
+    CODEC_ID_MMVIDEO,
+    CODEC_ID_ZMBV,
+    CODEC_ID_AVS,
+    CODEC_ID_SMACKVIDEO,
+    CODEC_ID_NUV,
+    CODEC_ID_KMVC,
+    CODEC_ID_FLASHSV,
+    CODEC_ID_CAVS,
+    CODEC_ID_JPEG2000,
+    CODEC_ID_VMNC,
+    CODEC_ID_VP5,
+    CODEC_ID_VP6,
+    CODEC_ID_VP6F,
+    CODEC_ID_TARGA,
+    CODEC_ID_DSICINVIDEO,
+    CODEC_ID_TIERTEXSEQVIDEO,
+    CODEC_ID_TIFF,
+    CODEC_ID_GIF,
+    CODEC_ID_DXA,
+    CODEC_ID_DNXHD,
+    CODEC_ID_THP,
+    CODEC_ID_SGI,
+    CODEC_ID_C93,
+    CODEC_ID_BETHSOFTVID,
+    CODEC_ID_PTX,
+    CODEC_ID_TXD,
+    CODEC_ID_VP6A,
+    CODEC_ID_AMV,
+    CODEC_ID_VB,
+    CODEC_ID_PCX,
+    CODEC_ID_SUNRAST,
+    CODEC_ID_INDEO4,
+    CODEC_ID_INDEO5,
+    CODEC_ID_MIMIC,
+    CODEC_ID_RL2,
+    CODEC_ID_ESCAPE124,
+    CODEC_ID_DIRAC,
+    CODEC_ID_BFI,
+    CODEC_ID_CMV,
+    CODEC_ID_MOTIONPIXELS,
+    CODEC_ID_TGV,
+    CODEC_ID_TGQ,
+    CODEC_ID_TQI,
+    CODEC_ID_AURA,
+    CODEC_ID_AURA2,
+    CODEC_ID_V210X,
+    CODEC_ID_TMV,
+    CODEC_ID_V210,
+    CODEC_ID_DPX,
+    CODEC_ID_MAD,
+    CODEC_ID_FRWU,
+    CODEC_ID_FLASHSV2,
+    CODEC_ID_CDGRAPHICS,
+    CODEC_ID_R210,
+    CODEC_ID_ANM,
+    CODEC_ID_BINKVIDEO,
+    CODEC_ID_IFF_ILBM,
+    CODEC_ID_IFF_BYTERUN1,
+    CODEC_ID_KGV1,
+    CODEC_ID_YOP,
+    CODEC_ID_VP8,
+    CODEC_ID_PICTOR,
+    CODEC_ID_ANSI,
+    CODEC_ID_A64_MULTI,
+    CODEC_ID_A64_MULTI5,
+    CODEC_ID_R10K,
+    CODEC_ID_MXPEG,
+    CODEC_ID_LAGARITH,
+    CODEC_ID_PRORES,
+    CODEC_ID_JV,
+    CODEC_ID_DFA,
+    CODEC_ID_WMV3IMAGE,
+    CODEC_ID_VC1IMAGE,
+    CODEC_ID_UTVIDEO,
+    CODEC_ID_BMV_VIDEO,
+    CODEC_ID_VBLE,
+    CODEC_ID_DXTORY,
+    CODEC_ID_V410,
+    CODEC_ID_XWD,
+    CODEC_ID_CDXL,
+    CODEC_ID_XBM,
+    CODEC_ID_ZEROCODEC,
+    CODEC_ID_MSS1,
+    CODEC_ID_MSA1,
+    CODEC_ID_TSCC2,
+    CODEC_ID_MTS2,
+    CODEC_ID_CLLC,
+    CODEC_ID_Y41P       = MKBETAG('Y','4','1','P'),
+    CODEC_ID_ESCAPE130  = MKBETAG('E','1','3','0'),
+    CODEC_ID_EXR        = MKBETAG('0','E','X','R'),
+    CODEC_ID_AVRP       = MKBETAG('A','V','R','P'),
+
+    CODEC_ID_G2M        = MKBETAG( 0 ,'G','2','M'),
+    CODEC_ID_AVUI       = MKBETAG('A','V','U','I'),
+    CODEC_ID_AYUV       = MKBETAG('A','Y','U','V'),
+    CODEC_ID_V308       = MKBETAG('V','3','0','8'),
+    CODEC_ID_V408       = MKBETAG('V','4','0','8'),
+    CODEC_ID_YUV4       = MKBETAG('Y','U','V','4'),
+    CODEC_ID_SANM       = MKBETAG('S','A','N','M'),
+    CODEC_ID_PAF_VIDEO  = MKBETAG('P','A','F','V'),
+    CODEC_ID_SNOW       = AV_CODEC_ID_SNOW,
+
+    /* various PCM "codecs" */
+    CODEC_ID_FIRST_AUDIO = 0x10000,     ///< A dummy id pointing at the start of audio codecs
+    CODEC_ID_PCM_S16LE = 0x10000,
+    CODEC_ID_PCM_S16BE,
+    CODEC_ID_PCM_U16LE,
+    CODEC_ID_PCM_U16BE,
+    CODEC_ID_PCM_S8,
+    CODEC_ID_PCM_U8,
+    CODEC_ID_PCM_MULAW,
+    CODEC_ID_PCM_ALAW,
+    CODEC_ID_PCM_S32LE,
+    CODEC_ID_PCM_S32BE,
+    CODEC_ID_PCM_U32LE,
+    CODEC_ID_PCM_U32BE,
+    CODEC_ID_PCM_S24LE,
+    CODEC_ID_PCM_S24BE,
+    CODEC_ID_PCM_U24LE,
+    CODEC_ID_PCM_U24BE,
+    CODEC_ID_PCM_S24DAUD,
+    CODEC_ID_PCM_ZORK,
+    CODEC_ID_PCM_S16LE_PLANAR,
+    CODEC_ID_PCM_DVD,
+    CODEC_ID_PCM_F32BE,
+    CODEC_ID_PCM_F32LE,
+    CODEC_ID_PCM_F64BE,
+    CODEC_ID_PCM_F64LE,
+    CODEC_ID_PCM_BLURAY,
+    CODEC_ID_PCM_LXF,
+    CODEC_ID_S302M,
+    CODEC_ID_PCM_S8_PLANAR,
+
+    /* various ADPCM codecs */
+    CODEC_ID_ADPCM_IMA_QT = 0x11000,
+    CODEC_ID_ADPCM_IMA_WAV,
+    CODEC_ID_ADPCM_IMA_DK3,
+    CODEC_ID_ADPCM_IMA_DK4,
+    CODEC_ID_ADPCM_IMA_WS,
+    CODEC_ID_ADPCM_IMA_SMJPEG,
+    CODEC_ID_ADPCM_MS,
+    CODEC_ID_ADPCM_4XM,
+    CODEC_ID_ADPCM_XA,
+    CODEC_ID_ADPCM_ADX,
+    CODEC_ID_ADPCM_EA,
+    CODEC_ID_ADPCM_G726,
+    CODEC_ID_ADPCM_CT,
+    CODEC_ID_ADPCM_SWF,
+    CODEC_ID_ADPCM_YAMAHA,
+    CODEC_ID_ADPCM_SBPRO_4,
+    CODEC_ID_ADPCM_SBPRO_3,
+    CODEC_ID_ADPCM_SBPRO_2,
+    CODEC_ID_ADPCM_THP,
+    CODEC_ID_ADPCM_IMA_AMV,
+    CODEC_ID_ADPCM_EA_R1,
+    CODEC_ID_ADPCM_EA_R3,
+    CODEC_ID_ADPCM_EA_R2,
+    CODEC_ID_ADPCM_IMA_EA_SEAD,
+    CODEC_ID_ADPCM_IMA_EA_EACS,
+    CODEC_ID_ADPCM_EA_XAS,
+    CODEC_ID_ADPCM_EA_MAXIS_XA,
+    CODEC_ID_ADPCM_IMA_ISS,
+    CODEC_ID_ADPCM_G722,
+    CODEC_ID_ADPCM_IMA_APC,
+    CODEC_ID_VIMA       = MKBETAG('V','I','M','A'),
+
+    /* AMR */
+    CODEC_ID_AMR_NB = 0x12000,
+    CODEC_ID_AMR_WB,
+
+    /* RealAudio codecs*/
+    CODEC_ID_RA_144 = 0x13000,
+    CODEC_ID_RA_288,
+
+    /* various DPCM codecs */
+    CODEC_ID_ROQ_DPCM = 0x14000,
+    CODEC_ID_INTERPLAY_DPCM,
+    CODEC_ID_XAN_DPCM,
+    CODEC_ID_SOL_DPCM,
+
+    /* audio codecs */
+    CODEC_ID_MP2 = 0x15000,
+    CODEC_ID_MP3, ///< preferred ID for decoding MPEG audio layer 1, 2 or 3
+    CODEC_ID_AAC,
+    CODEC_ID_AC3,
+    CODEC_ID_DTS,
+    CODEC_ID_VORBIS,
+    CODEC_ID_DVAUDIO,
+    CODEC_ID_WMAV1,
+    CODEC_ID_WMAV2,
+    CODEC_ID_MACE3,
+    CODEC_ID_MACE6,
+    CODEC_ID_VMDAUDIO,
+    CODEC_ID_FLAC,
+    CODEC_ID_MP3ADU,
+    CODEC_ID_MP3ON4,
+    CODEC_ID_SHORTEN,
+    CODEC_ID_ALAC,
+    CODEC_ID_WESTWOOD_SND1,
+    CODEC_ID_GSM, ///< as in Berlin toast format
+    CODEC_ID_QDM2,
+    CODEC_ID_COOK,
+    CODEC_ID_TRUESPEECH,
+    CODEC_ID_TTA,
+    CODEC_ID_SMACKAUDIO,
+    CODEC_ID_QCELP,
+    CODEC_ID_WAVPACK,
+    CODEC_ID_DSICINAUDIO,
+    CODEC_ID_IMC,
+    CODEC_ID_MUSEPACK7,
+    CODEC_ID_MLP,
+    CODEC_ID_GSM_MS, /* as found in WAV */
+    CODEC_ID_ATRAC3,
+    CODEC_ID_VOXWARE,
+    CODEC_ID_APE,
+    CODEC_ID_NELLYMOSER,
+    CODEC_ID_MUSEPACK8,
+    CODEC_ID_SPEEX,
+    CODEC_ID_WMAVOICE,
+    CODEC_ID_WMAPRO,
+    CODEC_ID_WMALOSSLESS,
+    CODEC_ID_ATRAC3P,
+    CODEC_ID_EAC3,
+    CODEC_ID_SIPR,
+    CODEC_ID_MP1,
+    CODEC_ID_TWINVQ,
+    CODEC_ID_TRUEHD,
+    CODEC_ID_MP4ALS,
+    CODEC_ID_ATRAC1,
+    CODEC_ID_BINKAUDIO_RDFT,
+    CODEC_ID_BINKAUDIO_DCT,
+    CODEC_ID_AAC_LATM,
+    CODEC_ID_QDMC,
+    CODEC_ID_CELT,
+    CODEC_ID_G723_1,
+    CODEC_ID_G729,
+    CODEC_ID_8SVX_EXP,
+    CODEC_ID_8SVX_FIB,
+    CODEC_ID_BMV_AUDIO,
+    CODEC_ID_RALF,
+    CODEC_ID_IAC,
+    CODEC_ID_ILBC,
+    CODEC_ID_FFWAVESYNTH = MKBETAG('F','F','W','S'),
+    CODEC_ID_SONIC       = MKBETAG('S','O','N','C'),
+    CODEC_ID_SONIC_LS    = MKBETAG('S','O','N','L'),
+    CODEC_ID_PAF_AUDIO   = MKBETAG('P','A','F','A'),
+    CODEC_ID_OPUS        = MKBETAG('O','P','U','S'),
+
+    /* subtitle codecs */
+    CODEC_ID_FIRST_SUBTITLE = 0x17000,          ///< A dummy ID pointing at the start of subtitle codecs.
+    CODEC_ID_DVD_SUBTITLE = 0x17000,
+    CODEC_ID_DVB_SUBTITLE,
+    CODEC_ID_TEXT,  ///< raw UTF-8 text
+    CODEC_ID_XSUB,
+    CODEC_ID_SSA,
+    CODEC_ID_MOV_TEXT,
+    CODEC_ID_HDMV_PGS_SUBTITLE,
+    CODEC_ID_DVB_TELETEXT,
+    CODEC_ID_SRT,
+    CODEC_ID_MICRODVD   = MKBETAG('m','D','V','D'),
+    CODEC_ID_EIA_608    = MKBETAG('c','6','0','8'),
+    CODEC_ID_JACOSUB    = MKBETAG('J','S','U','B'),
+    CODEC_ID_SAMI       = MKBETAG('S','A','M','I'),
+    CODEC_ID_REALTEXT   = MKBETAG('R','T','X','T'),
+    CODEC_ID_SUBVIEWER  = MKBETAG('S','u','b','V'),
+
+    /* other specific kind of codecs (generally used for attachments) */
+    CODEC_ID_FIRST_UNKNOWN = 0x18000,           ///< A dummy ID pointing at the start of various fake codecs.
+    CODEC_ID_TTF = 0x18000,
+    CODEC_ID_BINTEXT    = MKBETAG('B','T','X','T'),
+    CODEC_ID_XBIN       = MKBETAG('X','B','I','N'),
+    CODEC_ID_IDF        = MKBETAG( 0 ,'I','D','F'),
+    CODEC_ID_OTF        = MKBETAG( 0 ,'O','T','F'),
+
+    CODEC_ID_PROBE = 0x19000, ///< codec_id is not known (like CODEC_ID_NONE) but lavf should attempt to identify it
+
+    CODEC_ID_MPEG2TS = 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS
+                                * stream (only used by libavformat) */
+    CODEC_ID_MPEG4SYSTEMS = 0x20001, /**< _FAKE_ codec to indicate a MPEG-4 Systems
+                                * stream (only used by libavformat) */
+    CODEC_ID_FFMETADATA = 0x21000,   ///< Dummy codec for streams containing only metadata information.
+
+#endif /* AVCODEC_OLD_CODEC_IDS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/vaapi.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,173 @@
+/*
+ * Video Acceleration API (shared data between FFmpeg and the video player)
+ * HW decode acceleration for MPEG-2, MPEG-4, H.264 and VC-1
+ *
+ * Copyright (C) 2008-2009 Splitted-Desktop Systems
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VAAPI_H
+#define AVCODEC_VAAPI_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_vaapi
+ * Public libavcodec VA API header.
+ */
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavc_codec_hwaccel_vaapi VA API Decoding
+ * @ingroup lavc_codec_hwaccel
+ * @{
+ */
+
+/**
+ * This structure is used to share data between the FFmpeg library and
+ * the client video application.
+ * This shall be zero-allocated and available as
+ * AVCodecContext.hwaccel_context. All user members can be set once
+ * during initialization or through each AVCodecContext.get_buffer()
+ * function call. In any case, they must be valid prior to calling
+ * decoding functions.
+ */
+struct vaapi_context {
+    /**
+     * Window system dependent data
+     *
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    void *display;
+
+    /**
+     * Configuration ID
+     *
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    uint32_t config_id;
+
+    /**
+     * Context ID (video decode pipeline)
+     *
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    uint32_t context_id;
+
+    /**
+     * VAPictureParameterBuffer ID
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t pic_param_buf_id;
+
+    /**
+     * VAIQMatrixBuffer ID
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t iq_matrix_buf_id;
+
+    /**
+     * VABitPlaneBuffer ID (for VC-1 decoding)
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t bitplane_buf_id;
+
+    /**
+     * Slice parameter/data buffer IDs
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t *slice_buf_ids;
+
+    /**
+     * Number of effective slice buffer IDs to send to the HW
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int n_slice_buf_ids;
+
+    /**
+     * Size of pre-allocated slice_buf_ids
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_buf_ids_alloc;
+
+    /**
+     * Pointer to VASliceParameterBuffers
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    void *slice_params;
+
+    /**
+     * Size of a VASliceParameterBuffer element
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_param_size;
+
+    /**
+     * Size of pre-allocated slice_params
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_params_alloc;
+
+    /**
+     * Number of slices currently filled in
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_count;
+
+    /**
+     * Pointer to slice data buffer base
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    const uint8_t *slice_data;
+
+    /**
+     * Current size of slice data
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t slice_data_size;
+};
+
+/* @} */
+
+#endif /* AVCODEC_VAAPI_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/vda.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,151 @@
+/*
+ * VDA HW acceleration
+ *
+ * copyright (c) 2011 Sebastien Zwickert
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VDA_H
+#define AVCODEC_VDA_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_vda
+ * Public libavcodec VDA header.
+ */
+
+#include <stdint.h>
+
+// emmintrin.h is unable to compile with -std=c99 -Werror=missing-prototypes
+// http://openradar.appspot.com/8026390
+#undef __GNUC_STDC_INLINE__
+
+#define Picture QuickdrawPicture
+#include <VideoDecodeAcceleration/VDADecoder.h>
+#undef Picture
+
+#include "libavcodec/version.h"
+
+/**
+ * @defgroup lavc_codec_hwaccel_vda VDA
+ * @ingroup lavc_codec_hwaccel
+ *
+ * @{
+ */
+
+/**
+ * This structure is used to provide the necessary configurations and data
+ * to the VDA FFmpeg HWAccel implementation.
+ *
+ * The application must make it available as AVCodecContext.hwaccel_context.
+ */
+struct vda_context {
+    /**
+     * VDA decoder object.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by libavcodec.
+     */
+    VDADecoder          decoder;
+
+    /**
+     * The Core Video pixel buffer that contains the current image data.
+     *
+     * encoding: unused
+     * decoding: Set by libavcodec. Unset by user.
+     */
+    CVPixelBufferRef    cv_buffer;
+
+    /**
+     * Use the hardware decoder in synchronous mode.
+     *
+     * encoding: unused
+     * decoding: Set by user.
+     */
+    int                 use_sync_decoding;
+
+    /**
+     * The frame width.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by user.
+     */
+    int                 width;
+
+    /**
+     * The frame height.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by user.
+     */
+    int                 height;
+
+    /**
+     * The frame format.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by user.
+     */
+    int                 format;
+
+    /**
+     * The pixel format for output image buffers.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by user.
+     */
+    OSType              cv_pix_fmt_type;
+
+    /**
+     * The current bitstream buffer.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by libavcodec.
+     */
+    uint8_t             *priv_bitstream;
+
+    /**
+     * The current size of the bitstream.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by libavcodec.
+     */
+    int                 priv_bitstream_size;
+
+    /**
+     * The reference size used for fast reallocation.
+     *
+     * - encoding: unused
+     * - decoding: Set/Unset by libavcodec.
+     */
+    int                 priv_allocated_size;
+};
+
+/** Create the video decoder. */
+int ff_vda_create_decoder(struct vda_context *vda_ctx,
+                          uint8_t *extradata,
+                          int extradata_size);
+
+/** Destroy the video decoder. */
+int ff_vda_destroy_decoder(struct vda_context *vda_ctx);
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_VDA_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/vdpau.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,159 @@
+/*
+ * The Video Decode and Presentation API for UNIX (VDPAU) is used for
+ * hardware-accelerated decoding of MPEG-1/2, H.264 and VC-1.
+ *
+ * Copyright (C) 2008 NVIDIA
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VDPAU_H
+#define AVCODEC_VDPAU_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_vdpau
+ * Public libavcodec VDPAU header.
+ */
+
+
+/**
+ * @defgroup lavc_codec_hwaccel_vdpau VDPAU Decoder and Renderer
+ * @ingroup lavc_codec_hwaccel
+ *
+ * VDPAU hardware acceleration has two modules
+ * - VDPAU decoding
+ * - VDPAU presentation
+ *
+ * The VDPAU decoding module parses all headers using FFmpeg
+ * parsing mechanisms and uses VDPAU for the actual decoding.
+ *
+ * As per the current implementation, the actual decoding
+ * and rendering (API calls) are done as part of the VDPAU
+ * presentation (vo_vdpau.c) module.
+ *
+ * @{
+ */
+
+#include <vdpau/vdpau.h>
+#include <vdpau/vdpau_x11.h>
+#include "libavutil/avconfig.h"
+
+union FFVdpPictureInfo {
+    VdpPictureInfoH264        h264;
+    VdpPictureInfoMPEG1Or2    mpeg;
+    VdpPictureInfoVC1          vc1;
+    VdpPictureInfoMPEG4Part2 mpeg4;
+};
+
+/**
+ * This structure is used to share data between the libavcodec library and
+ * the client video application.
+ * The user shall zero-allocate the structure and make it available as
+ * AVCodecContext.hwaccel_context. Members can be set by the user once
+ * during initialization or through each AVCodecContext.get_buffer()
+ * function call. In any case, they must be valid prior to calling
+ * decoding functions.
+ */
+typedef struct AVVDPAUContext {
+    /**
+     * VDPAU decoder handle
+     *
+     * Set by user.
+     */
+    VdpDecoder decoder;
+
+    /**
+     * VDPAU decoder render callback
+     *
+     * Set by the user.
+     */
+    VdpDecoderRender *render;
+
+    /**
+     * VDPAU picture information
+     *
+     * Set by libavcodec.
+     */
+    union FFVdpPictureInfo info;
+
+    /**
+     * Allocated size of the bitstream_buffers table.
+     *
+     * Set by libavcodec.
+     */
+    int bitstream_buffers_allocated;
+
+    /**
+     * Useful bitstream buffers in the bitstream buffers table.
+     *
+     * Set by libavcodec.
+     */
+    int bitstream_buffers_used;
+
+   /**
+     * Table of bitstream buffers.
+     * The user is responsible for freeing this buffer using av_freep().
+     *
+     * Set by libavcodec.
+     */
+    VdpBitstreamBuffer *bitstream_buffers;
+} AVVDPAUContext;
+
+
+/** @brief The videoSurface is used for rendering. */
+#define FF_VDPAU_STATE_USED_FOR_RENDER 1
+
+/**
+ * @brief The videoSurface is needed for reference/prediction.
+ * The codec manipulates this.
+ */
+#define FF_VDPAU_STATE_USED_FOR_REFERENCE 2
+
+/**
+ * @brief This structure is used as a callback between the FFmpeg
+ * decoder (vd_) and presentation (vo_) module.
+ * This is used for defining a video frame containing surface,
+ * picture parameter, bitstream information etc which are passed
+ * between the FFmpeg decoder and its clients.
+ */
+struct vdpau_render_state {
+    VdpVideoSurface surface; ///< Used as rendered surface, never changed.
+
+    int state; ///< Holds FF_VDPAU_STATE_* values.
+
+#if AV_HAVE_INCOMPATIBLE_FORK_ABI
+    /** picture parameter information for all supported codecs */
+    union FFVdpPictureInfo info;
+#endif
+
+    /** Describe size/location of the compressed video data.
+        Set to 0 when freeing bitstream_buffers. */
+    int bitstream_buffers_allocated;
+    int bitstream_buffers_used;
+    /** The user is responsible for freeing this buffer using av_freep(). */
+    VdpBitstreamBuffer *bitstream_buffers;
+
+#if !AV_HAVE_INCOMPATIBLE_FORK_ABI
+    /** picture parameter information for all supported codecs */
+    union FFVdpPictureInfo info;
+#endif
+};
+
+/* @}*/
+
+#endif /* AVCODEC_VDPAU_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/version.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,95 @@
+/*
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VERSION_H
+#define AVCODEC_VERSION_H
+
+/**
+ * @file
+ * @ingroup libavc
+ * Libavcodec version macros.
+ */
+
+#include "../libavutil/avutil.h"
+
+#define LIBAVCODEC_VERSION_MAJOR 55
+#define LIBAVCODEC_VERSION_MINOR  11
+#define LIBAVCODEC_VERSION_MICRO 100
+
+#define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
+                                               LIBAVCODEC_VERSION_MINOR, \
+                                               LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_VERSION      AV_VERSION(LIBAVCODEC_VERSION_MAJOR,    \
+                                           LIBAVCODEC_VERSION_MINOR,    \
+                                           LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_BUILD        LIBAVCODEC_VERSION_INT
+
+#define LIBAVCODEC_IDENT        "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION)
+
+/**
+ * FF_API_* defines may be placed below to indicate public API that will be
+ * dropped at a future version bump. The defines themselves are not part of
+ * the public API and may change, break or disappear at any time.
+ */
+
+#ifndef FF_API_REQUEST_CHANNELS
+#define FF_API_REQUEST_CHANNELS (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_ALLOC_CONTEXT
+#define FF_API_ALLOC_CONTEXT    (LIBAVCODEC_VERSION_MAJOR < 55)
+#endif
+#ifndef FF_API_AVCODEC_OPEN
+#define FF_API_AVCODEC_OPEN     (LIBAVCODEC_VERSION_MAJOR < 55)
+#endif
+#ifndef FF_API_OLD_DECODE_AUDIO
+#define FF_API_OLD_DECODE_AUDIO (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_OLD_TIMECODE
+#define FF_API_OLD_TIMECODE (LIBAVCODEC_VERSION_MAJOR < 55)
+#endif
+
+#ifndef FF_API_OLD_ENCODE_AUDIO
+#define FF_API_OLD_ENCODE_AUDIO (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_OLD_ENCODE_VIDEO
+#define FF_API_OLD_ENCODE_VIDEO (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_CODEC_ID
+#define FF_API_CODEC_ID          (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_AVCODEC_RESAMPLE
+#define FF_API_AVCODEC_RESAMPLE  (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_DEINTERLACE
+#define FF_API_DEINTERLACE       (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_DESTRUCT_PACKET
+#define FF_API_DESTRUCT_PACKET   (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_GET_BUFFER
+#define FF_API_GET_BUFFER        (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_MISSING_SAMPLE
+#define FF_API_MISSING_SAMPLE    (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_LOWRES
+#define FF_API_LOWRES            (LIBAVCODEC_VERSION_MAJOR < 56)
+#endif
+
+#endif /* AVCODEC_VERSION_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavcodec/xvmc.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2003 Ivan Kalvachev
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_XVMC_H
+#define AVCODEC_XVMC_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_xvmc
+ * Public libavcodec XvMC header.
+ */
+
+#include <X11/extensions/XvMC.h>
+
+#include "avcodec.h"
+
+/**
+ * @defgroup lavc_codec_hwaccel_xvmc XvMC
+ * @ingroup lavc_codec_hwaccel
+ *
+ * @{
+ */
+
+#define AV_XVMC_ID                    0x1DC711C0  /**< special value to ensure that regular pixel routines haven't corrupted the struct
+                                                       the number is 1337 speak for the letters IDCT MCo (motion compensation) */
+
+struct xvmc_pix_fmt {
+    /** The field contains the special constant value AV_XVMC_ID.
+        It is used as a test that the application correctly uses the API,
+        and that there is no corruption caused by pixel routines.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             xvmc_id;
+
+    /** Pointer to the block array allocated by XvMCCreateBlocks().
+        The array has to be freed by XvMCDestroyBlocks().
+        Each group of 64 values represents one data block of differential
+        pixel information (in MoCo mode) or coefficients for IDCT.
+        - application - set the pointer during initialization
+        - libavcodec  - fills coefficients/pixel data into the array
+    */
+    short*          data_blocks;
+
+    /** Pointer to the macroblock description array allocated by
+        XvMCCreateMacroBlocks() and freed by XvMCDestroyMacroBlocks().
+        - application - set the pointer during initialization
+        - libavcodec  - fills description data into the array
+    */
+    XvMCMacroBlock* mv_blocks;
+
+    /** Number of macroblock descriptions that can be stored in the mv_blocks
+        array.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             allocated_mv_blocks;
+
+    /** Number of blocks that can be stored at once in the data_blocks array.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             allocated_data_blocks;
+
+    /** Indicate that the hardware would interpret data_blocks as IDCT
+        coefficients and perform IDCT on them.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             idct;
+
+    /** In MoCo mode it indicates that intra macroblocks are assumed to be in
+        unsigned format; same as the XVMC_INTRA_UNSIGNED flag.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             unsigned_intra;
+
+    /** Pointer to the surface allocated by XvMCCreateSurface().
+        It has to be freed by XvMCDestroySurface() on application exit.
+        It identifies the frame and its state on the video hardware.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    XvMCSurface*    p_surface;
+
+/** Set by the decoder before calling ff_draw_horiz_band(),
+    needed by the XvMCRenderSurface function. */
+//@{
+    /** Pointer to the surface used as past reference
+        - application - unchanged
+        - libavcodec  - set
+    */
+    XvMCSurface*    p_past_surface;
+
+    /** Pointer to the surface used as future reference
+        - application - unchanged
+        - libavcodec  - set
+    */
+    XvMCSurface*    p_future_surface;
+
+    /** top/bottom field or frame
+        - application - unchanged
+        - libavcodec  - set
+    */
+    unsigned int    picture_structure;
+
+    /** XVMC_SECOND_FIELD - 1st or 2nd field in the sequence
+        - application - unchanged
+        - libavcodec  - set
+    */
+    unsigned int    flags;
+//}@
+
+    /** Number of macroblock descriptions in the mv_blocks array
+        that have already been passed to the hardware.
+        - application - zeroes it on get_buffer().
+                        A successful ff_draw_horiz_band() may increment it
+                        with filled_mb_block_num or zero both.
+        - libavcodec  - unchanged
+    */
+    int             start_mv_blocks_num;
+
+    /** Number of new macroblock descriptions in the mv_blocks array (after
+        start_mv_blocks_num) that are filled by libavcodec and have to be
+        passed to the hardware.
+        - application - zeroes it on get_buffer() or after successful
+                        ff_draw_horiz_band().
+        - libavcodec  - increment with one of each stored MB
+    */
+    int             filled_mv_blocks_num;
+
+    /** Number of the next free data block; one data block consists of
+        64 short values in the data_blocks array.
+        All blocks before this one have already been claimed by placing their
+        position into the corresponding block description structure field,
+        that are part of the mv_blocks array.
+        - application - zeroes it on get_buffer().
+                        A successful ff_draw_horiz_band() may zero it together
+                        with start_mb_blocks_num.
+        - libavcodec  - each decoded macroblock increases it by the number
+                        of coded blocks it contains.
+    */
+    int             next_free_data_block_num;
+};
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_XVMC_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavformat/avformat.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,2174 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_AVFORMAT_H
+#define AVFORMAT_AVFORMAT_H
+
+/**
+ * @file
+ * @ingroup libavf
+ * Main libavformat public API header
+ */
+
+/**
+ * @defgroup libavf I/O and Muxing/Demuxing Library
+ * @{
+ *
+ * Libavformat (lavf) is a library for dealing with various media container
+ * formats. Its main two purposes are demuxing - i.e. splitting a media file
+ * into component streams, and the reverse process of muxing - writing supplied
+ * data in a specified container format. It also has an @ref lavf_io
+ * "I/O module" which supports a number of protocols for accessing the data (e.g.
+ * file, tcp, http and others). Before using lavf, you need to call
+ * av_register_all() to register all compiled muxers, demuxers and protocols.
+ * Unless you are absolutely sure you won't use libavformat's network
+ * capabilities, you should also call avformat_network_init().
+ *
+ * A supported input format is described by an AVInputFormat struct, conversely
+ * an output format is described by AVOutputFormat. You can iterate over all
+ * registered input/output formats using the av_iformat_next() /
+ * av_oformat_next() functions. The protocols layer is not part of the public
+ * API, so you can only get the names of supported protocols with the
+ * avio_enum_protocols() function.
+ *
+ * Main lavf structure used for both muxing and demuxing is AVFormatContext,
+ * which exports all information about the file being read or written. As with
+ * most Libavformat structures, its size is not part of public ABI, so it cannot be
+ * allocated on stack or directly with av_malloc(). To create an
+ * AVFormatContext, use avformat_alloc_context() (some functions, like
+ * avformat_open_input() might do that for you).
+ *
+ * Most importantly an AVFormatContext contains:
+ * @li the @ref AVFormatContext.iformat "input" or @ref AVFormatContext.oformat
+ * "output" format. It is either autodetected or set by user for input;
+ * always set by user for output.
+ * @li an @ref AVFormatContext.streams "array" of AVStreams, which describe all
+ * elementary streams stored in the file. AVStreams are typically referred to
+ * using their index in this array.
+ * @li an @ref AVFormatContext.pb "I/O context". It is either opened by lavf or
+ * set by user for input, always set by user for output (unless you are dealing
+ * with an AVFMT_NOFILE format).
+ *
+ * @section lavf_options Passing options to (de)muxers
+ * Lavf allows to configure muxers and demuxers using the @ref avoptions
+ * mechanism. Generic (format-independent) libavformat options are provided by
+ * AVFormatContext, they can be examined from a user program by calling
+ * av_opt_next() / av_opt_find() on an allocated AVFormatContext (or its AVClass
+ * from avformat_get_class()). Private (format-specific) options are provided by
+ * AVFormatContext.priv_data if and only if AVInputFormat.priv_class /
+ * AVOutputFormat.priv_class of the corresponding format struct is non-NULL.
+ * Further options may be provided by the @ref AVFormatContext.pb "I/O context",
+ * if its AVClass is non-NULL, and the protocols layer. See the discussion on
+ * nesting in @ref avoptions documentation to learn how to access those.
+ *
+ * @defgroup lavf_decoding Demuxing
+ * @{
+ * Demuxers read a media file and split it into chunks of data (@em packets). A
+ * @ref AVPacket "packet" contains one or more encoded frames which belongs to a
+ * single elementary stream. In the lavf API this process is represented by the
+ * avformat_open_input() function for opening a file, av_read_frame() for
+ * reading a single packet and finally avformat_close_input(), which does the
+ * cleanup.
+ *
+ * @section lavf_decoding_open Opening a media file
+ * The minimum information required to open a file is its URL or filename, which
+ * is passed to avformat_open_input(), as in the following code:
+ * @code
+ * const char    *url = "in.mp3";
+ * AVFormatContext *s = NULL;
+ * int ret = avformat_open_input(&s, url, NULL, NULL);
+ * if (ret < 0)
+ *     abort();
+ * @endcode
+ * The above code attempts to allocate an AVFormatContext, open the
+ * specified file (autodetecting the format) and read the header, exporting the
+ * information stored there into s. Some formats do not have a header or do not
+ * store enough information there, so it is recommended that you call the
+ * avformat_find_stream_info() function which tries to read and decode a few
+ * frames to find missing information.
+ *
+ * In some cases you might want to preallocate an AVFormatContext yourself with
+ * avformat_alloc_context() and do some tweaking on it before passing it to
+ * avformat_open_input(). One such case is when you want to use custom functions
+ * for reading input data instead of lavf internal I/O layer.
+ * To do that, create your own AVIOContext with avio_alloc_context(), passing
+ * your reading callbacks to it. Then set the @em pb field of your
+ * AVFormatContext to newly created AVIOContext.
+ *
+ * Since the format of the opened file is in general not known until after
+ * avformat_open_input() has returned, it is not possible to set demuxer private
+ * options on a preallocated context. Instead, the options should be passed to
+ * avformat_open_input() wrapped in an AVDictionary:
+ * @code
+ * AVDictionary *options = NULL;
+ * av_dict_set(&options, "video_size", "640x480", 0);
+ * av_dict_set(&options, "pixel_format", "rgb24", 0);
+ *
+ * if (avformat_open_input(&s, url, NULL, &options) < 0)
+ *     abort();
+ * av_dict_free(&options);
+ * @endcode
+ * This code passes the private options 'video_size' and 'pixel_format' to the
+ * demuxer. They would be necessary for e.g. the rawvideo demuxer, since it
+ * cannot know how to interpret raw video data otherwise. If the format turns
+ * out to be something different than raw video, those options will not be
+ * recognized by the demuxer and therefore will not be applied. Such unrecognized
+ * options are then returned in the options dictionary (recognized options are
+ * consumed). The calling program can handle such unrecognized options as it
+ * wishes, e.g.
+ * @code
+ * AVDictionaryEntry *e;
+ * if (e = av_dict_get(options, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
+ *     fprintf(stderr, "Option %s not recognized by the demuxer.\n", e->key);
+ *     abort();
+ * }
+ * @endcode
+ *
+ * After you have finished reading the file, you must close it with
+ * avformat_close_input(). It will free everything associated with the file.
+ *
+ * @section lavf_decoding_read Reading from an opened file
+ * Reading data from an opened AVFormatContext is done by repeatedly calling
+ * av_read_frame() on it. Each call, if successful, will return an AVPacket
+ * containing encoded data for one AVStream, identified by
+ * AVPacket.stream_index. This packet may be passed straight into the libavcodec
+ * decoding functions avcodec_decode_video2(), avcodec_decode_audio4() or
+ * avcodec_decode_subtitle2() if the caller wishes to decode the data.
+ *
+ * AVPacket.pts, AVPacket.dts and AVPacket.duration timing information will be
+ * set if known. They may also be unset (i.e. AV_NOPTS_VALUE for
+ * pts/dts, 0 for duration) if the stream does not provide them. The timing
+ * information will be in AVStream.time_base units, i.e. it has to be
+ * multiplied by the timebase to convert them to seconds.
+ *
+ * If AVPacket.buf is set on the returned packet, then the packet is
+ * allocated dynamically and the user may keep it indefinitely.
+ * Otherwise, if AVPacket.buf is NULL, the packet data is backed by a
+ * static storage somewhere inside the demuxer and the packet is only valid
+ * until the next av_read_frame() call or closing the file. If the caller
+ * requires a longer lifetime, av_dup_packet() will make an av_malloc()ed copy
+ * of it.
+ * In both cases, the packet must be freed with av_free_packet() when it is no
+ * longer needed.
+ *
+ * @section lavf_decoding_seek Seeking
+ * @}
+ *
+ * @defgroup lavf_encoding Muxing
+ * @{
+ * @}
+ *
+ * @defgroup lavf_io I/O Read/Write
+ * @{
+ * @}
+ *
+ * @defgroup lavf_codec Demuxers
+ * @{
+ * @defgroup lavf_codec_native Native Demuxers
+ * @{
+ * @}
+ * @defgroup lavf_codec_wrappers External library wrappers
+ * @{
+ * @}
+ * @}
+ * @defgroup lavf_protos I/O Protocols
+ * @{
+ * @}
+ * @defgroup lavf_internal Internal
+ * @{
+ * @}
+ * @}
+ *
+ */
+
+#include <time.h>
+#include <stdio.h>  /* FILE */
+#include "../libavcodec/avcodec.h"
+#include "../libavutil/dict.h"
+#include "../libavutil/log.h"
+
+#include "avio.h"
+#include "version.h"
+
+struct AVFormatContext;
+
+
+/**
+ * @defgroup metadata_api Public Metadata API
+ * @{
+ * @ingroup libavf
+ * The metadata API allows libavformat to export metadata tags to a client
+ * application when demuxing. Conversely it allows a client application to
+ * set metadata when muxing.
+ *
+ * Metadata is exported or set as pairs of key/value strings in the 'metadata'
+ * fields of the AVFormatContext, AVStream, AVChapter and AVProgram structs
+ * using the @ref lavu_dict "AVDictionary" API. Like all strings in FFmpeg,
+ * metadata is assumed to be UTF-8 encoded Unicode. Note that metadata
+ * exported by demuxers isn't checked to be valid UTF-8 in most cases.
+ *
+ * Important concepts to keep in mind:
+ * -  Keys are unique; there can never be 2 tags with the same key. This is
+ *    also meant semantically, i.e., a demuxer should not knowingly produce
+ *    several keys that are literally different but semantically identical.
+ *    E.g., key=Author5, key=Author6. In this example, all authors must be
+ *    placed in the same tag.
+ * -  Metadata is flat, not hierarchical; there are no subtags. If you
+ *    want to store, e.g., the email address of the child of producer Alice
+ *    and actor Bob, that could have key=alice_and_bobs_childs_email_address.
+ * -  Several modifiers can be applied to the tag name. This is done by
+ *    appending a dash character ('-') and the modifier name in the order
+ *    they appear in the list below -- e.g. foo-eng-sort, not foo-sort-eng.
+ *    -  language -- a tag whose value is localized for a particular language
+ *       is appended with the ISO 639-2/B 3-letter language code.
+ *       For example: Author-ger=Michael, Author-eng=Mike
+ *       The original/default language is in the unqualified "Author" tag.
+ *       A demuxer should set a default if it sets any translated tag.
+ *    -  sorting  -- a modified version of a tag that should be used for
+ *       sorting will have '-sort' appended. E.g. artist="The Beatles",
+ *       artist-sort="Beatles, The".
+ *
+ * -  Demuxers attempt to export metadata in a generic format, however tags
+ *    with no generic equivalents are left as they are stored in the container.
+ *    Follows a list of generic tag names:
+ *
+ @verbatim
+ album        -- name of the set this work belongs to
+ album_artist -- main creator of the set/album, if different from artist.
+                 e.g. "Various Artists" for compilation albums.
+ artist       -- main creator of the work
+ comment      -- any additional description of the file.
+ composer     -- who composed the work, if different from artist.
+ copyright    -- name of copyright holder.
+ creation_time-- date when the file was created, preferably in ISO 8601.
+ date         -- date when the work was created, preferably in ISO 8601.
+ disc         -- number of a subset, e.g. disc in a multi-disc collection.
+ encoder      -- name/settings of the software/hardware that produced the file.
+ encoded_by   -- person/group who created the file.
+ filename     -- original name of the file.
+ genre        -- <self-evident>.
+ language     -- main language in which the work is performed, preferably
+                 in ISO 639-2 format. Multiple languages can be specified by
+                 separating them with commas.
+ performer    -- artist who performed the work, if different from artist.
+                 E.g for "Also sprach Zarathustra", artist would be "Richard
+                 Strauss" and performer "London Philharmonic Orchestra".
+ publisher    -- name of the label/publisher.
+ service_name     -- name of the service in broadcasting (channel name).
+ service_provider -- name of the service provider in broadcasting.
+ title        -- name of the work.
+ track        -- number of this work in the set, can be in form current/total.
+ variant_bitrate -- the total bitrate of the bitrate variant that the current stream is part of
+ @endverbatim
+ *
+ * Look in the examples section for an application example how to use the Metadata API.
+ *
+ * @}
+ */
+
+/* packet functions */
+
+
+/**
+ * Allocate and read the payload of a packet and initialize its
+ * fields with default values.
+ *
+ * @param pkt packet
+ * @param size desired payload size
+ * @return >0 (read size) if OK, AVERROR_xxx otherwise
+ */
+int av_get_packet(AVIOContext *s, AVPacket *pkt, int size);
+
+
+/**
+ * Read data and append it to the current content of the AVPacket.
+ * If pkt->size is 0 this is identical to av_get_packet.
+ * Note that this uses av_grow_packet and thus involves a realloc
+ * which is inefficient. Thus this function should only be used
+ * when there is no reasonable way to know (an upper bound of)
+ * the final size.
+ *
+ * @param pkt packet
+ * @param size amount of data to read
+ * @return >0 (read size) if OK, AVERROR_xxx otherwise, previous data
+ *         will not be lost even if an error occurs.
+ */
+int av_append_packet(AVIOContext *s, AVPacket *pkt, int size);
+
+/*************************************************/
+/* fractional numbers for exact pts handling */
+
+/**
+ * The exact value of the fractional number is: 'val + num / den'.
+ * num is assumed to be 0 <= num < den.
+ */
+typedef struct AVFrac {
+    int64_t val, num, den;
+} AVFrac;
+
+/*************************************************/
+/* input/output formats */
+
+struct AVCodecTag;
+
+/**
+ * This structure contains the data a format has to probe a file.
+ */
+typedef struct AVProbeData {
+    const char *filename;
+    unsigned char *buf; /**< Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero. */
+    int buf_size;       /**< Size of buf except extra allocated bytes */
+} AVProbeData;
+
+#define AVPROBE_SCORE_RETRY (AVPROBE_SCORE_MAX/4)
+#define AVPROBE_SCORE_EXTENSION  50 ///< score for file extension
+#define AVPROBE_SCORE_MAX       100 ///< maximum score
+
+#define AVPROBE_PADDING_SIZE 32             ///< extra allocated bytes at the end of the probe buffer
+
+/// Demuxer will use avio_open, no opened file should be provided by the caller.
+#define AVFMT_NOFILE        0x0001
+#define AVFMT_NEEDNUMBER    0x0002 /**< Needs '%d' in filename. */
+#define AVFMT_SHOW_IDS      0x0008 /**< Show format stream IDs numbers. */
+#define AVFMT_RAWPICTURE    0x0020 /**< Format wants AVPicture structure for
+                                      raw picture data. */
+#define AVFMT_GLOBALHEADER  0x0040 /**< Format wants global header. */
+#define AVFMT_NOTIMESTAMPS  0x0080 /**< Format does not need / have any timestamps. */
+#define AVFMT_GENERIC_INDEX 0x0100 /**< Use generic index building code. */
+#define AVFMT_TS_DISCONT    0x0200 /**< Format allows timestamp discontinuities. Note, muxers always require valid (monotone) timestamps */
+#define AVFMT_VARIABLE_FPS  0x0400 /**< Format allows variable fps. */
+#define AVFMT_NODIMENSIONS  0x0800 /**< Format does not need width/height */
+#define AVFMT_NOSTREAMS     0x1000 /**< Format does not require any streams */
+#define AVFMT_NOBINSEARCH   0x2000 /**< Format does not allow to fall back on binary search via read_timestamp */
+#define AVFMT_NOGENSEARCH   0x4000 /**< Format does not allow to fall back on generic search */
+#define AVFMT_NO_BYTE_SEEK  0x8000 /**< Format does not allow seeking by bytes */
+#define AVFMT_ALLOW_FLUSH  0x10000 /**< Format allows flushing. If not set, the muxer will not receive a NULL packet in the write_packet function. */
+#if LIBAVFORMAT_VERSION_MAJOR <= 54
+#define AVFMT_TS_NONSTRICT 0x8020000 //we try to be compatible to the ABIs of ffmpeg and major forks
+#else
+#define AVFMT_TS_NONSTRICT 0x20000
+#endif
+                                   /**< Format does not require strictly
+                                        increasing timestamps, but they must
+                                        still be monotonic */
+#define AVFMT_TS_NEGATIVE  0x40000 /**< Format allows muxing negative
+                                        timestamps. If not set the timestamp
+                                        will be shifted in av_write_frame and
+                                        av_interleaved_write_frame so they
+                                        start from 0.
+                                        The user or muxer can override this through
+                                        AVFormatContext.avoid_negative_ts
+                                        */
+
+#define AVFMT_SEEK_TO_PTS   0x4000000 /**< Seeking is based on PTS */
+
+/**
+ * @addtogroup lavf_encoding
+ * @{
+ */
+typedef struct AVOutputFormat {
+    const char *name;
+    /**
+     * Descriptive name for the format, meant to be more human-readable
+     * than name. You should use the NULL_IF_CONFIG_SMALL() macro
+     * to define it.
+     */
+    const char *long_name;
+    const char *mime_type;
+    const char *extensions; /**< comma-separated filename extensions */
+    /* output support */
+    enum AVCodecID audio_codec;    /**< default audio codec */
+    enum AVCodecID video_codec;    /**< default video codec */
+    enum AVCodecID subtitle_codec; /**< default subtitle codec */
+    /**
+     * can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_RAWPICTURE,
+     * AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS,
+     * AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS, AVFMT_ALLOW_FLUSH,
+     * AVFMT_TS_NONSTRICT
+     */
+    int flags;
+
+    /**
+     * List of supported codec_id-codec_tag pairs, ordered by "better
+     * choice first". The arrays are all terminated by AV_CODEC_ID_NONE.
+     */
+    const struct AVCodecTag * const *codec_tag;
+
+
+    const AVClass *priv_class; ///< AVClass for the private context
+
+    /*****************************************************************
+     * No fields below this line are part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+    struct AVOutputFormat *next;
+    /**
+     * size of private data so that it can be allocated in the wrapper
+     */
+    int priv_data_size;
+
+    int (*write_header)(struct AVFormatContext *);
+    /**
+     * Write a packet. If AVFMT_ALLOW_FLUSH is set in flags,
+     * pkt can be NULL in order to flush data buffered in the muxer.
+     * When flushing, return 0 if there still is more data to flush,
+     * or 1 if everything was flushed and there is no more buffered
+     * data.
+     */
+    int (*write_packet)(struct AVFormatContext *, AVPacket *pkt);
+    int (*write_trailer)(struct AVFormatContext *);
+    /**
+     * Currently only used to set pixel format if not YUV420P.
+     */
+    int (*interleave_packet)(struct AVFormatContext *, AVPacket *out,
+                             AVPacket *in, int flush);
+    /**
+     * Test if the given codec can be stored in this container.
+     *
+     * @return 1 if the codec is supported, 0 if it is not.
+     *         A negative number if unknown.
+     *         MKTAG('A', 'P', 'I', 'C') if the codec is only supported as AV_DISPOSITION_ATTACHED_PIC
+     */
+    int (*query_codec)(enum AVCodecID id, int std_compliance);
+
+    void (*get_output_timestamp)(struct AVFormatContext *s, int stream,
+                                 int64_t *dts, int64_t *wall);
+} AVOutputFormat;
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavf_decoding
+ * @{
+ */
+typedef struct AVInputFormat {
+    /**
+     * A comma separated list of short names for the format. New names
+     * may be appended with a minor bump.
+     */
+    const char *name;
+
+    /**
+     * Descriptive name for the format, meant to be more human-readable
+     * than name. You should use the NULL_IF_CONFIG_SMALL() macro
+     * to define it.
+     */
+    const char *long_name;
+
+    /**
+     * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS,
+     * AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH,
+     * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS.
+     */
+    int flags;
+
+    /**
+     * If extensions are defined, then no probe is done. You should
+     * usually not use extension format guessing because it is not
+     * reliable enough
+     */
+    const char *extensions;
+
+    const struct AVCodecTag * const *codec_tag;
+
+    const AVClass *priv_class; ///< AVClass for the private context
+
+    /*****************************************************************
+     * No fields below this line are part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+    struct AVInputFormat *next;
+
+    /**
+     * Raw demuxers store their codec ID here.
+     */
+    int raw_codec_id;
+
+    /**
+     * Size of private data so that it can be allocated in the wrapper.
+     */
+    int priv_data_size;
+
+    /**
+     * Tell if a given file has a chance of being parsed as this format.
+     * The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes
+     * big so you do not have to check for that unless you need more.
+     */
+    int (*read_probe)(AVProbeData *);
+
+    /**
+     * Read the format header and initialize the AVFormatContext
+     * structure. Return 0 if OK. Only used in raw format right
+     * now. 'avformat_new_stream' should be called to create new streams.
+     */
+    int (*read_header)(struct AVFormatContext *);
+
+    /**
+     * Read one packet and put it in 'pkt'. pts and flags are also
+     * set. 'avformat_new_stream' can be called only if the flag
+     * AVFMTCTX_NOHEADER is used and only in the calling thread (not in a
+     * background thread).
+     * @return 0 on success, < 0 on error.
+     *         When returning an error, pkt must not have been allocated
+     *         or must be freed before returning
+     */
+    int (*read_packet)(struct AVFormatContext *, AVPacket *pkt);
+
+    /**
+     * Close the stream. The AVFormatContext and AVStreams are not
+     * freed by this function
+     */
+    int (*read_close)(struct AVFormatContext *);
+
+    /**
+     * Seek to a given timestamp relative to the frames in
+     * stream component stream_index.
+     * @param stream_index Must not be -1.
+     * @param flags Selects which direction should be preferred if no exact
+     *              match is available.
+     * @return >= 0 on success (but not necessarily the new offset)
+     */
+    int (*read_seek)(struct AVFormatContext *,
+                     int stream_index, int64_t timestamp, int flags);
+
+    /**
+     * Get the next timestamp in stream[stream_index].time_base units.
+     * @return the timestamp or AV_NOPTS_VALUE if an error occurred
+     */
+    int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index,
+                              int64_t *pos, int64_t pos_limit);
+
+    /**
+     * Start/resume playing - only meaningful if using a network-based format
+     * (RTSP).
+     */
+    int (*read_play)(struct AVFormatContext *);
+
+    /**
+     * Pause playing - only meaningful if using a network-based format
+     * (RTSP).
+     */
+    int (*read_pause)(struct AVFormatContext *);
+
+    /**
+     * Seek to timestamp ts.
+     * Seeking will be done so that the point from which all active streams
+     * can be presented successfully will be closest to ts and within min/max_ts.
+     * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL.
+     */
+    int (*read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
+} AVInputFormat;
+/**
+ * @}
+ */
+
+enum AVStreamParseType {
+    AVSTREAM_PARSE_NONE,
+    AVSTREAM_PARSE_FULL,       /**< full parsing and repack */
+    AVSTREAM_PARSE_HEADERS,    /**< Only parse headers, do not repack. */
+    AVSTREAM_PARSE_TIMESTAMPS, /**< full parsing and interpolation of timestamps for frames not starting on a packet boundary */
+    AVSTREAM_PARSE_FULL_ONCE,  /**< full parsing and repack of the first frame only, only implemented for H.264 currently */
+    AVSTREAM_PARSE_FULL_RAW=MKTAG(0,'R','A','W'),       /**< full parsing and repack with timestamp and position generation by parser for raw
+                                                             this assumes that each packet in the file contains no demuxer level headers and
+                                                             just codec level data, otherwise position generation would fail */
+};
+
+typedef struct AVIndexEntry {
+    int64_t pos;
+    int64_t timestamp;        /**<
+                               * Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are available
+                               * when seeking to this entry. That means preferable PTS on keyframe based formats.
+                               * But demuxers can choose to store a different timestamp, if it is more convenient for the implementation or nothing better
+                               * is known
+                               */
+#define AVINDEX_KEYFRAME 0x0001
+    int flags:2;
+    int size:30; //Yeah, trying to keep the size of this small to reduce memory requirements (it is 24 vs. 32 bytes due to possible 8-byte alignment).
+    int min_distance;         /**< Minimum distance between this and the previous keyframe, used to avoid unneeded searching. */
+} AVIndexEntry;
+
+#define AV_DISPOSITION_DEFAULT   0x0001
+#define AV_DISPOSITION_DUB       0x0002
+#define AV_DISPOSITION_ORIGINAL  0x0004
+#define AV_DISPOSITION_COMMENT   0x0008
+#define AV_DISPOSITION_LYRICS    0x0010
+#define AV_DISPOSITION_KARAOKE   0x0020
+
+/**
+ * Track should be used during playback by default.
+ * Useful for subtitle track that should be displayed
+ * even when user did not explicitly ask for subtitles.
+ */
+#define AV_DISPOSITION_FORCED    0x0040
+#define AV_DISPOSITION_HEARING_IMPAIRED  0x0080  /**< stream for hearing impaired audiences */
+#define AV_DISPOSITION_VISUAL_IMPAIRED   0x0100  /**< stream for visual impaired audiences */
+#define AV_DISPOSITION_CLEAN_EFFECTS     0x0200  /**< stream without voice */
+/**
+ * The stream is stored in the file as an attached picture/"cover art" (e.g.
+ * APIC frame in ID3v2). The single packet associated with it will be returned
+ * among the first few packets read from the file unless seeking takes place.
+ * It can also be accessed at any time in AVStream.attached_pic.
+ */
+#define AV_DISPOSITION_ATTACHED_PIC      0x0400
+
+/**
+ * Options for behavior on timestamp wrap detection.
+ */
+#define AV_PTS_WRAP_IGNORE      0   ///< ignore the wrap
+#define AV_PTS_WRAP_ADD_OFFSET  1   ///< add the format specific offset on wrap detection
+#define AV_PTS_WRAP_SUB_OFFSET  -1  ///< subtract the format specific offset on wrap detection
+
+/**
+ * Stream structure.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVStream) must not be used outside libav*.
+ */
+typedef struct AVStream {
+    int index;    /**< stream index in AVFormatContext */
+    /**
+     * Format-specific stream ID.
+     * decoding: set by libavformat
+     * encoding: set by the user, replaced by libavformat if left unset
+     */
+    int id;
+    /**
+     * Codec context associated with this stream. Allocated and freed by
+     * libavformat.
+     *
+     * - decoding: The demuxer exports codec information stored in the headers
+     *             here.
+     * - encoding: The user sets codec information, the muxer writes it to the
+     *             output. Mandatory fields as specified in AVCodecContext
+     *             documentation must be set even if this AVCodecContext is
+     *             not actually used for encoding.
+     */
+    AVCodecContext *codec;
+    void *priv_data;
+
+    /**
+     * encoding: pts generation when outputting stream
+     */
+    struct AVFrac pts;
+
+    /**
+     * This is the fundamental unit of time (in seconds) in terms
+     * of which frame timestamps are represented.
+     *
+     * decoding: set by libavformat
+     * encoding: set by libavformat in avformat_write_header. The muxer may use the
+     * user-provided value of @ref AVCodecContext.time_base "codec->time_base"
+     * as a hint.
+     */
+    AVRational time_base;
+
+    /**
+     * Decoding: pts of the first frame of the stream in presentation order, in stream time base.
+     * Only set this if you are absolutely 100% sure that the value you set
+     * it to really is the pts of the first frame.
+     * This may be undefined (AV_NOPTS_VALUE).
+     * @note The ASF header does NOT contain a correct start_time the ASF
+     * demuxer must NOT set this.
+     */
+    int64_t start_time;
+
+    /**
+     * Decoding: duration of the stream, in stream time base.
+     * If a source file does not specify a duration, but does specify
+     * a bitrate, this value will be estimated from bitrate and file size.
+     */
+    int64_t duration;
+
+    int64_t nb_frames;                 ///< number of frames in this stream if known or 0
+
+    int disposition; /**< AV_DISPOSITION_* bit field */
+
+    enum AVDiscard discard; ///< Selects which packets can be discarded at will and do not need to be demuxed.
+
+    /**
+     * sample aspect ratio (0 if unknown)
+     * - encoding: Set by user.
+     * - decoding: Set by libavformat.
+     */
+    AVRational sample_aspect_ratio;
+
+    AVDictionary *metadata;
+
+    /**
+     * Average framerate
+     */
+    AVRational avg_frame_rate;
+
+    /**
+     * For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet
+     * will contain the attached picture.
+     *
+     * decoding: set by libavformat, must not be modified by the caller.
+     * encoding: unused
+     */
+    AVPacket attached_pic;
+
+    /**
+     * Real base framerate of the stream.
+     * This is the lowest framerate with which all timestamps can be
+     * represented accurately (it is the least common multiple of all
+     * framerates in the stream). Note, this value is just a guess!
+     * For example, if the time base is 1/90000 and all frames have either
+     * approximately 3600 or 1800 timer ticks, then r_frame_rate will be 50/1.
+     *
+     * Code outside avformat should access this field using:
+     * av_stream_get/set_r_frame_rate(stream)
+     */
+    AVRational r_frame_rate;
+
+    /*****************************************************************
+     * All fields below this line are not part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+
+    /**
+     * Stream information used internally by av_find_stream_info()
+     */
+#define MAX_STD_TIMEBASES (60*12+6)
+    struct {
+        int64_t last_dts;
+        int64_t duration_gcd;
+        int duration_count;
+        double (*duration_error)[2][MAX_STD_TIMEBASES];
+        int64_t codec_info_duration;
+        int64_t codec_info_duration_fields;
+        int found_decoder;
+
+        int64_t last_duration;
+
+        /**
+         * Those are used for average framerate estimation.
+         */
+        int64_t fps_first_dts;
+        int     fps_first_dts_idx;
+        int64_t fps_last_dts;
+        int     fps_last_dts_idx;
+
+    } *info;
+
+    int pts_wrap_bits; /**< number of bits in pts (used for wrapping control) */
+
+    // Timestamp generation support:
+    /**
+     * Timestamp corresponding to the last dts sync point.
+     *
+     * Initialized when AVCodecParserContext.dts_sync_point >= 0 and
+     * a DTS is received from the underlying container. Otherwise set to
+     * AV_NOPTS_VALUE by default.
+     */
+    int64_t reference_dts;
+    int64_t first_dts;
+    int64_t cur_dts;
+    int64_t last_IP_pts;
+    int last_IP_duration;
+
+    /**
+     * Number of packets to buffer for codec probing
+     */
+#define MAX_PROBE_PACKETS 2500
+    int probe_packets;
+
+    /**
+     * Number of frames that have been demuxed during av_find_stream_info()
+     */
+    int codec_info_nb_frames;
+
+    /**
+     * Stream Identifier
+     * This is the MPEG-TS stream identifier +1
+     * 0 means unknown
+     */
+    int stream_identifier;
+
+    int64_t interleaver_chunk_size;
+    int64_t interleaver_chunk_duration;
+
+    /* av_read_frame() support */
+    enum AVStreamParseType need_parsing;
+    struct AVCodecParserContext *parser;
+
+    /**
+     * last packet in packet_buffer for this stream when muxing.
+     */
+    struct AVPacketList *last_in_packet_buffer;
+    AVProbeData probe_data;
+#define MAX_REORDER_DELAY 16
+    int64_t pts_buffer[MAX_REORDER_DELAY+1];
+
+    AVIndexEntry *index_entries; /**< Only used if the format does not
+                                    support seeking natively. */
+    int nb_index_entries;
+    unsigned int index_entries_allocated_size;
+
+    /**
+     * stream probing state
+     * -1   -> probing finished
+     *  0   -> no probing requested
+     * rest -> perform probing with request_probe being the minimum score to accept.
+     * NOT PART OF PUBLIC API
+     */
+    int request_probe;
+    /**
+     * Indicates that everything up to the next keyframe
+     * should be discarded.
+     */
+    int skip_to_keyframe;
+
+    /**
+     * Number of samples to skip at the start of the frame decoded from the next packet.
+     */
+    int skip_samples;
+
+    /**
+     * Number of internally decoded frames, used internally in libavformat, do not access
+     * its lifetime differs from info which is why it is not in that structure.
+     */
+    int nb_decoded_frames;
+
+    /**
+     * Timestamp offset added to timestamps before muxing
+     * NOT PART OF PUBLIC API
+     */
+    int64_t mux_ts_offset;
+
+    /**
+     * Internal data to check for wrapping of the time stamp
+     */
+    int64_t pts_wrap_reference;
+
+    /**
+     * Options for behavior, when a wrap is detected.
+     *
+     * Defined by AV_PTS_WRAP_ values.
+     *
+     * If correction is enabled, there are two possibilities:
+     * If the first time stamp is near the wrap point, the wrap offset
+     * will be subtracted, which will create negative time stamps.
+     * Otherwise the offset will be added.
+     */
+    int pts_wrap_behavior;
+
+} AVStream;
+
+AVRational av_stream_get_r_frame_rate(const AVStream *s);
+void       av_stream_set_r_frame_rate(AVStream *s, AVRational r);
+
+#define AV_PROGRAM_RUNNING 1
+
+/**
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVProgram) must not be used outside libav*.
+ */
+typedef struct AVProgram {
+    int            id;
+    int            flags;
+    enum AVDiscard discard;        ///< selects which program to discard and which to feed to the caller
+    unsigned int   *stream_index;
+    unsigned int   nb_stream_indexes;
+    AVDictionary *metadata;
+
+    int program_num;
+    int pmt_pid;
+    int pcr_pid;
+
+    /*****************************************************************
+     * All fields below this line are not part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+    int64_t start_time;
+    int64_t end_time;
+
+    int64_t pts_wrap_reference;    ///< reference dts for wrap detection
+    int pts_wrap_behavior;         ///< behavior on wrap detection
+} AVProgram;
+
+#define AVFMTCTX_NOHEADER      0x0001 /**< signal that no header is present
+                                         (streams are added dynamically) */
+
+typedef struct AVChapter {
+    int id;                 ///< unique ID to identify the chapter
+    AVRational time_base;   ///< time base in which the start/end timestamps are specified
+    int64_t start, end;     ///< chapter start/end time in time_base units
+    AVDictionary *metadata;
+} AVChapter;
+
+
+/**
+ * The duration of a video can be estimated through various ways, and this enum can be used
+ * to know how the duration was estimated.
+ */
+enum AVDurationEstimationMethod {
+    AVFMT_DURATION_FROM_PTS,    ///< Duration accurately estimated from PTSes
+    AVFMT_DURATION_FROM_STREAM, ///< Duration estimated from a stream with a known duration
+    AVFMT_DURATION_FROM_BITRATE ///< Duration estimated from bitrate (less accurate)
+};
+
+/**
+ * Format I/O context.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVFormatContext) must not be used outside libav*, use
+ * avformat_alloc_context() to create an AVFormatContext.
+ */
+typedef struct AVFormatContext {
+    /**
+     * A class for logging and AVOptions. Set by avformat_alloc_context().
+     * Exports (de)muxer private options if they exist.
+     */
+    const AVClass *av_class;
+
+    /**
+     * Can only be iformat or oformat, not both at the same time.
+     *
+     * decoding: set by avformat_open_input().
+     * encoding: set by the user.
+     */
+    struct AVInputFormat *iformat;
+    struct AVOutputFormat *oformat;
+
+    /**
+     * Format private data. This is an AVOptions-enabled struct
+     * if and only if iformat/oformat.priv_class is not NULL.
+     */
+    void *priv_data;
+
+    /**
+     * I/O context.
+     *
+     * decoding: either set by the user before avformat_open_input() (then
+     * the user must close it manually) or set by avformat_open_input().
+     * encoding: set by the user.
+     *
+     * Do NOT set this field if AVFMT_NOFILE flag is set in
+     * iformat/oformat.flags. In such a case, the (de)muxer will handle
+     * I/O in some other way and this field will be NULL.
+     */
+    AVIOContext *pb;
+
+    /* stream info */
+    int ctx_flags; /**< Format-specific flags, see AVFMTCTX_xx */
+
+    /**
+     * A list of all streams in the file. New streams are created with
+     * avformat_new_stream().
+     *
+     * decoding: streams are created by libavformat in avformat_open_input().
+     * If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams may also
+     * appear in av_read_frame().
+     * encoding: streams are created by the user before avformat_write_header().
+     */
+    unsigned int nb_streams;
+    AVStream **streams;
+
+    char filename[1024]; /**< input or output filename */
+
+    /**
+     * Decoding: position of the first frame of the component, in
+     * AV_TIME_BASE fractional seconds. NEVER set this value directly:
+     * It is deduced from the AVStream values.
+     */
+    int64_t start_time;
+
+    /**
+     * Decoding: duration of the stream, in AV_TIME_BASE fractional
+     * seconds. Only set this value if you know none of the individual stream
+     * durations and also do not set any of them. This is deduced from the
+     * AVStream values if not set.
+     */
+    int64_t duration;
+
+    /**
+     * Decoding: total stream bitrate in bit/s, 0 if not
+     * available. Never set it directly if the file_size and the
+     * duration are known as FFmpeg can compute it automatically.
+     */
+    int bit_rate;
+
+    unsigned int packet_size;
+    int max_delay;
+
+    int flags;
+#define AVFMT_FLAG_GENPTS       0x0001 ///< Generate missing pts even if it requires parsing future frames.
+#define AVFMT_FLAG_IGNIDX       0x0002 ///< Ignore index.
+#define AVFMT_FLAG_NONBLOCK     0x0004 ///< Do not block when reading packets from input.
+#define AVFMT_FLAG_IGNDTS       0x0008 ///< Ignore DTS on frames that contain both DTS & PTS
+#define AVFMT_FLAG_NOFILLIN     0x0010 ///< Do not infer any values from other values, just return what is stored in the container
+#define AVFMT_FLAG_NOPARSE      0x0020 ///< Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fillin code works on frames and no parsing -> no frames. Also seeking to frames can not work if parsing to find frame boundaries has been disabled
+#define AVFMT_FLAG_NOBUFFER     0x0040 ///< Do not buffer frames when possible
+#define AVFMT_FLAG_CUSTOM_IO    0x0080 ///< The caller has supplied a custom AVIOContext, don't avio_close() it.
+#define AVFMT_FLAG_DISCARD_CORRUPT  0x0100 ///< Discard frames marked corrupted
+#define AVFMT_FLAG_MP4A_LATM    0x8000 ///< Enable RTP MP4A-LATM payload
+#define AVFMT_FLAG_SORT_DTS    0x10000 ///< try to interleave outputted packets by dts (using this flag can slow demuxing down)
+#define AVFMT_FLAG_PRIV_OPT    0x20000 ///< Enable use of private options by delaying codec open (this could be made default once all code is converted)
+#define AVFMT_FLAG_KEEP_SIDE_DATA 0x40000 ///< Don't merge side data but keep it separate.
+
+    /**
+     * decoding: size of data to probe; encoding: unused.
+     */
+    unsigned int probesize;
+
+    /**
+     * decoding: maximum time (in AV_TIME_BASE units) during which the input should
+     * be analyzed in avformat_find_stream_info().
+     */
+    int max_analyze_duration;
+
+    const uint8_t *key;
+    int keylen;
+
+    unsigned int nb_programs;
+    AVProgram **programs;
+
+    /**
+     * Forced video codec_id.
+     * Demuxing: Set by user.
+     */
+    enum AVCodecID video_codec_id;
+
+    /**
+     * Forced audio codec_id.
+     * Demuxing: Set by user.
+     */
+    enum AVCodecID audio_codec_id;
+
+    /**
+     * Forced subtitle codec_id.
+     * Demuxing: Set by user.
+     */
+    enum AVCodecID subtitle_codec_id;
+
+    /**
+     * Maximum amount of memory in bytes to use for the index of each stream.
+     * If the index exceeds this size, entries will be discarded as
+     * needed to maintain a smaller size. This can lead to slower or less
+     * accurate seeking (depends on demuxer).
+     * Demuxers for which a full in-memory index is mandatory will ignore
+     * this.
+     * muxing  : unused
+     * demuxing: set by user
+     */
+    unsigned int max_index_size;
+
+    /**
+     * Maximum amount of memory in bytes to use for buffering frames
+     * obtained from realtime capture devices.
+     */
+    unsigned int max_picture_buffer;
+
+    unsigned int nb_chapters;
+    AVChapter **chapters;
+
+    AVDictionary *metadata;
+
+    /**
+     * Start time of the stream in real world time, in microseconds
+     * since the unix epoch (00:00 1st January 1970). That is, pts=0
+     * in the stream was captured at this real world time.
+     * - encoding: Set by user.
+     * - decoding: Unused.
+     */
+    int64_t start_time_realtime;
+
+    /**
+     * decoding: number of frames used to probe fps
+     */
+    int fps_probe_size;
+
+    /**
+     * Error recognition; higher values will detect more errors but may
+     * misdetect some more or less valid parts as errors.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int error_recognition;
+
+    /**
+     * Custom interrupt callbacks for the I/O layer.
+     *
+     * decoding: set by the user before avformat_open_input().
+     * encoding: set by the user before avformat_write_header()
+     * (mainly useful for AVFMT_NOFILE formats). The callback
+     * should also be passed to avio_open2() if it's used to
+     * open the file.
+     */
+    AVIOInterruptCB interrupt_callback;
+
+    /**
+     * Flags to enable debugging.
+     */
+    int debug;
+#define FF_FDEBUG_TS        0x0001
+
+    /**
+     * Transport stream id.
+     * This will be moved into demuxer private options. Thus no API/ABI compatibility
+     */
+    int ts_id;
+
+    /**
+     * Audio preload in microseconds.
+     * Note, not all formats support this and unpredictable things may happen if it is used when not supported.
+     * - encoding: Set by user via AVOptions (NO direct access)
+     * - decoding: unused
+     */
+    int audio_preload;
+
+    /**
+     * Max chunk time in microseconds.
+     * Note, not all formats support this and unpredictable things may happen if it is used when not supported.
+     * - encoding: Set by user via AVOptions (NO direct access)
+     * - decoding: unused
+     */
+    int max_chunk_duration;
+
+    /**
+     * Max chunk size in bytes
+     * Note, not all formats support this and unpredictable things may happen if it is used when not supported.
+     * - encoding: Set by user via AVOptions (NO direct access)
+     * - decoding: unused
+     */
+    int max_chunk_size;
+
+    /**
+     * forces the use of wallclock timestamps as pts/dts of packets
+     * This has undefined results in the presence of B frames.
+     * - encoding: unused
+     * - decoding: Set by user via AVOptions (NO direct access)
+     */
+    int use_wallclock_as_timestamps;
+
+    /**
+     * Avoid negative timestamps during muxing.
+     *  0 -> allow negative timestamps
+     *  1 -> avoid negative timestamps
+     * -1 -> choose automatically (default)
+     * Note, this only works when interleave_packet_per_dts is in use.
+     * - encoding: Set by user via AVOptions (NO direct access)
+     * - decoding: unused
+     */
+    int avoid_negative_ts;
+
+    /**
+     * avio flags, used to force AVIO_FLAG_DIRECT.
+     * - encoding: unused
+     * - decoding: Set by user via AVOptions (NO direct access)
+     */
+    int avio_flags;
+
+    /**
+     * The duration field can be estimated through various ways, and this field can be used
+     * to know how the duration was estimated.
+     * - encoding: unused
+     * - decoding: Read by user via AVOptions (NO direct access)
+     */
+    enum AVDurationEstimationMethod duration_estimation_method;
+
+    /**
+     * Skip initial bytes when opening stream
+     * - encoding: unused
+     * - decoding: Set by user via AVOptions (NO direct access)
+     */
+    unsigned int skip_initial_bytes;
+
+    /**
+     * Correct single timestamp overflows
+     * - encoding: unused
+     * - decoding: Set by user via AVOPtions (NO direct access)
+     */
+    unsigned int correct_ts_overflow;
+
+    /**
+     * Force seeking to any (also non key) frames.
+     * - encoding: unused
+     * - decoding: Set by user via AVOPtions (NO direct access)
+     */
+    int seek2any;
+
+    /**
+     * Flush the I/O context after each packet.
+     * - encoding: Set by user via AVOptions (NO direct access)
+     * - decoding: unused
+     */
+    int flush_packets;
+
+    /*****************************************************************
+     * All fields below this line are not part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+
+    /**
+     * This buffer is only needed when packets were already buffered but
+     * not decoded, for example to get the codec parameters in MPEG
+     * streams.
+     */
+    struct AVPacketList *packet_buffer;
+    struct AVPacketList *packet_buffer_end;
+
+    /* av_seek_frame() support */
+    int64_t data_offset; /**< offset of the first packet */
+
+    /**
+     * Raw packets from the demuxer, prior to parsing and decoding.
+     * This buffer is used for buffering packets until the codec can
+     * be identified, as parsing cannot be done without knowing the
+     * codec.
+     */
+    struct AVPacketList *raw_packet_buffer;
+    struct AVPacketList *raw_packet_buffer_end;
+    /**
+     * Packets split by the parser get queued here.
+     */
+    struct AVPacketList *parse_queue;
+    struct AVPacketList *parse_queue_end;
+    /**
+     * Remaining size available for raw_packet_buffer, in bytes.
+     */
+#define RAW_PACKET_BUFFER_SIZE 2500000
+    int raw_packet_buffer_remaining_size;
+
+    /**
+     * Offset to remap timestamps to be non-negative.
+     * Expressed in timebase units.
+     * @see AVStream.mux_ts_offset
+     */
+    int64_t offset;
+
+    /**
+     * Timebase for the timestamp offset.
+     */
+    AVRational offset_timebase;
+
+    /**
+     * IO repositioned flag.
+     * This is set by avformat when the underlaying IO context read pointer
+     * is repositioned, for example when doing byte based seeking.
+     * Demuxers can use the flag to detect such changes.
+     */
+    int io_repositioned;
+} AVFormatContext;
+
+/**
+ * Returns the method used to set ctx->duration.
+ *
+ * @return AVFMT_DURATION_FROM_PTS, AVFMT_DURATION_FROM_STREAM, or AVFMT_DURATION_FROM_BITRATE.
+ */
+enum AVDurationEstimationMethod av_fmt_ctx_get_duration_estimation_method(const AVFormatContext* ctx);
+
+typedef struct AVPacketList {
+    AVPacket pkt;
+    struct AVPacketList *next;
+} AVPacketList;
+
+
+/**
+ * @defgroup lavf_core Core functions
+ * @ingroup libavf
+ *
+ * Functions for querying libavformat capabilities, allocating core structures,
+ * etc.
+ * @{
+ */
+
+/**
+ * Return the LIBAVFORMAT_VERSION_INT constant.
+ */
+unsigned avformat_version(void);
+
+/**
+ * Return the libavformat build-time configuration.
+ */
+const char *avformat_configuration(void);
+
+/**
+ * Return the libavformat license.
+ */
+const char *avformat_license(void);
+
+/**
+ * Initialize libavformat and register all the muxers, demuxers and
+ * protocols. If you do not call this function, then you can select
+ * exactly which formats you want to support.
+ *
+ * @see av_register_input_format()
+ * @see av_register_output_format()
+ */
+void av_register_all(void);
+
+void av_register_input_format(AVInputFormat *format);
+void av_register_output_format(AVOutputFormat *format);
+
+/**
+ * Do global initialization of network components. This is optional,
+ * but recommended, since it avoids the overhead of implicitly
+ * doing the setup for each session.
+ *
+ * Calling this function will become mandatory if using network
+ * protocols at some major version bump.
+ */
+int avformat_network_init(void);
+
+/**
+ * Undo the initialization done by avformat_network_init.
+ */
+int avformat_network_deinit(void);
+
+/**
+ * If f is NULL, returns the first registered input format,
+ * if f is non-NULL, returns the next registered input format after f
+ * or NULL if f is the last one.
+ */
+AVInputFormat  *av_iformat_next(AVInputFormat  *f);
+
+/**
+ * If f is NULL, returns the first registered output format,
+ * if f is non-NULL, returns the next registered output format after f
+ * or NULL if f is the last one.
+ */
+AVOutputFormat *av_oformat_next(AVOutputFormat *f);
+
+/**
+ * Allocate an AVFormatContext.
+ * avformat_free_context() can be used to free the context and everything
+ * allocated by the framework within it.
+ */
+AVFormatContext *avformat_alloc_context(void);
+
+/**
+ * Free an AVFormatContext and all its streams.
+ * @param s context to free
+ */
+void avformat_free_context(AVFormatContext *s);
+
+/**
+ * Get the AVClass for AVFormatContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avformat_get_class(void);
+
+/**
+ * Add a new stream to a media file.
+ *
+ * When demuxing, it is called by the demuxer in read_header(). If the
+ * flag AVFMTCTX_NOHEADER is set in s.ctx_flags, then it may also
+ * be called in read_packet().
+ *
+ * When muxing, should be called by the user before avformat_write_header().
+ *
+ * @param c If non-NULL, the AVCodecContext corresponding to the new stream
+ * will be initialized to use this codec. This is needed for e.g. codec-specific
+ * defaults to be set, so codec should be provided if it is known.
+ *
+ * @return newly created stream or NULL on error.
+ */
+AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c);
+
+AVProgram *av_new_program(AVFormatContext *s, int id);
+
+/**
+ * @}
+ */
+
+
+#if FF_API_PKT_DUMP
+attribute_deprecated void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload);
+attribute_deprecated void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt,
+                                          int dump_payload);
+#endif
+
+#if FF_API_ALLOC_OUTPUT_CONTEXT
+/**
+ * @deprecated deprecated in favor of avformat_alloc_output_context2()
+ */
+attribute_deprecated
+AVFormatContext *avformat_alloc_output_context(const char *format,
+                                               AVOutputFormat *oformat,
+                                               const char *filename);
+#endif
+
+/**
+ * Allocate an AVFormatContext for an output format.
+ * avformat_free_context() can be used to free the context and
+ * everything allocated by the framework within it.
+ *
+ * @param *ctx is set to the created format context, or to NULL in
+ * case of failure
+ * @param oformat format to use for allocating the context, if NULL
+ * format_name and filename are used instead
+ * @param format_name the name of output format to use for allocating the
+ * context, if NULL filename is used instead
+ * @param filename the name of the filename to use for allocating the
+ * context, may be NULL
+ * @return >= 0 in case of success, a negative AVERROR code in case of
+ * failure
+ */
+int avformat_alloc_output_context2(AVFormatContext **ctx, AVOutputFormat *oformat,
+                                   const char *format_name, const char *filename);
+
+/**
+ * @addtogroup lavf_decoding
+ * @{
+ */
+
+/**
+ * Find AVInputFormat based on the short name of the input format.
+ */
+AVInputFormat *av_find_input_format(const char *short_name);
+
+/**
+ * Guess the file format.
+ *
+ * @param is_opened Whether the file is already opened; determines whether
+ *                  demuxers with or without AVFMT_NOFILE are probed.
+ */
+AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened);
+
+/**
+ * Guess the file format.
+ *
+ * @param is_opened Whether the file is already opened; determines whether
+ *                  demuxers with or without AVFMT_NOFILE are probed.
+ * @param score_max A probe score larger that this is required to accept a
+ *                  detection, the variable is set to the actual detection
+ *                  score afterwards.
+ *                  If the score is <= AVPROBE_SCORE_MAX / 4 it is recommended
+ *                  to retry with a larger probe buffer.
+ */
+AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max);
+
+/**
+ * Guess the file format.
+ *
+ * @param is_opened Whether the file is already opened; determines whether
+ *                  demuxers with or without AVFMT_NOFILE are probed.
+ * @param score_ret The score of the best detection.
+ */
+AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret);
+
+/**
+ * Probe a bytestream to determine the input format. Each time a probe returns
+ * with a score that is too low, the probe buffer size is increased and another
+ * attempt is made. When the maximum probe size is reached, the input format
+ * with the highest score is returned.
+ *
+ * @param pb the bytestream to probe
+ * @param fmt the input format is put here
+ * @param filename the filename of the stream
+ * @param logctx the log context
+ * @param offset the offset within the bytestream to probe from
+ * @param max_probe_size the maximum probe buffer size (zero for default)
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
+                          const char *filename, void *logctx,
+                          unsigned int offset, unsigned int max_probe_size);
+
+/**
+ * Open an input stream and read the header. The codecs are not opened.
+ * The stream must be closed with av_close_input_file().
+ *
+ * @param ps Pointer to user-supplied AVFormatContext (allocated by avformat_alloc_context).
+ *           May be a pointer to NULL, in which case an AVFormatContext is allocated by this
+ *           function and written into ps.
+ *           Note that a user-supplied AVFormatContext will be freed on failure.
+ * @param filename Name of the stream to open.
+ * @param fmt If non-NULL, this parameter forces a specific input format.
+ *            Otherwise the format is autodetected.
+ * @param options  A dictionary filled with AVFormatContext and demuxer-private options.
+ *                 On return this parameter will be destroyed and replaced with a dict containing
+ *                 options that were not found. May be NULL.
+ *
+ * @return 0 on success, a negative AVERROR on failure.
+ *
+ * @note If you want to use custom IO, preallocate the format context and set its pb field.
+ */
+int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options);
+
+attribute_deprecated
+int av_demuxer_open(AVFormatContext *ic);
+
+#if FF_API_FORMAT_PARAMETERS
+/**
+ * Read packets of a media file to get stream information. This
+ * is useful for file formats with no headers such as MPEG. This
+ * function also computes the real framerate in case of MPEG-2 repeat
+ * frame mode.
+ * The logical file position is not changed by this function;
+ * examined packets may be buffered for later processing.
+ *
+ * @param ic media file handle
+ * @return >=0 if OK, AVERROR_xxx on error
+ * @todo Let the user decide somehow what information is needed so that
+ *       we do not waste time getting stuff the user does not need.
+ *
+ * @deprecated use avformat_find_stream_info.
+ */
+attribute_deprecated
+int av_find_stream_info(AVFormatContext *ic);
+#endif
+
+/**
+ * Read packets of a media file to get stream information. This
+ * is useful for file formats with no headers such as MPEG. This
+ * function also computes the real framerate in case of MPEG-2 repeat
+ * frame mode.
+ * The logical file position is not changed by this function;
+ * examined packets may be buffered for later processing.
+ *
+ * @param ic media file handle
+ * @param options  If non-NULL, an ic.nb_streams long array of pointers to
+ *                 dictionaries, where i-th member contains options for
+ *                 codec corresponding to i-th stream.
+ *                 On return each dictionary will be filled with options that were not found.
+ * @return >=0 if OK, AVERROR_xxx on error
+ *
+ * @note this function isn't guaranteed to open all the codecs, so
+ *       options being non-empty at return is a perfectly normal behavior.
+ *
+ * @todo Let the user decide somehow what information is needed so that
+ *       we do not waste time getting stuff the user does not need.
+ */
+int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options);
+
+/**
+ * Find the programs which belong to a given stream.
+ *
+ * @param ic    media file handle
+ * @param last  the last found program, the search will start after this
+ *              program, or from the beginning if it is NULL
+ * @param s     stream index
+ * @return the next program which belongs to s, NULL if no program is found or
+ *         the last program is not among the programs of ic.
+ */
+AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s);
+
+/**
+ * Find the "best" stream in the file.
+ * The best stream is determined according to various heuristics as the most
+ * likely to be what the user expects.
+ * If the decoder parameter is non-NULL, av_find_best_stream will find the
+ * default decoder for the stream's codec; streams for which no decoder can
+ * be found are ignored.
+ *
+ * @param ic                media file handle
+ * @param type              stream type: video, audio, subtitles, etc.
+ * @param wanted_stream_nb  user-requested stream number,
+ *                          or -1 for automatic selection
+ * @param related_stream    try to find a stream related (eg. in the same
+ *                          program) to this one, or -1 if none
+ * @param decoder_ret       if non-NULL, returns the decoder for the
+ *                          selected stream
+ * @param flags             flags; none are currently defined
+ * @return  the non-negative stream number in case of success,
+ *          AVERROR_STREAM_NOT_FOUND if no stream with the requested type
+ *          could be found,
+ *          AVERROR_DECODER_NOT_FOUND if streams were found but no decoder
+ * @note  If av_find_best_stream returns successfully and decoder_ret is not
+ *        NULL, then *decoder_ret is guaranteed to be set to a valid AVCodec.
+ */
+int av_find_best_stream(AVFormatContext *ic,
+                        enum AVMediaType type,
+                        int wanted_stream_nb,
+                        int related_stream,
+                        AVCodec **decoder_ret,
+                        int flags);
+
+#if FF_API_READ_PACKET
+/**
+ * @deprecated use AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE to read raw
+ * unprocessed packets
+ *
+ * Read a transport packet from a media file.
+ *
+ * This function is obsolete and should never be used.
+ * Use av_read_frame() instead.
+ *
+ * @param s media file handle
+ * @param pkt is filled
+ * @return 0 if OK, AVERROR_xxx on error
+ */
+attribute_deprecated
+int av_read_packet(AVFormatContext *s, AVPacket *pkt);
+#endif
+
+/**
+ * Return the next frame of a stream.
+ * This function returns what is stored in the file, and does not validate
+ * that what is there are valid frames for the decoder. It will split what is
+ * stored in the file into frames and return one for each call. It will not
+ * omit invalid data between valid frames so as to give the decoder the maximum
+ * information possible for decoding.
+ *
+ * If pkt->buf is NULL, then the packet is valid until the next
+ * av_read_frame() or until av_close_input_file(). Otherwise the packet is valid
+ * indefinitely. In both cases the packet must be freed with
+ * av_free_packet when it is no longer needed. For video, the packet contains
+ * exactly one frame. For audio, it contains an integer number of frames if each
+ * frame has a known fixed size (e.g. PCM or ADPCM data). If the audio frames
+ * have a variable size (e.g. MPEG audio), then it contains one frame.
+ *
+ * pkt->pts, pkt->dts and pkt->duration are always set to correct
+ * values in AVStream.time_base units (and guessed if the format cannot
+ * provide them). pkt->pts can be AV_NOPTS_VALUE if the video format
+ * has B-frames, so it is better to rely on pkt->dts if you do not
+ * decompress the payload.
+ *
+ * @return 0 if OK, < 0 on error or end of file
+ */
+int av_read_frame(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Seek to the keyframe at timestamp.
+ * 'timestamp' in 'stream_index'.
+ * @param stream_index If stream_index is (-1), a default
+ * stream is selected, and timestamp is automatically converted
+ * from AV_TIME_BASE units to the stream specific time_base.
+ * @param timestamp Timestamp in AVStream.time_base units
+ *        or, if no stream is specified, in AV_TIME_BASE units.
+ * @param flags flags which select direction and seeking mode
+ * @return >= 0 on success
+ */
+int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp,
+                  int flags);
+
+/**
+ * Seek to timestamp ts.
+ * Seeking will be done so that the point from which all active streams
+ * can be presented successfully will be closest to ts and within min/max_ts.
+ * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL.
+ *
+ * If flags contain AVSEEK_FLAG_BYTE, then all timestamps are in bytes and
+ * are the file position (this may not be supported by all demuxers).
+ * If flags contain AVSEEK_FLAG_FRAME, then all timestamps are in frames
+ * in the stream with stream_index (this may not be supported by all demuxers).
+ * Otherwise all timestamps are in units of the stream selected by stream_index
+ * or if stream_index is -1, in AV_TIME_BASE units.
+ * If flags contain AVSEEK_FLAG_ANY, then non-keyframes are treated as
+ * keyframes (this may not be supported by all demuxers).
+ * If flags contain AVSEEK_FLAG_BACKWARD, it is ignored.
+ *
+ * @param stream_index index of the stream which is used as time base reference
+ * @param min_ts smallest acceptable timestamp
+ * @param ts target timestamp
+ * @param max_ts largest acceptable timestamp
+ * @param flags flags
+ * @return >=0 on success, error code otherwise
+ *
+ * @note This is part of the new seek API which is still under construction.
+ *       Thus do not use this yet. It may change at any time, do not expect
+ *       ABI compatibility yet!
+ */
+int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
+
+/**
+ * Start playing a network-based stream (e.g. RTSP stream) at the
+ * current position.
+ */
+int av_read_play(AVFormatContext *s);
+
+/**
+ * Pause a network-based stream (e.g. RTSP stream).
+ *
+ * Use av_read_play() to resume it.
+ */
+int av_read_pause(AVFormatContext *s);
+
+#if FF_API_CLOSE_INPUT_FILE
+/**
+ * @deprecated use avformat_close_input()
+ * Close a media file (but not its codecs).
+ *
+ * @param s media file handle
+ */
+attribute_deprecated
+void av_close_input_file(AVFormatContext *s);
+#endif
+
+/**
+ * Close an opened input AVFormatContext. Free it and all its contents
+ * and set *s to NULL.
+ */
+void avformat_close_input(AVFormatContext **s);
+/**
+ * @}
+ */
+
+#if FF_API_NEW_STREAM
+/**
+ * Add a new stream to a media file.
+ *
+ * Can only be called in the read_header() function. If the flag
+ * AVFMTCTX_NOHEADER is in the format context, then new streams
+ * can be added in read_packet too.
+ *
+ * @param s media file handle
+ * @param id file-format-dependent stream ID
+ */
+attribute_deprecated
+AVStream *av_new_stream(AVFormatContext *s, int id);
+#endif
+
+#if FF_API_SET_PTS_INFO
+/**
+ * @deprecated this function is not supposed to be called outside of lavf
+ */
+attribute_deprecated
+void av_set_pts_info(AVStream *s, int pts_wrap_bits,
+                     unsigned int pts_num, unsigned int pts_den);
+#endif
+
+#define AVSEEK_FLAG_BACKWARD 1 ///< seek backward
+#define AVSEEK_FLAG_BYTE     2 ///< seeking based on position in bytes
+#define AVSEEK_FLAG_ANY      4 ///< seek to any frame, even non-keyframes
+#define AVSEEK_FLAG_FRAME    8 ///< seeking based on frame number
+
+/**
+ * @addtogroup lavf_encoding
+ * @{
+ */
+/**
+ * Allocate the stream private data and write the stream header to
+ * an output media file.
+ *
+ * @param s Media file handle, must be allocated with avformat_alloc_context().
+ *          Its oformat field must be set to the desired output format;
+ *          Its pb field must be set to an already opened AVIOContext.
+ * @param options  An AVDictionary filled with AVFormatContext and muxer-private options.
+ *                 On return this parameter will be destroyed and replaced with a dict containing
+ *                 options that were not found. May be NULL.
+ *
+ * @return 0 on success, negative AVERROR on failure.
+ *
+ * @see av_opt_find, av_dict_set, avio_open, av_oformat_next.
+ */
+int avformat_write_header(AVFormatContext *s, AVDictionary **options);
+
+/**
+ * Write a packet to an output media file.
+ *
+ * The packet shall contain one audio or video frame.
+ * The packet must be correctly interleaved according to the container
+ * specification, if not then av_interleaved_write_frame must be used.
+ *
+ * @param s media file handle
+ * @param pkt The packet, which contains the stream_index, buf/buf_size,
+ *            dts/pts, ...
+ *            This can be NULL (at any time, not just at the end), in
+ *            order to immediately flush data buffered within the muxer,
+ *            for muxers that buffer up data internally before writing it
+ *            to the output.
+ * @return < 0 on error, = 0 if OK, 1 if flushed and there is no more data to flush
+ */
+int av_write_frame(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Write a packet to an output media file ensuring correct interleaving.
+ *
+ * The packet must contain one audio or video frame.
+ * If the packets are already correctly interleaved, the application should
+ * call av_write_frame() instead as it is slightly faster. It is also important
+ * to keep in mind that completely non-interleaved input will need huge amounts
+ * of memory to interleave with this, so it is preferable to interleave at the
+ * demuxer level.
+ *
+ * @param s media file handle
+ * @param pkt The packet containing the data to be written. pkt->buf must be set
+ * to a valid AVBufferRef describing the packet data. Libavformat takes
+ * ownership of this reference and will unref it when it sees fit. The caller
+ * must not access the data through this reference after this function returns.
+ * This can be NULL (at any time, not just at the end), to flush the
+ * interleaving queues.
+ * Packet's @ref AVPacket.stream_index "stream_index" field must be set to the
+ * index of the corresponding stream in @ref AVFormatContext.streams
+ * "s.streams".
+ * It is very strongly recommended that timing information (@ref AVPacket.pts
+ * "pts", @ref AVPacket.dts "dts" @ref AVPacket.duration "duration") is set to
+ * correct values.
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ */
+int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Write the stream trailer to an output media file and free the
+ * file private data.
+ *
+ * May only be called after a successful call to avformat_write_header.
+ *
+ * @param s media file handle
+ * @return 0 if OK, AVERROR_xxx on error
+ */
+int av_write_trailer(AVFormatContext *s);
+
+/**
+ * Return the output format in the list of registered output formats
+ * which best matches the provided parameters, or return NULL if
+ * there is no match.
+ *
+ * @param short_name if non-NULL checks if short_name matches with the
+ * names of the registered formats
+ * @param filename if non-NULL checks if filename terminates with the
+ * extensions of the registered formats
+ * @param mime_type if non-NULL checks if mime_type matches with the
+ * MIME type of the registered formats
+ */
+AVOutputFormat *av_guess_format(const char *short_name,
+                                const char *filename,
+                                const char *mime_type);
+
+/**
+ * Guess the codec ID based upon muxer and filename.
+ */
+enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
+                            const char *filename, const char *mime_type,
+                            enum AVMediaType type);
+
+/**
+ * Get timing information for the data currently output.
+ * The exact meaning of "currently output" depends on the format.
+ * It is mostly relevant for devices that have an internal buffer and/or
+ * work in real time.
+ * @param s          media file handle
+ * @param stream     stream in the media file
+ * @param[out] dts   DTS of the last packet output for the stream, in stream
+ *                   time_base units
+ * @param[out] wall  absolute time when that packet whas output,
+ *                   in microsecond
+ * @return  0 if OK, AVERROR(ENOSYS) if the format does not support it
+ * Note: some formats or devices may not allow to measure dts and wall
+ * atomically.
+ */
+int av_get_output_timestamp(struct AVFormatContext *s, int stream,
+                            int64_t *dts, int64_t *wall);
+
+
+/**
+ * @}
+ */
+
+
+/**
+ * @defgroup lavf_misc Utility functions
+ * @ingroup libavf
+ * @{
+ *
+ * Miscellaneous utility functions related to both muxing and demuxing
+ * (or neither).
+ */
+
+/**
+ * Send a nice hexadecimal dump of a buffer to the specified file stream.
+ *
+ * @param f The file stream pointer where the dump should be sent to.
+ * @param buf buffer
+ * @param size buffer size
+ *
+ * @see av_hex_dump_log, av_pkt_dump2, av_pkt_dump_log2
+ */
+void av_hex_dump(FILE *f, const uint8_t *buf, int size);
+
+/**
+ * Send a nice hexadecimal dump of a buffer to the log.
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message, lower values signifying
+ * higher importance.
+ * @param buf buffer
+ * @param size buffer size
+ *
+ * @see av_hex_dump, av_pkt_dump2, av_pkt_dump_log2
+ */
+void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size);
+
+/**
+ * Send a nice dump of a packet to the specified file stream.
+ *
+ * @param f The file stream pointer where the dump should be sent to.
+ * @param pkt packet to dump
+ * @param dump_payload True if the payload must be displayed, too.
+ * @param st AVStream that the packet belongs to
+ */
+void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st);
+
+
+/**
+ * Send a nice dump of a packet to the log.
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message, lower values signifying
+ * higher importance.
+ * @param pkt packet to dump
+ * @param dump_payload True if the payload must be displayed, too.
+ * @param st AVStream that the packet belongs to
+ */
+void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
+                      AVStream *st);
+
+/**
+ * Get the AVCodecID for the given codec tag tag.
+ * If no codec id is found returns AV_CODEC_ID_NONE.
+ *
+ * @param tags list of supported codec_id-codec_tag pairs, as stored
+ * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag
+ */
+enum AVCodecID av_codec_get_id(const struct AVCodecTag * const *tags, unsigned int tag);
+
+/**
+ * Get the codec tag for the given codec id id.
+ * If no codec tag is found returns 0.
+ *
+ * @param tags list of supported codec_id-codec_tag pairs, as stored
+ * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag
+ */
+unsigned int av_codec_get_tag(const struct AVCodecTag * const *tags, enum AVCodecID id);
+
+/**
+ * Get the codec tag for the given codec id.
+ *
+ * @param tags list of supported codec_id - codec_tag pairs, as stored
+ * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag
+ * @param id codec id that should be searched for in the list
+ * @param tag A pointer to the found tag
+ * @return 0 if id was not found in tags, > 0 if it was found
+ */
+int av_codec_get_tag2(const struct AVCodecTag * const *tags, enum AVCodecID id,
+                      unsigned int *tag);
+
+int av_find_default_stream_index(AVFormatContext *s);
+
+/**
+ * Get the index for a specific timestamp.
+ * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond
+ *                 to the timestamp which is <= the requested one, if backward
+ *                 is 0, then it will be >=
+ *              if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
+ * @return < 0 if no such timestamp could be found
+ */
+int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags);
+
+/**
+ * Add an index entry into a sorted list. Update the entry if the list
+ * already contains it.
+ *
+ * @param timestamp timestamp in the time base of the given stream
+ */
+int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
+                       int size, int distance, int flags);
+
+
+/**
+ * Split a URL string into components.
+ *
+ * The pointers to buffers for storing individual components may be null,
+ * in order to ignore that component. Buffers for components not found are
+ * set to empty strings. If the port is not found, it is set to a negative
+ * value.
+ *
+ * @param proto the buffer for the protocol
+ * @param proto_size the size of the proto buffer
+ * @param authorization the buffer for the authorization
+ * @param authorization_size the size of the authorization buffer
+ * @param hostname the buffer for the host name
+ * @param hostname_size the size of the hostname buffer
+ * @param port_ptr a pointer to store the port number in
+ * @param path the buffer for the path
+ * @param path_size the size of the path buffer
+ * @param url the URL to split
+ */
+void av_url_split(char *proto,         int proto_size,
+                  char *authorization, int authorization_size,
+                  char *hostname,      int hostname_size,
+                  int *port_ptr,
+                  char *path,          int path_size,
+                  const char *url);
+
+
+void av_dump_format(AVFormatContext *ic,
+                    int index,
+                    const char *url,
+                    int is_output);
+
+/**
+ * Return in 'buf' the path with '%d' replaced by a number.
+ *
+ * Also handles the '%0nd' format where 'n' is the total number
+ * of digits and '%%'.
+ *
+ * @param buf destination buffer
+ * @param buf_size destination buffer size
+ * @param path numbered sequence string
+ * @param number frame number
+ * @return 0 if OK, -1 on format error
+ */
+int av_get_frame_filename(char *buf, int buf_size,
+                          const char *path, int number);
+
+/**
+ * Check whether filename actually is a numbered sequence generator.
+ *
+ * @param filename possible numbered sequence string
+ * @return 1 if a valid numbered sequence string, 0 otherwise
+ */
+int av_filename_number_test(const char *filename);
+
+/**
+ * Generate an SDP for an RTP session.
+ *
+ * Note, this overwrites the id values of AVStreams in the muxer contexts
+ * for getting unique dynamic payload types.
+ *
+ * @param ac array of AVFormatContexts describing the RTP streams. If the
+ *           array is composed by only one context, such context can contain
+ *           multiple AVStreams (one AVStream per RTP stream). Otherwise,
+ *           all the contexts in the array (an AVCodecContext per RTP stream)
+ *           must contain only one AVStream.
+ * @param n_files number of AVCodecContexts contained in ac
+ * @param buf buffer where the SDP will be stored (must be allocated by
+ *            the caller)
+ * @param size the size of the buffer
+ * @return 0 if OK, AVERROR_xxx on error
+ */
+int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size);
+
+/**
+ * Return a positive value if the given filename has one of the given
+ * extensions, 0 otherwise.
+ *
+ * @param extensions a comma-separated list of filename extensions
+ */
+int av_match_ext(const char *filename, const char *extensions);
+
+/**
+ * Test if the given container can store a codec.
+ *
+ * @param std_compliance standards compliance level, one of FF_COMPLIANCE_*
+ *
+ * @return 1 if codec with ID codec_id can be stored in ofmt, 0 if it cannot.
+ *         A negative number if this information is not available.
+ */
+int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance);
+
+/**
+ * @defgroup riff_fourcc RIFF FourCCs
+ * @{
+ * Get the tables mapping RIFF FourCCs to libavcodec AVCodecIDs. The tables are
+ * meant to be passed to av_codec_get_id()/av_codec_get_tag() as in the
+ * following code:
+ * @code
+ * uint32_t tag = MKTAG('H', '2', '6', '4');
+ * const struct AVCodecTag *table[] = { avformat_get_riff_video_tags(), 0 };
+ * enum AVCodecID id = av_codec_get_id(table, tag);
+ * @endcode
+ */
+/**
+ * @return the table mapping RIFF FourCCs for video to libavcodec AVCodecID.
+ */
+const struct AVCodecTag *avformat_get_riff_video_tags(void);
+/**
+ * @return the table mapping RIFF FourCCs for audio to AVCodecID.
+ */
+const struct AVCodecTag *avformat_get_riff_audio_tags(void);
+
+/**
+ * @}
+ */
+
+/**
+ * Guess the sample aspect ratio of a frame, based on both the stream and the
+ * frame aspect ratio.
+ *
+ * Since the frame aspect ratio is set by the codec but the stream aspect ratio
+ * is set by the demuxer, these two may not be equal. This function tries to
+ * return the value that you should use if you would like to display the frame.
+ *
+ * Basic logic is to use the stream aspect ratio if it is set to something sane
+ * otherwise use the frame aspect ratio. This way a container setting, which is
+ * usually easy to modify can override the coded value in the frames.
+ *
+ * @param format the format context which the stream is part of
+ * @param stream the stream which the frame is part of
+ * @param frame the frame with the aspect ratio to be determined
+ * @return the guessed (valid) sample_aspect_ratio, 0/1 if no idea
+ */
+AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame);
+
+/**
+ * Guess the frame rate, based on both the container and codec information.
+ *
+ * @param ctx the format context which the stream is part of
+ * @param stream the stream which the frame is part of
+ * @param frame the frame for which the frame rate should be determined, may be NULL
+ * @return the guessed (valid) frame rate, 0/1 if no idea
+ */
+AVRational av_guess_frame_rate(AVFormatContext *ctx, AVStream *stream, AVFrame *frame);
+
+/**
+ * Check if the stream st contained in s is matched by the stream specifier
+ * spec.
+ *
+ * See the "stream specifiers" chapter in the documentation for the syntax
+ * of spec.
+ *
+ * @return  >0 if st is matched by spec;
+ *          0  if st is not matched by spec;
+ *          AVERROR code if spec is invalid
+ *
+ * @note  A stream specifier can match several streams in the format.
+ */
+int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
+                                    const char *spec);
+
+int avformat_queue_attached_pictures(AVFormatContext *s);
+
+
+/**
+ * @}
+ */
+
+#endif /* AVFORMAT_AVFORMAT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavformat/avio.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,481 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifndef AVFORMAT_AVIO_H
+#define AVFORMAT_AVIO_H
+
+/**
+ * @file
+ * @ingroup lavf_io
+ * Buffered I/O operations
+ */
+
+#include <stdint.h>
+
+#include "../libavutil/common.h"
+#include "../libavutil/dict.h"
+#include "../libavutil/log.h"
+
+#include "version.h"
+
+
+#define AVIO_SEEKABLE_NORMAL 0x0001 /**< Seeking works like for a local file */
+
+/**
+ * Callback for checking whether to abort blocking functions.
+ * AVERROR_EXIT is returned in this case by the interrupted
+ * function. During blocking operations, callback is called with
+ * opaque as parameter. If the callback returns 1, the
+ * blocking operation will be aborted.
+ *
+ * No members can be added to this struct without a major bump, if
+ * new elements have been added after this struct in AVFormatContext
+ * or AVIOContext.
+ */
+typedef struct AVIOInterruptCB {
+    int (*callback)(void*);
+    void *opaque;
+} AVIOInterruptCB;
+
+/**
+ * Bytestream IO Context.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVIOContext) must not be used outside libav*.
+ *
+ * @note None of the function pointers in AVIOContext should be called
+ *       directly, they should only be set by the client application
+ *       when implementing custom I/O. Normally these are set to the
+ *       function pointers specified in avio_alloc_context()
+ */
+typedef struct AVIOContext {
+    /**
+     * A class for private options.
+     *
+     * If this AVIOContext is created by avio_open2(), av_class is set and
+     * passes the options down to protocols.
+     *
+     * If this AVIOContext is manually allocated, then av_class may be set by
+     * the caller.
+     *
+     * warning -- this field can be NULL, be sure to not pass this AVIOContext
+     * to any av_opt_* functions in that case.
+     */
+    const AVClass *av_class;
+    unsigned char *buffer;  /**< Start of the buffer. */
+    int buffer_size;        /**< Maximum buffer size */
+    unsigned char *buf_ptr; /**< Current position in the buffer */
+    unsigned char *buf_end; /**< End of the data, may be less than
+                                 buffer+buffer_size if the read function returned
+                                 less data than requested, e.g. for streams where
+                                 no more data has been received yet. */
+    void *opaque;           /**< A private pointer, passed to the read/write/seek/...
+                                 functions. */
+    int (*read_packet)(void *opaque, uint8_t *buf, int buf_size);
+    int (*write_packet)(void *opaque, uint8_t *buf, int buf_size);
+    int64_t (*seek)(void *opaque, int64_t offset, int whence);
+    int64_t pos;            /**< position in the file of the current buffer */
+    int must_flush;         /**< true if the next seek should flush */
+    int eof_reached;        /**< true if eof reached */
+    int write_flag;         /**< true if open for writing */
+    int max_packet_size;
+    unsigned long checksum;
+    unsigned char *checksum_ptr;
+    unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size);
+    int error;              /**< contains the error code or 0 if no error happened */
+    /**
+     * Pause or resume playback for network streaming protocols - e.g. MMS.
+     */
+    int (*read_pause)(void *opaque, int pause);
+    /**
+     * Seek to a given timestamp in stream with the specified stream_index.
+     * Needed for some network streaming protocols which don't support seeking
+     * to byte position.
+     */
+    int64_t (*read_seek)(void *opaque, int stream_index,
+                         int64_t timestamp, int flags);
+    /**
+     * A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
+     */
+    int seekable;
+
+    /**
+     * max filesize, used to limit allocations
+     * This field is internal to libavformat and access from outside is not allowed.
+     */
+    int64_t maxsize;
+
+    /**
+     * avio_read and avio_write should if possible be satisfied directly
+     * instead of going through a buffer, and avio_seek will always
+     * call the underlying seek function directly.
+     */
+    int direct;
+
+    /**
+     * Bytes read statistic
+     * This field is internal to libavformat and access from outside is not allowed.
+     */
+    int64_t bytes_read;
+
+    /**
+     * seek statistic
+     * This field is internal to libavformat and access from outside is not allowed.
+     */
+    int seek_count;
+
+    /**
+     * writeout statistic
+     * This field is internal to libavformat and access from outside is not allowed.
+     */
+    int writeout_count;
+} AVIOContext;
+
+/* unbuffered I/O */
+
+/**
+ * Return AVIO_FLAG_* access flags corresponding to the access permissions
+ * of the resource in url, or a negative value corresponding to an
+ * AVERROR code in case of failure. The returned access flags are
+ * masked by the value in flags.
+ *
+ * @note This function is intrinsically unsafe, in the sense that the
+ * checked resource may change its existence or permission status from
+ * one call to another. Thus you should not trust the returned value,
+ * unless you are sure that no other processes are accessing the
+ * checked resource.
+ */
+int avio_check(const char *url, int flags);
+
+/**
+ * Allocate and initialize an AVIOContext for buffered I/O. It must be later
+ * freed with av_free().
+ *
+ * @param buffer Memory block for input/output operations via AVIOContext.
+ *        The buffer must be allocated with av_malloc() and friends.
+ * @param buffer_size The buffer size is very important for performance.
+ *        For protocols with fixed blocksize it should be set to this blocksize.
+ *        For others a typical size is a cache page, e.g. 4kb.
+ * @param write_flag Set to 1 if the buffer should be writable, 0 otherwise.
+ * @param opaque An opaque pointer to user-specific data.
+ * @param read_packet  A function for refilling the buffer, may be NULL.
+ * @param write_packet A function for writing the buffer contents, may be NULL.
+ *        The function may not change the input buffers content.
+ * @param seek A function for seeking to specified byte position, may be NULL.
+ *
+ * @return Allocated AVIOContext or NULL on failure.
+ */
+AVIOContext *avio_alloc_context(
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
+
+void avio_w8(AVIOContext *s, int b);
+void avio_write(AVIOContext *s, const unsigned char *buf, int size);
+void avio_wl64(AVIOContext *s, uint64_t val);
+void avio_wb64(AVIOContext *s, uint64_t val);
+void avio_wl32(AVIOContext *s, unsigned int val);
+void avio_wb32(AVIOContext *s, unsigned int val);
+void avio_wl24(AVIOContext *s, unsigned int val);
+void avio_wb24(AVIOContext *s, unsigned int val);
+void avio_wl16(AVIOContext *s, unsigned int val);
+void avio_wb16(AVIOContext *s, unsigned int val);
+
+/**
+ * Write a NULL-terminated string.
+ * @return number of bytes written.
+ */
+int avio_put_str(AVIOContext *s, const char *str);
+
+/**
+ * Convert an UTF-8 string to UTF-16LE and write it.
+ * @return number of bytes written.
+ */
+int avio_put_str16le(AVIOContext *s, const char *str);
+
+/**
+ * Passing this as the "whence" parameter to a seek function causes it to
+ * return the filesize without seeking anywhere. Supporting this is optional.
+ * If it is not supported then the seek function will return <0.
+ */
+#define AVSEEK_SIZE 0x10000
+
+/**
+ * Oring this flag as into the "whence" parameter to a seek function causes it to
+ * seek by any means (like reopening and linear reading) or other normally unreasonable
+ * means that can be extremely slow.
+ * This may be ignored by the seek code.
+ */
+#define AVSEEK_FORCE 0x20000
+
+/**
+ * fseek() equivalent for AVIOContext.
+ * @return new position or AVERROR.
+ */
+int64_t avio_seek(AVIOContext *s, int64_t offset, int whence);
+
+/**
+ * Skip given number of bytes forward
+ * @return new position or AVERROR.
+ */
+int64_t avio_skip(AVIOContext *s, int64_t offset);
+
+/**
+ * ftell() equivalent for AVIOContext.
+ * @return position or AVERROR.
+ */
+static av_always_inline int64_t avio_tell(AVIOContext *s)
+{
+    return avio_seek(s, 0, SEEK_CUR);
+}
+
+/**
+ * Get the filesize.
+ * @return filesize or AVERROR
+ */
+int64_t avio_size(AVIOContext *s);
+
+/**
+ * feof() equivalent for AVIOContext.
+ * @return non zero if and only if end of file
+ */
+int url_feof(AVIOContext *s);
+
+/** @warning currently size is limited */
+int avio_printf(AVIOContext *s, const char *fmt, ...) av_printf_format(2, 3);
+
+/**
+ * Force flushing of buffered data to the output s.
+ *
+ * Force the buffered data to be immediately written to the output,
+ * without to wait to fill the internal buffer.
+ */
+void avio_flush(AVIOContext *s);
+
+/**
+ * Read size bytes from AVIOContext into buf.
+ * @return number of bytes read or AVERROR
+ */
+int avio_read(AVIOContext *s, unsigned char *buf, int size);
+
+/**
+ * @name Functions for reading from AVIOContext
+ * @{
+ *
+ * @note return 0 if EOF, so you cannot use it if EOF handling is
+ *       necessary
+ */
+int          avio_r8  (AVIOContext *s);
+unsigned int avio_rl16(AVIOContext *s);
+unsigned int avio_rl24(AVIOContext *s);
+unsigned int avio_rl32(AVIOContext *s);
+uint64_t     avio_rl64(AVIOContext *s);
+unsigned int avio_rb16(AVIOContext *s);
+unsigned int avio_rb24(AVIOContext *s);
+unsigned int avio_rb32(AVIOContext *s);
+uint64_t     avio_rb64(AVIOContext *s);
+/**
+ * @}
+ */
+
+/**
+ * Read a string from pb into buf. The reading will terminate when either
+ * a NULL character was encountered, maxlen bytes have been read, or nothing
+ * more can be read from pb. The result is guaranteed to be NULL-terminated, it
+ * will be truncated if buf is too small.
+ * Note that the string is not interpreted or validated in any way, it
+ * might get truncated in the middle of a sequence for multi-byte encodings.
+ *
+ * @return number of bytes read (is always <= maxlen).
+ * If reading ends on EOF or error, the return value will be one more than
+ * bytes actually read.
+ */
+int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen);
+
+/**
+ * Read a UTF-16 string from pb and convert it to UTF-8.
+ * The reading will terminate when either a null or invalid character was
+ * encountered or maxlen bytes have been read.
+ * @return number of bytes read (is always <= maxlen)
+ */
+int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen);
+int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen);
+
+
+/**
+ * @name URL open modes
+ * The flags argument to avio_open must be one of the following
+ * constants, optionally ORed with other flags.
+ * @{
+ */
+#define AVIO_FLAG_READ  1                                      /**< read-only */
+#define AVIO_FLAG_WRITE 2                                      /**< write-only */
+#define AVIO_FLAG_READ_WRITE (AVIO_FLAG_READ|AVIO_FLAG_WRITE)  /**< read-write pseudo flag */
+/**
+ * @}
+ */
+
+/**
+ * Use non-blocking mode.
+ * If this flag is set, operations on the context will return
+ * AVERROR(EAGAIN) if they can not be performed immediately.
+ * If this flag is not set, operations on the context will never return
+ * AVERROR(EAGAIN).
+ * Note that this flag does not affect the opening/connecting of the
+ * context. Connecting a protocol will always block if necessary (e.g. on
+ * network protocols) but never hang (e.g. on busy devices).
+ * Warning: non-blocking protocols is work-in-progress; this flag may be
+ * silently ignored.
+ */
+#define AVIO_FLAG_NONBLOCK 8
+
+/**
+ * Use direct mode.
+ * avio_read and avio_write should if possible be satisfied directly
+ * instead of going through a buffer, and avio_seek will always
+ * call the underlying seek function directly.
+ */
+#define AVIO_FLAG_DIRECT 0x8000
+
+/**
+ * Create and initialize a AVIOContext for accessing the
+ * resource indicated by url.
+ * @note When the resource indicated by url has been opened in
+ * read+write mode, the AVIOContext can be used only for writing.
+ *
+ * @param s Used to return the pointer to the created AVIOContext.
+ * In case of failure the pointed to value is set to NULL.
+ * @param flags flags which control how the resource indicated by url
+ * is to be opened
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int avio_open(AVIOContext **s, const char *url, int flags);
+
+/**
+ * Create and initialize a AVIOContext for accessing the
+ * resource indicated by url.
+ * @note When the resource indicated by url has been opened in
+ * read+write mode, the AVIOContext can be used only for writing.
+ *
+ * @param s Used to return the pointer to the created AVIOContext.
+ * In case of failure the pointed to value is set to NULL.
+ * @param flags flags which control how the resource indicated by url
+ * is to be opened
+ * @param int_cb an interrupt callback to be used at the protocols level
+ * @param options  A dictionary filled with protocol-private options. On return
+ * this parameter will be destroyed and replaced with a dict containing options
+ * that were not found. May be NULL.
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int avio_open2(AVIOContext **s, const char *url, int flags,
+               const AVIOInterruptCB *int_cb, AVDictionary **options);
+
+/**
+ * Close the resource accessed by the AVIOContext s and free it.
+ * This function can only be used if s was opened by avio_open().
+ *
+ * The internal buffer is automatically flushed before closing the
+ * resource.
+ *
+ * @return 0 on success, an AVERROR < 0 on error.
+ * @see avio_closep
+ */
+int avio_close(AVIOContext *s);
+
+/**
+ * Close the resource accessed by the AVIOContext *s, free it
+ * and set the pointer pointing to it to NULL.
+ * This function can only be used if s was opened by avio_open().
+ *
+ * The internal buffer is automatically flushed before closing the
+ * resource.
+ *
+ * @return 0 on success, an AVERROR < 0 on error.
+ * @see avio_close
+ */
+int avio_closep(AVIOContext **s);
+
+
+/**
+ * Open a write only memory stream.
+ *
+ * @param s new IO context
+ * @return zero if no error.
+ */
+int avio_open_dyn_buf(AVIOContext **s);
+
+/**
+ * Return the written size and a pointer to the buffer. The buffer
+ * must be freed with av_free().
+ * Padding of FF_INPUT_BUFFER_PADDING_SIZE is added to the buffer.
+ *
+ * @param s IO context
+ * @param pbuffer pointer to a byte buffer
+ * @return the length of the byte buffer
+ */
+int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer);
+
+/**
+ * Iterate through names of available protocols.
+ *
+ * @param opaque A private pointer representing current protocol.
+ *        It must be a pointer to NULL on first iteration and will
+ *        be updated by successive calls to avio_enum_protocols.
+ * @param output If set to 1, iterate over output protocols,
+ *               otherwise over input protocols.
+ *
+ * @return A static string containing the name of current protocol or NULL
+ */
+const char *avio_enum_protocols(void **opaque, int output);
+
+/**
+ * Pause and resume playing - only meaningful if using a network streaming
+ * protocol (e.g. MMS).
+ * @param pause 1 for pause, 0 for resume
+ */
+int     avio_pause(AVIOContext *h, int pause);
+
+/**
+ * Seek to a given timestamp relative to some component stream.
+ * Only meaningful if using a network streaming protocol (e.g. MMS.).
+ * @param stream_index The stream index that the timestamp is relative to.
+ *        If stream_index is (-1) the timestamp should be in AV_TIME_BASE
+ *        units from the beginning of the presentation.
+ *        If a stream_index >= 0 is used and the protocol does not support
+ *        seeking based on component streams, the call will fail.
+ * @param timestamp timestamp in AVStream.time_base units
+ *        or if there is no stream specified then in AV_TIME_BASE units.
+ * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE
+ *        and AVSEEK_FLAG_ANY. The protocol may silently ignore
+ *        AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will
+ *        fail if used and not supported.
+ * @return >= 0 on success
+ * @see AVInputFormat::read_seek
+ */
+int64_t avio_seek_time(AVIOContext *h, int stream_index,
+                       int64_t timestamp, int flags);
+
+#endif /* AVFORMAT_AVIO_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavformat/version.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,82 @@
+/*
+ * Version macros.
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_VERSION_H
+#define AVFORMAT_VERSION_H
+
+/**
+ * @file
+ * @ingroup libavf
+ * Libavformat version macros
+ */
+
+#include "../libavutil/avutil.h"
+
+#define LIBAVFORMAT_VERSION_MAJOR 55
+#define LIBAVFORMAT_VERSION_MINOR  7
+#define LIBAVFORMAT_VERSION_MICRO 100
+
+#define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
+                                               LIBAVFORMAT_VERSION_MINOR, \
+                                               LIBAVFORMAT_VERSION_MICRO)
+#define LIBAVFORMAT_VERSION     AV_VERSION(LIBAVFORMAT_VERSION_MAJOR,   \
+                                           LIBAVFORMAT_VERSION_MINOR,   \
+                                           LIBAVFORMAT_VERSION_MICRO)
+#define LIBAVFORMAT_BUILD       LIBAVFORMAT_VERSION_INT
+
+#define LIBAVFORMAT_IDENT       "Lavf" AV_STRINGIFY(LIBAVFORMAT_VERSION)
+
+/**
+ * FF_API_* defines may be placed below to indicate public API that will be
+ * dropped at a future version bump. The defines themselves are not part of
+ * the public API and may change, break or disappear at any time.
+ */
+
+#ifndef FF_API_OLD_AVIO
+#define FF_API_OLD_AVIO                (LIBAVFORMAT_VERSION_MAJOR < 55)
+#endif
+#ifndef FF_API_PKT_DUMP
+#define FF_API_PKT_DUMP                (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_ALLOC_OUTPUT_CONTEXT
+#define FF_API_ALLOC_OUTPUT_CONTEXT    (LIBAVFORMAT_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_FORMAT_PARAMETERS
+#define FF_API_FORMAT_PARAMETERS       (LIBAVFORMAT_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_NEW_STREAM
+#define FF_API_NEW_STREAM              (LIBAVFORMAT_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_SET_PTS_INFO
+#define FF_API_SET_PTS_INFO            (LIBAVFORMAT_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_CLOSE_INPUT_FILE
+#define FF_API_CLOSE_INPUT_FILE        (LIBAVFORMAT_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_READ_PACKET
+#define FF_API_READ_PACKET             (LIBAVFORMAT_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_ASS_SSA
+#define FF_API_ASS_SSA                 (LIBAVFORMAT_VERSION_MAJOR < 56)
+#endif
+#ifndef FF_API_R_FRAME_RATE
+#define FF_API_R_FRAME_RATE            1
+#endif
+#endif /* AVFORMAT_VERSION_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/adler32.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,43 @@
+/*
+ * copyright (c) 2006 Mans Rullgard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_ADLER32_H
+#define AVUTIL_ADLER32_H
+
+#include <stdint.h>
+#include "attributes.h"
+
+/**
+ * @ingroup lavu_crypto
+ * Calculate the Adler32 checksum of a buffer.
+ *
+ * Passing the return value to a subsequent av_adler32_update() call
+ * allows the checksum of multiple buffers to be calculated as though
+ * they were concatenated.
+ *
+ * @param adler initial checksum value
+ * @param buf   pointer to input buffer
+ * @param len   size of input buffer
+ * @return      updated checksum
+ */
+unsigned long av_adler32_update(unsigned long adler, const uint8_t *buf,
+                                unsigned int len) av_pure;
+
+#endif /* AVUTIL_ADLER32_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/aes.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,65 @@
+/*
+ * copyright (c) 2007 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AES_H
+#define AVUTIL_AES_H
+
+#include <stdint.h>
+
+#include "attributes.h"
+#include "version.h"
+
+/**
+ * @defgroup lavu_aes AES
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+extern const int av_aes_size;
+
+struct AVAES;
+
+/**
+ * Allocate an AVAES context.
+ */
+struct AVAES *av_aes_alloc(void);
+
+/**
+ * Initialize an AVAES context.
+ * @param key_bits 128, 192 or 256
+ * @param decrypt 0 for encryption, 1 for decryption
+ */
+int av_aes_init(struct AVAES *a, const uint8_t *key, int key_bits, int decrypt);
+
+/**
+ * Encrypt or decrypt a buffer using a previously initialized context.
+ * @param count number of 16 byte blocks
+ * @param dst destination array, can be equal to src
+ * @param src source array, can be equal to dst
+ * @param iv initialization vector for CBC mode, if NULL then ECB will be used
+ * @param decrypt 0 for encryption, 1 for decryption
+ */
+void av_aes_crypt(struct AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_AES_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/attributes.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,154 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Macro definitions for various function/variable attributes
+ */
+
+#ifndef AVUTIL_ATTRIBUTES_H
+#define AVUTIL_ATTRIBUTES_H
+
+#ifdef __GNUC__
+#    define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > x || __GNUC__ == x && __GNUC_MINOR__ >= y)
+#else
+#    define AV_GCC_VERSION_AT_LEAST(x,y) 0
+#endif
+
+#ifndef av_always_inline
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_always_inline __attribute__((always_inline)) inline
+#elif defined(_MSC_VER)
+#    define av_always_inline __forceinline
+#else
+#    define av_always_inline inline
+#endif
+#endif
+
+#ifndef av_extern_inline
+#if defined(__ICL) && __ICL >= 1210 || defined(__GNUC_STDC_INLINE__)
+#    define av_extern_inline extern inline
+#else
+#    define av_extern_inline inline
+#endif
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_noinline __attribute__((noinline))
+#else
+#    define av_noinline
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_pure __attribute__((pure))
+#else
+#    define av_pure
+#endif
+
+#ifndef av_restrict
+#define av_restrict restrict
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(2,6)
+#    define av_const __attribute__((const))
+#else
+#    define av_const
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(4,3)
+#    define av_cold __attribute__((cold))
+#else
+#    define av_cold
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(4,1)
+#    define av_flatten __attribute__((flatten))
+#else
+#    define av_flatten
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define attribute_deprecated __attribute__((deprecated))
+#else
+#    define attribute_deprecated
+#endif
+
+/**
+ * Disable warnings about deprecated features
+ * This is useful for sections of code kept for backward compatibility and
+ * scheduled for removal.
+ */
+#ifndef AV_NOWARN_DEPRECATED
+#if AV_GCC_VERSION_AT_LEAST(4,6)
+#    define AV_NOWARN_DEPRECATED(code) \
+        _Pragma("GCC diagnostic push") \
+        _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \
+        code \
+        _Pragma("GCC diagnostic pop")
+#else
+#    define AV_NOWARN_DEPRECATED(code) code
+#endif
+#endif
+
+
+#if defined(__GNUC__)
+#    define av_unused __attribute__((unused))
+#else
+#    define av_unused
+#endif
+
+/**
+ * Mark a variable as used and prevent the compiler from optimizing it
+ * away.  This is useful for variables accessed only from inline
+ * assembler without the compiler being aware.
+ */
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_used __attribute__((used))
+#else
+#    define av_used
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,3)
+#   define av_alias __attribute__((may_alias))
+#else
+#   define av_alias
+#endif
+
+#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !defined(__clang__)
+#    define av_uninit(x) x=x
+#else
+#    define av_uninit(x) x
+#endif
+
+#ifdef __GNUC__
+#    define av_builtin_constant_p __builtin_constant_p
+#    define av_printf_format(fmtpos, attrpos) __attribute__((__format__(__printf__, fmtpos, attrpos)))
+#else
+#    define av_builtin_constant_p(x) 0
+#    define av_printf_format(fmtpos, attrpos)
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(2,5)
+#    define av_noreturn __attribute__((noreturn))
+#else
+#    define av_noreturn
+#endif
+
+#endif /* AVUTIL_ATTRIBUTES_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/audio_fifo.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,149 @@
+/*
+ * Audio FIFO
+ * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Audio FIFO Buffer
+ */
+
+#ifndef AVUTIL_AUDIO_FIFO_H
+#define AVUTIL_AUDIO_FIFO_H
+
+#include "avutil.h"
+#include "fifo.h"
+#include "samplefmt.h"
+
+/**
+ * @addtogroup lavu_audio
+ * @{
+ */
+
+/**
+ * Context for an Audio FIFO Buffer.
+ *
+ * - Operates at the sample level rather than the byte level.
+ * - Supports multiple channels with either planar or packed sample format.
+ * - Automatic reallocation when writing to a full buffer.
+ */
+typedef struct AVAudioFifo AVAudioFifo;
+
+/**
+ * Free an AVAudioFifo.
+ *
+ * @param af  AVAudioFifo to free
+ */
+void av_audio_fifo_free(AVAudioFifo *af);
+
+/**
+ * Allocate an AVAudioFifo.
+ *
+ * @param sample_fmt  sample format
+ * @param channels    number of channels
+ * @param nb_samples  initial allocation size, in samples
+ * @return            newly allocated AVAudioFifo, or NULL on error
+ */
+AVAudioFifo *av_audio_fifo_alloc(enum AVSampleFormat sample_fmt, int channels,
+                                 int nb_samples);
+
+/**
+ * Reallocate an AVAudioFifo.
+ *
+ * @param af          AVAudioFifo to reallocate
+ * @param nb_samples  new allocation size, in samples
+ * @return            0 if OK, or negative AVERROR code on failure
+ */
+int av_audio_fifo_realloc(AVAudioFifo *af, int nb_samples);
+
+/**
+ * Write data to an AVAudioFifo.
+ *
+ * The AVAudioFifo will be reallocated automatically if the available space
+ * is less than nb_samples.
+ *
+ * @see enum AVSampleFormat
+ * The documentation for AVSampleFormat describes the data layout.
+ *
+ * @param af          AVAudioFifo to write to
+ * @param data        audio data plane pointers
+ * @param nb_samples  number of samples to write
+ * @return            number of samples actually written, or negative AVERROR
+ *                    code on failure. If successful, the number of samples
+ *                    actually written will always be nb_samples.
+ */
+int av_audio_fifo_write(AVAudioFifo *af, void **data, int nb_samples);
+
+/**
+ * Read data from an AVAudioFifo.
+ *
+ * @see enum AVSampleFormat
+ * The documentation for AVSampleFormat describes the data layout.
+ *
+ * @param af          AVAudioFifo to read from
+ * @param data        audio data plane pointers
+ * @param nb_samples  number of samples to read
+ * @return            number of samples actually read, or negative AVERROR code
+ *                    on failure. The number of samples actually read will not
+ *                    be greater than nb_samples, and will only be less than
+ *                    nb_samples if av_audio_fifo_size is less than nb_samples.
+ */
+int av_audio_fifo_read(AVAudioFifo *af, void **data, int nb_samples);
+
+/**
+ * Drain data from an AVAudioFifo.
+ *
+ * Removes the data without reading it.
+ *
+ * @param af          AVAudioFifo to drain
+ * @param nb_samples  number of samples to drain
+ * @return            0 if OK, or negative AVERROR code on failure
+ */
+int av_audio_fifo_drain(AVAudioFifo *af, int nb_samples);
+
+/**
+ * Reset the AVAudioFifo buffer.
+ *
+ * This empties all data in the buffer.
+ *
+ * @param af  AVAudioFifo to reset
+ */
+void av_audio_fifo_reset(AVAudioFifo *af);
+
+/**
+ * Get the current number of samples in the AVAudioFifo available for reading.
+ *
+ * @param af  the AVAudioFifo to query
+ * @return    number of samples available for reading
+ */
+int av_audio_fifo_size(AVAudioFifo *af);
+
+/**
+ * Get the current number of samples in the AVAudioFifo available for writing.
+ *
+ * @param af  the AVAudioFifo to query
+ * @return    number of samples available for writing
+ */
+int av_audio_fifo_space(AVAudioFifo *af);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_AUDIO_FIFO_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/audioconvert.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,6 @@
+
+#include "version.h"
+
+#if FF_API_AUDIOCONVERT
+#include "channel_layout.h"
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/avassert.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,66 @@
+/*
+ * copyright (c) 2010 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * simple assert() macros that are a bit more flexible than ISO C assert().
+ * @author Michael Niedermayer <michaelni@gmx.at>
+ */
+
+#ifndef AVUTIL_AVASSERT_H
+#define AVUTIL_AVASSERT_H
+
+#include <stdlib.h>
+#include "avutil.h"
+#include "log.h"
+
+/**
+ * assert() equivalent, that is always enabled.
+ */
+#define av_assert0(cond) do {                                           \
+    if (!(cond)) {                                                      \
+        av_log(NULL, AV_LOG_PANIC, "Assertion %s failed at %s:%d\n",    \
+               AV_STRINGIFY(cond), __FILE__, __LINE__);                 \
+        abort();                                                        \
+    }                                                                   \
+} while (0)
+
+
+/**
+ * assert() equivalent, that does not lie in speed critical code.
+ * These asserts() thus can be enabled without fearing speedloss.
+ */
+#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 0
+#define av_assert1(cond) av_assert0(cond)
+#else
+#define av_assert1(cond) ((void)0)
+#endif
+
+
+/**
+ * assert() equivalent, that does lie in speed critical code.
+ */
+#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 1
+#define av_assert2(cond) av_assert0(cond)
+#else
+#define av_assert2(cond) ((void)0)
+#endif
+
+#endif /* AVUTIL_AVASSERT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/avconfig.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,7 @@
+/* Generated by ffconf */
+#ifndef AVUTIL_AVCONFIG_H
+#define AVUTIL_AVCONFIG_H
+#define AV_HAVE_BIGENDIAN 0
+#define AV_HAVE_FAST_UNALIGNED 1
+#define AV_HAVE_INCOMPATIBLE_FORK_ABI 0
+#endif /* AVUTIL_AVCONFIG_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/avstring.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,302 @@
+/*
+ * Copyright (c) 2007 Mans Rullgard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AVSTRING_H
+#define AVUTIL_AVSTRING_H
+
+#include <stddef.h>
+#include "attributes.h"
+
+/**
+ * @addtogroup lavu_string
+ * @{
+ */
+
+/**
+ * Return non-zero if pfx is a prefix of str. If it is, *ptr is set to
+ * the address of the first character in str after the prefix.
+ *
+ * @param str input string
+ * @param pfx prefix to test
+ * @param ptr updated if the prefix is matched inside str
+ * @return non-zero if the prefix matches, zero otherwise
+ */
+int av_strstart(const char *str, const char *pfx, const char **ptr);
+
+/**
+ * Return non-zero if pfx is a prefix of str independent of case. If
+ * it is, *ptr is set to the address of the first character in str
+ * after the prefix.
+ *
+ * @param str input string
+ * @param pfx prefix to test
+ * @param ptr updated if the prefix is matched inside str
+ * @return non-zero if the prefix matches, zero otherwise
+ */
+int av_stristart(const char *str, const char *pfx, const char **ptr);
+
+/**
+ * Locate the first case-independent occurrence in the string haystack
+ * of the string needle.  A zero-length string needle is considered to
+ * match at the start of haystack.
+ *
+ * This function is a case-insensitive version of the standard strstr().
+ *
+ * @param haystack string to search in
+ * @param needle   string to search for
+ * @return         pointer to the located match within haystack
+ *                 or a null pointer if no match
+ */
+char *av_stristr(const char *haystack, const char *needle);
+
+/**
+ * Locate the first occurrence of the string needle in the string haystack
+ * where not more than hay_length characters are searched. A zero-length
+ * string needle is considered to match at the start of haystack.
+ *
+ * This function is a length-limited version of the standard strstr().
+ *
+ * @param haystack   string to search in
+ * @param needle     string to search for
+ * @param hay_length length of string to search in
+ * @return           pointer to the located match within haystack
+ *                   or a null pointer if no match
+ */
+char *av_strnstr(const char *haystack, const char *needle, size_t hay_length);
+
+/**
+ * Copy the string src to dst, but no more than size - 1 bytes, and
+ * null-terminate dst.
+ *
+ * This function is the same as BSD strlcpy().
+ *
+ * @param dst destination buffer
+ * @param src source string
+ * @param size size of destination buffer
+ * @return the length of src
+ *
+ * @warning since the return value is the length of src, src absolutely
+ * _must_ be a properly 0-terminated string, otherwise this will read beyond
+ * the end of the buffer and possibly crash.
+ */
+size_t av_strlcpy(char *dst, const char *src, size_t size);
+
+/**
+ * Append the string src to the string dst, but to a total length of
+ * no more than size - 1 bytes, and null-terminate dst.
+ *
+ * This function is similar to BSD strlcat(), but differs when
+ * size <= strlen(dst).
+ *
+ * @param dst destination buffer
+ * @param src source string
+ * @param size size of destination buffer
+ * @return the total length of src and dst
+ *
+ * @warning since the return value use the length of src and dst, these
+ * absolutely _must_ be a properly 0-terminated strings, otherwise this
+ * will read beyond the end of the buffer and possibly crash.
+ */
+size_t av_strlcat(char *dst, const char *src, size_t size);
+
+/**
+ * Append output to a string, according to a format. Never write out of
+ * the destination buffer, and always put a terminating 0 within
+ * the buffer.
+ * @param dst destination buffer (string to which the output is
+ *  appended)
+ * @param size total size of the destination buffer
+ * @param fmt printf-compatible format string, specifying how the
+ *  following parameters are used
+ * @return the length of the string that would have been generated
+ *  if enough space had been available
+ */
+size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...) av_printf_format(3, 4);
+
+/**
+ * Print arguments following specified format into a large enough auto
+ * allocated buffer. It is similar to GNU asprintf().
+ * @param fmt printf-compatible format string, specifying how the
+ *            following parameters are used.
+ * @return the allocated string
+ * @note You have to free the string yourself with av_free().
+ */
+char *av_asprintf(const char *fmt, ...) av_printf_format(1, 2);
+
+/**
+ * Convert a number to a av_malloced string.
+ */
+char *av_d2str(double d);
+
+/**
+ * Unescape the given string until a non escaped terminating char,
+ * and return the token corresponding to the unescaped string.
+ *
+ * The normal \ and ' escaping is supported. Leading and trailing
+ * whitespaces are removed, unless they are escaped with '\' or are
+ * enclosed between ''.
+ *
+ * @param buf the buffer to parse, buf will be updated to point to the
+ * terminating char
+ * @param term a 0-terminated list of terminating chars
+ * @return the malloced unescaped string, which must be av_freed by
+ * the user, NULL in case of allocation failure
+ */
+char *av_get_token(const char **buf, const char *term);
+
+/**
+ * Split the string into several tokens which can be accessed by
+ * successive calls to av_strtok().
+ *
+ * A token is defined as a sequence of characters not belonging to the
+ * set specified in delim.
+ *
+ * On the first call to av_strtok(), s should point to the string to
+ * parse, and the value of saveptr is ignored. In subsequent calls, s
+ * should be NULL, and saveptr should be unchanged since the previous
+ * call.
+ *
+ * This function is similar to strtok_r() defined in POSIX.1.
+ *
+ * @param s the string to parse, may be NULL
+ * @param delim 0-terminated list of token delimiters, must be non-NULL
+ * @param saveptr user-provided pointer which points to stored
+ * information necessary for av_strtok() to continue scanning the same
+ * string. saveptr is updated to point to the next character after the
+ * first delimiter found, or to NULL if the string was terminated
+ * @return the found token, or NULL when no token is found
+ */
+char *av_strtok(char *s, const char *delim, char **saveptr);
+
+/**
+ * Locale-independent conversion of ASCII isdigit.
+ */
+int av_isdigit(int c);
+
+/**
+ * Locale-independent conversion of ASCII isgraph.
+ */
+int av_isgraph(int c);
+
+/**
+ * Locale-independent conversion of ASCII isspace.
+ */
+int av_isspace(int c);
+
+/**
+ * Locale-independent conversion of ASCII characters to uppercase.
+ */
+static inline int av_toupper(int c)
+{
+    if (c >= 'a' && c <= 'z')
+        c ^= 0x20;
+    return c;
+}
+
+/**
+ * Locale-independent conversion of ASCII characters to lowercase.
+ */
+static inline int av_tolower(int c)
+{
+    if (c >= 'A' && c <= 'Z')
+        c ^= 0x20;
+    return c;
+}
+
+/**
+ * Locale-independent conversion of ASCII isxdigit.
+ */
+int av_isxdigit(int c);
+
+/**
+ * Locale-independent case-insensitive compare.
+ * @note This means only ASCII-range characters are case-insensitive
+ */
+int av_strcasecmp(const char *a, const char *b);
+
+/**
+ * Locale-independent case-insensitive compare.
+ * @note This means only ASCII-range characters are case-insensitive
+ */
+int av_strncasecmp(const char *a, const char *b, size_t n);
+
+
+/**
+ * Thread safe basename.
+ * @param path the path, on DOS both \ and / are considered separators.
+ * @return pointer to the basename substring.
+ */
+const char *av_basename(const char *path);
+
+/**
+ * Thread safe dirname.
+ * @param path the path, on DOS both \ and / are considered separators.
+ * @return the path with the separator replaced by the string terminator or ".".
+ * @note the function may change the input string.
+ */
+const char *av_dirname(char *path);
+
+enum AVEscapeMode {
+    AV_ESCAPE_MODE_AUTO,      ///< Use auto-selected escaping mode.
+    AV_ESCAPE_MODE_BACKSLASH, ///< Use backslash escaping.
+    AV_ESCAPE_MODE_QUOTE,     ///< Use single-quote escaping.
+};
+
+/**
+ * Consider spaces special and escape them even in the middle of the
+ * string.
+ *
+ * This is equivalent to adding the whitespace characters to the special
+ * characters lists, except it is guaranteed to use the exact same list
+ * of whitespace characters as the rest of libavutil.
+ */
+#define AV_ESCAPE_FLAG_WHITESPACE 0x01
+
+/**
+ * Escape only specified special characters.
+ * Without this flag, escape also any characters that may be considered
+ * special by av_get_token(), such as the single quote.
+ */
+#define AV_ESCAPE_FLAG_STRICT 0x02
+
+/**
+ * Escape string in src, and put the escaped string in an allocated
+ * string in *dst, which must be freed with av_free().
+ *
+ * @param dst           pointer where an allocated string is put
+ * @param src           string to escape, must be non-NULL
+ * @param special_chars string containing the special characters which
+ *                      need to be escaped, can be NULL
+ * @param mode          escape mode to employ, see AV_ESCAPE_MODE_* macros.
+ *                      Any unknown value for mode will be considered equivalent to
+ *                      AV_ESCAPE_MODE_BACKSLASH, but this behaviour can change without
+ *                      notice.
+ * @param flags         flags which control how to escape, see AV_ESCAPE_FLAG_ macros
+ * @return the length of the allocated string, or a negative error code in case of error
+ * @see av_bprint_escape()
+ */
+int av_escape(char **dst, const char *src, const char *special_chars,
+              enum AVEscapeMode mode, int flags);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_AVSTRING_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/avutil.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,314 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AVUTIL_H
+#define AVUTIL_AVUTIL_H
+
+/**
+ * @file
+ * external API header
+ */
+
+/**
+ * @mainpage
+ *
+ * @section ffmpeg_intro Introduction
+ *
+ * This document describes the usage of the different libraries
+ * provided by FFmpeg.
+ *
+ * @li @ref libavc "libavcodec" encoding/decoding library
+ * @li @ref lavfi "libavfilter" graph-based frame editing library
+ * @li @ref libavf "libavformat" I/O and muxing/demuxing library
+ * @li @ref lavd "libavdevice" special devices muxing/demuxing library
+ * @li @ref lavu "libavutil" common utility library
+ * @li @ref lswr "libswresample" audio resampling, format conversion and mixing
+ * @li @ref lpp  "libpostproc" post processing library
+ * @li @ref lsws "libswscale" color conversion and scaling library
+ *
+ * @section ffmpeg_versioning Versioning and compatibility
+ *
+ * Each of the FFmpeg libraries contains a version.h header, which defines a
+ * major, minor and micro version number with the
+ * <em>LIBRARYNAME_VERSION_{MAJOR,MINOR,MICRO}</em> macros. The major version
+ * number is incremented with backward incompatible changes - e.g. removing
+ * parts of the public API, reordering public struct members, etc. The minor
+ * version number is incremented for backward compatible API changes or major
+ * new features - e.g. adding a new public function or a new decoder. The micro
+ * version number is incremented for smaller changes that a calling program
+ * might still want to check for - e.g. changing behavior in a previously
+ * unspecified situation.
+ *
+ * FFmpeg guarantees backward API and ABI compatibility for each library as long
+ * as its major version number is unchanged. This means that no public symbols
+ * will be removed or renamed. Types and names of the public struct members and
+ * values of public macros and enums will remain the same (unless they were
+ * explicitly declared as not part of the public API). Documented behavior will
+ * not change.
+ *
+ * In other words, any correct program that works with a given FFmpeg snapshot
+ * should work just as well without any changes with any later snapshot with the
+ * same major versions. This applies to both rebuilding the program against new
+ * FFmpeg versions or to replacing the dynamic FFmpeg libraries that a program
+ * links against.
+ *
+ * However, new public symbols may be added and new members may be appended to
+ * public structs whose size is not part of public ABI (most public structs in
+ * FFmpeg). New macros and enum values may be added. Behavior in undocumented
+ * situations may change slightly (and be documented). All those are accompanied
+ * by an entry in doc/APIchanges and incrementing either the minor or micro
+ * version number.
+ */
+
+/**
+ * @defgroup lavu Common utility functions
+ *
+ * @brief
+ * libavutil contains the code shared across all the other FFmpeg
+ * libraries
+ *
+ * @note In order to use the functions provided by avutil you must include
+ * the specific header.
+ *
+ * @{
+ *
+ * @defgroup lavu_crypto Crypto and Hashing
+ *
+ * @{
+ * @}
+ *
+ * @defgroup lavu_math Maths
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_string String Manipulation
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_mem Memory Management
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_data Data Structures
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_audio Audio related
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_error Error Codes
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_misc Other
+ *
+ * @{
+ *
+ * @defgroup lavu_internal Internal
+ *
+ * Not exported functions, for internal usage only
+ *
+ * @{
+ *
+ * @}
+ */
+
+
+/**
+ * @addtogroup lavu_ver
+ * @{
+ */
+
+/**
+ * Return the LIBAVUTIL_VERSION_INT constant.
+ */
+unsigned avutil_version(void);
+
+/**
+ * Return the libavutil build-time configuration.
+ */
+const char *avutil_configuration(void);
+
+/**
+ * Return the libavutil license.
+ */
+const char *avutil_license(void);
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavu_media Media Type
+ * @brief Media Type
+ */
+
+enum AVMediaType {
+    AVMEDIA_TYPE_UNKNOWN = -1,  ///< Usually treated as AVMEDIA_TYPE_DATA
+    AVMEDIA_TYPE_VIDEO,
+    AVMEDIA_TYPE_AUDIO,
+    AVMEDIA_TYPE_DATA,          ///< Opaque data information usually continuous
+    AVMEDIA_TYPE_SUBTITLE,
+    AVMEDIA_TYPE_ATTACHMENT,    ///< Opaque data information usually sparse
+    AVMEDIA_TYPE_NB
+};
+
+/**
+ * Return a string describing the media_type enum, NULL if media_type
+ * is unknown.
+ */
+const char *av_get_media_type_string(enum AVMediaType media_type);
+
+/**
+ * @defgroup lavu_const Constants
+ * @{
+ *
+ * @defgroup lavu_enc Encoding specific
+ *
+ * @note those definition should move to avcodec
+ * @{
+ */
+
+#define FF_LAMBDA_SHIFT 7
+#define FF_LAMBDA_SCALE (1<<FF_LAMBDA_SHIFT)
+#define FF_QP2LAMBDA 118 ///< factor to convert from H.263 QP to lambda
+#define FF_LAMBDA_MAX (256*128-1)
+
+#define FF_QUALITY_SCALE FF_LAMBDA_SCALE //FIXME maybe remove
+
+/**
+ * @}
+ * @defgroup lavu_time Timestamp specific
+ *
+ * FFmpeg internal timebase and timestamp definitions
+ *
+ * @{
+ */
+
+/**
+ * @brief Undefined timestamp value
+ *
+ * Usually reported by demuxer that work on containers that do not provide
+ * either pts or dts.
+ */
+
+#define AV_NOPTS_VALUE          ((int64_t)UINT64_C(0x8000000000000000))
+
+/**
+ * Internal time base represented as integer
+ */
+
+#define AV_TIME_BASE            1000000
+
+/**
+ * Internal time base represented as fractional value
+ */
+
+#define AV_TIME_BASE_Q          (AVRational){1, AV_TIME_BASE}
+
+/**
+ * @}
+ * @}
+ * @defgroup lavu_picture Image related
+ *
+ * AVPicture types, pixel formats and basic image planes manipulation.
+ *
+ * @{
+ */
+
+enum AVPictureType {
+    AV_PICTURE_TYPE_NONE = 0, ///< Undefined
+    AV_PICTURE_TYPE_I,     ///< Intra
+    AV_PICTURE_TYPE_P,     ///< Predicted
+    AV_PICTURE_TYPE_B,     ///< Bi-dir predicted
+    AV_PICTURE_TYPE_S,     ///< S(GMC)-VOP MPEG4
+    AV_PICTURE_TYPE_SI,    ///< Switching Intra
+    AV_PICTURE_TYPE_SP,    ///< Switching Predicted
+    AV_PICTURE_TYPE_BI,    ///< BI type
+};
+
+/**
+ * Return a single letter to describe the given picture type
+ * pict_type.
+ *
+ * @param[in] pict_type the picture type @return a single character
+ * representing the picture type, '?' if pict_type is unknown
+ */
+char av_get_picture_type_char(enum AVPictureType pict_type);
+
+/**
+ * @}
+ */
+
+#include "common.h"
+#include "error.h"
+#include "version.h"
+#include "mathematics.h"
+#include "rational.h"
+#include "intfloat_readwrite.h"
+#include "log.h"
+#include "pixfmt.h"
+
+/**
+ * Return x default pointer in case p is NULL.
+ */
+static inline void *av_x_if_null(const void *p, const void *x)
+{
+    return (void *)(intptr_t)(p ? p : x);
+}
+
+/**
+ * Compute the length of an integer list.
+ *
+ * @param elsize  size in bytes of each list element (only 1, 2, 4 or 8)
+ * @param term    list terminator (usually 0 or -1)
+ * @param list    pointer to the list
+ * @return  length of the list, in elements, not counting the terminator
+ */
+unsigned av_int_list_length_for_size(unsigned elsize,
+                                     const void *list, uint64_t term) av_pure;
+
+/**
+ * Compute the length of an integer list.
+ *
+ * @param term  list terminator (usually 0 or -1)
+ * @param list  pointer to the list
+ * @return  length of the list, in elements, not counting the terminator
+ */
+#define av_int_list_length(list, term) \
+    av_int_list_length_for_size(sizeof(*(list)), list, term)
+
+/**
+ * @}
+ * @}
+ */
+
+#endif /* AVUTIL_AVUTIL_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/base64.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2006 Ryan Martell. (rdm4@martellventures.com)
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_BASE64_H
+#define AVUTIL_BASE64_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_base64 Base64
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+
+/**
+ * Decode a base64-encoded string.
+ *
+ * @param out      buffer for decoded data
+ * @param in       null-terminated input string
+ * @param out_size size in bytes of the out buffer, must be at
+ *                 least 3/4 of the length of in
+ * @return         number of bytes written, or a negative value in case of
+ *                 invalid input
+ */
+int av_base64_decode(uint8_t *out, const char *in, int out_size);
+
+/**
+ * Encode data to base64 and null-terminate.
+ *
+ * @param out      buffer for encoded data
+ * @param out_size size in bytes of the out buffer (including the
+ *                 null terminator), must be at least AV_BASE64_SIZE(in_size)
+ * @param in       input buffer containing the data to encode
+ * @param in_size  size in bytes of the in buffer
+ * @return         out or NULL in case of error
+ */
+char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size);
+
+/**
+ * Calculate the output size needed to base64-encode x bytes to a
+ * null-terminated string.
+ */
+#define AV_BASE64_SIZE(x)  (((x)+2) / 3 * 4 + 1)
+
+ /**
+  * @}
+  */
+
+#endif /* AVUTIL_BASE64_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/blowfish.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,77 @@
+/*
+ * Blowfish algorithm
+ * Copyright (c) 2012 Samuel Pitoiset
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_BLOWFISH_H
+#define AVUTIL_BLOWFISH_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_blowfish Blowfish
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+#define AV_BF_ROUNDS 16
+
+typedef struct AVBlowfish {
+    uint32_t p[AV_BF_ROUNDS + 2];
+    uint32_t s[4][256];
+} AVBlowfish;
+
+/**
+ * Initialize an AVBlowfish context.
+ *
+ * @param ctx an AVBlowfish context
+ * @param key a key
+ * @param key_len length of the key
+ */
+void av_blowfish_init(struct AVBlowfish *ctx, const uint8_t *key, int key_len);
+
+/**
+ * Encrypt or decrypt a buffer using a previously initialized context.
+ *
+ * @param ctx an AVBlowfish context
+ * @param xl left four bytes halves of input to be encrypted
+ * @param xr right four bytes halves of input to be encrypted
+ * @param decrypt 0 for encryption, 1 for decryption
+ */
+void av_blowfish_crypt_ecb(struct AVBlowfish *ctx, uint32_t *xl, uint32_t *xr,
+                           int decrypt);
+
+/**
+ * Encrypt or decrypt a buffer using a previously initialized context.
+ *
+ * @param ctx an AVBlowfish context
+ * @param dst destination array, can be equal to src
+ * @param src source array, can be equal to dst
+ * @param count number of 8 byte blocks
+ * @param iv initialization vector for CBC mode, if NULL ECB will be used
+ * @param decrypt 0 for encryption, 1 for decryption
+ */
+void av_blowfish_crypt(struct AVBlowfish *ctx, uint8_t *dst, const uint8_t *src,
+                       int count, uint8_t *iv, int decrypt);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_BLOWFISH_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/bprint.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2012 Nicolas George
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_BPRINT_H
+#define AVUTIL_BPRINT_H
+
+#include "attributes.h"
+#include "avstring.h"
+
+/**
+ * Define a structure with extra padding to a fixed size
+ * This helps ensuring binary compatibility with future versions.
+ */
+#define FF_PAD_STRUCTURE(size, ...) \
+    __VA_ARGS__ \
+    char reserved_padding[size - sizeof(struct { __VA_ARGS__ })];
+
+/**
+ * Buffer to print data progressively
+ *
+ * The string buffer grows as necessary and is always 0-terminated.
+ * The content of the string is never accessed, and thus is
+ * encoding-agnostic and can even hold binary data.
+ *
+ * Small buffers are kept in the structure itself, and thus require no
+ * memory allocation at all (unless the contents of the buffer is needed
+ * after the structure goes out of scope). This is almost as lightweight as
+ * declaring a local "char buf[512]".
+ *
+ * The length of the string can go beyond the allocated size: the buffer is
+ * then truncated, but the functions still keep account of the actual total
+ * length.
+ *
+ * In other words, buf->len can be greater than buf->size and records the
+ * total length of what would have been to the buffer if there had been
+ * enough memory.
+ *
+ * Append operations do not need to be tested for failure: if a memory
+ * allocation fails, data stop being appended to the buffer, but the length
+ * is still updated. This situation can be tested with
+ * av_bprint_is_complete().
+ *
+ * The size_max field determines several possible behaviours:
+ *
+ * size_max = -1 (= UINT_MAX) or any large value will let the buffer be
+ * reallocated as necessary, with an amortized linear cost.
+ *
+ * size_max = 0 prevents writing anything to the buffer: only the total
+ * length is computed. The write operations can then possibly be repeated in
+ * a buffer with exactly the necessary size
+ * (using size_init = size_max = len + 1).
+ *
+ * size_max = 1 is automatically replaced by the exact size available in the
+ * structure itself, thus ensuring no dynamic memory allocation. The
+ * internal buffer is large enough to hold a reasonable paragraph of text,
+ * such as the current paragraph.
+ */
+typedef struct AVBPrint {
+    FF_PAD_STRUCTURE(1024,
+    char *str;         /** string so far */
+    unsigned len;      /** length so far */
+    unsigned size;     /** allocated memory */
+    unsigned size_max; /** maximum allocated memory */
+    char reserved_internal_buffer[1];
+    )
+} AVBPrint;
+
+/**
+ * Convenience macros for special values for av_bprint_init() size_max
+ * parameter.
+ */
+#define AV_BPRINT_SIZE_UNLIMITED  ((unsigned)-1)
+#define AV_BPRINT_SIZE_AUTOMATIC  1
+#define AV_BPRINT_SIZE_COUNT_ONLY 0
+
+/**
+ * Init a print buffer.
+ *
+ * @param buf        buffer to init
+ * @param size_init  initial size (including the final 0)
+ * @param size_max   maximum size;
+ *                   0 means do not write anything, just count the length;
+ *                   1 is replaced by the maximum value for automatic storage;
+ *                   any large value means that the internal buffer will be
+ *                   reallocated as needed up to that limit; -1 is converted to
+ *                   UINT_MAX, the largest limit possible.
+ *                   Check also AV_BPRINT_SIZE_* macros.
+ */
+void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max);
+
+/**
+ * Init a print buffer using a pre-existing buffer.
+ *
+ * The buffer will not be reallocated.
+ *
+ * @param buf     buffer structure to init
+ * @param buffer  byte buffer to use for the string data
+ * @param size    size of buffer
+ */
+void av_bprint_init_for_buffer(AVBPrint *buf, char *buffer, unsigned size);
+
+/**
+ * Append a formatted string to a print buffer.
+ */
+void av_bprintf(AVBPrint *buf, const char *fmt, ...) av_printf_format(2, 3);
+
+/**
+ * Append char c n times to a print buffer.
+ */
+void av_bprint_chars(AVBPrint *buf, char c, unsigned n);
+
+struct tm;
+/**
+ * Append a formatted date and time to a print buffer.
+ *
+ * param buf  bprint buffer to use
+ * param fmt  date and time format string, see strftime()
+ * param tm   broken-down time structure to translate
+ *
+ * @note due to poor design of the standard strftime function, it may
+ * produce poor results if the format string expands to a very long text and
+ * the bprint buffer is near the limit stated by the size_max option.
+ */
+void av_bprint_strftime(AVBPrint *buf, const char *fmt, const struct tm *tm);
+
+/**
+ * Allocate bytes in the buffer for external use.
+ *
+ * @param[in]  buf          buffer structure
+ * @param[in]  size         required size
+ * @param[out] mem          pointer to the memory area
+ * @param[out] actual_size  size of the memory area after allocation;
+ *                          can be larger or smaller than size
+ */
+void av_bprint_get_buffer(AVBPrint *buf, unsigned size,
+                          unsigned char **mem, unsigned *actual_size);
+
+/**
+ * Reset the string to "" but keep internal allocated data.
+ */
+void av_bprint_clear(AVBPrint *buf);
+
+/**
+ * Test if the print buffer is complete (not truncated).
+ *
+ * It may have been truncated due to a memory allocation failure
+ * or the size_max limit (compare size and size_max if necessary).
+ */
+static inline int av_bprint_is_complete(AVBPrint *buf)
+{
+    return buf->len < buf->size;
+}
+
+/**
+ * Finalize a print buffer.
+ *
+ * The print buffer can no longer be used afterwards,
+ * but the len and size fields are still valid.
+ *
+ * @arg[out] ret_str  if not NULL, used to return a permanent copy of the
+ *                    buffer contents, or NULL if memory allocation fails;
+ *                    if NULL, the buffer is discarded and freed
+ * @return  0 for success or error code (probably AVERROR(ENOMEM))
+ */
+int av_bprint_finalize(AVBPrint *buf, char **ret_str);
+
+/**
+ * Escape the content in src and append it to dstbuf.
+ *
+ * @param dstbuf        already inited destination bprint buffer
+ * @param src           string containing the text to escape
+ * @param special_chars string containing the special characters which
+ *                      need to be escaped, can be NULL
+ * @param mode          escape mode to employ, see AV_ESCAPE_MODE_* macros.
+ *                      Any unknown value for mode will be considered equivalent to
+ *                      AV_ESCAPE_MODE_BACKSLASH, but this behaviour can change without
+ *                      notice.
+ * @param flags         flags which control how to escape, see AV_ESCAPE_FLAG_* macros
+ */
+void av_bprint_escape(AVBPrint *dstbuf, const char *src, const char *special_chars,
+                      enum AVEscapeMode mode, int flags);
+
+#endif /* AVUTIL_BPRINT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/bswap.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,109 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * byte swapping routines
+ */
+
+#ifndef AVUTIL_BSWAP_H
+#define AVUTIL_BSWAP_H
+
+#include <stdint.h>
+#include "libavutil/avconfig.h"
+#include "attributes.h"
+
+#ifdef HAVE_AV_CONFIG_H
+
+#include "config.h"
+
+#if   ARCH_ARM
+#   include "arm/bswap.h"
+#elif ARCH_AVR32
+#   include "avr32/bswap.h"
+#elif ARCH_BFIN
+#   include "bfin/bswap.h"
+#elif ARCH_SH4
+#   include "sh4/bswap.h"
+#elif ARCH_X86
+#   include "x86/bswap.h"
+#endif
+
+#endif /* HAVE_AV_CONFIG_H */
+
+#define AV_BSWAP16C(x) (((x) << 8 & 0xff00)  | ((x) >> 8 & 0x00ff))
+#define AV_BSWAP32C(x) (AV_BSWAP16C(x) << 16 | AV_BSWAP16C((x) >> 16))
+#define AV_BSWAP64C(x) (AV_BSWAP32C(x) << 32 | AV_BSWAP32C((x) >> 32))
+
+#define AV_BSWAPC(s, x) AV_BSWAP##s##C(x)
+
+#ifndef av_bswap16
+static av_always_inline av_const uint16_t av_bswap16(uint16_t x)
+{
+    x= (x>>8) | (x<<8);
+    return x;
+}
+#endif
+
+#ifndef av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
+{
+    return AV_BSWAP32C(x);
+}
+#endif
+
+#ifndef av_bswap64
+static inline uint64_t av_const av_bswap64(uint64_t x)
+{
+    return (uint64_t)av_bswap32(x) << 32 | av_bswap32(x >> 32);
+}
+#endif
+
+// be2ne ... big-endian to native-endian
+// le2ne ... little-endian to native-endian
+
+#if AV_HAVE_BIGENDIAN
+#define av_be2ne16(x) (x)
+#define av_be2ne32(x) (x)
+#define av_be2ne64(x) (x)
+#define av_le2ne16(x) av_bswap16(x)
+#define av_le2ne32(x) av_bswap32(x)
+#define av_le2ne64(x) av_bswap64(x)
+#define AV_BE2NEC(s, x) (x)
+#define AV_LE2NEC(s, x) AV_BSWAPC(s, x)
+#else
+#define av_be2ne16(x) av_bswap16(x)
+#define av_be2ne32(x) av_bswap32(x)
+#define av_be2ne64(x) av_bswap64(x)
+#define av_le2ne16(x) (x)
+#define av_le2ne32(x) (x)
+#define av_le2ne64(x) (x)
+#define AV_BE2NEC(s, x) AV_BSWAPC(s, x)
+#define AV_LE2NEC(s, x) (x)
+#endif
+
+#define AV_BE2NE16C(x) AV_BE2NEC(16, x)
+#define AV_BE2NE32C(x) AV_BE2NEC(32, x)
+#define AV_BE2NE64C(x) AV_BE2NEC(64, x)
+#define AV_LE2NE16C(x) AV_LE2NEC(16, x)
+#define AV_LE2NE32C(x) AV_LE2NEC(32, x)
+#define AV_LE2NE64C(x) AV_LE2NEC(64, x)
+
+#endif /* AVUTIL_BSWAP_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/buffer.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,274 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @ingroup lavu_buffer
+ * refcounted data buffer API
+ */
+
+#ifndef AVUTIL_BUFFER_H
+#define AVUTIL_BUFFER_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_buffer AVBuffer
+ * @ingroup lavu_data
+ *
+ * @{
+ * AVBuffer is an API for reference-counted data buffers.
+ *
+ * There are two core objects in this API -- AVBuffer and AVBufferRef. AVBuffer
+ * represents the data buffer itself; it is opaque and not meant to be accessed
+ * by the caller directly, but only through AVBufferRef. However, the caller may
+ * e.g. compare two AVBuffer pointers to check whether two different references
+ * are describing the same data buffer. AVBufferRef represents a single
+ * reference to an AVBuffer and it is the object that may be manipulated by the
+ * caller directly.
+ *
+ * There are two functions provided for creating a new AVBuffer with a single
+ * reference -- av_buffer_alloc() to just allocate a new buffer, and
+ * av_buffer_create() to wrap an existing array in an AVBuffer. From an existing
+ * reference, additional references may be created with av_buffer_ref().
+ * Use av_buffer_unref() to free a reference (this will automatically free the
+ * data once all the references are freed).
+ *
+ * The convention throughout this API and the rest of FFmpeg is such that the
+ * buffer is considered writable if there exists only one reference to it (and
+ * it has not been marked as read-only). The av_buffer_is_writable() function is
+ * provided to check whether this is true and av_buffer_make_writable() will
+ * automatically create a new writable buffer when necessary.
+ * Of course nothing prevents the calling code from violating this convention,
+ * however that is safe only when all the existing references are under its
+ * control.
+ *
+ * @note Referencing and unreferencing the buffers is thread-safe and thus
+ * may be done from multiple threads simultaneously without any need for
+ * additional locking.
+ *
+ * @note Two different references to the same buffer can point to different
+ * parts of the buffer (i.e. their AVBufferRef.data will not be equal).
+ */
+
+/**
+ * A reference counted buffer type. It is opaque and is meant to be used through
+ * references (AVBufferRef).
+ */
+typedef struct AVBuffer AVBuffer;
+
+/**
+ * A reference to a data buffer.
+ *
+ * The size of this struct is not a part of the public ABI and it is not meant
+ * to be allocated directly.
+ */
+typedef struct AVBufferRef {
+    AVBuffer *buffer;
+
+    /**
+     * The data buffer. It is considered writable if and only if
+     * this is the only reference to the buffer, in which case
+     * av_buffer_is_writable() returns 1.
+     */
+    uint8_t *data;
+    /**
+     * Size of data in bytes.
+     */
+    int      size;
+} AVBufferRef;
+
+/**
+ * Allocate an AVBuffer of the given size using av_malloc().
+ *
+ * @return an AVBufferRef of given size or NULL when out of memory
+ */
+AVBufferRef *av_buffer_alloc(int size);
+
+/**
+ * Same as av_buffer_alloc(), except the returned buffer will be initialized
+ * to zero.
+ */
+AVBufferRef *av_buffer_allocz(int size);
+
+/**
+ * Always treat the buffer as read-only, even when it has only one
+ * reference.
+ */
+#define AV_BUFFER_FLAG_READONLY (1 << 0)
+
+/**
+ * Create an AVBuffer from an existing array.
+ *
+ * If this function is successful, data is owned by the AVBuffer. The caller may
+ * only access data through the returned AVBufferRef and references derived from
+ * it.
+ * If this function fails, data is left untouched.
+ * @param data   data array
+ * @param size   size of data in bytes
+ * @param free   a callback for freeing this buffer's data
+ * @param opaque parameter to be got for processing or passed to free
+ * @param flags  a combination of AV_BUFFER_FLAG_*
+ *
+ * @return an AVBufferRef referring to data on success, NULL on failure.
+ */
+AVBufferRef *av_buffer_create(uint8_t *data, int size,
+                              void (*free)(void *opaque, uint8_t *data),
+                              void *opaque, int flags);
+
+/**
+ * Default free callback, which calls av_free() on the buffer data.
+ * This function is meant to be passed to av_buffer_create(), not called
+ * directly.
+ */
+void av_buffer_default_free(void *opaque, uint8_t *data);
+
+/**
+ * Create a new reference to an AVBuffer.
+ *
+ * @return a new AVBufferRef referring to the same AVBuffer as buf or NULL on
+ * failure.
+ */
+AVBufferRef *av_buffer_ref(AVBufferRef *buf);
+
+/**
+ * Free a given reference and automatically free the buffer if there are no more
+ * references to it.
+ *
+ * @param buf the reference to be freed. The pointer is set to NULL on return.
+ */
+void av_buffer_unref(AVBufferRef **buf);
+
+/**
+ * @return 1 if the caller may write to the data referred to by buf (which is
+ * true if and only if buf is the only reference to the underlying AVBuffer).
+ * Return 0 otherwise.
+ * A positive answer is valid until av_buffer_ref() is called on buf.
+ */
+int av_buffer_is_writable(const AVBufferRef *buf);
+
+/**
+ * @return the opaque parameter set by av_buffer_create.
+ */
+void *av_buffer_get_opaque(const AVBufferRef *buf);
+
+int av_buffer_get_ref_count(const AVBufferRef *buf);
+
+/**
+ * Create a writable reference from a given buffer reference, avoiding data copy
+ * if possible.
+ *
+ * @param buf buffer reference to make writable. On success, buf is either left
+ *            untouched, or it is unreferenced and a new writable AVBufferRef is
+ *            written in its place. On failure, buf is left untouched.
+ * @return 0 on success, a negative AVERROR on failure.
+ */
+int av_buffer_make_writable(AVBufferRef **buf);
+
+/**
+ * Reallocate a given buffer.
+ *
+ * @param buf  a buffer reference to reallocate. On success, buf will be
+ *             unreferenced and a new reference with the required size will be
+ *             written in its place. On failure buf will be left untouched. *buf
+ *             may be NULL, then a new buffer is allocated.
+ * @param size required new buffer size.
+ * @return 0 on success, a negative AVERROR on failure.
+ *
+ * @note the buffer is actually reallocated with av_realloc() only if it was
+ * initially allocated through av_buffer_realloc(NULL) and there is only one
+ * reference to it (i.e. the one passed to this function). In all other cases
+ * a new buffer is allocated and the data is copied.
+ */
+int av_buffer_realloc(AVBufferRef **buf, int size);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavu_bufferpool AVBufferPool
+ * @ingroup lavu_data
+ *
+ * @{
+ * AVBufferPool is an API for a lock-free thread-safe pool of AVBuffers.
+ *
+ * Frequently allocating and freeing large buffers may be slow. AVBufferPool is
+ * meant to solve this in cases when the caller needs a set of buffers of the
+ * same size (the most obvious use case being buffers for raw video or audio
+ * frames).
+ *
+ * At the beginning, the user must call av_buffer_pool_init() to create the
+ * buffer pool. Then whenever a buffer is needed, call av_buffer_pool_get() to
+ * get a reference to a new buffer, similar to av_buffer_alloc(). This new
+ * reference works in all aspects the same way as the one created by
+ * av_buffer_alloc(). However, when the last reference to this buffer is
+ * unreferenced, it is returned to the pool instead of being freed and will be
+ * reused for subsequent av_buffer_pool_get() calls.
+ *
+ * When the caller is done with the pool and no longer needs to allocate any new
+ * buffers, av_buffer_pool_uninit() must be called to mark the pool as freeable.
+ * Once all the buffers are released, it will automatically be freed.
+ *
+ * Allocating and releasing buffers with this API is thread-safe as long as
+ * either the default alloc callback is used, or the user-supplied one is
+ * thread-safe.
+ */
+
+/**
+ * The buffer pool. This structure is opaque and not meant to be accessed
+ * directly. It is allocated with av_buffer_pool_init() and freed with
+ * av_buffer_pool_uninit().
+ */
+typedef struct AVBufferPool AVBufferPool;
+
+/**
+ * Allocate and initialize a buffer pool.
+ *
+ * @param size size of each buffer in this pool
+ * @param alloc a function that will be used to allocate new buffers when the
+ * pool is empty. May be NULL, then the default allocator will be used
+ * (av_buffer_alloc()).
+ * @return newly created buffer pool on success, NULL on error.
+ */
+AVBufferPool *av_buffer_pool_init(int size, AVBufferRef* (*alloc)(int size));
+
+/**
+ * Mark the pool as being available for freeing. It will actually be freed only
+ * once all the allocated buffers associated with the pool are released. Thus it
+ * is safe to call this function while some of the allocated buffers are still
+ * in use.
+ *
+ * @param pool pointer to the pool to be freed. It will be set to NULL.
+ * @see av_buffer_pool_can_uninit()
+ */
+void av_buffer_pool_uninit(AVBufferPool **pool);
+
+/**
+ * Allocate a new AVBuffer, reusing an old buffer from the pool when available.
+ * This function may be called simultaneously from multiple threads.
+ *
+ * @return a reference to the new buffer on success, NULL on error.
+ */
+AVBufferRef *av_buffer_pool_get(AVBufferPool *pool);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_BUFFER_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/channel_layout.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ * Copyright (c) 2008 Peter Ross
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CHANNEL_LAYOUT_H
+#define AVUTIL_CHANNEL_LAYOUT_H
+
+#include <stdint.h>
+
+/**
+ * @file
+ * audio channel layout utility functions
+ */
+
+/**
+ * @addtogroup lavu_audio
+ * @{
+ */
+
+/**
+ * @defgroup channel_masks Audio channel masks
+ *
+ * A channel layout is a 64-bits integer with a bit set for every channel.
+ * The number of bits set must be equal to the number of channels.
+ * The value 0 means that the channel layout is not known.
+ * @note this data structure is not powerful enough to handle channels
+ * combinations that have the same channel multiple times, such as
+ * dual-mono.
+ *
+ * @{
+ */
+#define AV_CH_FRONT_LEFT             0x00000001
+#define AV_CH_FRONT_RIGHT            0x00000002
+#define AV_CH_FRONT_CENTER           0x00000004
+#define AV_CH_LOW_FREQUENCY          0x00000008
+#define AV_CH_BACK_LEFT              0x00000010
+#define AV_CH_BACK_RIGHT             0x00000020
+#define AV_CH_FRONT_LEFT_OF_CENTER   0x00000040
+#define AV_CH_FRONT_RIGHT_OF_CENTER  0x00000080
+#define AV_CH_BACK_CENTER            0x00000100
+#define AV_CH_SIDE_LEFT              0x00000200
+#define AV_CH_SIDE_RIGHT             0x00000400
+#define AV_CH_TOP_CENTER             0x00000800
+#define AV_CH_TOP_FRONT_LEFT         0x00001000
+#define AV_CH_TOP_FRONT_CENTER       0x00002000
+#define AV_CH_TOP_FRONT_RIGHT        0x00004000
+#define AV_CH_TOP_BACK_LEFT          0x00008000
+#define AV_CH_TOP_BACK_CENTER        0x00010000
+#define AV_CH_TOP_BACK_RIGHT         0x00020000
+#define AV_CH_STEREO_LEFT            0x20000000  ///< Stereo downmix.
+#define AV_CH_STEREO_RIGHT           0x40000000  ///< See AV_CH_STEREO_LEFT.
+#define AV_CH_WIDE_LEFT              0x0000000080000000ULL
+#define AV_CH_WIDE_RIGHT             0x0000000100000000ULL
+#define AV_CH_SURROUND_DIRECT_LEFT   0x0000000200000000ULL
+#define AV_CH_SURROUND_DIRECT_RIGHT  0x0000000400000000ULL
+#define AV_CH_LOW_FREQUENCY_2        0x0000000800000000ULL
+
+/** Channel mask value used for AVCodecContext.request_channel_layout
+    to indicate that the user requests the channel order of the decoder output
+    to be the native codec channel order. */
+#define AV_CH_LAYOUT_NATIVE          0x8000000000000000ULL
+
+/**
+ * @}
+ * @defgroup channel_mask_c Audio channel convenience macros
+ * @{
+ * */
+#define AV_CH_LAYOUT_MONO              (AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_STEREO            (AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT)
+#define AV_CH_LAYOUT_2POINT1           (AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_2_1               (AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_SURROUND          (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_3POINT1           (AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_4POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_4POINT1           (AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_2_2               (AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_QUAD              (AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_5POINT1           (AV_CH_LAYOUT_5POINT0|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_5POINT0_BACK      (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT1_BACK      (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_6POINT0           (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT0_FRONT     (AV_CH_LAYOUT_2_2|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_HEXAGONAL         (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1           (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_BACK      (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_FRONT     (AV_CH_LAYOUT_6POINT0_FRONT|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_7POINT0           (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT0_FRONT     (AV_CH_LAYOUT_5POINT0|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_7POINT1           (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT1_WIDE      (AV_CH_LAYOUT_5POINT1|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_7POINT1_WIDE_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_OCTAGONAL         (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_CENTER|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_STEREO_DOWNMIX    (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT)
+
+enum AVMatrixEncoding {
+    AV_MATRIX_ENCODING_NONE,
+    AV_MATRIX_ENCODING_DOLBY,
+    AV_MATRIX_ENCODING_DPLII,
+    AV_MATRIX_ENCODING_NB
+};
+
+/**
+ * @}
+ */
+
+/**
+ * Return a channel layout id that matches name, or 0 if no match is found.
+ *
+ * name can be one or several of the following notations,
+ * separated by '+' or '|':
+ * - the name of an usual channel layout (mono, stereo, 4.0, quad, 5.0,
+ *   5.0(side), 5.1, 5.1(side), 7.1, 7.1(wide), downmix);
+ * - the name of a single channel (FL, FR, FC, LFE, BL, BR, FLC, FRC, BC,
+ *   SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR);
+ * - a number of channels, in decimal, optionally followed by 'c', yielding
+ *   the default channel layout for that number of channels (@see
+ *   av_get_default_channel_layout);
+ * - a channel layout mask, in hexadecimal starting with "0x" (see the
+ *   AV_CH_* macros).
+ *
+ * Example: "stereo+FC" = "2+FC" = "2c+1c" = "0x7"
+ */
+uint64_t av_get_channel_layout(const char *name);
+
+/**
+ * Return a description of a channel layout.
+ * If nb_channels is <= 0, it is guessed from the channel_layout.
+ *
+ * @param buf put here the string containing the channel layout
+ * @param buf_size size in bytes of the buffer
+ */
+void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout);
+
+struct AVBPrint;
+/**
+ * Append a description of a channel layout to a bprint buffer.
+ */
+void av_bprint_channel_layout(struct AVBPrint *bp, int nb_channels, uint64_t channel_layout);
+
+/**
+ * Return the number of channels in the channel layout.
+ */
+int av_get_channel_layout_nb_channels(uint64_t channel_layout);
+
+/**
+ * Return default channel layout for a given number of channels.
+ */
+int64_t av_get_default_channel_layout(int nb_channels);
+
+/**
+ * Get the index of a channel in channel_layout.
+ *
+ * @param channel a channel layout describing exactly one channel which must be
+ *                present in channel_layout.
+ *
+ * @return index of channel in channel_layout on success, a negative AVERROR
+ *         on error.
+ */
+int av_get_channel_layout_channel_index(uint64_t channel_layout,
+                                        uint64_t channel);
+
+/**
+ * Get the channel with the given index in channel_layout.
+ */
+uint64_t av_channel_layout_extract_channel(uint64_t channel_layout, int index);
+
+/**
+ * Get the name of a given channel.
+ *
+ * @return channel name on success, NULL on error.
+ */
+const char *av_get_channel_name(uint64_t channel);
+
+/**
+ * Get the description of a given channel.
+ *
+ * @param channel  a channel layout with a single channel
+ * @return  channel description on success, NULL on error
+ */
+const char *av_get_channel_description(uint64_t channel);
+
+/**
+ * Get the value and name of a standard channel layout.
+ *
+ * @param[in]  index   index in an internal list, starting at 0
+ * @param[out] layout  channel layout mask
+ * @param[out] name    name of the layout
+ * @return  0  if the layout exists,
+ *          <0 if index is beyond the limits
+ */
+int av_get_standard_channel_layout(unsigned index, uint64_t *layout,
+                                   const char **name);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_CHANNEL_LAYOUT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/common.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,459 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * common internal and external API header
+ */
+
+#ifndef AVUTIL_COMMON_H
+#define AVUTIL_COMMON_H
+
+#include <errno.h>
+#include <stdint.h>
+#include <limits.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "attributes.h"
+#include "version.h"
+#include "avconfig.h"
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_NE(be, le) (be)
+#else
+#   define AV_NE(be, le) (le)
+#endif
+
+//rounded division & shift
+#define RSHIFT(a,b) ((a) > 0 ? ((a) + ((1<<(b))>>1))>>(b) : ((a) + ((1<<(b))>>1)-1)>>(b))
+/* assume b>0 */
+#define ROUNDED_DIV(a,b) (((a)>0 ? (a) + ((b)>>1) : (a) - ((b)>>1))/(b))
+/* assume a>0 and b>0 */
+#define FF_CEIL_RSHIFT(a,b) (!av_builtin_constant_p(b) ? -((-(a)) >> (b)) \
+                                                       : ((a) + (1<<(b)) - 1) >> (b))
+#define FFUDIV(a,b) (((a)>0 ?(a):(a)-(b)+1) / (b))
+#define FFUMOD(a,b) ((a)-(b)*FFUDIV(a,b))
+#define FFABS(a) ((a) >= 0 ? (a) : (-(a)))
+#define FFSIGN(a) ((a) > 0 ? 1 : -1)
+
+#define FFMAX(a,b) ((a) > (b) ? (a) : (b))
+#define FFMAX3(a,b,c) FFMAX(FFMAX(a,b),c)
+#define FFMIN(a,b) ((a) > (b) ? (b) : (a))
+#define FFMIN3(a,b,c) FFMIN(FFMIN(a,b),c)
+
+#define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0)
+#define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0]))
+#define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1))
+
+/* misc math functions */
+
+/**
+ * Reverse the order of the bits of an 8-bits unsigned integer.
+ */
+#if FF_API_AV_REVERSE
+extern attribute_deprecated const uint8_t av_reverse[256];
+#endif
+
+#ifdef HAVE_AV_CONFIG_H
+#   include "config.h"
+#   include "intmath.h"
+#endif
+
+/* Pull in unguarded fallback defines at the end of this file. */
+#include "common.h"
+
+#ifndef av_log2
+av_const int av_log2(unsigned v);
+#endif
+
+#ifndef av_log2_16bit
+av_const int av_log2_16bit(unsigned v);
+#endif
+
+/**
+ * Clip a signed integer value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const int av_clip_c(int a, int amin, int amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+    if (amin > amax) abort();
+#endif
+    if      (a < amin) return amin;
+    else if (a > amax) return amax;
+    else               return a;
+}
+
+/**
+ * Clip a signed 64bit integer value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const int64_t av_clip64_c(int64_t a, int64_t amin, int64_t amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+    if (amin > amax) abort();
+#endif
+    if      (a < amin) return amin;
+    else if (a > amax) return amax;
+    else               return a;
+}
+
+/**
+ * Clip a signed integer value into the 0-255 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const uint8_t av_clip_uint8_c(int a)
+{
+    if (a&(~0xFF)) return (-a)>>31;
+    else           return a;
+}
+
+/**
+ * Clip a signed integer value into the -128,127 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int8_t av_clip_int8_c(int a)
+{
+    if ((a+0x80) & ~0xFF) return (a>>31) ^ 0x7F;
+    else                  return a;
+}
+
+/**
+ * Clip a signed integer value into the 0-65535 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const uint16_t av_clip_uint16_c(int a)
+{
+    if (a&(~0xFFFF)) return (-a)>>31;
+    else             return a;
+}
+
+/**
+ * Clip a signed integer value into the -32768,32767 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int16_t av_clip_int16_c(int a)
+{
+    if ((a+0x8000) & ~0xFFFF) return (a>>31) ^ 0x7FFF;
+    else                      return a;
+}
+
+/**
+ * Clip a signed 64-bit integer value into the -2147483648,2147483647 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int32_t av_clipl_int32_c(int64_t a)
+{
+    if ((a+0x80000000u) & ~UINT64_C(0xFFFFFFFF)) return (a>>63) ^ 0x7FFFFFFF;
+    else                                         return (int32_t)a;
+}
+
+/**
+ * Clip a signed integer to an unsigned power of two range.
+ * @param  a value to clip
+ * @param  p bit position to clip at
+ * @return clipped value
+ */
+static av_always_inline av_const unsigned av_clip_uintp2_c(int a, int p)
+{
+    if (a & ~((1<<p) - 1)) return -a >> 31 & ((1<<p) - 1);
+    else                   return  a;
+}
+
+/**
+ * Add two signed 32-bit values with saturation.
+ *
+ * @param  a one value
+ * @param  b another value
+ * @return sum with signed saturation
+ */
+static av_always_inline int av_sat_add32_c(int a, int b)
+{
+    return av_clipl_int32((int64_t)a + b);
+}
+
+/**
+ * Add a doubled value to another value with saturation at both stages.
+ *
+ * @param  a first value
+ * @param  b value doubled and added to a
+ * @return sum with signed saturation
+ */
+static av_always_inline int av_sat_dadd32_c(int a, int b)
+{
+    return av_sat_add32(a, av_sat_add32(b, b));
+}
+
+/**
+ * Clip a float value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const float av_clipf_c(float a, float amin, float amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+    if (amin > amax) abort();
+#endif
+    if      (a < amin) return amin;
+    else if (a > amax) return amax;
+    else               return a;
+}
+
+/**
+ * Clip a double value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const double av_clipd_c(double a, double amin, double amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+    if (amin > amax) abort();
+#endif
+    if      (a < amin) return amin;
+    else if (a > amax) return amax;
+    else               return a;
+}
+
+/** Compute ceil(log2(x)).
+ * @param x value used to compute ceil(log2(x))
+ * @return computed ceiling of log2(x)
+ */
+static av_always_inline av_const int av_ceil_log2_c(int x)
+{
+    return av_log2((x - 1) << 1);
+}
+
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount_c(uint32_t x)
+{
+    x -= (x >> 1) & 0x55555555;
+    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
+    x = (x + (x >> 4)) & 0x0F0F0F0F;
+    x += x >> 8;
+    return (x + (x >> 16)) & 0x3F;
+}
+
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount64_c(uint64_t x)
+{
+    return av_popcount((uint32_t)x) + av_popcount(x >> 32);
+}
+
+#define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((unsigned)(d) << 24))
+#define MKBETAG(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((unsigned)(a) << 24))
+
+/**
+ * Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val      Output value, must be an lvalue of type uint32_t.
+ * @param GET_BYTE Expression reading one byte from the input.
+ *                 Evaluated up to 7 times (4 for the currently
+ *                 assigned Unicode range).  With a memory buffer
+ *                 input, this could be *ptr++.
+ * @param ERROR    Expression to be evaluated on invalid input,
+ *                 typically a goto statement.
+ */
+#define GET_UTF8(val, GET_BYTE, ERROR)\
+    val= GET_BYTE;\
+    {\
+        uint32_t top = (val & 128) >> 1;\
+        if ((val & 0xc0) == 0x80 || val >= 0xFE)\
+            ERROR\
+        while (val & top) {\
+            int tmp= GET_BYTE - 128;\
+            if(tmp>>6)\
+                ERROR\
+            val= (val<<6) + tmp;\
+            top <<= 5;\
+        }\
+        val &= (top << 1) - 1;\
+    }
+
+/**
+ * Convert a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val       Output value, must be an lvalue of type uint32_t.
+ * @param GET_16BIT Expression returning two bytes of UTF-16 data converted
+ *                  to native byte order.  Evaluated one or two times.
+ * @param ERROR     Expression to be evaluated on invalid input,
+ *                  typically a goto statement.
+ */
+#define GET_UTF16(val, GET_16BIT, ERROR)\
+    val = GET_16BIT;\
+    {\
+        unsigned int hi = val - 0xD800;\
+        if (hi < 0x800) {\
+            val = GET_16BIT - 0xDC00;\
+            if (val > 0x3FFU || hi > 0x3FFU)\
+                ERROR\
+            val += (hi<<10) + 0x10000;\
+        }\
+    }\
+
+/**
+ * @def PUT_UTF8(val, tmp, PUT_BYTE)
+ * Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
+ * @param val is an input-only argument and should be of type uint32_t. It holds
+ * a UCS-4 encoded Unicode character that is to be converted to UTF-8. If
+ * val is given as a function it is executed only once.
+ * @param tmp is a temporary variable and should be of type uint8_t. It
+ * represents an intermediate value during conversion that is to be
+ * output by PUT_BYTE.
+ * @param PUT_BYTE writes the converted UTF-8 bytes to any proper destination.
+ * It could be a function or a statement, and uses tmp as the input byte.
+ * For example, PUT_BYTE could be "*output++ = tmp;" PUT_BYTE will be
+ * executed up to 4 times for values in the valid UTF-8 range and up to
+ * 7 times in the general case, depending on the length of the converted
+ * Unicode character.
+ */
+#define PUT_UTF8(val, tmp, PUT_BYTE)\
+    {\
+        int bytes, shift;\
+        uint32_t in = val;\
+        if (in < 0x80) {\
+            tmp = in;\
+            PUT_BYTE\
+        } else {\
+            bytes = (av_log2(in) + 4) / 5;\
+            shift = (bytes - 1) * 6;\
+            tmp = (256 - (256 >> bytes)) | (in >> shift);\
+            PUT_BYTE\
+            while (shift >= 6) {\
+                shift -= 6;\
+                tmp = 0x80 | ((in >> shift) & 0x3f);\
+                PUT_BYTE\
+            }\
+        }\
+    }
+
+/**
+ * @def PUT_UTF16(val, tmp, PUT_16BIT)
+ * Convert a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes).
+ * @param val is an input-only argument and should be of type uint32_t. It holds
+ * a UCS-4 encoded Unicode character that is to be converted to UTF-16. If
+ * val is given as a function it is executed only once.
+ * @param tmp is a temporary variable and should be of type uint16_t. It
+ * represents an intermediate value during conversion that is to be
+ * output by PUT_16BIT.
+ * @param PUT_16BIT writes the converted UTF-16 data to any proper destination
+ * in desired endianness. It could be a function or a statement, and uses tmp
+ * as the input byte.  For example, PUT_BYTE could be "*output++ = tmp;"
+ * PUT_BYTE will be executed 1 or 2 times depending on input character.
+ */
+#define PUT_UTF16(val, tmp, PUT_16BIT)\
+    {\
+        uint32_t in = val;\
+        if (in < 0x10000) {\
+            tmp = in;\
+            PUT_16BIT\
+        } else {\
+            tmp = 0xD800 | ((in - 0x10000) >> 10);\
+            PUT_16BIT\
+            tmp = 0xDC00 | ((in - 0x10000) & 0x3FF);\
+            PUT_16BIT\
+        }\
+    }\
+
+
+
+#include "mem.h"
+
+#ifdef HAVE_AV_CONFIG_H
+#    include "internal.h"
+#endif /* HAVE_AV_CONFIG_H */
+
+#endif /* AVUTIL_COMMON_H */
+
+/*
+ * The following definitions are outside the multiple inclusion guard
+ * to ensure they are immediately available in intmath.h.
+ */
+
+#ifndef av_ceil_log2
+#   define av_ceil_log2     av_ceil_log2_c
+#endif
+#ifndef av_clip
+#   define av_clip          av_clip_c
+#endif
+#ifndef av_clip64
+#   define av_clip64        av_clip64_c
+#endif
+#ifndef av_clip_uint8
+#   define av_clip_uint8    av_clip_uint8_c
+#endif
+#ifndef av_clip_int8
+#   define av_clip_int8     av_clip_int8_c
+#endif
+#ifndef av_clip_uint16
+#   define av_clip_uint16   av_clip_uint16_c
+#endif
+#ifndef av_clip_int16
+#   define av_clip_int16    av_clip_int16_c
+#endif
+#ifndef av_clipl_int32
+#   define av_clipl_int32   av_clipl_int32_c
+#endif
+#ifndef av_clip_uintp2
+#   define av_clip_uintp2   av_clip_uintp2_c
+#endif
+#ifndef av_sat_add32
+#   define av_sat_add32     av_sat_add32_c
+#endif
+#ifndef av_sat_dadd32
+#   define av_sat_dadd32    av_sat_dadd32_c
+#endif
+#ifndef av_clipf
+#   define av_clipf         av_clipf_c
+#endif
+#ifndef av_clipd
+#   define av_clipd         av_clipd_c
+#endif
+#ifndef av_popcount
+#   define av_popcount      av_popcount_c
+#endif
+#ifndef av_popcount64
+#   define av_popcount64    av_popcount64_c
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/cpu.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CPU_H
+#define AVUTIL_CPU_H
+
+#include "attributes.h"
+
+#define AV_CPU_FLAG_FORCE    0x80000000 /* force usage of selected flags (OR) */
+
+    /* lower 16 bits - CPU features */
+#define AV_CPU_FLAG_MMX          0x0001 ///< standard MMX
+#define AV_CPU_FLAG_MMXEXT       0x0002 ///< SSE integer functions or AMD MMX ext
+#define AV_CPU_FLAG_MMX2         0x0002 ///< SSE integer functions or AMD MMX ext
+#define AV_CPU_FLAG_3DNOW        0x0004 ///< AMD 3DNOW
+#define AV_CPU_FLAG_SSE          0x0008 ///< SSE functions
+#define AV_CPU_FLAG_SSE2         0x0010 ///< PIV SSE2 functions
+#define AV_CPU_FLAG_SSE2SLOW 0x40000000 ///< SSE2 supported, but usually not faster
+#define AV_CPU_FLAG_3DNOWEXT     0x0020 ///< AMD 3DNowExt
+#define AV_CPU_FLAG_SSE3         0x0040 ///< Prescott SSE3 functions
+#define AV_CPU_FLAG_SSE3SLOW 0x20000000 ///< SSE3 supported, but usually not faster
+#define AV_CPU_FLAG_SSSE3        0x0080 ///< Conroe SSSE3 functions
+#define AV_CPU_FLAG_ATOM     0x10000000 ///< Atom processor, some SSSE3 instructions are slower
+#define AV_CPU_FLAG_SSE4         0x0100 ///< Penryn SSE4.1 functions
+#define AV_CPU_FLAG_SSE42        0x0200 ///< Nehalem SSE4.2 functions
+#define AV_CPU_FLAG_AVX          0x4000 ///< AVX functions: requires OS support even if YMM registers aren't used
+#define AV_CPU_FLAG_XOP          0x0400 ///< Bulldozer XOP functions
+#define AV_CPU_FLAG_FMA4         0x0800 ///< Bulldozer FMA4 functions
+// #if LIBAVUTIL_VERSION_MAJOR <52
+#define AV_CPU_FLAG_CMOV      0x1001000 ///< supports cmov instruction
+// #else
+// #define AV_CPU_FLAG_CMOV         0x1000 ///< supports cmov instruction
+// #endif
+
+#define AV_CPU_FLAG_ALTIVEC      0x0001 ///< standard
+
+#define AV_CPU_FLAG_ARMV5TE      (1 << 0)
+#define AV_CPU_FLAG_ARMV6        (1 << 1)
+#define AV_CPU_FLAG_ARMV6T2      (1 << 2)
+#define AV_CPU_FLAG_VFP          (1 << 3)
+#define AV_CPU_FLAG_VFPV3        (1 << 4)
+#define AV_CPU_FLAG_NEON         (1 << 5)
+
+/**
+ * Return the flags which specify extensions supported by the CPU.
+ * The returned value is affected by av_force_cpu_flags() if that was used
+ * before. So av_get_cpu_flags() can easily be used in a application to
+ * detect the enabled cpu flags.
+ */
+int av_get_cpu_flags(void);
+
+/**
+ * Disables cpu detection and forces the specified flags.
+ * -1 is a special case that disables forcing of specific flags.
+ */
+void av_force_cpu_flags(int flags);
+
+/**
+ * Set a mask on flags returned by av_get_cpu_flags().
+ * This function is mainly useful for testing.
+ * Please use av_force_cpu_flags() and av_get_cpu_flags() instead which are more flexible
+ *
+ * @warning this function is not thread safe.
+ */
+attribute_deprecated void av_set_cpu_flags_mask(int mask);
+
+/**
+ * Parse CPU flags from a string.
+ *
+ * The returned flags contain the specified flags as well as related unspecified flags.
+ *
+ * This function exists only for compatibility with libav.
+ * Please use av_parse_cpu_caps() when possible.
+ * @return a combination of AV_CPU_* flags, negative on error.
+ */
+attribute_deprecated
+int av_parse_cpu_flags(const char *s);
+
+/**
+ * Parse CPU caps from a string and update the given AV_CPU_* flags based on that.
+ *
+ * @return negative on error.
+ */
+int av_parse_cpu_caps(unsigned *flags, const char *s);
+
+/* The following CPU-specific functions shall not be called directly. */
+int ff_get_cpu_flags_arm(void);
+int ff_get_cpu_flags_ppc(void);
+int ff_get_cpu_flags_x86(void);
+
+#endif /* AVUTIL_CPU_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/crc.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,74 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CRC_H
+#define AVUTIL_CRC_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include "attributes.h"
+
+typedef uint32_t AVCRC;
+
+typedef enum {
+    AV_CRC_8_ATM,
+    AV_CRC_16_ANSI,
+    AV_CRC_16_CCITT,
+    AV_CRC_32_IEEE,
+    AV_CRC_32_IEEE_LE,  /*< reversed bitorder version of AV_CRC_32_IEEE */
+    AV_CRC_MAX,         /*< Not part of public API! Do not use outside libavutil. */
+}AVCRCId;
+
+/**
+ * Initialize a CRC table.
+ * @param ctx must be an array of size sizeof(AVCRC)*257 or sizeof(AVCRC)*1024
+ * @param le If 1, the lowest bit represents the coefficient for the highest
+ *           exponent of the corresponding polynomial (both for poly and
+ *           actual CRC).
+ *           If 0, you must swap the CRC parameter and the result of av_crc
+ *           if you need the standard representation (can be simplified in
+ *           most cases to e.g. bswap16):
+ *           av_bswap32(crc << (32-bits))
+ * @param bits number of bits for the CRC
+ * @param poly generator polynomial without the x**bits coefficient, in the
+ *             representation as specified by le
+ * @param ctx_size size of ctx in bytes
+ * @return <0 on failure
+ */
+int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size);
+
+/**
+ * Get an initialized standard CRC table.
+ * @param crc_id ID of a standard CRC
+ * @return a pointer to the CRC table or NULL on failure
+ */
+const AVCRC *av_crc_get_table(AVCRCId crc_id);
+
+/**
+ * Calculate the CRC of a block.
+ * @param crc CRC of previous blocks if any or initial value for CRC
+ * @return CRC updated with the data from the given block
+ *
+ * @see av_crc_init() "le" parameter
+ */
+uint32_t av_crc(const AVCRC *ctx, uint32_t crc,
+                const uint8_t *buffer, size_t length) av_pure;
+
+#endif /* AVUTIL_CRC_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/dict.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,152 @@
+/*
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Public dictionary API.
+ * @deprecated
+ *  AVDictionary is provided for compatibility with libav. It is both in
+ *  implementation as well as API inefficient. It does not scale and is
+ *  extremely slow with large dictionaries.
+ *  It is recommended that new code uses our tree container from tree.c/h
+ *  where applicable, which uses AVL trees to achieve O(log n) performance.
+ */
+
+#ifndef AVUTIL_DICT_H
+#define AVUTIL_DICT_H
+
+/**
+ * @addtogroup lavu_dict AVDictionary
+ * @ingroup lavu_data
+ *
+ * @brief Simple key:value store
+ *
+ * @{
+ * Dictionaries are used for storing key:value pairs. To create
+ * an AVDictionary, simply pass an address of a NULL pointer to
+ * av_dict_set(). NULL can be used as an empty dictionary wherever
+ * a pointer to an AVDictionary is required.
+ * Use av_dict_get() to retrieve an entry or iterate over all
+ * entries and finally av_dict_free() to free the dictionary
+ * and all its contents.
+ *
+ * @code
+ * AVDictionary *d = NULL;                // "create" an empty dictionary
+ * av_dict_set(&d, "foo", "bar", 0);      // add an entry
+ *
+ * char *k = av_strdup("key");            // if your strings are already allocated,
+ * char *v = av_strdup("value");          // you can avoid copying them like this
+ * av_dict_set(&d, k, v, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
+ *
+ * AVDictionaryEntry *t = NULL;
+ * while (t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX)) {
+ *     <....>                             // iterate over all entries in d
+ * }
+ *
+ * av_dict_free(&d);
+ * @endcode
+ *
+ */
+
+#define AV_DICT_MATCH_CASE      1
+#define AV_DICT_IGNORE_SUFFIX   2
+#define AV_DICT_DONT_STRDUP_KEY 4   /**< Take ownership of a key that's been
+                                         allocated with av_malloc() and children. */
+#define AV_DICT_DONT_STRDUP_VAL 8   /**< Take ownership of a value that's been
+                                         allocated with av_malloc() and chilren. */
+#define AV_DICT_DONT_OVERWRITE 16   ///< Don't overwrite existing entries.
+#define AV_DICT_APPEND         32   /**< If the entry already exists, append to it.  Note that no
+                                      delimiter is added, the strings are simply concatenated. */
+
+typedef struct AVDictionaryEntry {
+    char *key;
+    char *value;
+} AVDictionaryEntry;
+
+typedef struct AVDictionary AVDictionary;
+
+/**
+ * Get a dictionary entry with matching key.
+ *
+ * @param prev Set to the previous matching element to find the next.
+ *             If set to NULL the first matching element is returned.
+ * @param flags Allows case as well as suffix-insensitive comparisons.
+ * @return Found entry or NULL, changing key or value leads to undefined behavior.
+ */
+AVDictionaryEntry *
+av_dict_get(AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags);
+
+/**
+ * Get number of entries in dictionary.
+ *
+ * @param m dictionary
+ * @return  number of entries in dictionary
+ */
+int av_dict_count(const AVDictionary *m);
+
+/**
+ * Set the given entry in *pm, overwriting an existing entry.
+ *
+ * @param pm pointer to a pointer to a dictionary struct. If *pm is NULL
+ * a dictionary struct is allocated and put in *pm.
+ * @param key entry key to add to *pm (will be av_strduped depending on flags)
+ * @param value entry value to add to *pm (will be av_strduped depending on flags).
+ *        Passing a NULL value will cause an existing entry to be deleted.
+ * @return >= 0 on success otherwise an error code <0
+ */
+int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags);
+
+/**
+ * Parse the key/value pairs list and add to a dictionary.
+ *
+ * @param key_val_sep  a 0-terminated list of characters used to separate
+ *                     key from value
+ * @param pairs_sep    a 0-terminated list of characters used to separate
+ *                     two pairs from each other
+ * @param flags        flags to use when adding to dictionary.
+ *                     AV_DICT_DONT_STRDUP_KEY and AV_DICT_DONT_STRDUP_VAL
+ *                     are ignored since the key/value tokens will always
+ *                     be duplicated.
+ * @return             0 on success, negative AVERROR code on failure
+ */
+int av_dict_parse_string(AVDictionary **pm, const char *str,
+                         const char *key_val_sep, const char *pairs_sep,
+                         int flags);
+
+/**
+ * Copy entries from one AVDictionary struct into another.
+ * @param dst pointer to a pointer to a AVDictionary struct. If *dst is NULL,
+ *            this function will allocate a struct for you and put it in *dst
+ * @param src pointer to source AVDictionary struct
+ * @param flags flags to use when setting entries in *dst
+ * @note metadata is read using the AV_DICT_IGNORE_SUFFIX flag
+ */
+void av_dict_copy(AVDictionary **dst, AVDictionary *src, int flags);
+
+/**
+ * Free all the memory allocated for an AVDictionary struct
+ * and all keys and values.
+ */
+void av_dict_free(AVDictionary **m);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_DICT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/error.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,117 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * error code definitions
+ */
+
+#ifndef AVUTIL_ERROR_H
+#define AVUTIL_ERROR_H
+
+#include <errno.h>
+#include <stddef.h>
+
+/**
+ * @addtogroup lavu_error
+ *
+ * @{
+ */
+
+
+/* error handling */
+#if EDOM > 0
+#define AVERROR(e) (-(e))   ///< Returns a negative error code from a POSIX error code, to return from library functions.
+#define AVUNERROR(e) (-(e)) ///< Returns a POSIX error code from a library function error return value.
+#else
+/* Some platforms have E* and errno already negated. */
+#define AVERROR(e) (e)
+#define AVUNERROR(e) (e)
+#endif
+
+#define FFERRTAG(a, b, c, d) (-(int)MKTAG(a, b, c, d))
+
+#define AVERROR_BSF_NOT_FOUND      FFERRTAG(0xF8,'B','S','F') ///< Bitstream filter not found
+#define AVERROR_BUG                FFERRTAG( 'B','U','G','!') ///< Internal bug, also see AVERROR_BUG2
+#define AVERROR_BUFFER_TOO_SMALL   FFERRTAG( 'B','U','F','S') ///< Buffer too small
+#define AVERROR_DECODER_NOT_FOUND  FFERRTAG(0xF8,'D','E','C') ///< Decoder not found
+#define AVERROR_DEMUXER_NOT_FOUND  FFERRTAG(0xF8,'D','E','M') ///< Demuxer not found
+#define AVERROR_ENCODER_NOT_FOUND  FFERRTAG(0xF8,'E','N','C') ///< Encoder not found
+#define AVERROR_EOF                FFERRTAG( 'E','O','F',' ') ///< End of file
+#define AVERROR_EXIT               FFERRTAG( 'E','X','I','T') ///< Immediate exit was requested; the called function should not be restarted
+#define AVERROR_EXTERNAL           FFERRTAG( 'E','X','T',' ') ///< Generic error in an external library
+#define AVERROR_FILTER_NOT_FOUND   FFERRTAG(0xF8,'F','I','L') ///< Filter not found
+#define AVERROR_INVALIDDATA        FFERRTAG( 'I','N','D','A') ///< Invalid data found when processing input
+#define AVERROR_MUXER_NOT_FOUND    FFERRTAG(0xF8,'M','U','X') ///< Muxer not found
+#define AVERROR_OPTION_NOT_FOUND   FFERRTAG(0xF8,'O','P','T') ///< Option not found
+#define AVERROR_PATCHWELCOME       FFERRTAG( 'P','A','W','E') ///< Not yet implemented in FFmpeg, patches welcome
+#define AVERROR_PROTOCOL_NOT_FOUND FFERRTAG(0xF8,'P','R','O') ///< Protocol not found
+
+#define AVERROR_STREAM_NOT_FOUND   FFERRTAG(0xF8,'S','T','R') ///< Stream not found
+/**
+ * This is semantically identical to AVERROR_BUG
+ * it has been introduced in Libav after our AVERROR_BUG and with a modified value.
+ */
+#define AVERROR_BUG2               FFERRTAG( 'B','U','G',' ')
+#define AVERROR_UNKNOWN            FFERRTAG( 'U','N','K','N') ///< Unknown error, typically from an external library
+#define AVERROR_EXPERIMENTAL       (-0x2bb2afa8) ///< Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it.
+
+#define AV_ERROR_MAX_STRING_SIZE 64
+
+/**
+ * Put a description of the AVERROR code errnum in errbuf.
+ * In case of failure the global variable errno is set to indicate the
+ * error. Even in case of failure av_strerror() will print a generic
+ * error message indicating the errnum provided to errbuf.
+ *
+ * @param errnum      error code to describe
+ * @param errbuf      buffer to which description is written
+ * @param errbuf_size the size in bytes of errbuf
+ * @return 0 on success, a negative value if a description for errnum
+ * cannot be found
+ */
+int av_strerror(int errnum, char *errbuf, size_t errbuf_size);
+
+/**
+ * Fill the provided buffer with a string containing an error string
+ * corresponding to the AVERROR code errnum.
+ *
+ * @param errbuf         a buffer
+ * @param errbuf_size    size in bytes of errbuf
+ * @param errnum         error code to describe
+ * @return the buffer in input, filled with the error description
+ * @see av_strerror()
+ */
+static inline char *av_make_error_string(char *errbuf, size_t errbuf_size, int errnum)
+{
+    av_strerror(errnum, errbuf, errbuf_size);
+    return errbuf;
+}
+
+/**
+ * Convenience macro, the return value should be used only directly in
+ * function arguments but never stand-alone.
+ */
+#define av_err2str(errnum) \
+    av_make_error_string((char[AV_ERROR_MAX_STRING_SIZE]){0}, AV_ERROR_MAX_STRING_SIZE, errnum)
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_ERROR_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/eval.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2002 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * simple arithmetic expression evaluator
+ */
+
+#ifndef AVUTIL_EVAL_H
+#define AVUTIL_EVAL_H
+
+#include "avutil.h"
+
+typedef struct AVExpr AVExpr;
+
+/**
+ * Parse and evaluate an expression.
+ * Note, this is significantly slower than av_expr_eval().
+ *
+ * @param res a pointer to a double where is put the result value of
+ * the expression, or NAN in case of error
+ * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)"
+ * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0}
+ * @param const_values a zero terminated array of values for the identifiers from const_names
+ * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers
+ * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument
+ * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers
+ * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments
+ * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2
+ * @param log_ctx parent logging context
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_expr_parse_and_eval(double *res, const char *s,
+                           const char * const *const_names, const double *const_values,
+                           const char * const *func1_names, double (* const *funcs1)(void *, double),
+                           const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                           void *opaque, int log_offset, void *log_ctx);
+
+/**
+ * Parse an expression.
+ *
+ * @param expr a pointer where is put an AVExpr containing the parsed
+ * value in case of successful parsing, or NULL otherwise.
+ * The pointed to AVExpr must be freed with av_expr_free() by the user
+ * when it is not needed anymore.
+ * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)"
+ * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0}
+ * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers
+ * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument
+ * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers
+ * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments
+ * @param log_ctx parent logging context
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_expr_parse(AVExpr **expr, const char *s,
+                  const char * const *const_names,
+                  const char * const *func1_names, double (* const *funcs1)(void *, double),
+                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                  int log_offset, void *log_ctx);
+
+/**
+ * Evaluate a previously parsed expression.
+ *
+ * @param const_values a zero terminated array of values for the identifiers from av_expr_parse() const_names
+ * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2
+ * @return the value of the expression
+ */
+double av_expr_eval(AVExpr *e, const double *const_values, void *opaque);
+
+/**
+ * Free a parsed expression previously created with av_expr_parse().
+ */
+void av_expr_free(AVExpr *e);
+
+/**
+ * Parse the string in numstr and return its value as a double. If
+ * the string is empty, contains only whitespaces, or does not contain
+ * an initial substring that has the expected syntax for a
+ * floating-point number, no conversion is performed. In this case,
+ * returns a value of zero and the value returned in tail is the value
+ * of numstr.
+ *
+ * @param numstr a string representing a number, may contain one of
+ * the International System number postfixes, for example 'K', 'M',
+ * 'G'. If 'i' is appended after the postfix, powers of 2 are used
+ * instead of powers of 10. The 'B' postfix multiplies the value for
+ * 8, and can be appended after another postfix or used alone. This
+ * allows using for example 'KB', 'MiB', 'G' and 'B' as postfix.
+ * @param tail if non-NULL puts here the pointer to the char next
+ * after the last parsed character
+ */
+double av_strtod(const char *numstr, char **tail);
+
+#endif /* AVUTIL_EVAL_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/fifo.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,144 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * a very simple circular buffer FIFO implementation
+ */
+
+#ifndef AVUTIL_FIFO_H
+#define AVUTIL_FIFO_H
+
+#include <stdint.h>
+#include "avutil.h"
+#include "attributes.h"
+
+typedef struct AVFifoBuffer {
+    uint8_t *buffer;
+    uint8_t *rptr, *wptr, *end;
+    uint32_t rndx, wndx;
+} AVFifoBuffer;
+
+/**
+ * Initialize an AVFifoBuffer.
+ * @param size of FIFO
+ * @return AVFifoBuffer or NULL in case of memory allocation failure
+ */
+AVFifoBuffer *av_fifo_alloc(unsigned int size);
+
+/**
+ * Free an AVFifoBuffer.
+ * @param f AVFifoBuffer to free
+ */
+void av_fifo_free(AVFifoBuffer *f);
+
+/**
+ * Reset the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied.
+ * @param f AVFifoBuffer to reset
+ */
+void av_fifo_reset(AVFifoBuffer *f);
+
+/**
+ * Return the amount of data in bytes in the AVFifoBuffer, that is the
+ * amount of data you can read from it.
+ * @param f AVFifoBuffer to read from
+ * @return size
+ */
+int av_fifo_size(AVFifoBuffer *f);
+
+/**
+ * Return the amount of space in bytes in the AVFifoBuffer, that is the
+ * amount of data you can write into it.
+ * @param f AVFifoBuffer to write into
+ * @return size
+ */
+int av_fifo_space(AVFifoBuffer *f);
+
+/**
+ * Feed data from an AVFifoBuffer to a user-supplied callback.
+ * @param f AVFifoBuffer to read from
+ * @param buf_size number of bytes to read
+ * @param func generic read function
+ * @param dest data destination
+ */
+int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int));
+
+/**
+ * Feed data from a user-supplied callback to an AVFifoBuffer.
+ * @param f AVFifoBuffer to write to
+ * @param src data source; non-const since it may be used as a
+ * modifiable context by the function defined in func
+ * @param size number of bytes to write
+ * @param func generic write function; the first parameter is src,
+ * the second is dest_buf, the third is dest_buf_size.
+ * func must return the number of bytes written to dest_buf, or <= 0 to
+ * indicate no more data available to write.
+ * If func is NULL, src is interpreted as a simple byte array for source data.
+ * @return the number of bytes written to the FIFO
+ */
+int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void*, void*, int));
+
+/**
+ * Resize an AVFifoBuffer.
+ * In case of reallocation failure, the old FIFO is kept unchanged.
+ *
+ * @param f AVFifoBuffer to resize
+ * @param size new AVFifoBuffer size in bytes
+ * @return <0 for failure, >=0 otherwise
+ */
+int av_fifo_realloc2(AVFifoBuffer *f, unsigned int size);
+
+/**
+ * Enlarge an AVFifoBuffer.
+ * In case of reallocation failure, the old FIFO is kept unchanged.
+ * The new fifo size may be larger than the requested size.
+ *
+ * @param f AVFifoBuffer to resize
+ * @param additional_space the amount of space in bytes to allocate in addition to av_fifo_size()
+ * @return <0 for failure, >=0 otherwise
+ */
+int av_fifo_grow(AVFifoBuffer *f, unsigned int additional_space);
+
+/**
+ * Read and discard the specified amount of data from an AVFifoBuffer.
+ * @param f AVFifoBuffer to read from
+ * @param size amount of data to read in bytes
+ */
+void av_fifo_drain(AVFifoBuffer *f, int size);
+
+/**
+ * Return a pointer to the data stored in a FIFO buffer at a certain offset.
+ * The FIFO buffer is not modified.
+ *
+ * @param f    AVFifoBuffer to peek at, f must be non-NULL
+ * @param offs an offset in bytes, its absolute value must be less
+ *             than the used buffer size or the returned pointer will
+ *             point outside to the buffer data.
+ *             The used buffer size can be checked with av_fifo_size().
+ */
+static inline uint8_t *av_fifo_peek2(const AVFifoBuffer *f, int offs)
+{
+    uint8_t *ptr = f->rptr + offs;
+    if (ptr >= f->end)
+        ptr = f->buffer + (ptr - f->end);
+    else if (ptr < f->buffer)
+        ptr = f->end - (f->buffer - ptr);
+    return ptr;
+}
+
+#endif /* AVUTIL_FIFO_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/file.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,66 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_FILE_H
+#define AVUTIL_FILE_H
+
+#include <stdint.h>
+
+#include "avutil.h"
+
+/**
+ * @file
+ * Misc file utilities.
+ */
+
+/**
+ * Read the file with name filename, and put its content in a newly
+ * allocated buffer or map it with mmap() when available.
+ * In case of success set *bufptr to the read or mmapped buffer, and
+ * *size to the size in bytes of the buffer in *bufptr.
+ * The returned buffer must be released with av_file_unmap().
+ *
+ * @param log_offset loglevel offset used for logging
+ * @param log_ctx context used for logging
+ * @return a non negative number in case of success, a negative value
+ * corresponding to an AVERROR error code in case of failure
+ */
+int av_file_map(const char *filename, uint8_t **bufptr, size_t *size,
+                int log_offset, void *log_ctx);
+
+/**
+ * Unmap or free the buffer bufptr created by av_file_map().
+ *
+ * @param size size in bytes of bufptr, must be the same as returned
+ * by av_file_map()
+ */
+void av_file_unmap(uint8_t *bufptr, size_t size);
+
+/**
+ * Wrapper to work around the lack of mkstemp() on mingw.
+ * Also, tries to create file in /tmp first, if possible.
+ * *prefix can be a character constant; *filename will be allocated internally.
+ * @return file descriptor of opened file (or -1 on error)
+ * and opened file name in **filename.
+ * @note On very old libcs it is necessary to set a secure umask before
+ *       calling this, av_tempfile() cant call umask itself as it is used in
+ *       libraries and could interfere with the calling application.
+ */
+int av_tempfile(const char *prefix, char **filename, int log_offset, void *log_ctx);
+
+#endif /* AVUTIL_FILE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/frame.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,607 @@
+/*
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_FRAME_H
+#define AVUTIL_FRAME_H
+
+#include <stdint.h>
+
+#include "version.h"
+
+#include "avutil.h"
+#include "buffer.h"
+#include "dict.h"
+#include "rational.h"
+#include "samplefmt.h"
+
+enum AVFrameSideDataType {
+    /**
+     * The data is the AVPanScan struct defined in libavcodec.
+     */
+    AV_FRAME_DATA_PANSCAN,
+};
+
+typedef struct AVFrameSideData {
+    enum AVFrameSideDataType type;
+    uint8_t *data;
+    int      size;
+    AVDictionary *metadata;
+} AVFrameSideData;
+
+/**
+ * This structure describes decoded (raw) audio or video data.
+ *
+ * AVFrame must be allocated using av_frame_alloc(). Note that this only
+ * allocates the AVFrame itself, the buffers for the data must be managed
+ * through other means (see below).
+ * AVFrame must be freed with av_frame_free().
+ *
+ * AVFrame is typically allocated once and then reused multiple times to hold
+ * different data (e.g. a single AVFrame to hold frames received from a
+ * decoder). In such a case, av_frame_unref() will free any references held by
+ * the frame and reset it to its original clean state before it
+ * is reused again.
+ *
+ * The data described by an AVFrame is usually reference counted through the
+ * AVBuffer API. The underlying buffer references are stored in AVFrame.buf /
+ * AVFrame.extended_buf. An AVFrame is considered to be reference counted if at
+ * least one reference is set, i.e. if AVFrame.buf[0] != NULL. In such a case,
+ * every single data plane must be contained in one of the buffers in
+ * AVFrame.buf or AVFrame.extended_buf.
+ * There may be a single buffer for all the data, or one separate buffer for
+ * each plane, or anything in between.
+ *
+ * sizeof(AVFrame) is not a part of the public ABI, so new fields may be added
+ * to the end with a minor bump.
+ * Similarly fields that are marked as to be only accessed by
+ * av_opt_ptr() can be reordered. This allows 2 forks to add fields
+ * without breaking compatibility with each other.
+ */
+typedef struct AVFrame {
+#define AV_NUM_DATA_POINTERS 8
+    /**
+     * pointer to the picture/channel planes.
+     * This might be different from the first allocated byte
+     *
+     * Some decoders access areas outside 0,0 - width,height, please
+     * see avcodec_align_dimensions2(). Some filters and swscale can read
+     * up to 16 bytes beyond the planes, if these filters are to be used,
+     * then 16 extra bytes must be allocated.
+     */
+    uint8_t *data[AV_NUM_DATA_POINTERS];
+
+    /**
+     * For video, size in bytes of each picture line.
+     * For audio, size in bytes of each plane.
+     *
+     * For audio, only linesize[0] may be set. For planar audio, each channel
+     * plane must be the same size.
+     *
+     * For video the linesizes should be multiplies of the CPUs alignment
+     * preference, this is 16 or 32 for modern desktop CPUs.
+     * Some code requires such alignment other code can be slower without
+     * correct alignment, for yet other it makes no difference.
+     */
+    int linesize[AV_NUM_DATA_POINTERS];
+
+    /**
+     * pointers to the data planes/channels.
+     *
+     * For video, this should simply point to data[].
+     *
+     * For planar audio, each channel has a separate data pointer, and
+     * linesize[0] contains the size of each channel buffer.
+     * For packed audio, there is just one data pointer, and linesize[0]
+     * contains the total size of the buffer for all channels.
+     *
+     * Note: Both data and extended_data should always be set in a valid frame,
+     * but for planar audio with more channels that can fit in data,
+     * extended_data must be used in order to access all channels.
+     */
+    uint8_t **extended_data;
+
+    /**
+     * width and height of the video frame
+     */
+    int width, height;
+
+    /**
+     * number of audio samples (per channel) described by this frame
+     */
+    int nb_samples;
+
+    /**
+     * format of the frame, -1 if unknown or unset
+     * Values correspond to enum AVPixelFormat for video frames,
+     * enum AVSampleFormat for audio)
+     */
+    int format;
+
+    /**
+     * 1 -> keyframe, 0-> not
+     */
+    int key_frame;
+
+    /**
+     * Picture type of the frame.
+     */
+    enum AVPictureType pict_type;
+
+#if FF_API_AVFRAME_LAVC
+    attribute_deprecated
+    uint8_t *base[AV_NUM_DATA_POINTERS];
+#endif
+
+    /**
+     * Sample aspect ratio for the video frame, 0/1 if unknown/unspecified.
+     */
+    AVRational sample_aspect_ratio;
+
+    /**
+     * Presentation timestamp in time_base units (time when frame should be shown to user).
+     */
+    int64_t pts;
+
+    /**
+     * PTS copied from the AVPacket that was decoded to produce this frame.
+     */
+    int64_t pkt_pts;
+
+    /**
+     * DTS copied from the AVPacket that triggered returning this frame. (if frame threading isnt used)
+     * This is also the Presentation time of this AVFrame calculated from
+     * only AVPacket.dts values without pts values.
+     */
+    int64_t pkt_dts;
+
+    /**
+     * picture number in bitstream order
+     */
+    int coded_picture_number;
+    /**
+     * picture number in display order
+     */
+    int display_picture_number;
+
+    /**
+     * quality (between 1 (good) and FF_LAMBDA_MAX (bad))
+     */
+    int quality;
+
+#if FF_API_AVFRAME_LAVC
+    attribute_deprecated
+    int reference;
+
+    /**
+     * QP table
+     */
+    attribute_deprecated
+    int8_t *qscale_table;
+    /**
+     * QP store stride
+     */
+    attribute_deprecated
+    int qstride;
+
+    attribute_deprecated
+    int qscale_type;
+
+    /**
+     * mbskip_table[mb]>=1 if MB didn't change
+     * stride= mb_width = (width+15)>>4
+     */
+    attribute_deprecated
+    uint8_t *mbskip_table;
+
+    /**
+     * motion vector table
+     * @code
+     * example:
+     * int mv_sample_log2= 4 - motion_subsample_log2;
+     * int mb_width= (width+15)>>4;
+     * int mv_stride= (mb_width << mv_sample_log2) + 1;
+     * motion_val[direction][x + y*mv_stride][0->mv_x, 1->mv_y];
+     * @endcode
+     */
+    attribute_deprecated
+    int16_t (*motion_val[2])[2];
+
+    /**
+     * macroblock type table
+     * mb_type_base + mb_width + 2
+     */
+    attribute_deprecated
+    uint32_t *mb_type;
+
+    /**
+     * DCT coefficients
+     */
+    attribute_deprecated
+    short *dct_coeff;
+
+    /**
+     * motion reference frame index
+     * the order in which these are stored can depend on the codec.
+     */
+    attribute_deprecated
+    int8_t *ref_index[2];
+#endif
+
+    /**
+     * for some private data of the user
+     */
+    void *opaque;
+
+    /**
+     * error
+     */
+    uint64_t error[AV_NUM_DATA_POINTERS];
+
+#if FF_API_AVFRAME_LAVC
+    attribute_deprecated
+    int type;
+#endif
+
+    /**
+     * When decoding, this signals how much the picture must be delayed.
+     * extra_delay = repeat_pict / (2*fps)
+     */
+    int repeat_pict;
+
+    /**
+     * The content of the picture is interlaced.
+     */
+    int interlaced_frame;
+
+    /**
+     * If the content is interlaced, is top field displayed first.
+     */
+    int top_field_first;
+
+    /**
+     * Tell user application that palette has changed from previous frame.
+     */
+    int palette_has_changed;
+
+#if FF_API_AVFRAME_LAVC
+    attribute_deprecated
+    int buffer_hints;
+
+    /**
+     * Pan scan.
+     */
+    attribute_deprecated
+    struct AVPanScan *pan_scan;
+#endif
+
+    /**
+     * reordered opaque 64bit (generally an integer or a double precision float
+     * PTS but can be anything).
+     * The user sets AVCodecContext.reordered_opaque to represent the input at
+     * that time,
+     * the decoder reorders values as needed and sets AVFrame.reordered_opaque
+     * to exactly one of the values provided by the user through AVCodecContext.reordered_opaque
+     * @deprecated in favor of pkt_pts
+     */
+    int64_t reordered_opaque;
+
+#if FF_API_AVFRAME_LAVC
+    /**
+     * @deprecated this field is unused
+     */
+    attribute_deprecated void *hwaccel_picture_private;
+
+    attribute_deprecated
+    struct AVCodecContext *owner;
+    attribute_deprecated
+    void *thread_opaque;
+
+    /**
+     * log2 of the size of the block which a single vector in motion_val represents:
+     * (4->16x16, 3->8x8, 2-> 4x4, 1-> 2x2)
+     */
+    attribute_deprecated
+    uint8_t motion_subsample_log2;
+#endif
+
+    /**
+     * Sample rate of the audio data.
+     */
+    int sample_rate;
+
+    /**
+     * Channel layout of the audio data.
+     */
+    uint64_t channel_layout;
+
+    /**
+     * AVBuffer references backing the data for this frame. If all elements of
+     * this array are NULL, then this frame is not reference counted.
+     *
+     * There may be at most one AVBuffer per data plane, so for video this array
+     * always contains all the references. For planar audio with more than
+     * AV_NUM_DATA_POINTERS channels, there may be more buffers than can fit in
+     * this array. Then the extra AVBufferRef pointers are stored in the
+     * extended_buf array.
+     */
+    AVBufferRef *buf[AV_NUM_DATA_POINTERS];
+
+    /**
+     * For planar audio which requires more than AV_NUM_DATA_POINTERS
+     * AVBufferRef pointers, this array will hold all the references which
+     * cannot fit into AVFrame.buf.
+     *
+     * Note that this is different from AVFrame.extended_data, which always
+     * contains all the pointers. This array only contains the extra pointers,
+     * which cannot fit into AVFrame.buf.
+     *
+     * This array is always allocated using av_malloc() by whoever constructs
+     * the frame. It is freed in av_frame_unref().
+     */
+    AVBufferRef **extended_buf;
+    /**
+     * Number of elements in extended_buf.
+     */
+    int        nb_extended_buf;
+
+    AVFrameSideData **side_data;
+    int            nb_side_data;
+
+    /**
+     * frame timestamp estimated using various heuristics, in stream time base
+     * Code outside libavcodec should access this field using:
+     * av_frame_get_best_effort_timestamp(frame)
+     * - encoding: unused
+     * - decoding: set by libavcodec, read by user.
+     */
+    int64_t best_effort_timestamp;
+
+    /**
+     * reordered pos from the last AVPacket that has been input into the decoder
+     * Code outside libavcodec should access this field using:
+     * av_frame_get_pkt_pos(frame)
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int64_t pkt_pos;
+
+    /**
+     * duration of the corresponding packet, expressed in
+     * AVStream->time_base units, 0 if unknown.
+     * Code outside libavcodec should access this field using:
+     * av_frame_get_pkt_duration(frame)
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int64_t pkt_duration;
+
+    /**
+     * metadata.
+     * Code outside libavcodec should access this field using:
+     * av_frame_get_metadata(frame)
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    AVDictionary *metadata;
+
+    /**
+     * decode error flags of the frame, set to a combination of
+     * FF_DECODE_ERROR_xxx flags if the decoder produced a frame, but there
+     * were errors during the decoding.
+     * Code outside libavcodec should access this field using:
+     * av_frame_get_decode_error_flags(frame)
+     * - encoding: unused
+     * - decoding: set by libavcodec, read by user.
+     */
+    int decode_error_flags;
+#define FF_DECODE_ERROR_INVALID_BITSTREAM   1
+#define FF_DECODE_ERROR_MISSING_REFERENCE   2
+
+    /**
+     * number of audio channels, only used for audio.
+     * Code outside libavcodec should access this field using:
+     * av_frame_get_channels(frame)
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int channels;
+
+    /**
+     * size of the corresponding packet containing the compressed
+     * frame. It must be accessed using av_frame_get_pkt_size() and
+     * av_frame_set_pkt_size().
+     * It is set to a negative value if unknown.
+     * - encoding: unused
+     * - decoding: set by libavcodec, read by user.
+     */
+    int pkt_size;
+
+    /**
+     * Not to be accessed directly from outside libavutil
+     */
+    AVBufferRef *qp_table_buf;
+} AVFrame;
+
+/**
+ * Accessors for some AVFrame fields.
+ * The position of these field in the structure is not part of the ABI,
+ * they should not be accessed directly outside libavcodec.
+ */
+int64_t av_frame_get_best_effort_timestamp(const AVFrame *frame);
+void    av_frame_set_best_effort_timestamp(AVFrame *frame, int64_t val);
+int64_t av_frame_get_pkt_duration         (const AVFrame *frame);
+void    av_frame_set_pkt_duration         (AVFrame *frame, int64_t val);
+int64_t av_frame_get_pkt_pos              (const AVFrame *frame);
+void    av_frame_set_pkt_pos              (AVFrame *frame, int64_t val);
+int64_t av_frame_get_channel_layout       (const AVFrame *frame);
+void    av_frame_set_channel_layout       (AVFrame *frame, int64_t val);
+int     av_frame_get_channels             (const AVFrame *frame);
+void    av_frame_set_channels             (AVFrame *frame, int     val);
+int     av_frame_get_sample_rate          (const AVFrame *frame);
+void    av_frame_set_sample_rate          (AVFrame *frame, int     val);
+AVDictionary *av_frame_get_metadata       (const AVFrame *frame);
+void          av_frame_set_metadata       (AVFrame *frame, AVDictionary *val);
+int     av_frame_get_decode_error_flags   (const AVFrame *frame);
+void    av_frame_set_decode_error_flags   (AVFrame *frame, int     val);
+int     av_frame_get_pkt_size(const AVFrame *frame);
+void    av_frame_set_pkt_size(AVFrame *frame, int val);
+AVDictionary **avpriv_frame_get_metadatap(AVFrame *frame);
+int8_t *av_frame_get_qp_table(AVFrame *f, int *stride, int *type);
+int av_frame_set_qp_table(AVFrame *f, AVBufferRef *buf, int stride, int type);
+
+/**
+ * Allocate an AVFrame and set its fields to default values.  The resulting
+ * struct must be freed using av_frame_free().
+ *
+ * @return An AVFrame filled with default values or NULL on failure.
+ *
+ * @note this only allocates the AVFrame itself, not the data buffers. Those
+ * must be allocated through other means, e.g. with av_frame_get_buffer() or
+ * manually.
+ */
+AVFrame *av_frame_alloc(void);
+
+/**
+ * Free the frame and any dynamically allocated objects in it,
+ * e.g. extended_data. If the frame is reference counted, it will be
+ * unreferenced first.
+ *
+ * @param frame frame to be freed. The pointer will be set to NULL.
+ */
+void av_frame_free(AVFrame **frame);
+
+/**
+ * Setup a new reference to the data described by an given frame.
+ *
+ * Copy frame properties from src to dst and create a new reference for each
+ * AVBufferRef from src.
+ *
+ * If src is not reference counted, new buffers are allocated and the data is
+ * copied.
+ *
+ * @return 0 on success, a negative AVERROR on error
+ */
+int av_frame_ref(AVFrame *dst, AVFrame *src);
+
+/**
+ * Create a new frame that references the same data as src.
+ *
+ * This is a shortcut for av_frame_alloc()+av_frame_ref().
+ *
+ * @return newly created AVFrame on success, NULL on error.
+ */
+AVFrame *av_frame_clone(AVFrame *src);
+
+/**
+ * Unreference all the buffers referenced by frame and reset the frame fields.
+ */
+void av_frame_unref(AVFrame *frame);
+
+/**
+ * Move everythnig contained in src to dst and reset src.
+ */
+void av_frame_move_ref(AVFrame *dst, AVFrame *src);
+
+/**
+ * Allocate new buffer(s) for audio or video data.
+ *
+ * The following fields must be set on frame before calling this function:
+ * - format (pixel format for video, sample format for audio)
+ * - width and height for video
+ * - nb_samples and channel_layout for audio
+ *
+ * This function will fill AVFrame.data and AVFrame.buf arrays and, if
+ * necessary, allocate and fill AVFrame.extended_data and AVFrame.extended_buf.
+ * For planar formats, one buffer will be allocated for each plane.
+ *
+ * @param frame frame in which to store the new buffers.
+ * @param align required buffer size alignment
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ */
+int av_frame_get_buffer(AVFrame *frame, int align);
+
+/**
+ * Check if the frame data is writable.
+ *
+ * @return A positive value if the frame data is writable (which is true if and
+ * only if each of the underlying buffers has only one reference, namely the one
+ * stored in this frame). Return 0 otherwise.
+ *
+ * If 1 is returned the answer is valid until av_buffer_ref() is called on any
+ * of the underlying AVBufferRefs (e.g. through av_frame_ref() or directly).
+ *
+ * @see av_frame_make_writable(), av_buffer_is_writable()
+ */
+int av_frame_is_writable(AVFrame *frame);
+
+/**
+ * Ensure that the frame data is writable, avoiding data copy if possible.
+ *
+ * Do nothing if the frame is writable, allocate new buffers and copy the data
+ * if it is not.
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ *
+ * @see av_frame_is_writable(), av_buffer_is_writable(),
+ * av_buffer_make_writable()
+ */
+int av_frame_make_writable(AVFrame *frame);
+
+/**
+ * Copy only "metadata" fields from src to dst.
+ *
+ * Metadata for the purpose of this function are those fields that do not affect
+ * the data layout in the buffers.  E.g. pts, sample rate (for audio) or sample
+ * aspect ratio (for video), but not width/height or channel layout.
+ * Side data is also copied.
+ */
+int av_frame_copy_props(AVFrame *dst, const AVFrame *src);
+
+/**
+ * Get the buffer reference a given data plane is stored in.
+ *
+ * @param plane index of the data plane of interest in frame->extended_data.
+ *
+ * @return the buffer reference that contains the plane or NULL if the input
+ * frame is not valid.
+ */
+AVBufferRef *av_frame_get_plane_buffer(AVFrame *frame, int plane);
+
+/**
+ * Add a new side data to a frame.
+ *
+ * @param frame a frame to which the side data should be added
+ * @param type type of the added side data
+ * @param size size of the side data
+ *
+ * @return newly added side data on success, NULL on error
+ */
+AVFrameSideData *av_frame_new_side_data(AVFrame *frame,
+                                        enum AVFrameSideDataType type,
+                                        int size);
+
+/**
+ * @return a pointer to the side data of a given type on success, NULL if there
+ * is no side data with such type in this frame.
+ */
+AVFrameSideData *av_frame_get_side_data(AVFrame *frame,
+                                        enum AVFrameSideDataType type);
+
+#endif /* AVUTIL_FRAME_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/hmac.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2012 Martin Storsjo
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_HMAC_H
+#define AVUTIL_HMAC_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_hmac HMAC
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+enum AVHMACType {
+    AV_HMAC_MD5,
+    AV_HMAC_SHA1,
+};
+
+typedef struct AVHMAC AVHMAC;
+
+/**
+ * Allocate an AVHMAC context.
+ * @param type The hash function used for the HMAC.
+ */
+AVHMAC *av_hmac_alloc(enum AVHMACType type);
+
+/**
+ * Free an AVHMAC context.
+ * @param ctx The context to free, may be NULL
+ */
+void av_hmac_free(AVHMAC *ctx);
+
+/**
+ * Initialize an AVHMAC context with an authentication key.
+ * @param ctx    The HMAC context
+ * @param key    The authentication key
+ * @param keylen The length of the key, in bytes
+ */
+void av_hmac_init(AVHMAC *ctx, const uint8_t *key, unsigned int keylen);
+
+/**
+ * Hash data with the HMAC.
+ * @param ctx  The HMAC context
+ * @param data The data to hash
+ * @param len  The length of the data, in bytes
+ */
+void av_hmac_update(AVHMAC *ctx, const uint8_t *data, unsigned int len);
+
+/**
+ * Finish hashing and output the HMAC digest.
+ * @param ctx    The HMAC context
+ * @param out    The output buffer to write the digest into
+ * @param outlen The length of the out buffer, in bytes
+ * @return       The number of bytes written to out, or a negative error code.
+ */
+int av_hmac_final(AVHMAC *ctx, uint8_t *out, unsigned int outlen);
+
+/**
+ * Hash an array of data with a key.
+ * @param ctx    The HMAC context
+ * @param data   The data to hash
+ * @param len    The length of the data, in bytes
+ * @param key    The authentication key
+ * @param keylen The length of the key, in bytes
+ * @param out    The output buffer to write the digest into
+ * @param outlen The length of the out buffer, in bytes
+ * @return       The number of bytes written to out, or a negative error code.
+ */
+int av_hmac_calc(AVHMAC *ctx, const uint8_t *data, unsigned int len,
+                 const uint8_t *key, unsigned int keylen,
+                 uint8_t *out, unsigned int outlen);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_HMAC_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/imgutils.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,200 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_IMGUTILS_H
+#define AVUTIL_IMGUTILS_H
+
+/**
+ * @file
+ * misc image utilities
+ *
+ * @addtogroup lavu_picture
+ * @{
+ */
+
+#include "avutil.h"
+#include "pixdesc.h"
+
+/**
+ * Compute the max pixel step for each plane of an image with a
+ * format described by pixdesc.
+ *
+ * The pixel step is the distance in bytes between the first byte of
+ * the group of bytes which describe a pixel component and the first
+ * byte of the successive group in the same plane for the same
+ * component.
+ *
+ * @param max_pixsteps an array which is filled with the max pixel step
+ * for each plane. Since a plane may contain different pixel
+ * components, the computed max_pixsteps[plane] is relative to the
+ * component in the plane with the max pixel step.
+ * @param max_pixstep_comps an array which is filled with the component
+ * for each plane which has the max pixel step. May be NULL.
+ */
+void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4],
+                                const AVPixFmtDescriptor *pixdesc);
+
+/**
+ * Compute the size of an image line with format pix_fmt and width
+ * width for the plane plane.
+ *
+ * @return the computed size in bytes
+ */
+int av_image_get_linesize(enum AVPixelFormat pix_fmt, int width, int plane);
+
+/**
+ * Fill plane linesizes for an image with pixel format pix_fmt and
+ * width width.
+ *
+ * @param linesizes array to be filled with the linesize for each plane
+ * @return >= 0 in case of success, a negative error code otherwise
+ */
+int av_image_fill_linesizes(int linesizes[4], enum AVPixelFormat pix_fmt, int width);
+
+/**
+ * Fill plane data pointers for an image with pixel format pix_fmt and
+ * height height.
+ *
+ * @param data pointers array to be filled with the pointer for each image plane
+ * @param ptr the pointer to a buffer which will contain the image
+ * @param linesizes the array containing the linesize for each
+ * plane, should be filled by av_image_fill_linesizes()
+ * @return the size in bytes required for the image buffer, a negative
+ * error code in case of failure
+ */
+int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height,
+                           uint8_t *ptr, const int linesizes[4]);
+
+/**
+ * Allocate an image with size w and h and pixel format pix_fmt, and
+ * fill pointers and linesizes accordingly.
+ * The allocated image buffer has to be freed by using
+ * av_freep(&pointers[0]).
+ *
+ * @param align the value to use for buffer size alignment
+ * @return the size in bytes required for the image buffer, a negative
+ * error code in case of failure
+ */
+int av_image_alloc(uint8_t *pointers[4], int linesizes[4],
+                   int w, int h, enum AVPixelFormat pix_fmt, int align);
+
+/**
+ * Copy image plane from src to dst.
+ * That is, copy "height" number of lines of "bytewidth" bytes each.
+ * The first byte of each successive line is separated by *_linesize
+ * bytes.
+ *
+ * bytewidth must be contained by both absolute values of dst_linesize
+ * and src_linesize, otherwise the function behavior is undefined.
+ *
+ * @param dst_linesize linesize for the image plane in dst
+ * @param src_linesize linesize for the image plane in src
+ */
+void av_image_copy_plane(uint8_t       *dst, int dst_linesize,
+                         const uint8_t *src, int src_linesize,
+                         int bytewidth, int height);
+
+/**
+ * Copy image in src_data to dst_data.
+ *
+ * @param dst_linesizes linesizes for the image in dst_data
+ * @param src_linesizes linesizes for the image in src_data
+ */
+void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
+                   const uint8_t *src_data[4], const int src_linesizes[4],
+                   enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * Setup the data pointers and linesizes based on the specified image
+ * parameters and the provided array.
+ *
+ * The fields of the given image are filled in by using the src
+ * address which points to the image data buffer. Depending on the
+ * specified pixel format, one or multiple image data pointers and
+ * line sizes will be set.  If a planar format is specified, several
+ * pointers will be set pointing to the different picture planes and
+ * the line sizes of the different planes will be stored in the
+ * lines_sizes array. Call with src == NULL to get the required
+ * size for the src buffer.
+ *
+ * To allocate the buffer and fill in the dst_data and dst_linesize in
+ * one call, use av_image_alloc().
+ *
+ * @param dst_data      data pointers to be filled in
+ * @param dst_linesizes linesizes for the image in dst_data to be filled in
+ * @param src           buffer which will contain or contains the actual image data, can be NULL
+ * @param pix_fmt       the pixel format of the image
+ * @param width         the width of the image in pixels
+ * @param height        the height of the image in pixels
+ * @param align         the value used in src for linesize alignment
+ * @return the size in bytes required for src, a negative error code
+ * in case of failure
+ */
+int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4],
+                         const uint8_t *src,
+                         enum AVPixelFormat pix_fmt, int width, int height, int align);
+
+/**
+ * Return the size in bytes of the amount of data required to store an
+ * image with the given parameters.
+ *
+ * @param[in] align the assumed linesize alignment
+ */
+int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align);
+
+/**
+ * Copy image data from an image into a buffer.
+ *
+ * av_image_get_buffer_size() can be used to compute the required size
+ * for the buffer to fill.
+ *
+ * @param dst           a buffer into which picture data will be copied
+ * @param dst_size      the size in bytes of dst
+ * @param src_data      pointers containing the source image data
+ * @param src_linesizes linesizes for the image in src_data
+ * @param pix_fmt       the pixel format of the source image
+ * @param width         the width of the source image in pixels
+ * @param height        the height of the source image in pixels
+ * @param align         the assumed linesize alignment for dst
+ * @return the number of bytes written to dst, or a negative value
+ * (error code) on error
+ */
+int av_image_copy_to_buffer(uint8_t *dst, int dst_size,
+                            const uint8_t * const src_data[4], const int src_linesize[4],
+                            enum AVPixelFormat pix_fmt, int width, int height, int align);
+
+/**
+ * Check if the given dimension of an image is valid, meaning that all
+ * bytes of the image can be addressed with a signed int.
+ *
+ * @param w the width of the picture
+ * @param h the height of the picture
+ * @param log_offset the offset to sum to the log level for logging with log_ctx
+ * @param log_ctx the parent logging context, it may be NULL
+ * @return >= 0 if valid, a negative error code otherwise
+ */
+int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx);
+
+int avpriv_set_systematic_pal2(uint32_t pal[256], enum AVPixelFormat pix_fmt);
+
+/**
+ * @}
+ */
+
+
+#endif /* AVUTIL_IMGUTILS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/intfloat.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_INTFLOAT_H
+#define AVUTIL_INTFLOAT_H
+
+#include <stdint.h>
+#include "attributes.h"
+
+union av_intfloat32 {
+    uint32_t i;
+    float    f;
+};
+
+union av_intfloat64 {
+    uint64_t i;
+    double   f;
+};
+
+/**
+ * Reinterpret a 32-bit integer as a float.
+ */
+static av_always_inline float av_int2float(uint32_t i)
+{
+    union av_intfloat32 v;
+    v.i = i;
+    return v.f;
+}
+
+/**
+ * Reinterpret a float as a 32-bit integer.
+ */
+static av_always_inline uint32_t av_float2int(float f)
+{
+    union av_intfloat32 v;
+    v.f = f;
+    return v.i;
+}
+
+/**
+ * Reinterpret a 64-bit integer as a double.
+ */
+static av_always_inline double av_int2double(uint64_t i)
+{
+    union av_intfloat64 v;
+    v.i = i;
+    return v.f;
+}
+
+/**
+ * Reinterpret a double as a 64-bit integer.
+ */
+static av_always_inline uint64_t av_double2int(double f)
+{
+    union av_intfloat64 v;
+    v.f = f;
+    return v.i;
+}
+
+#endif /* AVUTIL_INTFLOAT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/intfloat_readwrite.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,40 @@
+/*
+ * copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_INTFLOAT_READWRITE_H
+#define AVUTIL_INTFLOAT_READWRITE_H
+
+#include <stdint.h>
+#include "attributes.h"
+
+/* IEEE 80 bits extended float */
+typedef struct AVExtFloat  {
+    uint8_t exponent[2];
+    uint8_t mantissa[8];
+} AVExtFloat;
+
+attribute_deprecated double av_int2dbl(int64_t v) av_const;
+attribute_deprecated float av_int2flt(int32_t v) av_const;
+attribute_deprecated double av_ext2dbl(const AVExtFloat ext) av_const;
+attribute_deprecated int64_t av_dbl2int(double d) av_const;
+attribute_deprecated int32_t av_flt2int(float d) av_const;
+attribute_deprecated AVExtFloat av_dbl2ext(double d) av_const;
+
+#endif /* AVUTIL_INTFLOAT_READWRITE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/intreadwrite.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,621 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_INTREADWRITE_H
+#define AVUTIL_INTREADWRITE_H
+
+#include <stdint.h>
+#include "libavutil/avconfig.h"
+#include "attributes.h"
+#include "bswap.h"
+
+typedef union {
+    uint64_t u64;
+    uint32_t u32[2];
+    uint16_t u16[4];
+    uint8_t  u8 [8];
+    double   f64;
+    float    f32[2];
+} av_alias av_alias64;
+
+typedef union {
+    uint32_t u32;
+    uint16_t u16[2];
+    uint8_t  u8 [4];
+    float    f32;
+} av_alias av_alias32;
+
+typedef union {
+    uint16_t u16;
+    uint8_t  u8 [2];
+} av_alias av_alias16;
+
+/*
+ * Arch-specific headers can provide any combination of
+ * AV_[RW][BLN](16|24|32|48|64) and AV_(COPY|SWAP|ZERO)(64|128) macros.
+ * Preprocessor symbols must be defined, even if these are implemented
+ * as inline functions.
+ */
+
+#ifdef HAVE_AV_CONFIG_H
+
+#include "config.h"
+
+#if   ARCH_ARM
+#   include "arm/intreadwrite.h"
+#elif ARCH_AVR32
+#   include "avr32/intreadwrite.h"
+#elif ARCH_MIPS
+#   include "mips/intreadwrite.h"
+#elif ARCH_PPC
+#   include "ppc/intreadwrite.h"
+#elif ARCH_TOMI
+#   include "tomi/intreadwrite.h"
+#elif ARCH_X86
+#   include "x86/intreadwrite.h"
+#endif
+
+#endif /* HAVE_AV_CONFIG_H */
+
+/*
+ * Map AV_RNXX <-> AV_R[BL]XX for all variants provided by per-arch headers.
+ */
+
+#if AV_HAVE_BIGENDIAN
+
+#   if    defined(AV_RN16) && !defined(AV_RB16)
+#       define AV_RB16(p) AV_RN16(p)
+#   elif !defined(AV_RN16) &&  defined(AV_RB16)
+#       define AV_RN16(p) AV_RB16(p)
+#   endif
+
+#   if    defined(AV_WN16) && !defined(AV_WB16)
+#       define AV_WB16(p, v) AV_WN16(p, v)
+#   elif !defined(AV_WN16) &&  defined(AV_WB16)
+#       define AV_WN16(p, v) AV_WB16(p, v)
+#   endif
+
+#   if    defined(AV_RN24) && !defined(AV_RB24)
+#       define AV_RB24(p) AV_RN24(p)
+#   elif !defined(AV_RN24) &&  defined(AV_RB24)
+#       define AV_RN24(p) AV_RB24(p)
+#   endif
+
+#   if    defined(AV_WN24) && !defined(AV_WB24)
+#       define AV_WB24(p, v) AV_WN24(p, v)
+#   elif !defined(AV_WN24) &&  defined(AV_WB24)
+#       define AV_WN24(p, v) AV_WB24(p, v)
+#   endif
+
+#   if    defined(AV_RN32) && !defined(AV_RB32)
+#       define AV_RB32(p) AV_RN32(p)
+#   elif !defined(AV_RN32) &&  defined(AV_RB32)
+#       define AV_RN32(p) AV_RB32(p)
+#   endif
+
+#   if    defined(AV_WN32) && !defined(AV_WB32)
+#       define AV_WB32(p, v) AV_WN32(p, v)
+#   elif !defined(AV_WN32) &&  defined(AV_WB32)
+#       define AV_WN32(p, v) AV_WB32(p, v)
+#   endif
+
+#   if    defined(AV_RN48) && !defined(AV_RB48)
+#       define AV_RB48(p) AV_RN48(p)
+#   elif !defined(AV_RN48) &&  defined(AV_RB48)
+#       define AV_RN48(p) AV_RB48(p)
+#   endif
+
+#   if    defined(AV_WN48) && !defined(AV_WB48)
+#       define AV_WB48(p, v) AV_WN48(p, v)
+#   elif !defined(AV_WN48) &&  defined(AV_WB48)
+#       define AV_WN48(p, v) AV_WB48(p, v)
+#   endif
+
+#   if    defined(AV_RN64) && !defined(AV_RB64)
+#       define AV_RB64(p) AV_RN64(p)
+#   elif !defined(AV_RN64) &&  defined(AV_RB64)
+#       define AV_RN64(p) AV_RB64(p)
+#   endif
+
+#   if    defined(AV_WN64) && !defined(AV_WB64)
+#       define AV_WB64(p, v) AV_WN64(p, v)
+#   elif !defined(AV_WN64) &&  defined(AV_WB64)
+#       define AV_WN64(p, v) AV_WB64(p, v)
+#   endif
+
+#else /* AV_HAVE_BIGENDIAN */
+
+#   if    defined(AV_RN16) && !defined(AV_RL16)
+#       define AV_RL16(p) AV_RN16(p)
+#   elif !defined(AV_RN16) &&  defined(AV_RL16)
+#       define AV_RN16(p) AV_RL16(p)
+#   endif
+
+#   if    defined(AV_WN16) && !defined(AV_WL16)
+#       define AV_WL16(p, v) AV_WN16(p, v)
+#   elif !defined(AV_WN16) &&  defined(AV_WL16)
+#       define AV_WN16(p, v) AV_WL16(p, v)
+#   endif
+
+#   if    defined(AV_RN24) && !defined(AV_RL24)
+#       define AV_RL24(p) AV_RN24(p)
+#   elif !defined(AV_RN24) &&  defined(AV_RL24)
+#       define AV_RN24(p) AV_RL24(p)
+#   endif
+
+#   if    defined(AV_WN24) && !defined(AV_WL24)
+#       define AV_WL24(p, v) AV_WN24(p, v)
+#   elif !defined(AV_WN24) &&  defined(AV_WL24)
+#       define AV_WN24(p, v) AV_WL24(p, v)
+#   endif
+
+#   if    defined(AV_RN32) && !defined(AV_RL32)
+#       define AV_RL32(p) AV_RN32(p)
+#   elif !defined(AV_RN32) &&  defined(AV_RL32)
+#       define AV_RN32(p) AV_RL32(p)
+#   endif
+
+#   if    defined(AV_WN32) && !defined(AV_WL32)
+#       define AV_WL32(p, v) AV_WN32(p, v)
+#   elif !defined(AV_WN32) &&  defined(AV_WL32)
+#       define AV_WN32(p, v) AV_WL32(p, v)
+#   endif
+
+#   if    defined(AV_RN48) && !defined(AV_RL48)
+#       define AV_RL48(p) AV_RN48(p)
+#   elif !defined(AV_RN48) &&  defined(AV_RL48)
+#       define AV_RN48(p) AV_RL48(p)
+#   endif
+
+#   if    defined(AV_WN48) && !defined(AV_WL48)
+#       define AV_WL48(p, v) AV_WN48(p, v)
+#   elif !defined(AV_WN48) &&  defined(AV_WL48)
+#       define AV_WN48(p, v) AV_WL48(p, v)
+#   endif
+
+#   if    defined(AV_RN64) && !defined(AV_RL64)
+#       define AV_RL64(p) AV_RN64(p)
+#   elif !defined(AV_RN64) &&  defined(AV_RL64)
+#       define AV_RN64(p) AV_RL64(p)
+#   endif
+
+#   if    defined(AV_WN64) && !defined(AV_WL64)
+#       define AV_WL64(p, v) AV_WN64(p, v)
+#   elif !defined(AV_WN64) &&  defined(AV_WL64)
+#       define AV_WN64(p, v) AV_WL64(p, v)
+#   endif
+
+#endif /* !AV_HAVE_BIGENDIAN */
+
+/*
+ * Define AV_[RW]N helper macros to simplify definitions not provided
+ * by per-arch headers.
+ */
+
+#if defined(__GNUC__) && !defined(__TI_COMPILER_VERSION__)
+
+union unaligned_64 { uint64_t l; } __attribute__((packed)) av_alias;
+union unaligned_32 { uint32_t l; } __attribute__((packed)) av_alias;
+union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
+
+#   define AV_RN(s, p) (((const union unaligned_##s *) (p))->l)
+#   define AV_WN(s, p, v) ((((union unaligned_##s *) (p))->l) = (v))
+
+#elif defined(__DECC)
+
+#   define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p)))
+#   define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v))
+
+#elif AV_HAVE_FAST_UNALIGNED
+
+#   define AV_RN(s, p) (((const av_alias##s*)(p))->u##s)
+#   define AV_WN(s, p, v) (((av_alias##s*)(p))->u##s = (v))
+
+#else
+
+#ifndef AV_RB16
+#   define AV_RB16(x)                           \
+    ((((const uint8_t*)(x))[0] << 8) |          \
+      ((const uint8_t*)(x))[1])
+#endif
+#ifndef AV_WB16
+#   define AV_WB16(p, darg) do {                \
+        unsigned d = (darg);                    \
+        ((uint8_t*)(p))[1] = (d);               \
+        ((uint8_t*)(p))[0] = (d)>>8;            \
+    } while(0)
+#endif
+
+#ifndef AV_RL16
+#   define AV_RL16(x)                           \
+    ((((const uint8_t*)(x))[1] << 8) |          \
+      ((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL16
+#   define AV_WL16(p, darg) do {                \
+        unsigned d = (darg);                    \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+    } while(0)
+#endif
+
+#ifndef AV_RB32
+#   define AV_RB32(x)                                \
+    (((uint32_t)((const uint8_t*)(x))[0] << 24) |    \
+               (((const uint8_t*)(x))[1] << 16) |    \
+               (((const uint8_t*)(x))[2] <<  8) |    \
+                ((const uint8_t*)(x))[3])
+#endif
+#ifndef AV_WB32
+#   define AV_WB32(p, darg) do {                \
+        unsigned d = (darg);                    \
+        ((uint8_t*)(p))[3] = (d);               \
+        ((uint8_t*)(p))[2] = (d)>>8;            \
+        ((uint8_t*)(p))[1] = (d)>>16;           \
+        ((uint8_t*)(p))[0] = (d)>>24;           \
+    } while(0)
+#endif
+
+#ifndef AV_RL32
+#   define AV_RL32(x)                                \
+    (((uint32_t)((const uint8_t*)(x))[3] << 24) |    \
+               (((const uint8_t*)(x))[2] << 16) |    \
+               (((const uint8_t*)(x))[1] <<  8) |    \
+                ((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL32
+#   define AV_WL32(p, darg) do {                \
+        unsigned d = (darg);                    \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[2] = (d)>>16;           \
+        ((uint8_t*)(p))[3] = (d)>>24;           \
+    } while(0)
+#endif
+
+#ifndef AV_RB64
+#   define AV_RB64(x)                                   \
+    (((uint64_t)((const uint8_t*)(x))[0] << 56) |       \
+     ((uint64_t)((const uint8_t*)(x))[1] << 48) |       \
+     ((uint64_t)((const uint8_t*)(x))[2] << 40) |       \
+     ((uint64_t)((const uint8_t*)(x))[3] << 32) |       \
+     ((uint64_t)((const uint8_t*)(x))[4] << 24) |       \
+     ((uint64_t)((const uint8_t*)(x))[5] << 16) |       \
+     ((uint64_t)((const uint8_t*)(x))[6] <<  8) |       \
+      (uint64_t)((const uint8_t*)(x))[7])
+#endif
+#ifndef AV_WB64
+#   define AV_WB64(p, darg) do {                \
+        uint64_t d = (darg);                    \
+        ((uint8_t*)(p))[7] = (d);               \
+        ((uint8_t*)(p))[6] = (d)>>8;            \
+        ((uint8_t*)(p))[5] = (d)>>16;           \
+        ((uint8_t*)(p))[4] = (d)>>24;           \
+        ((uint8_t*)(p))[3] = (d)>>32;           \
+        ((uint8_t*)(p))[2] = (d)>>40;           \
+        ((uint8_t*)(p))[1] = (d)>>48;           \
+        ((uint8_t*)(p))[0] = (d)>>56;           \
+    } while(0)
+#endif
+
+#ifndef AV_RL64
+#   define AV_RL64(x)                                   \
+    (((uint64_t)((const uint8_t*)(x))[7] << 56) |       \
+     ((uint64_t)((const uint8_t*)(x))[6] << 48) |       \
+     ((uint64_t)((const uint8_t*)(x))[5] << 40) |       \
+     ((uint64_t)((const uint8_t*)(x))[4] << 32) |       \
+     ((uint64_t)((const uint8_t*)(x))[3] << 24) |       \
+     ((uint64_t)((const uint8_t*)(x))[2] << 16) |       \
+     ((uint64_t)((const uint8_t*)(x))[1] <<  8) |       \
+      (uint64_t)((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL64
+#   define AV_WL64(p, darg) do {                \
+        uint64_t d = (darg);                    \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[2] = (d)>>16;           \
+        ((uint8_t*)(p))[3] = (d)>>24;           \
+        ((uint8_t*)(p))[4] = (d)>>32;           \
+        ((uint8_t*)(p))[5] = (d)>>40;           \
+        ((uint8_t*)(p))[6] = (d)>>48;           \
+        ((uint8_t*)(p))[7] = (d)>>56;           \
+    } while(0)
+#endif
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_RN(s, p)    AV_RB##s(p)
+#   define AV_WN(s, p, v) AV_WB##s(p, v)
+#else
+#   define AV_RN(s, p)    AV_RL##s(p)
+#   define AV_WN(s, p, v) AV_WL##s(p, v)
+#endif
+
+#endif /* HAVE_FAST_UNALIGNED */
+
+#ifndef AV_RN16
+#   define AV_RN16(p) AV_RN(16, p)
+#endif
+
+#ifndef AV_RN32
+#   define AV_RN32(p) AV_RN(32, p)
+#endif
+
+#ifndef AV_RN64
+#   define AV_RN64(p) AV_RN(64, p)
+#endif
+
+#ifndef AV_WN16
+#   define AV_WN16(p, v) AV_WN(16, p, v)
+#endif
+
+#ifndef AV_WN32
+#   define AV_WN32(p, v) AV_WN(32, p, v)
+#endif
+
+#ifndef AV_WN64
+#   define AV_WN64(p, v) AV_WN(64, p, v)
+#endif
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_RB(s, p)    AV_RN##s(p)
+#   define AV_WB(s, p, v) AV_WN##s(p, v)
+#   define AV_RL(s, p)    av_bswap##s(AV_RN##s(p))
+#   define AV_WL(s, p, v) AV_WN##s(p, av_bswap##s(v))
+#else
+#   define AV_RB(s, p)    av_bswap##s(AV_RN##s(p))
+#   define AV_WB(s, p, v) AV_WN##s(p, av_bswap##s(v))
+#   define AV_RL(s, p)    AV_RN##s(p)
+#   define AV_WL(s, p, v) AV_WN##s(p, v)
+#endif
+
+#define AV_RB8(x)     (((const uint8_t*)(x))[0])
+#define AV_WB8(p, d)  do { ((uint8_t*)(p))[0] = (d); } while(0)
+
+#define AV_RL8(x)     AV_RB8(x)
+#define AV_WL8(p, d)  AV_WB8(p, d)
+
+#ifndef AV_RB16
+#   define AV_RB16(p)    AV_RB(16, p)
+#endif
+#ifndef AV_WB16
+#   define AV_WB16(p, v) AV_WB(16, p, v)
+#endif
+
+#ifndef AV_RL16
+#   define AV_RL16(p)    AV_RL(16, p)
+#endif
+#ifndef AV_WL16
+#   define AV_WL16(p, v) AV_WL(16, p, v)
+#endif
+
+#ifndef AV_RB32
+#   define AV_RB32(p)    AV_RB(32, p)
+#endif
+#ifndef AV_WB32
+#   define AV_WB32(p, v) AV_WB(32, p, v)
+#endif
+
+#ifndef AV_RL32
+#   define AV_RL32(p)    AV_RL(32, p)
+#endif
+#ifndef AV_WL32
+#   define AV_WL32(p, v) AV_WL(32, p, v)
+#endif
+
+#ifndef AV_RB64
+#   define AV_RB64(p)    AV_RB(64, p)
+#endif
+#ifndef AV_WB64
+#   define AV_WB64(p, v) AV_WB(64, p, v)
+#endif
+
+#ifndef AV_RL64
+#   define AV_RL64(p)    AV_RL(64, p)
+#endif
+#ifndef AV_WL64
+#   define AV_WL64(p, v) AV_WL(64, p, v)
+#endif
+
+#ifndef AV_RB24
+#   define AV_RB24(x)                           \
+    ((((const uint8_t*)(x))[0] << 16) |         \
+     (((const uint8_t*)(x))[1] <<  8) |         \
+      ((const uint8_t*)(x))[2])
+#endif
+#ifndef AV_WB24
+#   define AV_WB24(p, d) do {                   \
+        ((uint8_t*)(p))[2] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[0] = (d)>>16;           \
+    } while(0)
+#endif
+
+#ifndef AV_RL24
+#   define AV_RL24(x)                           \
+    ((((const uint8_t*)(x))[2] << 16) |         \
+     (((const uint8_t*)(x))[1] <<  8) |         \
+      ((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL24
+#   define AV_WL24(p, d) do {                   \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[2] = (d)>>16;           \
+    } while(0)
+#endif
+
+#ifndef AV_RB48
+#   define AV_RB48(x)                                     \
+    (((uint64_t)((const uint8_t*)(x))[0] << 40) |         \
+     ((uint64_t)((const uint8_t*)(x))[1] << 32) |         \
+     ((uint64_t)((const uint8_t*)(x))[2] << 24) |         \
+     ((uint64_t)((const uint8_t*)(x))[3] << 16) |         \
+     ((uint64_t)((const uint8_t*)(x))[4] <<  8) |         \
+      (uint64_t)((const uint8_t*)(x))[5])
+#endif
+#ifndef AV_WB48
+#   define AV_WB48(p, darg) do {                \
+        uint64_t d = (darg);                    \
+        ((uint8_t*)(p))[5] = (d);               \
+        ((uint8_t*)(p))[4] = (d)>>8;            \
+        ((uint8_t*)(p))[3] = (d)>>16;           \
+        ((uint8_t*)(p))[2] = (d)>>24;           \
+        ((uint8_t*)(p))[1] = (d)>>32;           \
+        ((uint8_t*)(p))[0] = (d)>>40;           \
+    } while(0)
+#endif
+
+#ifndef AV_RL48
+#   define AV_RL48(x)                                     \
+    (((uint64_t)((const uint8_t*)(x))[5] << 40) |         \
+     ((uint64_t)((const uint8_t*)(x))[4] << 32) |         \
+     ((uint64_t)((const uint8_t*)(x))[3] << 24) |         \
+     ((uint64_t)((const uint8_t*)(x))[2] << 16) |         \
+     ((uint64_t)((const uint8_t*)(x))[1] <<  8) |         \
+      (uint64_t)((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL48
+#   define AV_WL48(p, darg) do {                \
+        uint64_t d = (darg);                    \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[2] = (d)>>16;           \
+        ((uint8_t*)(p))[3] = (d)>>24;           \
+        ((uint8_t*)(p))[4] = (d)>>32;           \
+        ((uint8_t*)(p))[5] = (d)>>40;           \
+    } while(0)
+#endif
+
+/*
+ * The AV_[RW]NA macros access naturally aligned data
+ * in a type-safe way.
+ */
+
+#define AV_RNA(s, p)    (((const av_alias##s*)(p))->u##s)
+#define AV_WNA(s, p, v) (((av_alias##s*)(p))->u##s = (v))
+
+#ifndef AV_RN16A
+#   define AV_RN16A(p) AV_RNA(16, p)
+#endif
+
+#ifndef AV_RN32A
+#   define AV_RN32A(p) AV_RNA(32, p)
+#endif
+
+#ifndef AV_RN64A
+#   define AV_RN64A(p) AV_RNA(64, p)
+#endif
+
+#ifndef AV_WN16A
+#   define AV_WN16A(p, v) AV_WNA(16, p, v)
+#endif
+
+#ifndef AV_WN32A
+#   define AV_WN32A(p, v) AV_WNA(32, p, v)
+#endif
+
+#ifndef AV_WN64A
+#   define AV_WN64A(p, v) AV_WNA(64, p, v)
+#endif
+
+/*
+ * The AV_COPYxxU macros are suitable for copying data to/from unaligned
+ * memory locations.
+ */
+
+#define AV_COPYU(n, d, s) AV_WN##n(d, AV_RN##n(s));
+
+#ifndef AV_COPY16U
+#   define AV_COPY16U(d, s) AV_COPYU(16, d, s)
+#endif
+
+#ifndef AV_COPY32U
+#   define AV_COPY32U(d, s) AV_COPYU(32, d, s)
+#endif
+
+#ifndef AV_COPY64U
+#   define AV_COPY64U(d, s) AV_COPYU(64, d, s)
+#endif
+
+#ifndef AV_COPY128U
+#   define AV_COPY128U(d, s)                                    \
+    do {                                                        \
+        AV_COPY64U(d, s);                                       \
+        AV_COPY64U((char *)(d) + 8, (const char *)(s) + 8);     \
+    } while(0)
+#endif
+
+/* Parameters for AV_COPY*, AV_SWAP*, AV_ZERO* must be
+ * naturally aligned. They may be implemented using MMX,
+ * so emms_c() must be called before using any float code
+ * afterwards.
+ */
+
+#define AV_COPY(n, d, s) \
+    (((av_alias##n*)(d))->u##n = ((const av_alias##n*)(s))->u##n)
+
+#ifndef AV_COPY16
+#   define AV_COPY16(d, s) AV_COPY(16, d, s)
+#endif
+
+#ifndef AV_COPY32
+#   define AV_COPY32(d, s) AV_COPY(32, d, s)
+#endif
+
+#ifndef AV_COPY64
+#   define AV_COPY64(d, s) AV_COPY(64, d, s)
+#endif
+
+#ifndef AV_COPY128
+#   define AV_COPY128(d, s)                    \
+    do {                                       \
+        AV_COPY64(d, s);                       \
+        AV_COPY64((char*)(d)+8, (char*)(s)+8); \
+    } while(0)
+#endif
+
+#define AV_SWAP(n, a, b) FFSWAP(av_alias##n, *(av_alias##n*)(a), *(av_alias##n*)(b))
+
+#ifndef AV_SWAP64
+#   define AV_SWAP64(a, b) AV_SWAP(64, a, b)
+#endif
+
+#define AV_ZERO(n, d) (((av_alias##n*)(d))->u##n = 0)
+
+#ifndef AV_ZERO16
+#   define AV_ZERO16(d) AV_ZERO(16, d)
+#endif
+
+#ifndef AV_ZERO32
+#   define AV_ZERO32(d) AV_ZERO(32, d)
+#endif
+
+#ifndef AV_ZERO64
+#   define AV_ZERO64(d) AV_ZERO(64, d)
+#endif
+
+#ifndef AV_ZERO128
+#   define AV_ZERO128(d)         \
+    do {                         \
+        AV_ZERO64(d);            \
+        AV_ZERO64((char*)(d)+8); \
+    } while(0)
+#endif
+
+#endif /* AVUTIL_INTREADWRITE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/lfg.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,62 @@
+/*
+ * Lagged Fibonacci PRNG
+ * Copyright (c) 2008 Michael Niedermayer
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_LFG_H
+#define AVUTIL_LFG_H
+
+typedef struct AVLFG {
+    unsigned int state[64];
+    int index;
+} AVLFG;
+
+void av_lfg_init(AVLFG *c, unsigned int seed);
+
+/**
+ * Get the next random unsigned 32-bit number using an ALFG.
+ *
+ * Please also consider a simple LCG like state= state*1664525+1013904223,
+ * it may be good enough and faster for your specific use case.
+ */
+static inline unsigned int av_lfg_get(AVLFG *c){
+    c->state[c->index & 63] = c->state[(c->index-24) & 63] + c->state[(c->index-55) & 63];
+    return c->state[c->index++ & 63];
+}
+
+/**
+ * Get the next random unsigned 32-bit number using a MLFG.
+ *
+ * Please also consider av_lfg_get() above, it is faster.
+ */
+static inline unsigned int av_mlfg_get(AVLFG *c){
+    unsigned int a= c->state[(c->index-55) & 63];
+    unsigned int b= c->state[(c->index-24) & 63];
+    return c->state[c->index++ & 63] = 2*a*b+a+b;
+}
+
+/**
+ * Get the next two numbers generated by a Box-Muller Gaussian
+ * generator using the random numbers issued by lfg.
+ *
+ * @param out array where the two generated numbers are placed
+ */
+void av_bmg_get(AVLFG *lfg, double out[2]);
+
+#endif /* AVUTIL_LFG_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/log.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,222 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_LOG_H
+#define AVUTIL_LOG_H
+
+#include <stdarg.h>
+#include "avutil.h"
+#include "attributes.h"
+
+typedef enum {
+    AV_CLASS_CATEGORY_NA = 0,
+    AV_CLASS_CATEGORY_INPUT,
+    AV_CLASS_CATEGORY_OUTPUT,
+    AV_CLASS_CATEGORY_MUXER,
+    AV_CLASS_CATEGORY_DEMUXER,
+    AV_CLASS_CATEGORY_ENCODER,
+    AV_CLASS_CATEGORY_DECODER,
+    AV_CLASS_CATEGORY_FILTER,
+    AV_CLASS_CATEGORY_BITSTREAM_FILTER,
+    AV_CLASS_CATEGORY_SWSCALER,
+    AV_CLASS_CATEGORY_SWRESAMPLER,
+    AV_CLASS_CATEGORY_NB, ///< not part of ABI/API
+}AVClassCategory;
+
+struct AVOptionRanges;
+
+/**
+ * Describe the class of an AVClass context structure. That is an
+ * arbitrary struct of which the first field is a pointer to an
+ * AVClass struct (e.g. AVCodecContext, AVFormatContext etc.).
+ */
+typedef struct AVClass {
+    /**
+     * The name of the class; usually it is the same name as the
+     * context structure type to which the AVClass is associated.
+     */
+    const char* class_name;
+
+    /**
+     * A pointer to a function which returns the name of a context
+     * instance ctx associated with the class.
+     */
+    const char* (*item_name)(void* ctx);
+
+    /**
+     * a pointer to the first option specified in the class if any or NULL
+     *
+     * @see av_set_default_options()
+     */
+    const struct AVOption *option;
+
+    /**
+     * LIBAVUTIL_VERSION with which this structure was created.
+     * This is used to allow fields to be added without requiring major
+     * version bumps everywhere.
+     */
+
+    int version;
+
+    /**
+     * Offset in the structure where log_level_offset is stored.
+     * 0 means there is no such variable
+     */
+    int log_level_offset_offset;
+
+    /**
+     * Offset in the structure where a pointer to the parent context for
+     * logging is stored. For example a decoder could pass its AVCodecContext
+     * to eval as such a parent context, which an av_log() implementation
+     * could then leverage to display the parent context.
+     * The offset can be NULL.
+     */
+    int parent_log_context_offset;
+
+    /**
+     * Return next AVOptions-enabled child or NULL
+     */
+    void* (*child_next)(void *obj, void *prev);
+
+    /**
+     * Return an AVClass corresponding to the next potential
+     * AVOptions-enabled child.
+     *
+     * The difference between child_next and this is that
+     * child_next iterates over _already existing_ objects, while
+     * child_class_next iterates over _all possible_ children.
+     */
+    const struct AVClass* (*child_class_next)(const struct AVClass *prev);
+
+    /**
+     * Category used for visualization (like color)
+     * This is only set if the category is equal for all objects using this class.
+     * available since version (51 << 16 | 56 << 8 | 100)
+     */
+    AVClassCategory category;
+
+    /**
+     * Callback to return the category.
+     * available since version (51 << 16 | 59 << 8 | 100)
+     */
+    AVClassCategory (*get_category)(void* ctx);
+
+    /**
+     * Callback to return the supported/allowed ranges.
+     * available since version (52.12)
+     */
+    int (*query_ranges)(struct AVOptionRanges **, void *obj, const char *key, int flags);
+} AVClass;
+
+/* av_log API */
+
+#define AV_LOG_QUIET    -8
+
+/**
+ * Something went really wrong and we will crash now.
+ */
+#define AV_LOG_PANIC     0
+
+/**
+ * Something went wrong and recovery is not possible.
+ * For example, no header was found for a format which depends
+ * on headers or an illegal combination of parameters is used.
+ */
+#define AV_LOG_FATAL     8
+
+/**
+ * Something went wrong and cannot losslessly be recovered.
+ * However, not all future data is affected.
+ */
+#define AV_LOG_ERROR    16
+
+/**
+ * Something somehow does not look correct. This may or may not
+ * lead to problems. An example would be the use of '-vstrict -2'.
+ */
+#define AV_LOG_WARNING  24
+
+#define AV_LOG_INFO     32
+#define AV_LOG_VERBOSE  40
+
+/**
+ * Stuff which is only useful for libav* developers.
+ */
+#define AV_LOG_DEBUG    48
+
+#define AV_LOG_MAX_OFFSET (AV_LOG_DEBUG - AV_LOG_QUIET)
+
+/**
+ * Send the specified message to the log if the level is less than or equal
+ * to the current av_log_level. By default, all logging messages are sent to
+ * stderr. This behavior can be altered by setting a different av_vlog callback
+ * function.
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message, lower values signifying
+ * higher importance.
+ * @param fmt The format string (printf-compatible) that specifies how
+ * subsequent arguments are converted to output.
+ * @see av_vlog
+ */
+void av_log(void *avcl, int level, const char *fmt, ...) av_printf_format(3, 4);
+
+void av_vlog(void *avcl, int level, const char *fmt, va_list);
+int av_log_get_level(void);
+void av_log_set_level(int);
+void av_log_set_callback(void (*)(void*, int, const char*, va_list));
+void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl);
+const char* av_default_item_name(void* ctx);
+AVClassCategory av_default_get_category(void *ptr);
+
+/**
+ * Format a line of log the same way as the default callback.
+ * @param line          buffer to receive the formated line
+ * @param line_size     size of the buffer
+ * @param print_prefix  used to store whether the prefix must be printed;
+ *                      must point to a persistent integer initially set to 1
+ */
+void av_log_format_line(void *ptr, int level, const char *fmt, va_list vl,
+                        char *line, int line_size, int *print_prefix);
+
+/**
+ * av_dlog macros
+ * Useful to print debug messages that shouldn't get compiled in normally.
+ */
+
+#ifdef DEBUG
+#    define av_dlog(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
+#else
+#    define av_dlog(pctx, ...) do { if (0) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__); } while (0)
+#endif
+
+/**
+ * Skip repeated messages, this requires the user app to use av_log() instead of
+ * (f)printf as the 2 would otherwise interfere and lead to
+ * "Last message repeated x times" messages below (f)printf messages with some
+ * bad luck.
+ * Also to receive the last, "last repeated" line if any, the user app must
+ * call av_log(NULL, AV_LOG_QUIET, "%s", ""); at the end
+ */
+#define AV_LOG_SKIP_REPEATED 1
+void av_log_set_flags(int arg);
+
+#endif /* AVUTIL_LOG_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/lzo.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,66 @@
+/*
+ * LZO 1x decompression
+ * copyright (c) 2006 Reimar Doeffinger
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_LZO_H
+#define AVUTIL_LZO_H
+
+/**
+ * @defgroup lavu_lzo LZO
+ * @ingroup lavu_crypto
+ *
+ * @{
+ */
+
+#include <stdint.h>
+
+/** @name Error flags returned by av_lzo1x_decode
+ * @{ */
+/// end of the input buffer reached before decoding finished
+#define AV_LZO_INPUT_DEPLETED  1
+/// decoded data did not fit into output buffer
+#define AV_LZO_OUTPUT_FULL     2
+/// a reference to previously decoded data was wrong
+#define AV_LZO_INVALID_BACKPTR 4
+/// a non-specific error in the compressed bitstream
+#define AV_LZO_ERROR           8
+/** @} */
+
+#define AV_LZO_INPUT_PADDING   8
+#define AV_LZO_OUTPUT_PADDING 12
+
+/**
+ * @brief Decodes LZO 1x compressed data.
+ * @param out output buffer
+ * @param outlen size of output buffer, number of bytes left are returned here
+ * @param in input buffer
+ * @param inlen size of input buffer, number of bytes left are returned here
+ * @return 0 on success, otherwise a combination of the error flags above
+ *
+ * Make sure all buffers are appropriately padded, in must provide
+ * AV_LZO_INPUT_PADDING, out must provide AV_LZO_OUTPUT_PADDING additional bytes.
+ */
+int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_LZO_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/mathematics.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,147 @@
+/*
+ * copyright (c) 2005-2012 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_MATHEMATICS_H
+#define AVUTIL_MATHEMATICS_H
+
+#include <stdint.h>
+#include <math.h>
+#include "attributes.h"
+#include "rational.h"
+#include "intfloat.h"
+
+#ifndef M_E
+#define M_E            2.7182818284590452354   /* e */
+#endif
+#ifndef M_LN2
+#define M_LN2          0.69314718055994530942  /* log_e 2 */
+#endif
+#ifndef M_LN10
+#define M_LN10         2.30258509299404568402  /* log_e 10 */
+#endif
+#ifndef M_LOG2_10
+#define M_LOG2_10      3.32192809488736234787  /* log_2 10 */
+#endif
+#ifndef M_PHI
+#define M_PHI          1.61803398874989484820   /* phi / golden ratio */
+#endif
+#ifndef M_PI
+#define M_PI           3.14159265358979323846  /* pi */
+#endif
+#ifndef M_SQRT1_2
+#define M_SQRT1_2      0.70710678118654752440  /* 1/sqrt(2) */
+#endif
+#ifndef M_SQRT2
+#define M_SQRT2        1.41421356237309504880  /* sqrt(2) */
+#endif
+#ifndef NAN
+#define NAN            av_int2float(0x7fc00000)
+#endif
+#ifndef INFINITY
+#define INFINITY       av_int2float(0x7f800000)
+#endif
+
+/**
+ * @addtogroup lavu_math
+ * @{
+ */
+
+
+enum AVRounding {
+    AV_ROUND_ZERO     = 0, ///< Round toward zero.
+    AV_ROUND_INF      = 1, ///< Round away from zero.
+    AV_ROUND_DOWN     = 2, ///< Round toward -infinity.
+    AV_ROUND_UP       = 3, ///< Round toward +infinity.
+    AV_ROUND_NEAR_INF = 5, ///< Round to nearest and halfway cases away from zero.
+    AV_ROUND_PASS_MINMAX = 8192, ///< Flag to pass INT64_MIN/MAX through instead of rescaling, this avoids special cases for AV_NOPTS_VALUE
+};
+
+/**
+ * Return the greatest common divisor of a and b.
+ * If both a and b are 0 or either or both are <0 then behavior is
+ * undefined.
+ */
+int64_t av_const av_gcd(int64_t a, int64_t b);
+
+/**
+ * Rescale a 64-bit integer with rounding to nearest.
+ * A simple a*b/c isn't possible as it can overflow.
+ */
+int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const;
+
+/**
+ * Rescale a 64-bit integer with specified rounding.
+ * A simple a*b/c isn't possible as it can overflow.
+ *
+ * @return rescaled value a, or if AV_ROUND_PASS_MINMAX is set and a is
+ *         INT64_MIN or INT64_MAX then a is passed through unchanged.
+ */
+int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding) av_const;
+
+/**
+ * Rescale a 64-bit integer by 2 rational numbers.
+ */
+int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const;
+
+/**
+ * Rescale a 64-bit integer by 2 rational numbers with specified rounding.
+ *
+ * @return rescaled value a, or if AV_ROUND_PASS_MINMAX is set and a is
+ *         INT64_MIN or INT64_MAX then a is passed through unchanged.
+ */
+int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq,
+                         enum AVRounding) av_const;
+
+/**
+ * Compare 2 timestamps each in its own timebases.
+ * The result of the function is undefined if one of the timestamps
+ * is outside the int64_t range when represented in the others timebase.
+ * @return -1 if ts_a is before ts_b, 1 if ts_a is after ts_b or 0 if they represent the same position
+ */
+int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b);
+
+/**
+ * Compare 2 integers modulo mod.
+ * That is we compare integers a and b for which only the least
+ * significant log2(mod) bits are known.
+ *
+ * @param mod must be a power of 2
+ * @return a negative value if a is smaller than b
+ *         a positive value if a is greater than b
+ *         0                if a equals          b
+ */
+int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod);
+
+/**
+ * Rescale a timestamp while preserving known durations.
+ *
+ * @param in_ts Input timestamp
+ * @param in_tb Input timesbase
+ * @param fs_tb Duration and *last timebase
+ * @param duration duration till the next call
+ * @param out_tb Output timesbase
+ */
+int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts,  AVRational fs_tb, int duration, int64_t *last, AVRational out_tb);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_MATHEMATICS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/md5.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,49 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_MD5_H
+#define AVUTIL_MD5_H
+
+#include <stdint.h>
+
+#include "attributes.h"
+#include "version.h"
+
+/**
+ * @defgroup lavu_md5 MD5
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+extern const int av_md5_size;
+
+struct AVMD5;
+
+struct AVMD5 *av_md5_alloc(void);
+void av_md5_init(struct AVMD5 *ctx);
+void av_md5_update(struct AVMD5 *ctx, const uint8_t *src, int len);
+void av_md5_final(struct AVMD5 *ctx, uint8_t *dst);
+void av_md5_sum(uint8_t *dst, const uint8_t *src, const int len);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_MD5_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/mem.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,281 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * memory handling functions
+ */
+
+#ifndef AVUTIL_MEM_H
+#define AVUTIL_MEM_H
+
+#include <limits.h>
+#include <stdint.h>
+
+#include "attributes.h"
+#include "error.h"
+#include "avutil.h"
+
+/**
+ * @addtogroup lavu_mem
+ * @{
+ */
+
+
+#if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1110 || defined(__SUNPRO_C)
+    #define DECLARE_ALIGNED(n,t,v)      t __attribute__ ((aligned (n))) v
+    #define DECLARE_ASM_CONST(n,t,v)    const t __attribute__ ((aligned (n))) v
+#elif defined(__TI_COMPILER_VERSION__)
+    #define DECLARE_ALIGNED(n,t,v)                      \
+        AV_PRAGMA(DATA_ALIGN(v,n))                      \
+        t __attribute__((aligned(n))) v
+    #define DECLARE_ASM_CONST(n,t,v)                    \
+        AV_PRAGMA(DATA_ALIGN(v,n))                      \
+        static const t __attribute__((aligned(n))) v
+#elif defined(__GNUC__)
+    #define DECLARE_ALIGNED(n,t,v)      t __attribute__ ((aligned (n))) v
+    #define DECLARE_ASM_CONST(n,t,v)    static const t av_used __attribute__ ((aligned (n))) v
+#elif defined(_MSC_VER)
+    #define DECLARE_ALIGNED(n,t,v)      __declspec(align(n)) t v
+    #define DECLARE_ASM_CONST(n,t,v)    __declspec(align(n)) static const t v
+#else
+    #define DECLARE_ALIGNED(n,t,v)      t v
+    #define DECLARE_ASM_CONST(n,t,v)    static const t v
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+    #define av_malloc_attrib __attribute__((__malloc__))
+#else
+    #define av_malloc_attrib
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(4,3)
+    #define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__)))
+#else
+    #define av_alloc_size(...)
+#endif
+
+/**
+ * Allocate a block of size bytes with alignment suitable for all
+ * memory accesses (including vectors if available on the CPU).
+ * @param size Size in bytes for the memory block to be allocated.
+ * @return Pointer to the allocated block, NULL if the block cannot
+ * be allocated.
+ * @see av_mallocz()
+ */
+void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1);
+
+/**
+ * Helper function to allocate a block of size * nmemb bytes with
+ * using av_malloc()
+ * @param nmemb Number of elements
+ * @param size Size of the single element
+ * @return Pointer to the allocated block, NULL if the block cannot
+ * be allocated.
+ * @see av_malloc()
+ */
+av_alloc_size(1, 2) static inline void *av_malloc_array(size_t nmemb, size_t size)
+{
+    if (size <= 0 || nmemb >= INT_MAX / size)
+        return NULL;
+    return av_malloc(nmemb * size);
+}
+
+/**
+ * Allocate or reallocate a block of memory.
+ * If ptr is NULL and size > 0, allocate a new block. If
+ * size is zero, free the memory block pointed to by ptr.
+ * @param ptr Pointer to a memory block already allocated with
+ * av_malloc(z)() or av_realloc() or NULL.
+ * @param size Size in bytes for the memory block to be allocated or
+ * reallocated.
+ * @return Pointer to a newly reallocated block or NULL if the block
+ * cannot be reallocated or the function is used to free the memory block.
+ * @see av_fast_realloc()
+ */
+void *av_realloc(void *ptr, size_t size) av_alloc_size(2);
+
+/**
+ * Allocate or reallocate a block of memory.
+ * This function does the same thing as av_realloc, except:
+ * - It takes two arguments and checks the result of the multiplication for
+ *   integer overflow.
+ * - It frees the input block in case of failure, thus avoiding the memory
+ *   leak with the classic "buf = realloc(buf); if (!buf) return -1;".
+ */
+void *av_realloc_f(void *ptr, size_t nelem, size_t elsize);
+
+/**
+ * Free a memory block which has been allocated with av_malloc(z)() or
+ * av_realloc().
+ * @param ptr Pointer to the memory block which should be freed.
+ * @note ptr = NULL is explicitly allowed.
+ * @note It is recommended that you use av_freep() instead.
+ * @see av_freep()
+ */
+void av_free(void *ptr);
+
+/**
+ * Allocate a block of size bytes with alignment suitable for all
+ * memory accesses (including vectors if available on the CPU) and
+ * zero all the bytes of the block.
+ * @param size Size in bytes for the memory block to be allocated.
+ * @return Pointer to the allocated block, NULL if it cannot be allocated.
+ * @see av_malloc()
+ */
+void *av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1);
+
+/**
+ * Allocate a block of nmemb * size bytes with alignment suitable for all
+ * memory accesses (including vectors if available on the CPU) and
+ * zero all the bytes of the block.
+ * The allocation will fail if nmemb * size is greater than or equal
+ * to INT_MAX.
+ * @param nmemb
+ * @param size
+ * @return Pointer to the allocated block, NULL if it cannot be allocated.
+ */
+void *av_calloc(size_t nmemb, size_t size) av_malloc_attrib;
+
+/**
+ * Helper function to allocate a block of size * nmemb bytes with
+ * using av_mallocz()
+ * @param nmemb Number of elements
+ * @param size Size of the single element
+ * @return Pointer to the allocated block, NULL if the block cannot
+ * be allocated.
+ * @see av_mallocz()
+ * @see av_malloc_array()
+ */
+av_alloc_size(1, 2) static inline void *av_mallocz_array(size_t nmemb, size_t size)
+{
+    if (size <= 0 || nmemb >= INT_MAX / size)
+        return NULL;
+    return av_mallocz(nmemb * size);
+}
+
+/**
+ * Duplicate the string s.
+ * @param s string to be duplicated
+ * @return Pointer to a newly allocated string containing a
+ * copy of s or NULL if the string cannot be allocated.
+ */
+char *av_strdup(const char *s) av_malloc_attrib;
+
+/**
+ * Duplicate the buffer p.
+ * @param p buffer to be duplicated
+ * @return Pointer to a newly allocated buffer containing a
+ * copy of p or NULL if the buffer cannot be allocated.
+ */
+void *av_memdup(const void *p, size_t size);
+
+/**
+ * Free a memory block which has been allocated with av_malloc(z)() or
+ * av_realloc() and set the pointer pointing to it to NULL.
+ * @param ptr Pointer to the pointer to the memory block which should
+ * be freed.
+ * @see av_free()
+ */
+void av_freep(void *ptr);
+
+/**
+ * Add an element to a dynamic array.
+ *
+ * The array to grow is supposed to be an array of pointers to
+ * structures, and the element to add must be a pointer to an already
+ * allocated structure.
+ *
+ * The array is reallocated when its size reaches powers of 2.
+ * Therefore, the amortized cost of adding an element is constant.
+ *
+ * In case of success, the pointer to the array is updated in order to
+ * point to the new grown array, and the number pointed to by nb_ptr
+ * is incremented.
+ * In case of failure, the array is freed, *tab_ptr is set to NULL and
+ * *nb_ptr is set to 0.
+ *
+ * @param tab_ptr pointer to the array to grow
+ * @param nb_ptr  pointer to the number of elements in the array
+ * @param elem    element to add
+ * @see av_dynarray2_add()
+ */
+void av_dynarray_add(void *tab_ptr, int *nb_ptr, void *elem);
+
+/**
+ * Add an element of size elem_size to a dynamic array.
+ *
+ * The array is reallocated when its number of elements reaches powers of 2.
+ * Therefore, the amortized cost of adding an element is constant.
+ *
+ * In case of success, the pointer to the array is updated in order to
+ * point to the new grown array, and the number pointed to by nb_ptr
+ * is incremented.
+ * In case of failure, the array is freed, *tab_ptr is set to NULL and
+ * *nb_ptr is set to 0.
+ *
+ * @param tab_ptr   pointer to the array to grow
+ * @param nb_ptr    pointer to the number of elements in the array
+ * @param elem_size size in bytes of the elements in the array
+ * @param elem_data pointer to the data of the element to add. If NULL, the space of
+ *                  the new added element is not filled.
+ * @return          pointer to the data of the element to copy in the new allocated space.
+ *                  If NULL, the new allocated space is left uninitialized."
+ * @see av_dynarray_add()
+ */
+void *av_dynarray2_add(void **tab_ptr, int *nb_ptr, size_t elem_size,
+                       const uint8_t *elem_data);
+
+/**
+ * Multiply two size_t values checking for overflow.
+ * @return  0 if success, AVERROR(EINVAL) if overflow.
+ */
+static inline int av_size_mult(size_t a, size_t b, size_t *r)
+{
+    size_t t = a * b;
+    /* Hack inspired from glibc: only try the division if nelem and elsize
+     * are both greater than sqrt(SIZE_MAX). */
+    if ((a | b) >= ((size_t)1 << (sizeof(size_t) * 4)) && a && t / a != b)
+        return AVERROR(EINVAL);
+    *r = t;
+    return 0;
+}
+
+/**
+ * Set the maximum size that may me allocated in one block.
+ */
+void av_max_alloc(size_t max);
+
+/**
+ * @brief deliberately overlapping memcpy implementation
+ * @param dst destination buffer
+ * @param back how many bytes back we start (the initial size of the overlapping window), must be > 0
+ * @param cnt number of bytes to copy, must be >= 0
+ *
+ * cnt > back is valid, this will copy the bytes we just copied,
+ * thus creating a repeating pattern with a period length of back.
+ */
+void av_memcpy_backptr(uint8_t *dst, int back, int cnt);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_MEM_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/murmur3.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2013 Reimar Döffinger <Reimar.Doeffinger@gmx.de>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_MURMUR3_H
+#define AVUTIL_MURMUR3_H
+
+#include <stdint.h>
+
+struct AVMurMur3 *av_murmur3_alloc(void);
+void av_murmur3_init_seeded(struct AVMurMur3 *c, uint64_t seed);
+void av_murmur3_init(struct AVMurMur3 *c);
+void av_murmur3_update(struct AVMurMur3 *c, const uint8_t *src, int len);
+void av_murmur3_final(struct AVMurMur3 *c, uint8_t dst[16]);
+
+#endif /* AVUTIL_MURMUR3_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/old_pix_fmts.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,171 @@
+/*
+ * copyright (c) 2006-2012 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_OLD_PIX_FMTS_H
+#define AVUTIL_OLD_PIX_FMTS_H
+
+/*
+ * This header exists to prevent new pixel formats from being accidentally added
+ * to the deprecated list.
+ * Do not include it directly. It will be removed on next major bump
+ *
+ * Do not add new items to this list. Use the AVPixelFormat enum instead.
+ */
+    PIX_FMT_NONE = AV_PIX_FMT_NONE,
+    PIX_FMT_YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
+    PIX_FMT_YUYV422,   ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
+    PIX_FMT_RGB24,     ///< packed RGB 8:8:8, 24bpp, RGBRGB...
+    PIX_FMT_BGR24,     ///< packed RGB 8:8:8, 24bpp, BGRBGR...
+    PIX_FMT_YUV422P,   ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+    PIX_FMT_YUV444P,   ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
+    PIX_FMT_YUV410P,   ///< planar YUV 4:1:0,  9bpp, (1 Cr & Cb sample per 4x4 Y samples)
+    PIX_FMT_YUV411P,   ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
+    PIX_FMT_GRAY8,     ///<        Y        ,  8bpp
+    PIX_FMT_MONOWHITE, ///<        Y        ,  1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb
+    PIX_FMT_MONOBLACK, ///<        Y        ,  1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb
+    PIX_FMT_PAL8,      ///< 8 bit with PIX_FMT_RGB32 palette
+    PIX_FMT_YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV420P and setting color_range
+    PIX_FMT_YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV422P and setting color_range
+    PIX_FMT_YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV444P and setting color_range
+    PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing
+    PIX_FMT_XVMC_MPEG2_IDCT,
+    PIX_FMT_UYVY422,   ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
+    PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
+    PIX_FMT_BGR8,      ///< packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb)
+    PIX_FMT_BGR4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb)
+    PIX_FMT_RGB8,      ///< packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb)
+    PIX_FMT_RGB4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb)
+    PIX_FMT_NV12,      ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
+    PIX_FMT_NV21,      ///< as above, but U and V bytes are swapped
+
+    PIX_FMT_ARGB,      ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
+    PIX_FMT_RGBA,      ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
+    PIX_FMT_ABGR,      ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
+    PIX_FMT_BGRA,      ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
+
+    PIX_FMT_GRAY16BE,  ///<        Y        , 16bpp, big-endian
+    PIX_FMT_GRAY16LE,  ///<        Y        , 16bpp, little-endian
+    PIX_FMT_YUV440P,   ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
+    PIX_FMT_YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of PIX_FMT_YUV440P and setting color_range
+    PIX_FMT_YUVA420P,  ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
+    PIX_FMT_VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_RGB48BE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
+    PIX_FMT_RGB48LE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
+
+    PIX_FMT_RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
+    PIX_FMT_RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
+    PIX_FMT_RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0
+    PIX_FMT_RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0
+
+    PIX_FMT_BGR565BE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), big-endian
+    PIX_FMT_BGR565LE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), little-endian
+    PIX_FMT_BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1
+    PIX_FMT_BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1
+
+    PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
+    PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
+    PIX_FMT_VAAPI_VLD,  ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+
+    PIX_FMT_YUV420P16LE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P16BE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV422P16LE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV422P16BE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_VDPAU_MPEG4,  ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
+
+    PIX_FMT_RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0
+    PIX_FMT_RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0
+    PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
+    PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
+    PIX_FMT_GRAY8A,    ///< 8bit gray, 8bit alpha
+    PIX_FMT_BGR48BE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian
+    PIX_FMT_BGR48LE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian
+
+    //the following 10 formats have the disadvantage of needing 1 format for each bit depth, thus
+    //If you want to support multiple bit depths, then using PIX_FMT_YUV420P16* with the bpp stored separately
+    //is better
+    PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_VDA_VLD,    ///< hardware decoding through VDA
+
+#ifdef AV_PIX_FMT_ABI_GIT_MASTER
+    PIX_FMT_RGBA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+#endif
+    PIX_FMT_GBRP,      ///< planar GBR 4:4:4 24bpp
+    PIX_FMT_GBRP9BE,   ///< planar GBR 4:4:4 27bpp, big endian
+    PIX_FMT_GBRP9LE,   ///< planar GBR 4:4:4 27bpp, little endian
+    PIX_FMT_GBRP10BE,  ///< planar GBR 4:4:4 30bpp, big endian
+    PIX_FMT_GBRP10LE,  ///< planar GBR 4:4:4 30bpp, little endian
+    PIX_FMT_GBRP16BE,  ///< planar GBR 4:4:4 48bpp, big endian
+    PIX_FMT_GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little endian
+
+#ifndef AV_PIX_FMT_ABI_GIT_MASTER
+    PIX_FMT_RGBA64BE=0x123,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+#endif
+    PIX_FMT_0RGB=0x123+4,      ///< packed RGB 8:8:8, 32bpp, 0RGB0RGB...
+    PIX_FMT_RGB0,      ///< packed RGB 8:8:8, 32bpp, RGB0RGB0...
+    PIX_FMT_0BGR,      ///< packed BGR 8:8:8, 32bpp, 0BGR0BGR...
+    PIX_FMT_BGR0,      ///< packed BGR 8:8:8, 32bpp, BGR0BGR0...
+    PIX_FMT_YUVA444P,  ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
+    PIX_FMT_YUVA422P,  ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
+
+    PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_GBRP12BE,    ///< planar GBR 4:4:4 36bpp, big endian
+    PIX_FMT_GBRP12LE,    ///< planar GBR 4:4:4 36bpp, little endian
+    PIX_FMT_GBRP14BE,    ///< planar GBR 4:4:4 42bpp, big endian
+    PIX_FMT_GBRP14LE,    ///< planar GBR 4:4:4 42bpp, little endian
+
+    PIX_FMT_NB,        ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
+#endif /* AVUTIL_OLD_PIX_FMTS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/opt.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,754 @@
+/*
+ * AVOptions
+ * copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_OPT_H
+#define AVUTIL_OPT_H
+
+/**
+ * @file
+ * AVOptions
+ */
+
+#include "rational.h"
+#include "avutil.h"
+#include "dict.h"
+#include "log.h"
+#include "pixfmt.h"
+#include "samplefmt.h"
+
+/**
+ * @defgroup avoptions AVOptions
+ * @ingroup lavu_data
+ * @{
+ * AVOptions provide a generic system to declare options on arbitrary structs
+ * ("objects"). An option can have a help text, a type and a range of possible
+ * values. Options may then be enumerated, read and written to.
+ *
+ * @section avoptions_implement Implementing AVOptions
+ * This section describes how to add AVOptions capabilities to a struct.
+ *
+ * All AVOptions-related information is stored in an AVClass. Therefore
+ * the first member of the struct should be a pointer to an AVClass describing it.
+ * The option field of the AVClass must be set to a NULL-terminated static array
+ * of AVOptions. Each AVOption must have a non-empty name, a type, a default
+ * value and for number-type AVOptions also a range of allowed values. It must
+ * also declare an offset in bytes from the start of the struct, where the field
+ * associated with this AVOption is located. Other fields in the AVOption struct
+ * should also be set when applicable, but are not required.
+ *
+ * The following example illustrates an AVOptions-enabled struct:
+ * @code
+ * typedef struct test_struct {
+ *     AVClass *class;
+ *     int      int_opt;
+ *     char    *str_opt;
+ *     uint8_t *bin_opt;
+ *     int      bin_len;
+ * } test_struct;
+ *
+ * static const AVOption options[] = {
+ *   { "test_int", "This is a test option of int type.", offsetof(test_struct, int_opt),
+ *     AV_OPT_TYPE_INT, { .i64 = -1 }, INT_MIN, INT_MAX },
+ *   { "test_str", "This is a test option of string type.", offsetof(test_struct, str_opt),
+ *     AV_OPT_TYPE_STRING },
+ *   { "test_bin", "This is a test option of binary type.", offsetof(test_struct, bin_opt),
+ *     AV_OPT_TYPE_BINARY },
+ *   { NULL },
+ * };
+ *
+ * static const AVClass test_class = {
+ *     .class_name = "test class",
+ *     .item_name  = av_default_item_name,
+ *     .option     = options,
+ *     .version    = LIBAVUTIL_VERSION_INT,
+ * };
+ * @endcode
+ *
+ * Next, when allocating your struct, you must ensure that the AVClass pointer
+ * is set to the correct value. Then, av_opt_set_defaults() can be called to
+ * initialize defaults. After that the struct is ready to be used with the
+ * AVOptions API.
+ *
+ * When cleaning up, you may use the av_opt_free() function to automatically
+ * free all the allocated string and binary options.
+ *
+ * Continuing with the above example:
+ *
+ * @code
+ * test_struct *alloc_test_struct(void)
+ * {
+ *     test_struct *ret = av_malloc(sizeof(*ret));
+ *     ret->class = &test_class;
+ *     av_opt_set_defaults(ret);
+ *     return ret;
+ * }
+ * void free_test_struct(test_struct **foo)
+ * {
+ *     av_opt_free(*foo);
+ *     av_freep(foo);
+ * }
+ * @endcode
+ *
+ * @subsection avoptions_implement_nesting Nesting
+ *      It may happen that an AVOptions-enabled struct contains another
+ *      AVOptions-enabled struct as a member (e.g. AVCodecContext in
+ *      libavcodec exports generic options, while its priv_data field exports
+ *      codec-specific options). In such a case, it is possible to set up the
+ *      parent struct to export a child's options. To do that, simply
+ *      implement AVClass.child_next() and AVClass.child_class_next() in the
+ *      parent struct's AVClass.
+ *      Assuming that the test_struct from above now also contains a
+ *      child_struct field:
+ *
+ *      @code
+ *      typedef struct child_struct {
+ *          AVClass *class;
+ *          int flags_opt;
+ *      } child_struct;
+ *      static const AVOption child_opts[] = {
+ *          { "test_flags", "This is a test option of flags type.",
+ *            offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX },
+ *          { NULL },
+ *      };
+ *      static const AVClass child_class = {
+ *          .class_name = "child class",
+ *          .item_name  = av_default_item_name,
+ *          .option     = child_opts,
+ *          .version    = LIBAVUTIL_VERSION_INT,
+ *      };
+ *
+ *      void *child_next(void *obj, void *prev)
+ *      {
+ *          test_struct *t = obj;
+ *          if (!prev && t->child_struct)
+ *              return t->child_struct;
+ *          return NULL
+ *      }
+ *      const AVClass child_class_next(const AVClass *prev)
+ *      {
+ *          return prev ? NULL : &child_class;
+ *      }
+ *      @endcode
+ *      Putting child_next() and child_class_next() as defined above into
+ *      test_class will now make child_struct's options accessible through
+ *      test_struct (again, proper setup as described above needs to be done on
+ *      child_struct right after it is created).
+ *
+ *      From the above example it might not be clear why both child_next()
+ *      and child_class_next() are needed. The distinction is that child_next()
+ *      iterates over actually existing objects, while child_class_next()
+ *      iterates over all possible child classes. E.g. if an AVCodecContext
+ *      was initialized to use a codec which has private options, then its
+ *      child_next() will return AVCodecContext.priv_data and finish
+ *      iterating. OTOH child_class_next() on AVCodecContext.av_class will
+ *      iterate over all available codecs with private options.
+ *
+ * @subsection avoptions_implement_named_constants Named constants
+ *      It is possible to create named constants for options. Simply set the unit
+ *      field of the option the constants should apply to to a string and
+ *      create the constants themselves as options of type AV_OPT_TYPE_CONST
+ *      with their unit field set to the same string.
+ *      Their default_val field should contain the value of the named
+ *      constant.
+ *      For example, to add some named constants for the test_flags option
+ *      above, put the following into the child_opts array:
+ *      @code
+ *      { "test_flags", "This is a test option of flags type.",
+ *        offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX, "test_unit" },
+ *      { "flag1", "This is a flag with value 16", 0, AV_OPT_TYPE_CONST, { .i64 = 16 }, 0, 0, "test_unit" },
+ *      @endcode
+ *
+ * @section avoptions_use Using AVOptions
+ * This section deals with accessing options in an AVOptions-enabled struct.
+ * Such structs in FFmpeg are e.g. AVCodecContext in libavcodec or
+ * AVFormatContext in libavformat.
+ *
+ * @subsection avoptions_use_examine Examining AVOptions
+ * The basic functions for examining options are av_opt_next(), which iterates
+ * over all options defined for one object, and av_opt_find(), which searches
+ * for an option with the given name.
+ *
+ * The situation is more complicated with nesting. An AVOptions-enabled struct
+ * may have AVOptions-enabled children. Passing the AV_OPT_SEARCH_CHILDREN flag
+ * to av_opt_find() will make the function search children recursively.
+ *
+ * For enumerating there are basically two cases. The first is when you want to
+ * get all options that may potentially exist on the struct and its children
+ * (e.g.  when constructing documentation). In that case you should call
+ * av_opt_child_class_next() recursively on the parent struct's AVClass.  The
+ * second case is when you have an already initialized struct with all its
+ * children and you want to get all options that can be actually written or read
+ * from it. In that case you should call av_opt_child_next() recursively (and
+ * av_opt_next() on each result).
+ *
+ * @subsection avoptions_use_get_set Reading and writing AVOptions
+ * When setting options, you often have a string read directly from the
+ * user. In such a case, simply passing it to av_opt_set() is enough. For
+ * non-string type options, av_opt_set() will parse the string according to the
+ * option type.
+ *
+ * Similarly av_opt_get() will read any option type and convert it to a string
+ * which will be returned. Do not forget that the string is allocated, so you
+ * have to free it with av_free().
+ *
+ * In some cases it may be more convenient to put all options into an
+ * AVDictionary and call av_opt_set_dict() on it. A specific case of this
+ * are the format/codec open functions in lavf/lavc which take a dictionary
+ * filled with option as a parameter. This allows to set some options
+ * that cannot be set otherwise, since e.g. the input file format is not known
+ * before the file is actually opened.
+ */
+
+enum AVOptionType{
+    AV_OPT_TYPE_FLAGS,
+    AV_OPT_TYPE_INT,
+    AV_OPT_TYPE_INT64,
+    AV_OPT_TYPE_DOUBLE,
+    AV_OPT_TYPE_FLOAT,
+    AV_OPT_TYPE_STRING,
+    AV_OPT_TYPE_RATIONAL,
+    AV_OPT_TYPE_BINARY,  ///< offset must point to a pointer immediately followed by an int for the length
+    AV_OPT_TYPE_CONST = 128,
+    AV_OPT_TYPE_IMAGE_SIZE = MKBETAG('S','I','Z','E'), ///< offset must point to two consecutive integers
+    AV_OPT_TYPE_PIXEL_FMT  = MKBETAG('P','F','M','T'),
+    AV_OPT_TYPE_SAMPLE_FMT = MKBETAG('S','F','M','T'),
+    AV_OPT_TYPE_VIDEO_RATE = MKBETAG('V','R','A','T'), ///< offset must point to AVRational
+    AV_OPT_TYPE_DURATION   = MKBETAG('D','U','R',' '),
+    AV_OPT_TYPE_COLOR      = MKBETAG('C','O','L','R'),
+#if FF_API_OLD_AVOPTIONS
+    FF_OPT_TYPE_FLAGS = 0,
+    FF_OPT_TYPE_INT,
+    FF_OPT_TYPE_INT64,
+    FF_OPT_TYPE_DOUBLE,
+    FF_OPT_TYPE_FLOAT,
+    FF_OPT_TYPE_STRING,
+    FF_OPT_TYPE_RATIONAL,
+    FF_OPT_TYPE_BINARY,  ///< offset must point to a pointer immediately followed by an int for the length
+    FF_OPT_TYPE_CONST=128,
+#endif
+};
+
+/**
+ * AVOption
+ */
+typedef struct AVOption {
+    const char *name;
+
+    /**
+     * short English help text
+     * @todo What about other languages?
+     */
+    const char *help;
+
+    /**
+     * The offset relative to the context structure where the option
+     * value is stored. It should be 0 for named constants.
+     */
+    int offset;
+    enum AVOptionType type;
+
+    /**
+     * the default value for scalar options
+     */
+    union {
+        int64_t i64;
+        double dbl;
+        const char *str;
+        /* TODO those are unused now */
+        AVRational q;
+    } default_val;
+    double min;                 ///< minimum valid value for the option
+    double max;                 ///< maximum valid value for the option
+
+    int flags;
+#define AV_OPT_FLAG_ENCODING_PARAM  1   ///< a generic parameter which can be set by the user for muxing or encoding
+#define AV_OPT_FLAG_DECODING_PARAM  2   ///< a generic parameter which can be set by the user for demuxing or decoding
+#define AV_OPT_FLAG_METADATA        4   ///< some data extracted or inserted into the file like title, comment, ...
+#define AV_OPT_FLAG_AUDIO_PARAM     8
+#define AV_OPT_FLAG_VIDEO_PARAM     16
+#define AV_OPT_FLAG_SUBTITLE_PARAM  32
+#define AV_OPT_FLAG_FILTERING_PARAM (1<<16) ///< a generic parameter which can be set by the user for filtering
+//FIXME think about enc-audio, ... style flags
+
+    /**
+     * The logical unit to which the option belongs. Non-constant
+     * options and corresponding named constants share the same
+     * unit. May be NULL.
+     */
+    const char *unit;
+} AVOption;
+
+/**
+ * A single allowed range of values, or a single allowed value.
+ */
+typedef struct AVOptionRange {
+    const char *str;
+    double value_min, value_max;             ///< For string ranges this represents the min/max length, for dimensions this represents the min/max pixel count
+    double component_min, component_max;     ///< For string this represents the unicode range for chars, 0-127 limits to ASCII
+    int is_range;                            ///< if set to 1 the struct encodes a range, if set to 0 a single value
+} AVOptionRange;
+
+/**
+ * List of AVOptionRange structs
+ */
+typedef struct AVOptionRanges {
+    AVOptionRange **range;
+    int nb_ranges;
+} AVOptionRanges;
+
+
+#if FF_API_FIND_OPT
+/**
+ * Look for an option in obj. Look only for the options which
+ * have the flags set as specified in mask and flags (that is,
+ * for which it is the case that opt->flags & mask == flags).
+ *
+ * @param[in] obj a pointer to a struct whose first element is a
+ * pointer to an AVClass
+ * @param[in] name the name of the option to look for
+ * @param[in] unit the unit of the option to look for, or any if NULL
+ * @return a pointer to the option found, or NULL if no option
+ * has been found
+ *
+ * @deprecated use av_opt_find.
+ */
+attribute_deprecated
+const AVOption *av_find_opt(void *obj, const char *name, const char *unit, int mask, int flags);
+#endif
+
+#if FF_API_OLD_AVOPTIONS
+/**
+ * Set the field of obj with the given name to value.
+ *
+ * @param[in] obj A struct whose first element is a pointer to an
+ * AVClass.
+ * @param[in] name the name of the field to set
+ * @param[in] val The value to set. If the field is not of a string
+ * type, then the given string is parsed.
+ * SI postfixes and some named scalars are supported.
+ * If the field is of a numeric type, it has to be a numeric or named
+ * scalar. Behavior with more than one scalar and +- infix operators
+ * is undefined.
+ * If the field is of a flags type, it has to be a sequence of numeric
+ * scalars or named flags separated by '+' or '-'. Prefixing a flag
+ * with '+' causes it to be set without affecting the other flags;
+ * similarly, '-' unsets a flag.
+ * @param[out] o_out if non-NULL put here a pointer to the AVOption
+ * found
+ * @param alloc this parameter is currently ignored
+ * @return 0 if the value has been set, or an AVERROR code in case of
+ * error:
+ * AVERROR_OPTION_NOT_FOUND if no matching option exists
+ * AVERROR(ERANGE) if the value is out of range
+ * AVERROR(EINVAL) if the value is not valid
+ * @deprecated use av_opt_set()
+ */
+attribute_deprecated
+int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out);
+
+attribute_deprecated const AVOption *av_set_double(void *obj, const char *name, double n);
+attribute_deprecated const AVOption *av_set_q(void *obj, const char *name, AVRational n);
+attribute_deprecated const AVOption *av_set_int(void *obj, const char *name, int64_t n);
+
+double av_get_double(void *obj, const char *name, const AVOption **o_out);
+AVRational av_get_q(void *obj, const char *name, const AVOption **o_out);
+int64_t av_get_int(void *obj, const char *name, const AVOption **o_out);
+attribute_deprecated const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len);
+attribute_deprecated const AVOption *av_next_option(void *obj, const AVOption *last);
+#endif
+
+/**
+ * Show the obj options.
+ *
+ * @param req_flags requested flags for the options to show. Show only the
+ * options for which it is opt->flags & req_flags.
+ * @param rej_flags rejected flags for the options to show. Show only the
+ * options for which it is !(opt->flags & req_flags).
+ * @param av_log_obj log context to use for showing the options
+ */
+int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags);
+
+/**
+ * Set the values of all AVOption fields to their default values.
+ *
+ * @param s an AVOption-enabled struct (its first member must be a pointer to AVClass)
+ */
+void av_opt_set_defaults(void *s);
+
+#if FF_API_OLD_AVOPTIONS
+attribute_deprecated
+void av_opt_set_defaults2(void *s, int mask, int flags);
+#endif
+
+/**
+ * Parse the key/value pairs list in opts. For each key/value pair
+ * found, stores the value in the field in ctx that is named like the
+ * key. ctx must be an AVClass context, storing is done using
+ * AVOptions.
+ *
+ * @param opts options string to parse, may be NULL
+ * @param key_val_sep a 0-terminated list of characters used to
+ * separate key from value
+ * @param pairs_sep a 0-terminated list of characters used to separate
+ * two pairs from each other
+ * @return the number of successfully set key/value pairs, or a negative
+ * value corresponding to an AVERROR code in case of error:
+ * AVERROR(EINVAL) if opts cannot be parsed,
+ * the error code issued by av_set_string3() if a key/value pair
+ * cannot be set
+ */
+int av_set_options_string(void *ctx, const char *opts,
+                          const char *key_val_sep, const char *pairs_sep);
+
+/**
+ * Parse the key-value pairs list in opts. For each key=value pair found,
+ * set the value of the corresponding option in ctx.
+ *
+ * @param ctx          the AVClass object to set options on
+ * @param opts         the options string, key-value pairs separated by a
+ *                     delimiter
+ * @param shorthand    a NULL-terminated array of options names for shorthand
+ *                     notation: if the first field in opts has no key part,
+ *                     the key is taken from the first element of shorthand;
+ *                     then again for the second, etc., until either opts is
+ *                     finished, shorthand is finished or a named option is
+ *                     found; after that, all options must be named
+ * @param key_val_sep  a 0-terminated list of characters used to separate
+ *                     key from value, for example '='
+ * @param pairs_sep    a 0-terminated list of characters used to separate
+ *                     two pairs from each other, for example ':' or ','
+ * @return  the number of successfully set key=value pairs, or a negative
+ *          value corresponding to an AVERROR code in case of error:
+ *          AVERROR(EINVAL) if opts cannot be parsed,
+ *          the error code issued by av_set_string3() if a key/value pair
+ *          cannot be set
+ *
+ * Options names must use only the following characters: a-z A-Z 0-9 - . / _
+ * Separators must use characters distinct from option names and from each
+ * other.
+ */
+int av_opt_set_from_string(void *ctx, const char *opts,
+                           const char *const *shorthand,
+                           const char *key_val_sep, const char *pairs_sep);
+/**
+ * Free all string and binary options in obj.
+ */
+void av_opt_free(void *obj);
+
+/**
+ * Check whether a particular flag is set in a flags field.
+ *
+ * @param field_name the name of the flag field option
+ * @param flag_name the name of the flag to check
+ * @return non-zero if the flag is set, zero if the flag isn't set,
+ *         isn't of the right type, or the flags field doesn't exist.
+ */
+int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name);
+
+/**
+ * Set all the options from a given dictionary on an object.
+ *
+ * @param obj a struct whose first element is a pointer to AVClass
+ * @param options options to process. This dictionary will be freed and replaced
+ *                by a new one containing all options not found in obj.
+ *                Of course this new dictionary needs to be freed by caller
+ *                with av_dict_free().
+ *
+ * @return 0 on success, a negative AVERROR if some option was found in obj,
+ *         but could not be set.
+ *
+ * @see av_dict_copy()
+ */
+int av_opt_set_dict(void *obj, struct AVDictionary **options);
+
+/**
+ * Extract a key-value pair from the beginning of a string.
+ *
+ * @param ropts        pointer to the options string, will be updated to
+ *                     point to the rest of the string (one of the pairs_sep
+ *                     or the final NUL)
+ * @param key_val_sep  a 0-terminated list of characters used to separate
+ *                     key from value, for example '='
+ * @param pairs_sep    a 0-terminated list of characters used to separate
+ *                     two pairs from each other, for example ':' or ','
+ * @param flags        flags; see the AV_OPT_FLAG_* values below
+ * @param rkey         parsed key; must be freed using av_free()
+ * @param rval         parsed value; must be freed using av_free()
+ *
+ * @return  >=0 for success, or a negative value corresponding to an
+ *          AVERROR code in case of error; in particular:
+ *          AVERROR(EINVAL) if no key is present
+ *
+ */
+int av_opt_get_key_value(const char **ropts,
+                         const char *key_val_sep, const char *pairs_sep,
+                         unsigned flags,
+                         char **rkey, char **rval);
+
+enum {
+
+    /**
+     * Accept to parse a value without a key; the key will then be returned
+     * as NULL.
+     */
+    AV_OPT_FLAG_IMPLICIT_KEY = 1,
+};
+
+/**
+ * @defgroup opt_eval_funcs Evaluating option strings
+ * @{
+ * This group of functions can be used to evaluate option strings
+ * and get numbers out of them. They do the same thing as av_opt_set(),
+ * except the result is written into the caller-supplied pointer.
+ *
+ * @param obj a struct whose first element is a pointer to AVClass.
+ * @param o an option for which the string is to be evaluated.
+ * @param val string to be evaluated.
+ * @param *_out value of the string will be written here.
+ *
+ * @return 0 on success, a negative number on failure.
+ */
+int av_opt_eval_flags (void *obj, const AVOption *o, const char *val, int        *flags_out);
+int av_opt_eval_int   (void *obj, const AVOption *o, const char *val, int        *int_out);
+int av_opt_eval_int64 (void *obj, const AVOption *o, const char *val, int64_t    *int64_out);
+int av_opt_eval_float (void *obj, const AVOption *o, const char *val, float      *float_out);
+int av_opt_eval_double(void *obj, const AVOption *o, const char *val, double     *double_out);
+int av_opt_eval_q     (void *obj, const AVOption *o, const char *val, AVRational *q_out);
+/**
+ * @}
+ */
+
+#define AV_OPT_SEARCH_CHILDREN   0x0001 /**< Search in possible children of the
+                                             given object first. */
+/**
+ *  The obj passed to av_opt_find() is fake -- only a double pointer to AVClass
+ *  instead of a required pointer to a struct containing AVClass. This is
+ *  useful for searching for options without needing to allocate the corresponding
+ *  object.
+ */
+#define AV_OPT_SEARCH_FAKE_OBJ   0x0002
+
+/**
+ * Look for an option in an object. Consider only options which
+ * have all the specified flags set.
+ *
+ * @param[in] obj A pointer to a struct whose first element is a
+ *                pointer to an AVClass.
+ *                Alternatively a double pointer to an AVClass, if
+ *                AV_OPT_SEARCH_FAKE_OBJ search flag is set.
+ * @param[in] name The name of the option to look for.
+ * @param[in] unit When searching for named constants, name of the unit
+ *                 it belongs to.
+ * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG).
+ * @param search_flags A combination of AV_OPT_SEARCH_*.
+ *
+ * @return A pointer to the option found, or NULL if no option
+ *         was found.
+ *
+ * @note Options found with AV_OPT_SEARCH_CHILDREN flag may not be settable
+ * directly with av_set_string3(). Use special calls which take an options
+ * AVDictionary (e.g. avformat_open_input()) to set options found with this
+ * flag.
+ */
+const AVOption *av_opt_find(void *obj, const char *name, const char *unit,
+                            int opt_flags, int search_flags);
+
+/**
+ * Look for an option in an object. Consider only options which
+ * have all the specified flags set.
+ *
+ * @param[in] obj A pointer to a struct whose first element is a
+ *                pointer to an AVClass.
+ *                Alternatively a double pointer to an AVClass, if
+ *                AV_OPT_SEARCH_FAKE_OBJ search flag is set.
+ * @param[in] name The name of the option to look for.
+ * @param[in] unit When searching for named constants, name of the unit
+ *                 it belongs to.
+ * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG).
+ * @param search_flags A combination of AV_OPT_SEARCH_*.
+ * @param[out] target_obj if non-NULL, an object to which the option belongs will be
+ * written here. It may be different from obj if AV_OPT_SEARCH_CHILDREN is present
+ * in search_flags. This parameter is ignored if search_flags contain
+ * AV_OPT_SEARCH_FAKE_OBJ.
+ *
+ * @return A pointer to the option found, or NULL if no option
+ *         was found.
+ */
+const AVOption *av_opt_find2(void *obj, const char *name, const char *unit,
+                             int opt_flags, int search_flags, void **target_obj);
+
+/**
+ * Iterate over all AVOptions belonging to obj.
+ *
+ * @param obj an AVOptions-enabled struct or a double pointer to an
+ *            AVClass describing it.
+ * @param prev result of the previous call to av_opt_next() on this object
+ *             or NULL
+ * @return next AVOption or NULL
+ */
+const AVOption *av_opt_next(void *obj, const AVOption *prev);
+
+/**
+ * Iterate over AVOptions-enabled children of obj.
+ *
+ * @param prev result of a previous call to this function or NULL
+ * @return next AVOptions-enabled child or NULL
+ */
+void *av_opt_child_next(void *obj, void *prev);
+
+/**
+ * Iterate over potential AVOptions-enabled children of parent.
+ *
+ * @param prev result of a previous call to this function or NULL
+ * @return AVClass corresponding to next potential child or NULL
+ */
+const AVClass *av_opt_child_class_next(const AVClass *parent, const AVClass *prev);
+
+/**
+ * @defgroup opt_set_funcs Option setting functions
+ * @{
+ * Those functions set the field of obj with the given name to value.
+ *
+ * @param[in] obj A struct whose first element is a pointer to an AVClass.
+ * @param[in] name the name of the field to set
+ * @param[in] val The value to set. In case of av_opt_set() if the field is not
+ * of a string type, then the given string is parsed.
+ * SI postfixes and some named scalars are supported.
+ * If the field is of a numeric type, it has to be a numeric or named
+ * scalar. Behavior with more than one scalar and +- infix operators
+ * is undefined.
+ * If the field is of a flags type, it has to be a sequence of numeric
+ * scalars or named flags separated by '+' or '-'. Prefixing a flag
+ * with '+' causes it to be set without affecting the other flags;
+ * similarly, '-' unsets a flag.
+ * @param search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN
+ * is passed here, then the option may be set on a child of obj.
+ *
+ * @return 0 if the value has been set, or an AVERROR code in case of
+ * error:
+ * AVERROR_OPTION_NOT_FOUND if no matching option exists
+ * AVERROR(ERANGE) if the value is out of range
+ * AVERROR(EINVAL) if the value is not valid
+ */
+int av_opt_set       (void *obj, const char *name, const char *val, int search_flags);
+int av_opt_set_int   (void *obj, const char *name, int64_t     val, int search_flags);
+int av_opt_set_double(void *obj, const char *name, double      val, int search_flags);
+int av_opt_set_q     (void *obj, const char *name, AVRational  val, int search_flags);
+int av_opt_set_bin   (void *obj, const char *name, const uint8_t *val, int size, int search_flags);
+int av_opt_set_image_size(void *obj, const char *name, int w, int h, int search_flags);
+int av_opt_set_pixel_fmt (void *obj, const char *name, enum AVPixelFormat fmt, int search_flags);
+int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags);
+int av_opt_set_video_rate(void *obj, const char *name, AVRational val, int search_flags);
+
+/**
+ * Set a binary option to an integer list.
+ *
+ * @param obj    AVClass object to set options on
+ * @param name   name of the binary option
+ * @param val    pointer to an integer list (must have the correct type with
+ *               regard to the contents of the list)
+ * @param term   list terminator (usually 0 or -1)
+ * @param flags  search flags
+ */
+#define av_opt_set_int_list(obj, name, val, term, flags) \
+    (av_int_list_length(val, term) > INT_MAX / sizeof(*(val)) ? \
+     AVERROR(EINVAL) : \
+     av_opt_set_bin(obj, name, (const uint8_t *)(val), \
+                    av_int_list_length(val, term) * sizeof(*(val)), flags))
+/**
+ * @}
+ */
+
+/**
+ * @defgroup opt_get_funcs Option getting functions
+ * @{
+ * Those functions get a value of the option with the given name from an object.
+ *
+ * @param[in] obj a struct whose first element is a pointer to an AVClass.
+ * @param[in] name name of the option to get.
+ * @param[in] search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN
+ * is passed here, then the option may be found in a child of obj.
+ * @param[out] out_val value of the option will be written here
+ * @return 0 on success, a negative error code otherwise
+ */
+/**
+ * @note the returned string will av_malloc()ed and must be av_free()ed by the caller
+ */
+int av_opt_get       (void *obj, const char *name, int search_flags, uint8_t   **out_val);
+int av_opt_get_int   (void *obj, const char *name, int search_flags, int64_t    *out_val);
+int av_opt_get_double(void *obj, const char *name, int search_flags, double     *out_val);
+int av_opt_get_q     (void *obj, const char *name, int search_flags, AVRational *out_val);
+int av_opt_get_image_size(void *obj, const char *name, int search_flags, int *w_out, int *h_out);
+int av_opt_get_pixel_fmt (void *obj, const char *name, int search_flags, enum AVPixelFormat *out_fmt);
+int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt);
+int av_opt_get_video_rate(void *obj, const char *name, int search_flags, AVRational *out_val);
+/**
+ * @}
+ */
+/**
+ * Gets a pointer to the requested field in a struct.
+ * This function allows accessing a struct even when its fields are moved or
+ * renamed since the application making the access has been compiled,
+ *
+ * @returns a pointer to the field, it can be cast to the correct type and read
+ *          or written to.
+ */
+void *av_opt_ptr(const AVClass *avclass, void *obj, const char *name);
+
+/**
+ * Free an AVOptionRanges struct and set it to NULL.
+ */
+void av_opt_freep_ranges(AVOptionRanges **ranges);
+
+/**
+ * Get a list of allowed ranges for the given option.
+ *
+ * The returned list may depend on other fields in obj like for example profile.
+ *
+ * @param flags is a bitmask of flags, undefined flags should not be set and should be ignored
+ *              AV_OPT_SEARCH_FAKE_OBJ indicates that the obj is a double pointer to a AVClass instead of a full instance
+ *
+ * The result must be freed with av_opt_freep_ranges.
+ *
+ * @return >= 0 on success, a negative errro code otherwise
+ */
+int av_opt_query_ranges(AVOptionRanges **, void *obj, const char *key, int flags);
+
+/**
+ * Get a default list of allowed ranges for the given option.
+ *
+ * This list is constructed without using the AVClass.query_ranges() callback
+ * and can be used as fallback from within the callback.
+ *
+ * @param flags is a bitmask of flags, undefined flags should not be set and should be ignored
+ *              AV_OPT_SEARCH_FAKE_OBJ indicates that the obj is a double pointer to a AVClass instead of a full instance
+ *
+ * The result must be freed with av_opt_free_ranges.
+ *
+ * @return >= 0 on success, a negative errro code otherwise
+ */
+int av_opt_query_ranges_default(AVOptionRanges **, void *obj, const char *key, int flags);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_OPT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/parseutils.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,174 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PARSEUTILS_H
+#define AVUTIL_PARSEUTILS_H
+
+#include <time.h>
+
+#include "rational.h"
+
+/**
+ * @file
+ * misc parsing utilities
+ */
+
+/**
+ * Parse str and store the parsed ratio in q.
+ *
+ * Note that a ratio with infinite (1/0) or negative value is
+ * considered valid, so you should check on the returned value if you
+ * want to exclude those values.
+ *
+ * The undefined value can be expressed using the "0:0" string.
+ *
+ * @param[in,out] q pointer to the AVRational which will contain the ratio
+ * @param[in] str the string to parse: it has to be a string in the format
+ * num:den, a float number or an expression
+ * @param[in] max the maximum allowed numerator and denominator
+ * @param[in] log_offset log level offset which is applied to the log
+ * level of log_ctx
+ * @param[in] log_ctx parent logging context
+ * @return >= 0 on success, a negative error code otherwise
+ */
+int av_parse_ratio(AVRational *q, const char *str, int max,
+                   int log_offset, void *log_ctx);
+
+#define av_parse_ratio_quiet(rate, str, max) \
+    av_parse_ratio(rate, str, max, AV_LOG_MAX_OFFSET, NULL)
+
+/**
+ * Parse str and put in width_ptr and height_ptr the detected values.
+ *
+ * @param[in,out] width_ptr pointer to the variable which will contain the detected
+ * width value
+ * @param[in,out] height_ptr pointer to the variable which will contain the detected
+ * height value
+ * @param[in] str the string to parse: it has to be a string in the format
+ * width x height or a valid video size abbreviation.
+ * @return >= 0 on success, a negative error code otherwise
+ */
+int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str);
+
+/**
+ * Parse str and store the detected values in *rate.
+ *
+ * @param[in,out] rate pointer to the AVRational which will contain the detected
+ * frame rate
+ * @param[in] str the string to parse: it has to be a string in the format
+ * rate_num / rate_den, a float number or a valid video rate abbreviation
+ * @return >= 0 on success, a negative error code otherwise
+ */
+int av_parse_video_rate(AVRational *rate, const char *str);
+
+/**
+ * Put the RGBA values that correspond to color_string in rgba_color.
+ *
+ * @param color_string a string specifying a color. It can be the name of
+ * a color (case insensitive match) or a [0x|#]RRGGBB[AA] sequence,
+ * possibly followed by "@" and a string representing the alpha
+ * component.
+ * The alpha component may be a string composed by "0x" followed by an
+ * hexadecimal number or a decimal number between 0.0 and 1.0, which
+ * represents the opacity value (0x00/0.0 means completely transparent,
+ * 0xff/1.0 completely opaque).
+ * If the alpha component is not specified then 0xff is assumed.
+ * The string "random" will result in a random color.
+ * @param slen length of the initial part of color_string containing the
+ * color. It can be set to -1 if color_string is a null terminated string
+ * containing nothing else than the color.
+ * @return >= 0 in case of success, a negative value in case of
+ * failure (for example if color_string cannot be parsed).
+ */
+int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen,
+                   void *log_ctx);
+
+/**
+ * Parse timestr and return in *time a corresponding number of
+ * microseconds.
+ *
+ * @param timeval puts here the number of microseconds corresponding
+ * to the string in timestr. If the string represents a duration, it
+ * is the number of microseconds contained in the time interval.  If
+ * the string is a date, is the number of microseconds since 1st of
+ * January, 1970 up to the time of the parsed date.  If timestr cannot
+ * be successfully parsed, set *time to INT64_MIN.
+
+ * @param timestr a string representing a date or a duration.
+ * - If a date the syntax is:
+ * @code
+ * [{YYYY-MM-DD|YYYYMMDD}[T|t| ]]{{HH:MM:SS[.m...]]]}|{HHMMSS[.m...]]]}}[Z]
+ * now
+ * @endcode
+ * If the value is "now" it takes the current time.
+ * Time is local time unless Z is appended, in which case it is
+ * interpreted as UTC.
+ * If the year-month-day part is not specified it takes the current
+ * year-month-day.
+ * - If a duration the syntax is:
+ * @code
+ * [-][HH:]MM:SS[.m...]
+ * [-]S+[.m...]
+ * @endcode
+ * @param duration flag which tells how to interpret timestr, if not
+ * zero timestr is interpreted as a duration, otherwise as a date
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_parse_time(int64_t *timeval, const char *timestr, int duration);
+
+/**
+ * Parse the input string p according to the format string fmt and
+ * store its results in the structure dt.
+ * This implementation supports only a subset of the formats supported
+ * by the standard strptime().
+ *
+ * In particular it actually supports the parameters:
+ * - %H: the hour as a decimal number, using a 24-hour clock, in the
+ * range '00' through '23'
+ * - %J: hours as a decimal number, in the range '0' through INT_MAX
+ * - %M: the minute as a decimal number, using a 24-hour clock, in the
+ * range '00' through '59'
+ * - %S: the second as a decimal number, using a 24-hour clock, in the
+ * range '00' through '59'
+ * - %Y: the year as a decimal number, using the Gregorian calendar
+ * - %m: the month as a decimal number, in the range '1' through '12'
+ * - %d: the day of the month as a decimal number, in the range '1'
+ * through '31'
+ * - %%: a literal '%'
+ *
+ * @return a pointer to the first character not processed in this
+ * function call, or NULL in case the function fails to match all of
+ * the fmt string and therefore an error occurred
+ */
+char *av_small_strptime(const char *p, const char *fmt, struct tm *dt);
+
+/**
+ * Attempt to find a specific tag in a URL.
+ *
+ * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
+ * Return 1 if found.
+ */
+int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info);
+
+/**
+ * Convert the decomposed UTC time in tm to a time_t value.
+ */
+time_t av_timegm(struct tm *tm);
+
+#endif /* AVUTIL_PARSEUTILS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/pixdesc.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,289 @@
+/*
+ * pixel format descriptor
+ * Copyright (c) 2009 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PIXDESC_H
+#define AVUTIL_PIXDESC_H
+
+#include <stdint.h>
+#include "pixfmt.h"
+
+typedef struct AVComponentDescriptor{
+    uint16_t plane        :2;            ///< which of the 4 planes contains the component
+
+    /**
+     * Number of elements between 2 horizontally consecutive pixels minus 1.
+     * Elements are bits for bitstream formats, bytes otherwise.
+     */
+    uint16_t step_minus1  :3;
+
+    /**
+     * Number of elements before the component of the first pixel plus 1.
+     * Elements are bits for bitstream formats, bytes otherwise.
+     */
+    uint16_t offset_plus1 :3;
+    uint16_t shift        :3;            ///< number of least significant bits that must be shifted away to get the value
+    uint16_t depth_minus1 :4;            ///< number of bits in the component minus 1
+}AVComponentDescriptor;
+
+/**
+ * Descriptor that unambiguously describes how the bits of a pixel are
+ * stored in the up to 4 data planes of an image. It also stores the
+ * subsampling factors and number of components.
+ *
+ * @note This is separate of the colorspace (RGB, YCbCr, YPbPr, JPEG-style YUV
+ *       and all the YUV variants) AVPixFmtDescriptor just stores how values
+ *       are stored not what these values represent.
+ */
+typedef struct AVPixFmtDescriptor{
+    const char *name;
+    uint8_t nb_components;      ///< The number of components each pixel has, (1-4)
+
+    /**
+     * Amount to shift the luma width right to find the chroma width.
+     * For YV12 this is 1 for example.
+     * chroma_width = -((-luma_width) >> log2_chroma_w)
+     * The note above is needed to ensure rounding up.
+     * This value only refers to the chroma components.
+     */
+    uint8_t log2_chroma_w;      ///< chroma_width = -((-luma_width )>>log2_chroma_w)
+
+    /**
+     * Amount to shift the luma height right to find the chroma height.
+     * For YV12 this is 1 for example.
+     * chroma_height= -((-luma_height) >> log2_chroma_h)
+     * The note above is needed to ensure rounding up.
+     * This value only refers to the chroma components.
+     */
+    uint8_t log2_chroma_h;
+    uint8_t flags;
+
+    /**
+     * Parameters that describe how pixels are packed.
+     * If the format has 2 or 4 components, then alpha is last.
+     * If the format has 1 or 2 components, then luma is 0.
+     * If the format has 3 or 4 components,
+     * if the RGB flag is set then 0 is red, 1 is green and 2 is blue;
+     * otherwise 0 is luma, 1 is chroma-U and 2 is chroma-V.
+     */
+    AVComponentDescriptor comp[4];
+}AVPixFmtDescriptor;
+
+/**
+ * Pixel format is big-endian.
+ */
+#define AV_PIX_FMT_FLAG_BE           (1 << 0)
+/**
+ * Pixel format has a palette in data[1], values are indexes in this palette.
+ */
+#define AV_PIX_FMT_FLAG_PAL          (1 << 1)
+/**
+ * All values of a component are bit-wise packed end to end.
+ */
+#define AV_PIX_FMT_FLAG_BITSTREAM    (1 << 2)
+/**
+ * Pixel format is an HW accelerated format.
+ */
+#define AV_PIX_FMT_FLAG_HWACCEL      (1 << 3)
+/**
+ * At least one pixel component is not in the first data plane.
+ */
+#define AV_PIX_FMT_FLAG_PLANAR       (1 << 4)
+/**
+ * The pixel format contains RGB-like data (as opposed to YUV/grayscale).
+ */
+#define AV_PIX_FMT_FLAG_RGB          (1 << 5)
+/**
+ * The pixel format is "pseudo-paletted". This means that FFmpeg treats it as
+ * paletted internally, but the palette is generated by the decoder and is not
+ * stored in the file.
+ */
+#define AV_PIX_FMT_FLAG_PSEUDOPAL    (1 << 6)
+/**
+ * The pixel format has an alpha channel.
+ */
+#define AV_PIX_FMT_FLAG_ALPHA        (1 << 7)
+
+#if FF_API_PIX_FMT
+/**
+ * @deprecate use the AV_PIX_FMT_FLAG_* flags
+ */
+#define PIX_FMT_BE        AV_PIX_FMT_FLAG_BE
+#define PIX_FMT_PAL       AV_PIX_FMT_FLAG_PAL
+#define PIX_FMT_BITSTREAM AV_PIX_FMT_FLAG_BITSTREAM
+#define PIX_FMT_HWACCEL   AV_PIX_FMT_FLAG_HWACCEL
+#define PIX_FMT_PLANAR    AV_PIX_FMT_FLAG_PLANAR
+#define PIX_FMT_RGB       AV_PIX_FMT_FLAG_RGB
+#define PIX_FMT_PSEUDOPAL AV_PIX_FMT_FLAG_PSEUDOPAL
+#define PIX_FMT_ALPHA     AV_PIX_FMT_FLAG_ALPHA
+#endif
+
+#if FF_API_PIX_FMT_DESC
+/**
+ * The array of all the pixel format descriptors.
+ */
+extern const AVPixFmtDescriptor av_pix_fmt_descriptors[];
+#endif
+
+/**
+ * Read a line from an image, and write the values of the
+ * pixel format component c to dst.
+ *
+ * @param data the array containing the pointers to the planes of the image
+ * @param linesize the array containing the linesizes of the image
+ * @param desc the pixel format descriptor for the image
+ * @param x the horizontal coordinate of the first pixel to read
+ * @param y the vertical coordinate of the first pixel to read
+ * @param w the width of the line to read, that is the number of
+ * values to write to dst
+ * @param read_pal_component if not zero and the format is a paletted
+ * format writes the values corresponding to the palette
+ * component c in data[1] to dst, rather than the palette indexes in
+ * data[0]. The behavior is undefined if the format is not paletted.
+ */
+void av_read_image_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
+                        const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component);
+
+/**
+ * Write the values from src to the pixel format component c of an
+ * image line.
+ *
+ * @param src array containing the values to write
+ * @param data the array containing the pointers to the planes of the
+ * image to write into. It is supposed to be zeroed.
+ * @param linesize the array containing the linesizes of the image
+ * @param desc the pixel format descriptor for the image
+ * @param x the horizontal coordinate of the first pixel to write
+ * @param y the vertical coordinate of the first pixel to write
+ * @param w the width of the line to write, that is the number of
+ * values to write to the image line
+ */
+void av_write_image_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
+                         const AVPixFmtDescriptor *desc, int x, int y, int c, int w);
+
+/**
+ * Return the pixel format corresponding to name.
+ *
+ * If there is no pixel format with name name, then looks for a
+ * pixel format with the name corresponding to the native endian
+ * format of name.
+ * For example in a little-endian system, first looks for "gray16",
+ * then for "gray16le".
+ *
+ * Finally if no pixel format has been found, returns AV_PIX_FMT_NONE.
+ */
+enum AVPixelFormat av_get_pix_fmt(const char *name);
+
+/**
+ * Return the short name for a pixel format, NULL in case pix_fmt is
+ * unknown.
+ *
+ * @see av_get_pix_fmt(), av_get_pix_fmt_string()
+ */
+const char *av_get_pix_fmt_name(enum AVPixelFormat pix_fmt);
+
+/**
+ * Print in buf the string corresponding to the pixel format with
+ * number pix_fmt, or an header if pix_fmt is negative.
+ *
+ * @param buf the buffer where to write the string
+ * @param buf_size the size of buf
+ * @param pix_fmt the number of the pixel format to print the
+ * corresponding info string, or a negative value to print the
+ * corresponding header.
+ */
+char *av_get_pix_fmt_string (char *buf, int buf_size, enum AVPixelFormat pix_fmt);
+
+/**
+ * Return the number of bits per pixel used by the pixel format
+ * described by pixdesc. Note that this is not the same as the number
+ * of bits per sample.
+ *
+ * The returned number of bits refers to the number of bits actually
+ * used for storing the pixel information, that is padding bits are
+ * not counted.
+ */
+int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc);
+
+/**
+ * Return the number of bits per pixel for the pixel format
+ * described by pixdesc, including any padding or unused bits.
+ */
+int av_get_padded_bits_per_pixel(const AVPixFmtDescriptor *pixdesc);
+
+/**
+ * @return a pixel format descriptor for provided pixel format or NULL if
+ * this pixel format is unknown.
+ */
+const AVPixFmtDescriptor *av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt);
+
+/**
+ * Iterate over all pixel format descriptors known to libavutil.
+ *
+ * @param prev previous descriptor. NULL to get the first descriptor.
+ *
+ * @return next descriptor or NULL after the last descriptor
+ */
+const AVPixFmtDescriptor *av_pix_fmt_desc_next(const AVPixFmtDescriptor *prev);
+
+/**
+ * @return an AVPixelFormat id described by desc, or AV_PIX_FMT_NONE if desc
+ * is not a valid pointer to a pixel format descriptor.
+ */
+enum AVPixelFormat av_pix_fmt_desc_get_id(const AVPixFmtDescriptor *desc);
+
+/**
+ * Utility function to access log2_chroma_w log2_chroma_h from
+ * the pixel format AVPixFmtDescriptor.
+ *
+ * See avcodec_get_chroma_sub_sample() for a function that asserts a
+ * valid pixel format instead of returning an error code.
+ * Its recommanded that you use avcodec_get_chroma_sub_sample unless
+ * you do check the return code!
+ *
+ * @param[in]  pix_fmt the pixel format
+ * @param[out] h_shift store log2_chroma_w
+ * @param[out] v_shift store log2_chroma_h
+ *
+ * @return 0 on success, AVERROR(ENOSYS) on invalid or unknown pixel format
+ */
+int av_pix_fmt_get_chroma_sub_sample(enum AVPixelFormat pix_fmt,
+                                     int *h_shift, int *v_shift);
+
+/**
+ * @return number of planes in pix_fmt, a negative AVERROR if pix_fmt is not a
+ * valid pixel format.
+ */
+int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt);
+
+void ff_check_pixfmt_descriptors(void);
+
+/**
+ * Utility function to swap the endianness of a pixel format.
+ *
+ * @param[in]  pix_fmt the pixel format
+ *
+ * @return pixel format with swapped endianness if it exists,
+ * otherwise AV_PIX_FMT_NONE
+ */
+enum AVPixelFormat av_pix_fmt_swap_endianness(enum AVPixelFormat pix_fmt);
+
+
+#endif /* AVUTIL_PIXDESC_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/pixfmt.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,366 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PIXFMT_H
+#define AVUTIL_PIXFMT_H
+
+/**
+ * @file
+ * pixel format definitions
+ *
+ */
+
+#include "avconfig.h"
+#include "version.h"
+
+#define AVPALETTE_SIZE 1024
+#define AVPALETTE_COUNT 256
+
+/**
+ * Pixel format.
+ *
+ * @note
+ * PIX_FMT_RGB32 is handled in an endian-specific manner. An RGBA
+ * color is put together as:
+ *  (A << 24) | (R << 16) | (G << 8) | B
+ * This is stored as BGRA on little-endian CPU architectures and ARGB on
+ * big-endian CPUs.
+ *
+ * @par
+ * When the pixel format is palettized RGB (PIX_FMT_PAL8), the palettized
+ * image data is stored in AVFrame.data[0]. The palette is transported in
+ * AVFrame.data[1], is 1024 bytes long (256 4-byte entries) and is
+ * formatted the same as in PIX_FMT_RGB32 described above (i.e., it is
+ * also endian-specific). Note also that the individual RGB palette
+ * components stored in AVFrame.data[1] should be in the range 0..255.
+ * This is important as many custom PAL8 video codecs that were designed
+ * to run on the IBM VGA graphics adapter use 6-bit palette components.
+ *
+ * @par
+ * For all the 8bit per pixel formats, an RGB32 palette is in data[1] like
+ * for pal8. This palette is filled in automatically by the function
+ * allocating the picture.
+ *
+ * @note
+ * Make sure that all newly added big-endian formats have pix_fmt & 1 == 1
+ * and that all newly added little-endian formats have pix_fmt & 1 == 0.
+ * This allows simpler detection of big vs little-endian.
+ */
+enum AVPixelFormat {
+    AV_PIX_FMT_NONE = -1,
+    AV_PIX_FMT_YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
+    AV_PIX_FMT_YUYV422,   ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
+    AV_PIX_FMT_RGB24,     ///< packed RGB 8:8:8, 24bpp, RGBRGB...
+    AV_PIX_FMT_BGR24,     ///< packed RGB 8:8:8, 24bpp, BGRBGR...
+    AV_PIX_FMT_YUV422P,   ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+    AV_PIX_FMT_YUV444P,   ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
+    AV_PIX_FMT_YUV410P,   ///< planar YUV 4:1:0,  9bpp, (1 Cr & Cb sample per 4x4 Y samples)
+    AV_PIX_FMT_YUV411P,   ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
+    AV_PIX_FMT_GRAY8,     ///<        Y        ,  8bpp
+    AV_PIX_FMT_MONOWHITE, ///<        Y        ,  1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb
+    AV_PIX_FMT_MONOBLACK, ///<        Y        ,  1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb
+    AV_PIX_FMT_PAL8,      ///< 8 bit with PIX_FMT_RGB32 palette
+    AV_PIX_FMT_YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV420P and setting color_range
+    AV_PIX_FMT_YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV422P and setting color_range
+    AV_PIX_FMT_YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV444P and setting color_range
+    AV_PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing
+    AV_PIX_FMT_XVMC_MPEG2_IDCT,
+    AV_PIX_FMT_UYVY422,   ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
+    AV_PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
+    AV_PIX_FMT_BGR8,      ///< packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb)
+    AV_PIX_FMT_BGR4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    AV_PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb)
+    AV_PIX_FMT_RGB8,      ///< packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb)
+    AV_PIX_FMT_RGB4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    AV_PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb)
+    AV_PIX_FMT_NV12,      ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
+    AV_PIX_FMT_NV21,      ///< as above, but U and V bytes are swapped
+
+    AV_PIX_FMT_ARGB,      ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
+    AV_PIX_FMT_RGBA,      ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
+    AV_PIX_FMT_ABGR,      ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
+    AV_PIX_FMT_BGRA,      ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
+
+    AV_PIX_FMT_GRAY16BE,  ///<        Y        , 16bpp, big-endian
+    AV_PIX_FMT_GRAY16LE,  ///<        Y        , 16bpp, little-endian
+    AV_PIX_FMT_YUV440P,   ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
+    AV_PIX_FMT_YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of PIX_FMT_YUV440P and setting color_range
+    AV_PIX_FMT_YUVA420P,  ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
+    AV_PIX_FMT_VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    AV_PIX_FMT_VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    AV_PIX_FMT_VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    AV_PIX_FMT_VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    AV_PIX_FMT_VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    AV_PIX_FMT_RGB48BE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
+    AV_PIX_FMT_RGB48LE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
+
+    AV_PIX_FMT_RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
+    AV_PIX_FMT_RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
+    AV_PIX_FMT_RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0
+    AV_PIX_FMT_RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0
+
+    AV_PIX_FMT_BGR565BE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), big-endian
+    AV_PIX_FMT_BGR565LE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), little-endian
+    AV_PIX_FMT_BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1
+    AV_PIX_FMT_BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1
+
+    AV_PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
+    AV_PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
+    AV_PIX_FMT_VAAPI_VLD,  ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+
+    AV_PIX_FMT_YUV420P16LE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV420P16BE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV422P16LE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV422P16BE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_VDPAU_MPEG4,  ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    AV_PIX_FMT_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
+
+    AV_PIX_FMT_RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0
+    AV_PIX_FMT_RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0
+    AV_PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
+    AV_PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
+    AV_PIX_FMT_GRAY8A,    ///< 8bit gray, 8bit alpha
+    AV_PIX_FMT_BGR48BE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian
+    AV_PIX_FMT_BGR48LE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian
+
+    //the following 10 formats have the disadvantage of needing 1 format for each bit depth, thus
+    //If you want to support multiple bit depths, then using AV_PIX_FMT_YUV420P16* with the bpp stored separately
+    //is better
+    AV_PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_VDA_VLD,    ///< hardware decoding through VDA
+
+#ifdef AV_PIX_FMT_ABI_GIT_MASTER
+    AV_PIX_FMT_RGBA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    AV_PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+#endif
+    AV_PIX_FMT_GBRP,      ///< planar GBR 4:4:4 24bpp
+    AV_PIX_FMT_GBRP9BE,   ///< planar GBR 4:4:4 27bpp, big-endian
+    AV_PIX_FMT_GBRP9LE,   ///< planar GBR 4:4:4 27bpp, little-endian
+    AV_PIX_FMT_GBRP10BE,  ///< planar GBR 4:4:4 30bpp, big-endian
+    AV_PIX_FMT_GBRP10LE,  ///< planar GBR 4:4:4 30bpp, little-endian
+    AV_PIX_FMT_GBRP16BE,  ///< planar GBR 4:4:4 48bpp, big-endian
+    AV_PIX_FMT_GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little-endian
+
+    /**
+     * duplicated pixel formats for compatibility with libav.
+     * FFmpeg supports these formats since May 8 2012 and Jan 28 2012 (commits f9ca1ac7 and 143a5c55)
+     * Libav added them Oct 12 2012 with incompatible values (commit 6d5600e85)
+     */
+    AV_PIX_FMT_YUVA422P_LIBAV,  ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
+    AV_PIX_FMT_YUVA444P_LIBAV,  ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
+
+    AV_PIX_FMT_YUVA420P9BE,  ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), big-endian
+    AV_PIX_FMT_YUVA420P9LE,  ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), little-endian
+    AV_PIX_FMT_YUVA422P9BE,  ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), big-endian
+    AV_PIX_FMT_YUVA422P9LE,  ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), little-endian
+    AV_PIX_FMT_YUVA444P9BE,  ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), big-endian
+    AV_PIX_FMT_YUVA444P9LE,  ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), little-endian
+    AV_PIX_FMT_YUVA420P10BE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian)
+    AV_PIX_FMT_YUVA420P10LE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian)
+    AV_PIX_FMT_YUVA422P10BE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian)
+    AV_PIX_FMT_YUVA422P10LE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian)
+    AV_PIX_FMT_YUVA444P10BE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian)
+    AV_PIX_FMT_YUVA444P10LE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian)
+    AV_PIX_FMT_YUVA420P16BE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian)
+    AV_PIX_FMT_YUVA420P16LE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian)
+    AV_PIX_FMT_YUVA422P16BE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian)
+    AV_PIX_FMT_YUVA422P16LE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian)
+    AV_PIX_FMT_YUVA444P16BE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian)
+    AV_PIX_FMT_YUVA444P16LE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian)
+
+    AV_PIX_FMT_VDPAU,     ///< HW acceleration through VDPAU, Picture.data[3] contains a VdpVideoSurface
+
+    AV_PIX_FMT_XYZ12LE,      ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as little-endian, the 4 lower bits are set to 0
+    AV_PIX_FMT_XYZ12BE,      ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as big-endian, the 4 lower bits are set to 0
+
+#ifndef AV_PIX_FMT_ABI_GIT_MASTER
+    AV_PIX_FMT_RGBA64BE=0x123,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_RGBA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+    AV_PIX_FMT_BGRA64BE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+    AV_PIX_FMT_BGRA64LE,  ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+#endif
+    AV_PIX_FMT_0RGB=0x123+4,      ///< packed RGB 8:8:8, 32bpp, 0RGB0RGB...
+    AV_PIX_FMT_RGB0,      ///< packed RGB 8:8:8, 32bpp, RGB0RGB0...
+    AV_PIX_FMT_0BGR,      ///< packed BGR 8:8:8, 32bpp, 0BGR0BGR...
+    AV_PIX_FMT_BGR0,      ///< packed BGR 8:8:8, 32bpp, BGR0BGR0...
+    AV_PIX_FMT_YUVA444P,  ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
+    AV_PIX_FMT_YUVA422P,  ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
+
+    AV_PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    AV_PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    AV_PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    AV_PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    AV_PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    AV_PIX_FMT_GBRP12BE,    ///< planar GBR 4:4:4 36bpp, big-endian
+    AV_PIX_FMT_GBRP12LE,    ///< planar GBR 4:4:4 36bpp, little-endian
+    AV_PIX_FMT_GBRP14BE,    ///< planar GBR 4:4:4 42bpp, big-endian
+    AV_PIX_FMT_GBRP14LE,    ///< planar GBR 4:4:4 42bpp, little-endian
+    AV_PIX_FMT_GBRAP,       ///< planar GBRA 4:4:4:4 32bpp
+    AV_PIX_FMT_GBRAP16BE,   ///< planar GBRA 4:4:4:4 64bpp, big-endian
+    AV_PIX_FMT_GBRAP16LE,   ///< planar GBRA 4:4:4:4 64bpp, little-endian
+    AV_PIX_FMT_YUVJ411P,    ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor of PIX_FMT_YUV411P and setting color_range
+    AV_PIX_FMT_NB,        ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
+
+#if FF_API_PIX_FMT
+#include "old_pix_fmts.h"
+#endif
+};
+
+#if AV_HAVE_INCOMPATIBLE_FORK_ABI
+#define AV_PIX_FMT_YUVA422P AV_PIX_FMT_YUVA422P_LIBAV
+#define AV_PIX_FMT_YUVA444P AV_PIX_FMT_YUVA444P_LIBAV
+#endif
+
+
+#define AV_PIX_FMT_Y400A AV_PIX_FMT_GRAY8A
+#define AV_PIX_FMT_GBR24P AV_PIX_FMT_GBRP
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##be
+#else
+#   define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##le
+#endif
+
+#define AV_PIX_FMT_RGB32   AV_PIX_FMT_NE(ARGB, BGRA)
+#define AV_PIX_FMT_RGB32_1 AV_PIX_FMT_NE(RGBA, ABGR)
+#define AV_PIX_FMT_BGR32   AV_PIX_FMT_NE(ABGR, RGBA)
+#define AV_PIX_FMT_BGR32_1 AV_PIX_FMT_NE(BGRA, ARGB)
+#define AV_PIX_FMT_0RGB32  AV_PIX_FMT_NE(0RGB, BGR0)
+#define AV_PIX_FMT_0BGR32  AV_PIX_FMT_NE(0BGR, RGB0)
+
+#define AV_PIX_FMT_GRAY16 AV_PIX_FMT_NE(GRAY16BE, GRAY16LE)
+#define AV_PIX_FMT_RGB48  AV_PIX_FMT_NE(RGB48BE,  RGB48LE)
+#define AV_PIX_FMT_RGB565 AV_PIX_FMT_NE(RGB565BE, RGB565LE)
+#define AV_PIX_FMT_RGB555 AV_PIX_FMT_NE(RGB555BE, RGB555LE)
+#define AV_PIX_FMT_RGB444 AV_PIX_FMT_NE(RGB444BE, RGB444LE)
+#define AV_PIX_FMT_BGR48  AV_PIX_FMT_NE(BGR48BE,  BGR48LE)
+#define AV_PIX_FMT_BGR565 AV_PIX_FMT_NE(BGR565BE, BGR565LE)
+#define AV_PIX_FMT_BGR555 AV_PIX_FMT_NE(BGR555BE, BGR555LE)
+#define AV_PIX_FMT_BGR444 AV_PIX_FMT_NE(BGR444BE, BGR444LE)
+
+#define AV_PIX_FMT_YUV420P9  AV_PIX_FMT_NE(YUV420P9BE , YUV420P9LE)
+#define AV_PIX_FMT_YUV422P9  AV_PIX_FMT_NE(YUV422P9BE , YUV422P9LE)
+#define AV_PIX_FMT_YUV444P9  AV_PIX_FMT_NE(YUV444P9BE , YUV444P9LE)
+#define AV_PIX_FMT_YUV420P10 AV_PIX_FMT_NE(YUV420P10BE, YUV420P10LE)
+#define AV_PIX_FMT_YUV422P10 AV_PIX_FMT_NE(YUV422P10BE, YUV422P10LE)
+#define AV_PIX_FMT_YUV444P10 AV_PIX_FMT_NE(YUV444P10BE, YUV444P10LE)
+#define AV_PIX_FMT_YUV420P12 AV_PIX_FMT_NE(YUV420P12BE, YUV420P12LE)
+#define AV_PIX_FMT_YUV422P12 AV_PIX_FMT_NE(YUV422P12BE, YUV422P12LE)
+#define AV_PIX_FMT_YUV444P12 AV_PIX_FMT_NE(YUV444P12BE, YUV444P12LE)
+#define AV_PIX_FMT_YUV420P14 AV_PIX_FMT_NE(YUV420P14BE, YUV420P14LE)
+#define AV_PIX_FMT_YUV422P14 AV_PIX_FMT_NE(YUV422P14BE, YUV422P14LE)
+#define AV_PIX_FMT_YUV444P14 AV_PIX_FMT_NE(YUV444P14BE, YUV444P14LE)
+#define AV_PIX_FMT_YUV420P16 AV_PIX_FMT_NE(YUV420P16BE, YUV420P16LE)
+#define AV_PIX_FMT_YUV422P16 AV_PIX_FMT_NE(YUV422P16BE, YUV422P16LE)
+#define AV_PIX_FMT_YUV444P16 AV_PIX_FMT_NE(YUV444P16BE, YUV444P16LE)
+
+#define AV_PIX_FMT_RGBA64 AV_PIX_FMT_NE(RGBA64BE, RGBA64LE)
+#define AV_PIX_FMT_BGRA64 AV_PIX_FMT_NE(BGRA64BE, BGRA64LE)
+#define AV_PIX_FMT_GBRP9     AV_PIX_FMT_NE(GBRP9BE ,    GBRP9LE)
+#define AV_PIX_FMT_GBRP10    AV_PIX_FMT_NE(GBRP10BE,    GBRP10LE)
+#define AV_PIX_FMT_GBRP12    AV_PIX_FMT_NE(GBRP12BE,    GBRP12LE)
+#define AV_PIX_FMT_GBRP14    AV_PIX_FMT_NE(GBRP14BE,    GBRP14LE)
+#define AV_PIX_FMT_GBRP16    AV_PIX_FMT_NE(GBRP16BE,    GBRP16LE)
+
+#define AV_PIX_FMT_YUVA420P9  AV_PIX_FMT_NE(YUVA420P9BE , YUVA420P9LE)
+#define AV_PIX_FMT_YUVA422P9  AV_PIX_FMT_NE(YUVA422P9BE , YUVA422P9LE)
+#define AV_PIX_FMT_YUVA444P9  AV_PIX_FMT_NE(YUVA444P9BE , YUVA444P9LE)
+#define AV_PIX_FMT_YUVA420P10 AV_PIX_FMT_NE(YUVA420P10BE, YUVA420P10LE)
+#define AV_PIX_FMT_YUVA422P10 AV_PIX_FMT_NE(YUVA422P10BE, YUVA422P10LE)
+#define AV_PIX_FMT_YUVA444P10 AV_PIX_FMT_NE(YUVA444P10BE, YUVA444P10LE)
+#define AV_PIX_FMT_YUVA420P16 AV_PIX_FMT_NE(YUVA420P16BE, YUVA420P16LE)
+#define AV_PIX_FMT_YUVA422P16 AV_PIX_FMT_NE(YUVA422P16BE, YUVA422P16LE)
+#define AV_PIX_FMT_YUVA444P16 AV_PIX_FMT_NE(YUVA444P16BE, YUVA444P16LE)
+
+#define AV_PIX_FMT_XYZ12      AV_PIX_FMT_NE(XYZ12BE, XYZ12LE)
+
+#if FF_API_PIX_FMT
+#define PixelFormat AVPixelFormat
+
+#define PIX_FMT_Y400A AV_PIX_FMT_Y400A
+#define PIX_FMT_GBR24P AV_PIX_FMT_GBR24P
+
+#define PIX_FMT_NE(be, le) AV_PIX_FMT_NE(be, le)
+
+#define PIX_FMT_RGB32   AV_PIX_FMT_RGB32
+#define PIX_FMT_RGB32_1 AV_PIX_FMT_RGB32_1
+#define PIX_FMT_BGR32   AV_PIX_FMT_BGR32
+#define PIX_FMT_BGR32_1 AV_PIX_FMT_BGR32_1
+#define PIX_FMT_0RGB32  AV_PIX_FMT_0RGB32
+#define PIX_FMT_0BGR32  AV_PIX_FMT_0BGR32
+
+#define PIX_FMT_GRAY16 AV_PIX_FMT_GRAY16
+#define PIX_FMT_RGB48  AV_PIX_FMT_RGB48
+#define PIX_FMT_RGB565 AV_PIX_FMT_RGB565
+#define PIX_FMT_RGB555 AV_PIX_FMT_RGB555
+#define PIX_FMT_RGB444 AV_PIX_FMT_RGB444
+#define PIX_FMT_BGR48  AV_PIX_FMT_BGR48
+#define PIX_FMT_BGR565 AV_PIX_FMT_BGR565
+#define PIX_FMT_BGR555 AV_PIX_FMT_BGR555
+#define PIX_FMT_BGR444 AV_PIX_FMT_BGR444
+
+#define PIX_FMT_YUV420P9  AV_PIX_FMT_YUV420P9
+#define PIX_FMT_YUV422P9  AV_PIX_FMT_YUV422P9
+#define PIX_FMT_YUV444P9  AV_PIX_FMT_YUV444P9
+#define PIX_FMT_YUV420P10 AV_PIX_FMT_YUV420P10
+#define PIX_FMT_YUV422P10 AV_PIX_FMT_YUV422P10
+#define PIX_FMT_YUV444P10 AV_PIX_FMT_YUV444P10
+#define PIX_FMT_YUV420P12 AV_PIX_FMT_YUV420P12
+#define PIX_FMT_YUV422P12 AV_PIX_FMT_YUV422P12
+#define PIX_FMT_YUV444P12 AV_PIX_FMT_YUV444P12
+#define PIX_FMT_YUV420P14 AV_PIX_FMT_YUV420P14
+#define PIX_FMT_YUV422P14 AV_PIX_FMT_YUV422P14
+#define PIX_FMT_YUV444P14 AV_PIX_FMT_YUV444P14
+#define PIX_FMT_YUV420P16 AV_PIX_FMT_YUV420P16
+#define PIX_FMT_YUV422P16 AV_PIX_FMT_YUV422P16
+#define PIX_FMT_YUV444P16 AV_PIX_FMT_YUV444P16
+
+#define PIX_FMT_RGBA64 AV_PIX_FMT_RGBA64
+#define PIX_FMT_BGRA64 AV_PIX_FMT_BGRA64
+#define PIX_FMT_GBRP9  AV_PIX_FMT_GBRP9
+#define PIX_FMT_GBRP10 AV_PIX_FMT_GBRP10
+#define PIX_FMT_GBRP12 AV_PIX_FMT_GBRP12
+#define PIX_FMT_GBRP14 AV_PIX_FMT_GBRP14
+#define PIX_FMT_GBRP16 AV_PIX_FMT_GBRP16
+#endif
+
+#endif /* AVUTIL_PIXFMT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/random_seed.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier@gmail.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_RANDOM_SEED_H
+#define AVUTIL_RANDOM_SEED_H
+
+#include <stdint.h>
+/**
+ * @addtogroup lavu_crypto
+ * @{
+ */
+
+/**
+ * Get a seed to use in conjunction with random functions.
+ * This function tries to provide a good seed at a best effort bases.
+ * Its possible to call this function multiple times if more bits are needed.
+ * It can be quite slow, which is why it should only be used as seed for a faster
+ * PRNG. The quality of the seed depends on the platform.
+ */
+uint32_t av_get_random_seed(void);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_RANDOM_SEED_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/rational.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,155 @@
+/*
+ * rational numbers
+ * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * rational numbers
+ * @author Michael Niedermayer <michaelni@gmx.at>
+ */
+
+#ifndef AVUTIL_RATIONAL_H
+#define AVUTIL_RATIONAL_H
+
+#include <stdint.h>
+#include <limits.h>
+#include "attributes.h"
+
+/**
+ * @addtogroup lavu_math
+ * @{
+ */
+
+/**
+ * rational number numerator/denominator
+ */
+typedef struct AVRational{
+    int num; ///< numerator
+    int den; ///< denominator
+} AVRational;
+
+/**
+ * Compare two rationals.
+ * @param a first rational
+ * @param b second rational
+ * @return 0 if a==b, 1 if a>b, -1 if a<b, and INT_MIN if one of the
+ * values is of the form 0/0
+ */
+static inline int av_cmp_q(AVRational a, AVRational b){
+    const int64_t tmp= a.num * (int64_t)b.den - b.num * (int64_t)a.den;
+
+    if(tmp) return ((tmp ^ a.den ^ b.den)>>63)|1;
+    else if(b.den && a.den) return 0;
+    else if(a.num && b.num) return (a.num>>31) - (b.num>>31);
+    else                    return INT_MIN;
+}
+
+/**
+ * Convert rational to double.
+ * @param a rational to convert
+ * @return (double) a
+ */
+static inline double av_q2d(AVRational a){
+    return a.num / (double) a.den;
+}
+
+/**
+ * Reduce a fraction.
+ * This is useful for framerate calculations.
+ * @param dst_num destination numerator
+ * @param dst_den destination denominator
+ * @param num source numerator
+ * @param den source denominator
+ * @param max the maximum allowed for dst_num & dst_den
+ * @return 1 if exact, 0 otherwise
+ */
+int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max);
+
+/**
+ * Multiply two rationals.
+ * @param b first rational
+ * @param c second rational
+ * @return b*c
+ */
+AVRational av_mul_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Divide one rational by another.
+ * @param b first rational
+ * @param c second rational
+ * @return b/c
+ */
+AVRational av_div_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Add two rationals.
+ * @param b first rational
+ * @param c second rational
+ * @return b+c
+ */
+AVRational av_add_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Subtract one rational from another.
+ * @param b first rational
+ * @param c second rational
+ * @return b-c
+ */
+AVRational av_sub_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Invert a rational.
+ * @param q value
+ * @return 1 / q
+ */
+static av_always_inline AVRational av_inv_q(AVRational q)
+{
+    AVRational r = { q.den, q.num };
+    return r;
+}
+
+/**
+ * Convert a double precision floating point number to a rational.
+ * inf is expressed as {1,0} or {-1,0} depending on the sign.
+ *
+ * @param d double to convert
+ * @param max the maximum allowed numerator and denominator
+ * @return (AVRational) d
+ */
+AVRational av_d2q(double d, int max) av_const;
+
+/**
+ * @return 1 if q1 is nearer to q than q2, -1 if q2 is nearer
+ * than q1, 0 if they have the same distance.
+ */
+int av_nearer_q(AVRational q, AVRational q1, AVRational q2);
+
+/**
+ * Find the nearest value in q_list to q.
+ * @param q_list an array of rationals terminated by {0, 0}
+ * @return the index of the nearest value found in the array
+ */
+int av_find_nearest_q_idx(AVRational q, const AVRational* q_list);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_RATIONAL_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/samplefmt.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,256 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_SAMPLEFMT_H
+#define AVUTIL_SAMPLEFMT_H
+
+#include <stdint.h>
+
+#include "avutil.h"
+#include "attributes.h"
+
+/**
+ * Audio Sample Formats
+ *
+ * @par
+ * The data described by the sample format is always in native-endian order.
+ * Sample values can be expressed by native C types, hence the lack of a signed
+ * 24-bit sample format even though it is a common raw audio data format.
+ *
+ * @par
+ * The floating-point formats are based on full volume being in the range
+ * [-1.0, 1.0]. Any values outside this range are beyond full volume level.
+ *
+ * @par
+ * The data layout as used in av_samples_fill_arrays() and elsewhere in FFmpeg
+ * (such as AVFrame in libavcodec) is as follows:
+ *
+ * For planar sample formats, each audio channel is in a separate data plane,
+ * and linesize is the buffer size, in bytes, for a single plane. All data
+ * planes must be the same size. For packed sample formats, only the first data
+ * plane is used, and samples for each channel are interleaved. In this case,
+ * linesize is the buffer size, in bytes, for the 1 plane.
+ */
+enum AVSampleFormat {
+    AV_SAMPLE_FMT_NONE = -1,
+    AV_SAMPLE_FMT_U8,          ///< unsigned 8 bits
+    AV_SAMPLE_FMT_S16,         ///< signed 16 bits
+    AV_SAMPLE_FMT_S32,         ///< signed 32 bits
+    AV_SAMPLE_FMT_FLT,         ///< float
+    AV_SAMPLE_FMT_DBL,         ///< double
+
+    AV_SAMPLE_FMT_U8P,         ///< unsigned 8 bits, planar
+    AV_SAMPLE_FMT_S16P,        ///< signed 16 bits, planar
+    AV_SAMPLE_FMT_S32P,        ///< signed 32 bits, planar
+    AV_SAMPLE_FMT_FLTP,        ///< float, planar
+    AV_SAMPLE_FMT_DBLP,        ///< double, planar
+
+    AV_SAMPLE_FMT_NB           ///< Number of sample formats. DO NOT USE if linking dynamically
+};
+
+/**
+ * Return the name of sample_fmt, or NULL if sample_fmt is not
+ * recognized.
+ */
+const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt);
+
+/**
+ * Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE
+ * on error.
+ */
+enum AVSampleFormat av_get_sample_fmt(const char *name);
+
+/**
+ * Return the planar<->packed alternative form of the given sample format, or
+ * AV_SAMPLE_FMT_NONE on error. If the passed sample_fmt is already in the
+ * requested planar/packed format, the format returned is the same as the
+ * input.
+ */
+enum AVSampleFormat av_get_alt_sample_fmt(enum AVSampleFormat sample_fmt, int planar);
+
+/**
+ * Get the packed alternative form of the given sample format.
+ *
+ * If the passed sample_fmt is already in packed format, the format returned is
+ * the same as the input.
+ *
+ * @return  the packed alternative form of the given sample format or
+            AV_SAMPLE_FMT_NONE on error.
+ */
+enum AVSampleFormat av_get_packed_sample_fmt(enum AVSampleFormat sample_fmt);
+
+/**
+ * Get the planar alternative form of the given sample format.
+ *
+ * If the passed sample_fmt is already in planar format, the format returned is
+ * the same as the input.
+ *
+ * @return  the planar alternative form of the given sample format or
+            AV_SAMPLE_FMT_NONE on error.
+ */
+enum AVSampleFormat av_get_planar_sample_fmt(enum AVSampleFormat sample_fmt);
+
+/**
+ * Generate a string corresponding to the sample format with
+ * sample_fmt, or a header if sample_fmt is negative.
+ *
+ * @param buf the buffer where to write the string
+ * @param buf_size the size of buf
+ * @param sample_fmt the number of the sample format to print the
+ * corresponding info string, or a negative value to print the
+ * corresponding header.
+ * @return the pointer to the filled buffer or NULL if sample_fmt is
+ * unknown or in case of other errors
+ */
+char *av_get_sample_fmt_string(char *buf, int buf_size, enum AVSampleFormat sample_fmt);
+
+#if FF_API_GET_BITS_PER_SAMPLE_FMT
+/**
+ * @deprecated Use av_get_bytes_per_sample() instead.
+ */
+attribute_deprecated
+int av_get_bits_per_sample_fmt(enum AVSampleFormat sample_fmt);
+#endif
+
+/**
+ * Return number of bytes per sample.
+ *
+ * @param sample_fmt the sample format
+ * @return number of bytes per sample or zero if unknown for the given
+ * sample format
+ */
+int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt);
+
+/**
+ * Check if the sample format is planar.
+ *
+ * @param sample_fmt the sample format to inspect
+ * @return 1 if the sample format is planar, 0 if it is interleaved
+ */
+int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt);
+
+/**
+ * Get the required buffer size for the given audio parameters.
+ *
+ * @param[out] linesize calculated linesize, may be NULL
+ * @param nb_channels   the number of channels
+ * @param nb_samples    the number of samples in a single channel
+ * @param sample_fmt    the sample format
+ * @param align         buffer size alignment (0 = default, 1 = no alignment)
+ * @return              required buffer size, or negative error code on failure
+ */
+int av_samples_get_buffer_size(int *linesize, int nb_channels, int nb_samples,
+                               enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Fill plane data pointers and linesize for samples with sample
+ * format sample_fmt.
+ *
+ * The audio_data array is filled with the pointers to the samples data planes:
+ * for planar, set the start point of each channel's data within the buffer,
+ * for packed, set the start point of the entire buffer only.
+ *
+ * The value pointed to by linesize is set to the aligned size of each
+ * channel's data buffer for planar layout, or to the aligned size of the
+ * buffer for all channels for packed layout.
+ *
+ * The buffer in buf must be big enough to contain all the samples
+ * (use av_samples_get_buffer_size() to compute its minimum size),
+ * otherwise the audio_data pointers will point to invalid data.
+ *
+ * @see enum AVSampleFormat
+ * The documentation for AVSampleFormat describes the data layout.
+ *
+ * @param[out] audio_data  array to be filled with the pointer for each channel
+ * @param[out] linesize    calculated linesize, may be NULL
+ * @param buf              the pointer to a buffer containing the samples
+ * @param nb_channels      the number of channels
+ * @param nb_samples       the number of samples in a single channel
+ * @param sample_fmt       the sample format
+ * @param align            buffer size alignment (0 = default, 1 = no alignment)
+ * @return                 >=0 on success or a negative error code on failure
+ * @todo return minimum size in bytes required for the buffer in case
+ * of success at the next bump
+ */
+int av_samples_fill_arrays(uint8_t **audio_data, int *linesize,
+                           const uint8_t *buf,
+                           int nb_channels, int nb_samples,
+                           enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Allocate a samples buffer for nb_samples samples, and fill data pointers and
+ * linesize accordingly.
+ * The allocated samples buffer can be freed by using av_freep(&audio_data[0])
+ * Allocated data will be initialized to silence.
+ *
+ * @see enum AVSampleFormat
+ * The documentation for AVSampleFormat describes the data layout.
+ *
+ * @param[out] audio_data  array to be filled with the pointer for each channel
+ * @param[out] linesize    aligned size for audio buffer(s), may be NULL
+ * @param nb_channels      number of audio channels
+ * @param nb_samples       number of samples per channel
+ * @param align            buffer size alignment (0 = default, 1 = no alignment)
+ * @return                 >=0 on success or a negative error code on failure
+ * @todo return the size of the allocated buffer in case of success at the next bump
+ * @see av_samples_fill_arrays()
+ * @see av_samples_alloc_array_and_samples()
+ */
+int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels,
+                     int nb_samples, enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Allocate a data pointers array, samples buffer for nb_samples
+ * samples, and fill data pointers and linesize accordingly.
+ *
+ * This is the same as av_samples_alloc(), but also allocates the data
+ * pointers array.
+ *
+ * @see av_samples_alloc()
+ */
+int av_samples_alloc_array_and_samples(uint8_t ***audio_data, int *linesize, int nb_channels,
+                                       int nb_samples, enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Copy samples from src to dst.
+ *
+ * @param dst destination array of pointers to data planes
+ * @param src source array of pointers to data planes
+ * @param dst_offset offset in samples at which the data will be written to dst
+ * @param src_offset offset in samples at which the data will be read from src
+ * @param nb_samples number of samples to be copied
+ * @param nb_channels number of audio channels
+ * @param sample_fmt audio sample format
+ */
+int av_samples_copy(uint8_t **dst, uint8_t * const *src, int dst_offset,
+                    int src_offset, int nb_samples, int nb_channels,
+                    enum AVSampleFormat sample_fmt);
+
+/**
+ * Fill an audio buffer with silence.
+ *
+ * @param audio_data  array of pointers to data planes
+ * @param offset      offset in samples at which to start filling
+ * @param nb_samples  number of samples to fill
+ * @param nb_channels number of audio channels
+ * @param sample_fmt  audio sample format
+ */
+int av_samples_set_silence(uint8_t **audio_data, int offset, int nb_samples,
+                           int nb_channels, enum AVSampleFormat sample_fmt);
+
+#endif /* AVUTIL_SAMPLEFMT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/sha.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2007 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_SHA_H
+#define AVUTIL_SHA_H
+
+#include <stdint.h>
+
+#include "attributes.h"
+#include "version.h"
+
+/**
+ * @defgroup lavu_sha SHA
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+extern const int av_sha_size;
+
+struct AVSHA;
+
+/**
+ * Allocate an AVSHA context.
+ */
+struct AVSHA *av_sha_alloc(void);
+
+/**
+ * Initialize SHA-1 or SHA-2 hashing.
+ *
+ * @param context pointer to the function context (of size av_sha_size)
+ * @param bits    number of bits in digest (SHA-1 - 160 bits, SHA-2 224 or 256 bits)
+ * @return        zero if initialization succeeded, -1 otherwise
+ */
+int av_sha_init(struct AVSHA* context, int bits);
+
+/**
+ * Update hash value.
+ *
+ * @param context hash function context
+ * @param data    input data to update hash with
+ * @param len     input data length
+ */
+void av_sha_update(struct AVSHA* context, const uint8_t* data, unsigned int len);
+
+/**
+ * Finish hashing and output digest value.
+ *
+ * @param context hash function context
+ * @param digest  buffer where output digest value is stored
+ */
+void av_sha_final(struct AVSHA* context, uint8_t *digest);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_SHA_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/time.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2000-2003 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_TIME_H
+#define AVUTIL_TIME_H
+
+#include <stdint.h>
+
+/**
+ * Get the current time in microseconds.
+ */
+int64_t av_gettime(void);
+
+/**
+ * Sleep for a period of time.  Although the duration is expressed in
+ * microseconds, the actual delay may be rounded to the precision of the
+ * system timer.
+ *
+ * @param  usec Number of microseconds to sleep.
+ * @return zero on success or (negative) error code.
+ */
+int av_usleep(unsigned usec);
+
+#endif /* AVUTIL_TIME_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/timecode.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2006 Smartjog S.A.S, Baptiste Coudurier <baptiste.coudurier@gmail.com>
+ * Copyright (c) 2011-2012 Smartjog S.A.S, Clément Bœsch <clement.boesch@smartjog.com>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Timecode helpers header
+ */
+
+#ifndef AVUTIL_TIMECODE_H
+#define AVUTIL_TIMECODE_H
+
+#include <stdint.h>
+#include "rational.h"
+
+#define AV_TIMECODE_STR_SIZE 16
+
+enum AVTimecodeFlag {
+    AV_TIMECODE_FLAG_DROPFRAME      = 1<<0, ///< timecode is drop frame
+    AV_TIMECODE_FLAG_24HOURSMAX     = 1<<1, ///< timecode wraps after 24 hours
+    AV_TIMECODE_FLAG_ALLOWNEGATIVE  = 1<<2, ///< negative time values are allowed
+};
+
+typedef struct {
+    int start;          ///< timecode frame start (first base frame number)
+    uint32_t flags;     ///< flags such as drop frame, +24 hours support, ...
+    AVRational rate;    ///< frame rate in rational form
+    unsigned fps;       ///< frame per second; must be consistent with the rate field
+} AVTimecode;
+
+/**
+ * Adjust frame number for NTSC drop frame time code.
+ *
+ * @param framenum frame number to adjust
+ * @param fps      frame per second, 30 or 60
+ * @return         adjusted frame number
+ * @warning        adjustment is only valid in NTSC 29.97 and 59.94
+ */
+int av_timecode_adjust_ntsc_framenum2(int framenum, int fps);
+
+/**
+ * Convert frame number to SMPTE 12M binary representation.
+ *
+ * @param tc       timecode data correctly initialized
+ * @param framenum frame number
+ * @return         the SMPTE binary representation
+ *
+ * @note Frame number adjustment is automatically done in case of drop timecode,
+ *       you do NOT have to call av_timecode_adjust_ntsc_framenum2().
+ * @note The frame number is relative to tc->start.
+ * @note Color frame (CF), binary group flags (BGF) and biphase mark polarity
+ *       correction (PC) bits are set to zero.
+ */
+uint32_t av_timecode_get_smpte_from_framenum(const AVTimecode *tc, int framenum);
+
+/**
+ * Load timecode string in buf.
+ *
+ * @param buf      destination buffer, must be at least AV_TIMECODE_STR_SIZE long
+ * @param tc       timecode data correctly initialized
+ * @param framenum frame number
+ * @return         the buf parameter
+ *
+ * @note Timecode representation can be a negative timecode and have more than
+ *       24 hours, but will only be honored if the flags are correctly set.
+ * @note The frame number is relative to tc->start.
+ */
+char *av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum);
+
+/**
+ * Get the timecode string from the SMPTE timecode format.
+ *
+ * @param buf        destination buffer, must be at least AV_TIMECODE_STR_SIZE long
+ * @param tcsmpte    the 32-bit SMPTE timecode
+ * @param prevent_df prevent the use of a drop flag when it is known the DF bit
+ *                   is arbitrary
+ * @return           the buf parameter
+ */
+char *av_timecode_make_smpte_tc_string(char *buf, uint32_t tcsmpte, int prevent_df);
+
+/**
+ * Get the timecode string from the 25-bit timecode format (MPEG GOP format).
+ *
+ * @param buf     destination buffer, must be at least AV_TIMECODE_STR_SIZE long
+ * @param tc25bit the 25-bits timecode
+ * @return        the buf parameter
+ */
+char *av_timecode_make_mpeg_tc_string(char *buf, uint32_t tc25bit);
+
+/**
+ * Init a timecode struct with the passed parameters.
+ *
+ * @param log_ctx     a pointer to an arbitrary struct of which the first field
+ *                    is a pointer to an AVClass struct (used for av_log)
+ * @param tc          pointer to an allocated AVTimecode
+ * @param rate        frame rate in rational form
+ * @param flags       miscellaneous flags such as drop frame, +24 hours, ...
+ *                    (see AVTimecodeFlag)
+ * @param frame_start the first frame number
+ * @return            0 on success, AVERROR otherwise
+ */
+int av_timecode_init(AVTimecode *tc, AVRational rate, int flags, int frame_start, void *log_ctx);
+
+/**
+ * Parse timecode representation (hh:mm:ss[:;.]ff).
+ *
+ * @param log_ctx a pointer to an arbitrary struct of which the first field is a
+ *                pointer to an AVClass struct (used for av_log).
+ * @param tc      pointer to an allocated AVTimecode
+ * @param rate    frame rate in rational form
+ * @param str     timecode string which will determine the frame start
+ * @return        0 on success, AVERROR otherwise
+ */
+int av_timecode_init_from_string(AVTimecode *tc, AVRational rate, const char *str, void *log_ctx);
+
+/**
+ * Check if the timecode feature is available for the given frame rate
+ *
+ * @return 0 if supported, <0 otherwise
+ */
+int av_timecode_check_frame_rate(AVRational rate);
+
+#endif /* AVUTIL_TIMECODE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/timestamp.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,74 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * timestamp utils, mostly useful for debugging/logging purposes
+ */
+
+#ifndef AVUTIL_TIMESTAMP_H
+#define AVUTIL_TIMESTAMP_H
+
+#include "common.h"
+
+#define AV_TS_MAX_STRING_SIZE 32
+
+/**
+ * Fill the provided buffer with a string containing a timestamp
+ * representation.
+ *
+ * @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE
+ * @param ts the timestamp to represent
+ * @return the buffer in input
+ */
+static inline char *av_ts_make_string(char *buf, int64_t ts)
+{
+    if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS");
+    else                      snprintf(buf, AV_TS_MAX_STRING_SIZE, "%"PRId64"", ts);
+    return buf;
+}
+
+/**
+ * Convenience macro, the return value should be used only directly in
+ * function arguments but never stand-alone.
+ */
+#define av_ts2str(ts) av_ts_make_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts)
+
+/**
+ * Fill the provided buffer with a string containing a timestamp time
+ * representation.
+ *
+ * @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE
+ * @param ts the timestamp to represent
+ * @param tb the timebase of the timestamp
+ * @return the buffer in input
+ */
+static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)
+{
+    if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS");
+    else                      snprintf(buf, AV_TS_MAX_STRING_SIZE, "%.6g", av_q2d(*tb) * ts);
+    return buf;
+}
+
+/**
+ * Convenience macro, the return value should be used only directly in
+ * function arguments but never stand-alone.
+ */
+#define av_ts2timestr(ts, tb) av_ts_make_time_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts, tb)
+
+#endif /* AVUTIL_TIMESTAMP_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/version.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,144 @@
+/*
+ * copyright (c) 2003 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_VERSION_H
+#define AVUTIL_VERSION_H
+
+/**
+ * @defgroup preproc_misc Preprocessor String Macros
+ *
+ * String manipulation macros
+ *
+ * @{
+ */
+
+#define AV_STRINGIFY(s)         AV_TOSTRING(s)
+#define AV_TOSTRING(s) #s
+
+#define AV_GLUE(a, b) a ## b
+#define AV_JOIN(a, b) AV_GLUE(a, b)
+
+#define AV_PRAGMA(s) _Pragma(#s)
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup version_utils Library Version Macros
+ *
+ * Useful to check and match library version in order to maintain
+ * backward compatibility.
+ *
+ * @{
+ */
+
+#define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c)
+#define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
+#define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
+
+/**
+ * @}
+ */
+
+
+/**
+ * @file
+ * @ingroup lavu
+ * Libavutil version macros
+ */
+
+/**
+ * @defgroup lavu_ver Version and Build diagnostics
+ *
+ * Macros and function useful to check at compiletime and at runtime
+ * which version of libavutil is in use.
+ *
+ * @{
+ */
+
+#define LIBAVUTIL_VERSION_MAJOR  52
+#define LIBAVUTIL_VERSION_MINOR  33
+#define LIBAVUTIL_VERSION_MICRO 100
+
+#define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
+                                               LIBAVUTIL_VERSION_MINOR, \
+                                               LIBAVUTIL_VERSION_MICRO)
+#define LIBAVUTIL_VERSION       AV_VERSION(LIBAVUTIL_VERSION_MAJOR,     \
+                                           LIBAVUTIL_VERSION_MINOR,     \
+                                           LIBAVUTIL_VERSION_MICRO)
+#define LIBAVUTIL_BUILD         LIBAVUTIL_VERSION_INT
+
+#define LIBAVUTIL_IDENT         "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION)
+
+/**
+ * @}
+ *
+ * @defgroup depr_guards Deprecation guards
+ * FF_API_* defines may be placed below to indicate public API that will be
+ * dropped at a future version bump. The defines themselves are not part of
+ * the public API and may change, break or disappear at any time.
+ *
+ * @{
+ */
+
+#ifndef FF_API_GET_BITS_PER_SAMPLE_FMT
+#define FF_API_GET_BITS_PER_SAMPLE_FMT (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_FIND_OPT
+#define FF_API_FIND_OPT                 (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_OLD_AVOPTIONS
+#define FF_API_OLD_AVOPTIONS            (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_PIX_FMT
+#define FF_API_PIX_FMT                  (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_CONTEXT_SIZE
+#define FF_API_CONTEXT_SIZE             (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_PIX_FMT_DESC
+#define FF_API_PIX_FMT_DESC             (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_AV_REVERSE
+#define FF_API_AV_REVERSE               (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_AUDIOCONVERT
+#define FF_API_AUDIOCONVERT             (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_CPU_FLAG_MMX2
+#define FF_API_CPU_FLAG_MMX2            (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_SAMPLES_UTILS_RETURN_ZERO
+#define FF_API_SAMPLES_UTILS_RETURN_ZERO (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_LLS_PRIVATE
+#define FF_API_LLS_PRIVATE              (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+#ifndef FF_API_AVFRAME_LAVC
+#define FF_API_AVFRAME_LAVC             (LIBAVUTIL_VERSION_MAJOR < 53)
+#endif
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_VERSION_H */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libavutil/xtea.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,62 @@
+/*
+ * A 32-bit implementation of the XTEA algorithm
+ * Copyright (c) 2012 Samuel Pitoiset
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_XTEA_H
+#define AVUTIL_XTEA_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_xtea XTEA
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+typedef struct AVXTEA {
+    uint32_t key[16];
+} AVXTEA;
+
+/**
+ * Initialize an AVXTEA context.
+ *
+ * @param ctx an AVXTEA context
+ * @param key a key of 16 bytes used for encryption/decryption
+ */
+void av_xtea_init(struct AVXTEA *ctx, const uint8_t key[16]);
+
+/**
+ * Encrypt or decrypt a buffer using a previously initialized context.
+ *
+ * @param ctx an AVXTEA context
+ * @param dst destination array, can be equal to src
+ * @param src source array, can be equal to dst
+ * @param count number of 8 byte blocks
+ * @param iv initialization vector for CBC mode, if NULL then ECB will be used
+ * @param decrypt 0 for encryption, 1 for decryption
+ */
+void av_xtea_crypt(struct AVXTEA *ctx, uint8_t *dst, const uint8_t *src,
+                   int count, uint8_t *iv, int decrypt);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_XTEA_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libswresample/swresample.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,311 @@
+/*
+ * Copyright (C) 2011-2013 Michael Niedermayer (michaelni@gmx.at)
+ *
+ * This file is part of libswresample
+ *
+ * libswresample is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * libswresample 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with libswresample; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef SWRESAMPLE_SWRESAMPLE_H
+#define SWRESAMPLE_SWRESAMPLE_H
+
+/**
+ * @file
+ * @ingroup lswr
+ * libswresample public header
+ */
+
+/**
+ * @defgroup lswr Libswresample
+ * @{
+ *
+ * Libswresample (lswr) is a library that handles audio resampling, sample
+ * format conversion and mixing.
+ *
+ * Interaction with lswr is done through SwrContext, which is
+ * allocated with swr_alloc() or swr_alloc_set_opts(). It is opaque, so all parameters
+ * must be set with the @ref avoptions API.
+ *
+ * For example the following code will setup conversion from planar float sample
+ * format to interleaved signed 16-bit integer, downsampling from 48kHz to
+ * 44.1kHz and downmixing from 5.1 channels to stereo (using the default mixing
+ * matrix):
+ * @code
+ * SwrContext *swr = swr_alloc();
+ * av_opt_set_int(swr, "in_channel_layout",  AV_CH_LAYOUT_5POINT1, 0);
+ * av_opt_set_int(swr, "out_channel_layout", AV_CH_LAYOUT_STEREO,  0);
+ * av_opt_set_int(swr, "in_sample_rate",     48000,                0);
+ * av_opt_set_int(swr, "out_sample_rate",    44100,                0);
+ * av_opt_set_sample_fmt(swr, "in_sample_fmt",  AV_SAMPLE_FMT_FLTP, 0);
+ * av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16,  0);
+ * @endcode
+ *
+ * Once all values have been set, it must be initialized with swr_init(). If
+ * you need to change the conversion parameters, you can change the parameters
+ * as described above, or by using swr_alloc_set_opts(), then call swr_init()
+ * again.
+ *
+ * The conversion itself is done by repeatedly calling swr_convert().
+ * Note that the samples may get buffered in swr if you provide insufficient
+ * output space or if sample rate conversion is done, which requires "future"
+ * samples. Samples that do not require future input can be retrieved at any
+ * time by using swr_convert() (in_count can be set to 0).
+ * At the end of conversion the resampling buffer can be flushed by calling
+ * swr_convert() with NULL in and 0 in_count.
+ *
+ * The delay between input and output, can at any time be found by using
+ * swr_get_delay().
+ *
+ * The following code demonstrates the conversion loop assuming the parameters
+ * from above and caller-defined functions get_input() and handle_output():
+ * @code
+ * uint8_t **input;
+ * int in_samples;
+ *
+ * while (get_input(&input, &in_samples)) {
+ *     uint8_t *output;
+ *     int out_samples = av_rescale_rnd(swr_get_delay(swr, 48000) +
+ *                                      in_samples, 44100, 48000, AV_ROUND_UP);
+ *     av_samples_alloc(&output, NULL, 2, out_samples,
+ *                      AV_SAMPLE_FMT_S16, 0);
+ *     out_samples = swr_convert(swr, &output, out_samples,
+ *                                      input, in_samples);
+ *     handle_output(output, out_samples);
+ *     av_freep(&output);
+ *  }
+ *  @endcode
+ *
+ * When the conversion is finished, the conversion
+ * context and everything associated with it must be freed with swr_free().
+ * There will be no memory leak if the data is not completely flushed before
+ * swr_free().
+ */
+
+#include <stdint.h>
+#include "lib/libavutil/samplefmt.h"
+
+#include "lib/libswresample/version.h"
+
+#if LIBSWRESAMPLE_VERSION_MAJOR < 1
+#define SWR_CH_MAX 32   ///< Maximum number of channels
+#endif
+
+#define SWR_FLAG_RESAMPLE 1 ///< Force resampling even if equal sample rate
+//TODO use int resample ?
+//long term TODO can we enable this dynamically?
+
+enum SwrDitherType {
+    SWR_DITHER_NONE = 0,
+    SWR_DITHER_RECTANGULAR,
+    SWR_DITHER_TRIANGULAR,
+    SWR_DITHER_TRIANGULAR_HIGHPASS,
+
+    SWR_DITHER_NS = 64,         ///< not part of API/ABI
+    SWR_DITHER_NS_LIPSHITZ,
+    SWR_DITHER_NS_F_WEIGHTED,
+    SWR_DITHER_NS_MODIFIED_E_WEIGHTED,
+    SWR_DITHER_NS_IMPROVED_E_WEIGHTED,
+    SWR_DITHER_NS_SHIBATA,
+    SWR_DITHER_NS_LOW_SHIBATA,
+    SWR_DITHER_NS_HIGH_SHIBATA,
+    SWR_DITHER_NB,              ///< not part of API/ABI
+};
+
+/** Resampling Engines */
+enum SwrEngine {
+    SWR_ENGINE_SWR,             /**< SW Resampler */
+    SWR_ENGINE_SOXR,            /**< SoX Resampler */
+    SWR_ENGINE_NB,              ///< not part of API/ABI
+};
+
+/** Resampling Filter Types */
+enum SwrFilterType {
+    SWR_FILTER_TYPE_CUBIC,              /**< Cubic */
+    SWR_FILTER_TYPE_BLACKMAN_NUTTALL,   /**< Blackman Nuttall Windowed Sinc */
+    SWR_FILTER_TYPE_KAISER,             /**< Kaiser Windowed Sinc */
+};
+
+typedef struct SwrContext SwrContext;
+
+/**
+ * Get the AVClass for swrContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *swr_get_class(void);
+
+/**
+ * Allocate SwrContext.
+ *
+ * If you use this function you will need to set the parameters (manually or
+ * with swr_alloc_set_opts()) before calling swr_init().
+ *
+ * @see swr_alloc_set_opts(), swr_init(), swr_free()
+ * @return NULL on error, allocated context otherwise
+ */
+struct SwrContext *swr_alloc(void);
+
+/**
+ * Initialize context after user parameters have been set.
+ *
+ * @return AVERROR error code in case of failure.
+ */
+int swr_init(struct SwrContext *s);
+
+/**
+ * Allocate SwrContext if needed and set/reset common parameters.
+ *
+ * This function does not require s to be allocated with swr_alloc(). On the
+ * other hand, swr_alloc() can use swr_alloc_set_opts() to set the parameters
+ * on the allocated context.
+ *
+ * @param s               Swr context, can be NULL
+ * @param out_ch_layout   output channel layout (AV_CH_LAYOUT_*)
+ * @param out_sample_fmt  output sample format (AV_SAMPLE_FMT_*).
+ * @param out_sample_rate output sample rate (frequency in Hz)
+ * @param in_ch_layout    input channel layout (AV_CH_LAYOUT_*)
+ * @param in_sample_fmt   input sample format (AV_SAMPLE_FMT_*).
+ * @param in_sample_rate  input sample rate (frequency in Hz)
+ * @param log_offset      logging level offset
+ * @param log_ctx         parent logging context, can be NULL
+ *
+ * @see swr_init(), swr_free()
+ * @return NULL on error, allocated context otherwise
+ */
+struct SwrContext *swr_alloc_set_opts(struct SwrContext *s,
+                                      int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate,
+                                      int64_t  in_ch_layout, enum AVSampleFormat  in_sample_fmt, int  in_sample_rate,
+                                      int log_offset, void *log_ctx);
+
+/**
+ * Free the given SwrContext and set the pointer to NULL.
+ */
+void swr_free(struct SwrContext **s);
+
+/**
+ * Convert audio.
+ *
+ * in and in_count can be set to 0 to flush the last few samples out at the
+ * end.
+ *
+ * If more input is provided than output space then the input will be buffered.
+ * You can avoid this buffering by providing more output space than input.
+ * Convertion will run directly without copying whenever possible.
+ *
+ * @param s         allocated Swr context, with parameters set
+ * @param out       output buffers, only the first one need be set in case of packed audio
+ * @param out_count amount of space available for output in samples per channel
+ * @param in        input buffers, only the first one need to be set in case of packed audio
+ * @param in_count  number of input samples available in one channel
+ *
+ * @return number of samples output per channel, negative value on error
+ */
+int swr_convert(struct SwrContext *s, uint8_t **out, int out_count,
+                                const uint8_t **in , int in_count);
+
+/**
+ * Convert the next timestamp from input to output
+ * timestamps are in 1/(in_sample_rate * out_sample_rate) units.
+ *
+ * @note There are 2 slightly differently behaving modes.
+ *       First is when automatic timestamp compensation is not used, (min_compensation >= FLT_MAX)
+ *              in this case timestamps will be passed through with delays compensated
+ *       Second is when automatic timestamp compensation is used, (min_compensation < FLT_MAX)
+ *              in this case the output timestamps will match output sample numbers
+ *
+ * @param pts   timestamp for the next input sample, INT64_MIN if unknown
+ * @return the output timestamp for the next output sample
+ */
+int64_t swr_next_pts(struct SwrContext *s, int64_t pts);
+
+/**
+ * Activate resampling compensation.
+ */
+int swr_set_compensation(struct SwrContext *s, int sample_delta, int compensation_distance);
+
+/**
+ * Set a customized input channel mapping.
+ *
+ * @param s           allocated Swr context, not yet initialized
+ * @param channel_map customized input channel mapping (array of channel
+ *                    indexes, -1 for a muted channel)
+ * @return AVERROR error code in case of failure.
+ */
+int swr_set_channel_mapping(struct SwrContext *s, const int *channel_map);
+
+/**
+ * Set a customized remix matrix.
+ *
+ * @param s       allocated Swr context, not yet initialized
+ * @param matrix  remix coefficients; matrix[i + stride * o] is
+ *                the weight of input channel i in output channel o
+ * @param stride  offset between lines of the matrix
+ * @return  AVERROR error code in case of failure.
+ */
+int swr_set_matrix(struct SwrContext *s, const double *matrix, int stride);
+
+/**
+ * Drops the specified number of output samples.
+ */
+int swr_drop_output(struct SwrContext *s, int count);
+
+/**
+ * Injects the specified number of silence samples.
+ */
+int swr_inject_silence(struct SwrContext *s, int count);
+
+/**
+ * Gets the delay the next input sample will experience relative to the next output sample.
+ *
+ * Swresample can buffer data if more input has been provided than available
+ * output space, also converting between sample rates needs a delay.
+ * This function returns the sum of all such delays.
+ * The exact delay is not necessarily an integer value in either input or
+ * output sample rate. Especially when downsampling by a large value, the
+ * output sample rate may be a poor choice to represent the delay, similarly
+ * for upsampling and the input sample rate.
+ *
+ * @param s     swr context
+ * @param base  timebase in which the returned delay will be
+ *              if its set to 1 the returned delay is in seconds
+ *              if its set to 1000 the returned delay is in milli seconds
+ *              if its set to the input sample rate then the returned delay is in input samples
+ *              if its set to the output sample rate then the returned delay is in output samples
+ *              an exact rounding free delay can be found by using LCM(in_sample_rate, out_sample_rate)
+ * @returns     the delay in 1/base units.
+ */
+int64_t swr_get_delay(struct SwrContext *s, int64_t base);
+
+/**
+ * Return the LIBSWRESAMPLE_VERSION_INT constant.
+ */
+unsigned swresample_version(void);
+
+/**
+ * Return the swr build-time configuration.
+ */
+const char *swresample_configuration(void);
+
+/**
+ * Return the swr license.
+ */
+const char *swresample_license(void);
+
+/**
+ * @}
+ */
+
+#endif /* SWRESAMPLE_SWRESAMPLE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libswresample/version.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,45 @@
+/*
+ * Version macros.
+ *
+ * This file is part of libswresample
+ *
+ * libswresample is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * libswresample 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with libswresample; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef SWR_VERSION_H
+#define SWR_VERSION_H
+
+/**
+ * @file
+ * Libswresample version macros
+ */
+
+#include "lib/libavutil/avutil.h"
+
+#define LIBSWRESAMPLE_VERSION_MAJOR 0
+#define LIBSWRESAMPLE_VERSION_MINOR 17
+#define LIBSWRESAMPLE_VERSION_MICRO 102
+
+#define LIBSWRESAMPLE_VERSION_INT  AV_VERSION_INT(LIBSWRESAMPLE_VERSION_MAJOR, \
+                                                  LIBSWRESAMPLE_VERSION_MINOR, \
+                                                  LIBSWRESAMPLE_VERSION_MICRO)
+#define LIBSWRESAMPLE_VERSION      AV_VERSION(LIBSWRESAMPLE_VERSION_MAJOR, \
+                                              LIBSWRESAMPLE_VERSION_MINOR, \
+                                              LIBSWRESAMPLE_VERSION_MICRO)
+#define LIBSWRESAMPLE_BUILD        LIBSWRESAMPLE_VERSION_INT
+
+#define LIBSWRESAMPLE_IDENT        "SwR" AV_STRINGIFY(LIBSWRESAMPLE_VERSION)
+
+#endif /* SWR_VERSION_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libswscale/swscale.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,362 @@
+/*
+ * Copyright (C) 2001-2011 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef SWSCALE_SWSCALE_H
+#define SWSCALE_SWSCALE_H
+
+/**
+ * @file
+ * @ingroup lsws
+ * external API header
+ */
+
+/**
+ * @defgroup lsws Libswscale
+ * @{
+ */
+
+#include <stdint.h>
+
+#include "../libavutil/avutil.h"
+#include "../libavutil/log.h"
+#include "../libavutil/pixfmt.h"
+#include "version.h"
+
+/**
+ * Return the LIBSWSCALE_VERSION_INT constant.
+ */
+unsigned swscale_version(void);
+
+/**
+ * Return the libswscale build-time configuration.
+ */
+const char *swscale_configuration(void);
+
+/**
+ * Return the libswscale license.
+ */
+const char *swscale_license(void);
+
+/* values for the flags, the stuff on the command line is different */
+#define SWS_FAST_BILINEAR     1
+#define SWS_BILINEAR          2
+#define SWS_BICUBIC           4
+#define SWS_X                 8
+#define SWS_POINT          0x10
+#define SWS_AREA           0x20
+#define SWS_BICUBLIN       0x40
+#define SWS_GAUSS          0x80
+#define SWS_SINC          0x100
+#define SWS_LANCZOS       0x200
+#define SWS_SPLINE        0x400
+
+#define SWS_SRC_V_CHR_DROP_MASK     0x30000
+#define SWS_SRC_V_CHR_DROP_SHIFT    16
+
+#define SWS_PARAM_DEFAULT           123456
+
+#define SWS_PRINT_INFO              0x1000
+
+//the following 3 flags are not completely implemented
+//internal chrominace subsampling info
+#define SWS_FULL_CHR_H_INT    0x2000
+//input subsampling info
+#define SWS_FULL_CHR_H_INP    0x4000
+#define SWS_DIRECT_BGR        0x8000
+#define SWS_ACCURATE_RND      0x40000
+#define SWS_BITEXACT          0x80000
+#define SWS_ERROR_DIFFUSION  0x800000
+
+#if FF_API_SWS_CPU_CAPS
+/**
+ * CPU caps are autodetected now, those flags
+ * are only provided for API compatibility.
+ */
+#define SWS_CPU_CAPS_MMX      0x80000000
+#define SWS_CPU_CAPS_MMXEXT   0x20000000
+#define SWS_CPU_CAPS_MMX2     0x20000000
+#define SWS_CPU_CAPS_3DNOW    0x40000000
+#define SWS_CPU_CAPS_ALTIVEC  0x10000000
+#define SWS_CPU_CAPS_BFIN     0x01000000
+#define SWS_CPU_CAPS_SSE2     0x02000000
+#endif
+
+#define SWS_MAX_REDUCE_CUTOFF 0.002
+
+#define SWS_CS_ITU709         1
+#define SWS_CS_FCC            4
+#define SWS_CS_ITU601         5
+#define SWS_CS_ITU624         5
+#define SWS_CS_SMPTE170M      5
+#define SWS_CS_SMPTE240M      7
+#define SWS_CS_DEFAULT        5
+
+/**
+ * Return a pointer to yuv<->rgb coefficients for the given colorspace
+ * suitable for sws_setColorspaceDetails().
+ *
+ * @param colorspace One of the SWS_CS_* macros. If invalid,
+ * SWS_CS_DEFAULT is used.
+ */
+const int *sws_getCoefficients(int colorspace);
+
+// when used for filters they must have an odd number of elements
+// coeffs cannot be shared between vectors
+typedef struct SwsVector {
+    double *coeff;              ///< pointer to the list of coefficients
+    int length;                 ///< number of coefficients in the vector
+} SwsVector;
+
+// vectors can be shared
+typedef struct SwsFilter {
+    SwsVector *lumH;
+    SwsVector *lumV;
+    SwsVector *chrH;
+    SwsVector *chrV;
+} SwsFilter;
+
+struct SwsContext;
+
+/**
+ * Return a positive value if pix_fmt is a supported input format, 0
+ * otherwise.
+ */
+int sws_isSupportedInput(enum AVPixelFormat pix_fmt);
+
+/**
+ * Return a positive value if pix_fmt is a supported output format, 0
+ * otherwise.
+ */
+int sws_isSupportedOutput(enum AVPixelFormat pix_fmt);
+
+/**
+ * @param[in]  pix_fmt the pixel format
+ * @return a positive value if an endianness conversion for pix_fmt is
+ * supported, 0 otherwise.
+ */
+int sws_isSupportedEndiannessConversion(enum AVPixelFormat pix_fmt);
+
+/**
+ * Allocate an empty SwsContext. This must be filled and passed to
+ * sws_init_context(). For filling see AVOptions, options.c and
+ * sws_setColorspaceDetails().
+ */
+struct SwsContext *sws_alloc_context(void);
+
+/**
+ * Initialize the swscaler context sws_context.
+ *
+ * @return zero or positive value on success, a negative value on
+ * error
+ */
+int sws_init_context(struct SwsContext *sws_context, SwsFilter *srcFilter, SwsFilter *dstFilter);
+
+/**
+ * Free the swscaler context swsContext.
+ * If swsContext is NULL, then does nothing.
+ */
+void sws_freeContext(struct SwsContext *swsContext);
+
+#if FF_API_SWS_GETCONTEXT
+/**
+ * Allocate and return an SwsContext. You need it to perform
+ * scaling/conversion operations using sws_scale().
+ *
+ * @param srcW the width of the source image
+ * @param srcH the height of the source image
+ * @param srcFormat the source image format
+ * @param dstW the width of the destination image
+ * @param dstH the height of the destination image
+ * @param dstFormat the destination image format
+ * @param flags specify which algorithm and options to use for rescaling
+ * @return a pointer to an allocated context, or NULL in case of error
+ * @note this function is to be removed after a saner alternative is
+ *       written
+ * @deprecated Use sws_getCachedContext() instead.
+ */
+struct SwsContext *sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat,
+                                  int dstW, int dstH, enum AVPixelFormat dstFormat,
+                                  int flags, SwsFilter *srcFilter,
+                                  SwsFilter *dstFilter, const double *param);
+#endif
+
+/**
+ * Scale the image slice in srcSlice and put the resulting scaled
+ * slice in the image in dst. A slice is a sequence of consecutive
+ * rows in an image.
+ *
+ * Slices have to be provided in sequential order, either in
+ * top-bottom or bottom-top order. If slices are provided in
+ * non-sequential order the behavior of the function is undefined.
+ *
+ * @param c         the scaling context previously created with
+ *                  sws_getContext()
+ * @param srcSlice  the array containing the pointers to the planes of
+ *                  the source slice
+ * @param srcStride the array containing the strides for each plane of
+ *                  the source image
+ * @param srcSliceY the position in the source image of the slice to
+ *                  process, that is the number (counted starting from
+ *                  zero) in the image of the first row of the slice
+ * @param srcSliceH the height of the source slice, that is the number
+ *                  of rows in the slice
+ * @param dst       the array containing the pointers to the planes of
+ *                  the destination image
+ * @param dstStride the array containing the strides for each plane of
+ *                  the destination image
+ * @return          the height of the output slice
+ */
+int sws_scale(struct SwsContext *c, const uint8_t *const srcSlice[],
+              const int srcStride[], int srcSliceY, int srcSliceH,
+              uint8_t *const dst[], const int dstStride[]);
+
+/**
+ * @param dstRange flag indicating the while-black range of the output (1=jpeg / 0=mpeg)
+ * @param srcRange flag indicating the while-black range of the input (1=jpeg / 0=mpeg)
+ * @param table the yuv2rgb coefficients describing the output yuv space, normally ff_yuv2rgb_coeffs[x]
+ * @param inv_table the yuv2rgb coefficients describing the input yuv space, normally ff_yuv2rgb_coeffs[x]
+ * @param brightness 16.16 fixed point brightness correction
+ * @param contrast 16.16 fixed point contrast correction
+ * @param saturation 16.16 fixed point saturation correction
+ * @return -1 if not supported
+ */
+int sws_setColorspaceDetails(struct SwsContext *c, const int inv_table[4],
+                             int srcRange, const int table[4], int dstRange,
+                             int brightness, int contrast, int saturation);
+
+/**
+ * @return -1 if not supported
+ */
+int sws_getColorspaceDetails(struct SwsContext *c, int **inv_table,
+                             int *srcRange, int **table, int *dstRange,
+                             int *brightness, int *contrast, int *saturation);
+
+/**
+ * Allocate and return an uninitialized vector with length coefficients.
+ */
+SwsVector *sws_allocVec(int length);
+
+/**
+ * Return a normalized Gaussian curve used to filter stuff
+ * quality = 3 is high quality, lower is lower quality.
+ */
+SwsVector *sws_getGaussianVec(double variance, double quality);
+
+/**
+ * Allocate and return a vector with length coefficients, all
+ * with the same value c.
+ */
+SwsVector *sws_getConstVec(double c, int length);
+
+/**
+ * Allocate and return a vector with just one coefficient, with
+ * value 1.0.
+ */
+SwsVector *sws_getIdentityVec(void);
+
+/**
+ * Scale all the coefficients of a by the scalar value.
+ */
+void sws_scaleVec(SwsVector *a, double scalar);
+
+/**
+ * Scale all the coefficients of a so that their sum equals height.
+ */
+void sws_normalizeVec(SwsVector *a, double height);
+void sws_convVec(SwsVector *a, SwsVector *b);
+void sws_addVec(SwsVector *a, SwsVector *b);
+void sws_subVec(SwsVector *a, SwsVector *b);
+void sws_shiftVec(SwsVector *a, int shift);
+
+/**
+ * Allocate and return a clone of the vector a, that is a vector
+ * with the same coefficients as a.
+ */
+SwsVector *sws_cloneVec(SwsVector *a);
+
+/**
+ * Print with av_log() a textual representation of the vector a
+ * if log_level <= av_log_level.
+ */
+void sws_printVec2(SwsVector *a, AVClass *log_ctx, int log_level);
+
+void sws_freeVec(SwsVector *a);
+
+SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur,
+                                float lumaSharpen, float chromaSharpen,
+                                float chromaHShift, float chromaVShift,
+                                int verbose);
+void sws_freeFilter(SwsFilter *filter);
+
+/**
+ * Check if context can be reused, otherwise reallocate a new one.
+ *
+ * If context is NULL, just calls sws_getContext() to get a new
+ * context. Otherwise, checks if the parameters are the ones already
+ * saved in context. If that is the case, returns the current
+ * context. Otherwise, frees context and gets a new context with
+ * the new parameters.
+ *
+ * Be warned that srcFilter and dstFilter are not checked, they
+ * are assumed to remain the same.
+ */
+struct SwsContext *sws_getCachedContext(struct SwsContext *context,
+                                        int srcW, int srcH, enum AVPixelFormat srcFormat,
+                                        int dstW, int dstH, enum AVPixelFormat dstFormat,
+                                        int flags, SwsFilter *srcFilter,
+                                        SwsFilter *dstFilter, const double *param);
+
+/**
+ * Convert an 8-bit paletted frame into a frame with a color depth of 32 bits.
+ *
+ * The output frame will have the same packed format as the palette.
+ *
+ * @param src        source frame buffer
+ * @param dst        destination frame buffer
+ * @param num_pixels number of pixels to convert
+ * @param palette    array with [256] entries, which must match color arrangement (RGB or BGR) of src
+ */
+void sws_convertPalette8ToPacked32(const uint8_t *src, uint8_t *dst, int num_pixels, const uint8_t *palette);
+
+/**
+ * Convert an 8-bit paletted frame into a frame with a color depth of 24 bits.
+ *
+ * With the palette format "ABCD", the destination frame ends up with the format "ABC".
+ *
+ * @param src        source frame buffer
+ * @param dst        destination frame buffer
+ * @param num_pixels number of pixels to convert
+ * @param palette    array with [256] entries, which must match color arrangement (RGB or BGR) of src
+ */
+void sws_convertPalette8ToPacked24(const uint8_t *src, uint8_t *dst, int num_pixels, const uint8_t *palette);
+
+/**
+ * Get the AVClass for swsContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *sws_get_class(void);
+
+/**
+ * @}
+ */
+
+#endif /* SWSCALE_SWSCALE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/libswscale/version.h	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,59 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef SWSCALE_VERSION_H
+#define SWSCALE_VERSION_H
+
+/**
+ * @file
+ * swscale version macros
+ */
+
+#include "../libavutil/avutil.h"
+
+#define LIBSWSCALE_VERSION_MAJOR 2
+#define LIBSWSCALE_VERSION_MINOR 3
+#define LIBSWSCALE_VERSION_MICRO 100
+
+#define LIBSWSCALE_VERSION_INT  AV_VERSION_INT(LIBSWSCALE_VERSION_MAJOR, \
+                                               LIBSWSCALE_VERSION_MINOR, \
+                                               LIBSWSCALE_VERSION_MICRO)
+#define LIBSWSCALE_VERSION      AV_VERSION(LIBSWSCALE_VERSION_MAJOR, \
+                                           LIBSWSCALE_VERSION_MINOR, \
+                                           LIBSWSCALE_VERSION_MICRO)
+#define LIBSWSCALE_BUILD        LIBSWSCALE_VERSION_INT
+
+#define LIBSWSCALE_IDENT        "SwS" AV_STRINGIFY(LIBSWSCALE_VERSION)
+
+/**
+ * FF_API_* defines may be placed below to indicate public API that will be
+ * dropped at a future version bump. The defines themselves are not part of
+ * the public API and may change, break or disappear at any time.
+ */
+
+#ifndef FF_API_SWS_GETCONTEXT
+#define FF_API_SWS_GETCONTEXT  (LIBSWSCALE_VERSION_MAJOR < 3)
+#endif
+#ifndef FF_API_SWS_CPU_CAPS
+#define FF_API_SWS_CPU_CAPS    (LIBSWSCALE_VERSION_MAJOR < 3)
+#endif
+#ifndef FF_API_SWS_FORMAT_NAME
+#define FF_API_SWS_FORMAT_NAME  (LIBSWSCALE_VERSION_MAJOR < 3)
+#endif
+
+#endif /* SWSCALE_VERSION_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/swig/swigwin-2.0.11/UIControlModule.swig	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,6 @@
+%module UIControl
+%{
+#include "UIControl.h"
+%}
+
+%include "../../../NewUI/Core/UIControl.h"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lib/swig/swigwin-2.0.11/UIControlModule_wrap.cxx	Thu Jan 02 09:11:28 2014 +0600
@@ -0,0 +1,2523 @@
+/* ----------------------------------------------------------------------------
+ * This file was automatically generated by SWIG (http://www.swig.org).
+ * Version 2.0.11
+ *
+ * This file is not intended to be easily readable and contains a number of
+ * coding conventions designed to improve portability and efficiency. Do not make
+ * changes to this file unless you know what you are doing--modify the SWIG
+ * interface file instead.
+ * ----------------------------------------------------------------------------- */
+
+#define SWIGLUA
+#define SWIG_LUA_TARGET SWIG_LUA_FLAVOR_LUA
+#define SWIG_LUA_MODULE_GLOBAL
+
+
+#ifdef __cplusplus
+/* SwigValueWrapper is described in swig.swg */
+template<typename T> class SwigValueWrapper {
+  struct SwigMovePointer {
+    T *ptr;
+    SwigMovePointer(T *p) : ptr(p) { }
+    ~SwigMovePointer() { delete ptr; }
+    SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; }
+  } pointer;
+  SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
+  SwigValueWrapper(const SwigValueWrapper<T>& rhs);
+public:
+  SwigValueWrapper() : pointer(0) { }
+  SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }
+  operator T&() const { return *pointer.ptr; }
+  T *operator&() { return pointer.ptr; }
+};
+
+template <typename T> T SwigValueInit() {
+  return T();
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ *  This section contains generic SWIG labels for method/variable
+ *  declarations/attributes, and other compiler dependent labels.
+ * ----------------------------------------------------------------------------- */
+
+/* template workaround for compilers that cannot correctly implement the C++ standard */
+#ifndef SWIGTEMPLATEDISAMBIGUATOR
+# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# elif defined(__HP_aCC)
+/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
+/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# else
+#  define SWIGTEMPLATEDISAMBIGUATOR
+# endif
+#endif
+
+/* inline attribute */
+#ifndef SWIGINLINE
+# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
+#   define SWIGINLINE inline
+# else
+#   define SWIGINLINE
+# endif
+#endif
+
+/* attribute recognised by some compilers to avoid 'unused' warnings */
+#ifndef SWIGUNUSED
+# if defined(__GNUC__)
+#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+#     define SWIGUNUSED __attribute__ ((__unused__))
+#   else
+#     define SWIGUNUSED
+#   endif
+# elif defined(__ICC)
+#   define SWIGUNUSED __attribute__ ((__unused__))
+# else
+#   define SWIGUNUSED
+# endif
+#endif
+
+#ifndef SWIG_MSC_UNSUPPRESS_4505
+# if defined(_MSC_VER)
+#   pragma warning(disable : 4505) /* unreferenced local function has been removed */
+# endif
+#endif
+
+#ifndef SWIGUNUSEDPARM
+# ifdef __cplusplus
+#   define SWIGUNUSEDPARM(p)
+# else
+#   define SWIGUNUSEDPARM(p) p SWIGUNUSED
+# endif
+#endif
+
+/* internal SWIG method */
+#ifndef SWIGINTERN
+# define SWIGINTERN static SWIGUNUSED
+#endif
+
+/* internal inline SWIG method */
+#ifndef SWIGINTERNINLINE
+# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
+#endif
+
+/* exporting methods */
+#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+#  ifndef GCC_HASCLASSVISIBILITY
+#    define GCC_HASCLASSVISIBILITY
+#  endif
+#endif
+
+#ifndef SWIGEXPORT
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   if defined(STATIC_LINKED)
+#     define SWIGEXPORT
+#   else
+#     define SWIGEXPORT __declspec(dllexport)
+#   endif
+# else
+#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
+#     define SWIGEXPORT __attribute__ ((visibility("default")))
+#   else
+#     define SWIGEXPORT
+#   endif
+# endif
+#endif
+
+/* calling conventions for Windows */
+#ifndef SWIGSTDCALL
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   define SWIGSTDCALL __stdcall
+# else
+#   define SWIGSTDCALL
+# endif
+#endif
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
+#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
+# define _SCL_SECURE_NO_DEPRECATE
+#endif
+
+
+/* -----------------------------------------------------------------------------
+ * swigrun.swg
+ *
+ * This file contains generic C API SWIG runtime support for pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+
+/* This should only be incremented when either the layout of swig_type_info changes,
+   or for whatever reason, the runtime changes incompatibly */
+#define SWIG_RUNTIME_VERSION "4"
+
+/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
+#ifdef SWIG_TYPE_TABLE
+# define SWIG_QUOTE_STRING(x) #x
+# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
+# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
+#else
+# define SWIG_TYPE_TABLE_NAME
+#endif
+
+/*
+  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
+  creating a static or dynamic library from the SWIG runtime code.
+  In 99.9% of the cases, SWIG just needs to declare them as 'static'.
+
+  But only do this if strictly necessary, ie, if you have problems
+  with your compiler or suchlike.
+*/
+
+#ifndef SWIGRUNTIME
+# define SWIGRUNTIME SWIGINTERN
+#endif
+
+#ifndef SWIGRUNTIMEINLINE
+# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
+#endif
+
+/*  Generic buffer size */
+#ifndef SWIG_BUFFER_SIZE
+# define SWIG_BUFFER_SIZE 1024
+#endif
+
+/* Flags for pointer conversions */
+#define SWIG_POINTER_DISOWN        0x1
+#define SWIG_CAST_NEW_MEMORY       0x2
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_OWN           0x1
+
+
+/*
+   Flags/methods for returning states.
+
+   The SWIG conversion methods, as ConvertPtr, return an integer
+   that tells if the conversion was successful or not. And if not,
+   an error code can be returned (see swigerrors.swg for the codes).
+
+   Use the following macros/flags to set or process the returning
+   states.
+
+   In old versions of SWIG, code such as the following was usually written:
+
+     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
+       // success code
+     } else {
+       //fail code
+     }
+
+   Now you can be more explicit:
+
+    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+    } else {
+      // fail code
+    }
+
+   which is the same really, but now you can also do
+
+    Type *ptr;
+    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+      if (SWIG_IsNewObj(res) {
+        ...
+	delete *ptr;
+      } else {
+        ...
+      }
+    } else {
+      // fail code
+    }
+
+   I.e., now SWIG_ConvertPtr can return new objects and you can
+   identify the case and take care of the deallocation. Of course that
+   also requires SWIG_ConvertPtr to return new result values, such as
+
+      int SWIG_ConvertPtr(obj, ptr,...) {
+        if (<obj is ok>) {
+          if (<need new object>) {
+            *ptr = <ptr to new allocated object>;
+            return SWIG_NEWOBJ;
+          } else {
+            *ptr = <ptr to old object>;
+            return SWIG_OLDOBJ;
+          }
+        } else {
+          return SWIG_BADOBJ;
+        }
+      }
+
+   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
+   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
+   SWIG errors code.
+
+   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
+   allows to return the 'cast rank', for example, if you have this
+
+       int food(double)
+       int fooi(int);
+
+   and you call
+
+      food(1)   // cast rank '1'  (1 -> 1.0)
+      fooi(1)   // cast rank '0'
+
+   just use the SWIG_AddCast()/SWIG_CheckState()
+*/
+
+#define SWIG_OK                    (0)
+#define SWIG_ERROR                 (-1)
+#define SWIG_IsOK(r)               (r >= 0)
+#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)
+
+/* The CastRankLimit says how many bits are used for the cast rank */
+#define SWIG_CASTRANKLIMIT         (1 << 8)
+/* The NewMask denotes the object was created (using new/malloc) */
+#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)
+/* The TmpMask is for in/out typemaps that use temporal objects */
+#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)
+/* Simple returning values */
+#define SWIG_BADOBJ                (SWIG_ERROR)
+#define SWIG_OLDOBJ                (SWIG_OK)
+#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)
+#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)
+/* Check, add and del mask methods */
+#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
+#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
+#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
+#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
+#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
+#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
+
+/* Cast-Rank Mode */
+#if defined(SWIG_CASTRANK_MODE)
+#  ifndef SWIG_TypeRank
+#    define SWIG_TypeRank             unsigned long
+#  endif
+#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */
+#    define SWIG_MAXCASTRANK          (2)
+#  endif
+#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)
+#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)
+SWIGINTERNINLINE int SWIG_AddCast(int r) {
+  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
+}
+SWIGINTERNINLINE int SWIG_CheckState(int r) {
+  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0;
+}
+#else /* no cast-rank mode */
+#  define SWIG_AddCast(r) (r)
+#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
+#endif
+
+
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void *(*swig_converter_func)(void *, int *);
+typedef struct swig_type_info *(*swig_dycast_func)(void **);
+
+/* Structure to store information on one type */
+typedef struct swig_type_info {
+  const char             *name;			/* mangled name of this type */
+  const char             *str;			/* human readable name of this type */
+  swig_dycast_func        dcast;		/* dynamic cast function down a hierarchy */
+  struct swig_cast_info  *cast;			/* linked list of types that can cast into this type */
+  void                   *clientdata;		/* language specific type data */
+  int                    owndata;		/* flag if the structure owns the clientdata */
+} swig_type_info;
+
+/* Structure to store a type and conversion function used for casting */
+typedef struct swig_cast_info {
+  swig_type_info         *type;			/* pointer to type that is equivalent to this type */
+  swig_converter_func     converter;		/* function to cast the void pointers */
+  struct swig_cast_info  *next;			/* pointer to next cast in linked list */
+  struct swig_cast_info  *prev;			/* pointer to the previous cast */
+} swig_cast_info;
+
+/* Structure used to store module information
+ * Each module generates one structure like this, and the runtime collects
+ * all of these structures and stores them in a circularly linked list.*/
+typedef struct swig_module_info {
+  swig_type_info         **types;		/* Array of pointers to swig_type_info structures that are in this module */
+  size_t                 size;		        /* Number of types in this module */
+  struct swig_module_info *next;		/* Pointer to next element in circularly linked list */
+  swig_type_info         **type_initial;	/* Array of initially generated type structures */
+  swig_cast_info         **cast_initial;	/* Array of initially generated casting structures */
+  void                    *clientdata;		/* Language specific module data */
+} swig_module_info;
+
+/*
+  Compare two type names skipping the space characters, therefore
+  "char*" == "char *" and "Class<int>" == "Class<int >", etc.
+
+  Return 0 when the two name types are equivalent, as in
+  strncmp, but skipping ' '.
+*/
+SWIGRUNTIME int
+SWIG_TypeNameComp(const char *f1, const char *l1,
+		  const char *f2, const char *l2) {
+  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
+    while ((*f1 == ' ') && (f1 != l1)) ++f1;
+    while ((*f2 == ' ') && (f2 != l2)) ++f2;
+    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;
+  }
+  return (int)((l1 - f1) - (l2 - f2));
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if equal, -1 if nb < tb, 1 if nb > tb
+*/
+SWIGRUNTIME int
+SWIG_TypeCmp(const char *nb, const char *tb) {
+  int equiv = 1;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (equiv != 0 && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = SWIG_TypeNameComp(nb, ne, tb, te);
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if not equal, 1 if equal
+*/
+SWIGRUNTIME int
+SWIG_TypeEquiv(const char *nb, const char *tb) {
+  return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0;
+}
+
+/*
+  Check the typename
+*/
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheck(const char *c, swig_type_info *ty) {
+  if (ty) {
+    swig_cast_info *iter = ty->cast;
+    while (iter) {
+      if (strcmp(iter->type->name, c) == 0) {
+        if (iter == ty->cast)
+          return iter;
+        /* Move iter to the top of the linked list */
+        iter->prev->next = iter->next;
+        if (iter->next)
+          iter->next->prev = iter->prev;
+        iter->next = ty->cast;
+        iter->prev = 0;
+        if (ty->cast) ty->cast->prev = iter;
+        ty->cast = iter;
+        return iter;
+      }
+      iter = iter->next;
+    }
+  }
+  return 0;
+}
+
+/*
+  Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison
+*/
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) {
+  if (ty) {
+    swig_cast_info *iter = ty->cast;
+    while (iter) {
+      if (iter->type == from) {
+        if (iter == ty->cast)
+          return iter;
+        /* Move iter to the top of the linked list */
+        iter->prev->next = iter->next;
+        if (iter->next)
+          iter->next->prev = iter->prev;
+        iter->next = ty->cast;
+        iter->prev = 0;
+        if (ty->cast) ty->cast->prev = iter;
+        ty->cast = iter;
+        return iter;
+      }
+      iter = iter->next;
+    }
+  }
+  return 0;
+}
+
+/*
+  Cast a pointer up an inheritance hierarchy
+*/
+SWIGRUNTIMEINLINE void *
+SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {
+  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);
+}
+
+/*
+   Dynamic pointer casting. Down an inheritance hierarchy
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
+  swig_type_info *lastty = ty;
+  if (!ty || !ty->dcast) return ty;
+  while (ty && (ty->dcast)) {
+    ty = (*ty->dcast)(ptr);
+    if (ty) lastty = ty;
+  }
+  return lastty;
+}
+
+/*
+  Return the name associated with this type
+*/
+SWIGRUNTIMEINLINE const char *
+SWIG_TypeName(const swig_type_info *ty) {
+  return ty->name;
+}
+
+/*
+  Return the pretty name associated with this type,
+  that is an unmangled type name in a form presentable to the user.
+*/
+SWIGRUNTIME const char *
+SWIG_TypePrettyName(const swig_type_info *type) {
+  /* The "str" field contains the equivalent pretty names of the
+     type, separated by vertical-bar characters.  We choose
+     to print the last name, as it is often (?) the most
+     specific. */
+  if (!type) return NULL;
+  if (type->str != NULL) {
+    const char *last_name = type->str;
+    const char *s;
+    for (s = type->str; *s; s++)
+      if (*s == '|') last_name = s+1;
+    return last_name;
+  }
+  else
+    return type->name;
+}
+
+/*
+   Set the clientdata field for a type
+*/
+SWIGRUNTIME void
+SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
+  swig_cast_info *cast = ti->cast;
+  /* if (ti->clientdata == clientdata) return; */
+  ti->clientdata = clientdata;
+
+  while (cast) {
+    if (!cast->converter) {
+      swig_type_info *tc = cast->type;
+      if (!tc->clientdata) {
+	SWIG_TypeClientData(tc, clientdata);
+      }
+    }
+    cast = cast->next;
+  }
+}
+SWIGRUNTIME void
+SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
+  SWIG_TypeClientData(ti, clientdata);
+  ti->owndata = 1;
+}
+
+/*
+  Search for a swig_type_info structure only by mangled name
+  Search is a O(log #types)
+
+  We start searching at module start, and finish searching when start == end.
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_MangledTypeQueryModule(swig_module_info *start,
+                            swig_module_info *end,
+		            const char *name) {
+  swig_module_info *iter = start;
+  do {
+    if (iter->size) {
+      register size_t l = 0;
+      register size_t r = iter->size - 1;
+      do {
+	/* since l+r >= 0, we can (>> 1) instead (/ 2) */
+	register size_t i = (l + r) >> 1;
+	const char *iname = iter->types[i]->name;
+	if (iname) {
+	  register int compare = strcmp(name, iname);
+	  if (compare == 0) {
+	    return iter->types[i];
+	  } else if (compare < 0) {
+	    if (i) {
+	      r = i - 1;
+	    } else {
+	      break;
+	    }
+	  } else if (compare > 0) {
+	    l = i + 1;
+	  }
+	} else {
+	  break; /* should never happen */
+	}
+      } while (l <= r);
+    }
+    iter = iter->next;
+  } while (iter != end);
+  return 0;
+}
+
+/*
+  Search for a swig_type_info structure for either a mangled name or a human readable name.
+  It first searches the mangled names of the types, which is a O(log #types)
+  If a type is not found it then searches the human readable names, which is O(#types).
+
+  We start searching at module start, and finish searching when start == end.
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeQueryModule(swig_module_info *start,
+                     swig_module_info *end,
+		     const char *name) {
+  /* STEP 1: Search the name field using binary search */
+  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
+  if (ret) {
+    return ret;
+  } else {
+    /* STEP 2: If the type hasn't been found, do a complete search
+       of the str field (the human readable name) */
+    swig_module_info *iter = start;
+    do {
+      register size_t i = 0;
+      for (; i < iter->size; ++i) {
+	if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
+	  return iter->types[i];
+      }
+      iter = iter->next;
+    } while (iter != end);
+  }
+
+  /* neither found a match */
+  return 0;
+}
+
+/*
+   Pack binary data into a string
+*/
+SWIGRUNTIME char *
+SWIG_PackData(char *c, void *ptr, size_t sz) {
+  static const char hex[17] = "0123456789abcdef";
+  register const unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu =  u + sz;
+  for (; u != eu; ++u) {
+    register unsigned char uu = *u;
+    *(c++) = hex[(uu & 0xf0) >> 4];
+    *(c++) = hex[uu & 0xf];
+  }
+  return c;
+}
+
+/*
+   Unpack binary data from a string
+*/
+SWIGRUNTIME const char *
+SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+  register unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu = u + sz;
+  for (; u != eu; ++u) {
+    register char d = *(c++);
+    register unsigned char uu;
+    if ((d >= '0') && (d <= '9'))
+      uu = ((d - '0') << 4);
+    else if ((d >= 'a') && (d <= 'f'))
+      uu = ((d - ('a'-10)) << 4);
+    else
+      return (char *) 0;
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu |= (d - '0');
+    else if ((d >= 'a') && (d <= 'f'))
+      uu |= (d - ('a'-10));
+    else
+      return (char *) 0;
+    *u = uu;
+  }
+  return c;
+}
+
+/*
+   Pack 'void *' into a string buffer.
+*/
+SWIGRUNTIME char *
+SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
+  char *r = buff;
+  if ((2*sizeof(void *) + 2) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,&ptr,sizeof(void *));
+  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
+  strcpy(r,name);
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      *ptr = (void *) 0;
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sizeof(void *));
+}
+
+SWIGRUNTIME char *
+SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
+  char *r = buff;
+  size_t lname = (name ? strlen(name) : 0);
+  if ((2*sz + 2 + lname) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  if (lname) {
+    strncpy(r,name,lname+1);
+  } else {
+    *r = 0;
+  }
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      memset(ptr,0,sz);
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sz);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * luarun.swg
+ *
+ * This file contains the runtime support for Lua modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+ 
+#include "lib/lua/lua.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//#include "lua.h"
+//#include "lauxlib.h"
+#include <stdlib.h>  /* for malloc */
+#include <assert.h>  /* for a few sanity tests */
+
+/* -----------------------------------------------------------------------------
+ * Lua flavors
+ * ----------------------------------------------------------------------------- */
+
+#define SWIG_LUA_FLAVOR_LUA 1
+#define SWIG_LUA_FLAVOR_ELUA 2
+#define SWIG_LUA_FLAVOR_ELUAC 3
+
+#if !defined(SWIG_LUA_TARGET)
+# error SWIG_LUA_TARGET not defined
+#endif
+
+#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)
+#  define SWIG_LUA_CONSTTAB_INT(B, C) LSTRKEY(B), LNUMVAL(C)
+#  define SWIG_LUA_CONSTTAB_FLOAT(B, C) LSTRKEY(B), LNUMVAL(C)
+#  define SWIG_LUA_CONSTTAB_STRING(B, C) LSTRKEY(B), LSTRVAL(C)
+#  define SWIG_LUA_CONSTTAB_CHAR(B, C) LSTRKEY(B), LNUMVAL(C)
+#else /* SWIG_LUA_FLAVOR_LUA */
+#  define SWIG_LUA_CONSTTAB_INT(B, C) SWIG_LUA_INT, (char *)B, (long)C, 0, 0, 0
+#  define SWIG_LUA_CONSTTAB_FLOAT(B, C) SWIG_LUA_FLOAT, (char *)B, 0, (double)C, 0, 0
+#  define SWIG_LUA_CONSTTAB_STRING(B, C) SWIG_LUA_STRING, (char *)B, 0, 0, (void *)C, 0
+#  define SWIG_LUA_CONSTTAB_CHAR(B, C) SWIG_LUA_CHAR, (char *)B, (long)C, 0, 0, 0
+#endif
+
+#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)
+#  define LRO_STRVAL(v) {{.p = (char *) v}, LUA_TSTRING}
+#  define LSTRVAL LRO_STRVAL
+#endif
+
+/* -----------------------------------------------------------------------------
+ * compatibility defines
+ * ----------------------------------------------------------------------------- */
+
+/* History of Lua C API length functions:  In Lua 5.0 (and before?)
+   there was "lua_strlen".  In Lua 5.1, this was renamed "lua_objlen",
+   but a compatibility define of "lua_strlen" was added.  In Lua 5.2,
+   this function was again renamed, to "lua_rawlen" (to emphasize that
+   it doesn't call the "__len" metamethod), and the compatibility
+   define of lua_strlen was removed.  All SWIG uses have been updated
+   to "lua_rawlen", and we add our own defines of that here for older
+   versions of Lua.  */
+#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501
+# define lua_rawlen lua_strlen
+#elif LUA_VERSION_NUM == 501
+# define lua_rawlen lua_objlen
+#endif
+
+
+/* lua_pushglobaltable is the recommended "future-proof" way to get
+   the global table for Lua 5.2 and later.  Here we define
+   lua_pushglobaltable ourselves for Lua versions before 5.2.  */
+#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
+# define lua_pushglobaltable(L) lua_pushvalue(L, LUA_GLOBALSINDEX)
+#endif
+
+
+/* --------------------------------------------------------------------------
+ * Helper functions for error handling
+ * -------------------------------------------------------------------------- */
+
+/* Push the string STR on the Lua stack, like lua_pushstring, but
+   prefixed with the the location of the innermost Lua call-point
+   (as formated by luaL_where).  */
+SWIGRUNTIME void
+SWIG_Lua_pusherrstring (lua_State *L, const char *str)
+{
+  luaL_where (L, 1);
+  lua_pushstring (L, str);
+  lua_concat (L, 2);
+}
+
+/* Push a formatted string generated from FMT and following args on
+   the Lua stack, like lua_pushfstring, but prefixed with the the
+   location of the innermost Lua call-point (as formated by luaL_where).  */
+SWIGRUNTIME void
+SWIG_Lua_pushferrstring (lua_State *L, const char *fmt, ...)
+{
+  va_list argp;
+  va_start(argp, fmt);
+  luaL_where(L, 1);
+  lua_pushvfstring(L, fmt, argp);
+  va_end(argp);
+  lua_concat(L, 2);
+}
+
+
+/* -----------------------------------------------------------------------------
+ * global swig types
+ * ----------------------------------------------------------------------------- */
+/* Constant table */
+#define SWIG_LUA_INT     1
+#define SWIG_LUA_FLOAT   2
+#define SWIG_LUA_STRING  3
+#define SWIG_LUA_POINTER 4
+#define SWIG_LUA_BINARY  5
+#define SWIG_LUA_CHAR    6
+
+/* Structure for variable linking table */
+typedef struct {
+  const char *name;
+  lua_CFunction get;
+  lua_CFunction set;
+} swig_lua_var_info;
+
+/* Constant information structure */
+typedef struct {
+    int type;
+    char *name;
+    long lvalue;
+    double dvalue;
+    void   *pvalue;
+    swig_type_info **ptype;
+} swig_lua_const_info;
+
+typedef struct {
+  const char     *name;
+  lua_CFunction   method;
+} swig_lua_method;
+
+typedef struct {
+  const char     *name;
+  lua_CFunction   getmethod;
+  lua_CFunction   setmethod;
+} swig_lua_attribute;
+
+// Can be used to create namespaces. Currently used to
+// wrap class static methods/variables/constants
+typedef struct {
+  const char            *name;
+  swig_lua_method       *ns_methods;
+  swig_lua_attribute    *ns_attributes;
+  swig_lua_const_info   *ns_constants;
+} swig_lua_namespace;
+
+typedef struct swig_lua_class {
+  const char    *name;
+  swig_type_info   **type;
+  lua_CFunction  constructor;
+  void    (*destructor)(void *);
+  swig_lua_method   *methods;
+  swig_lua_attribute     *attributes;
+  swig_lua_namespace    cls_static;
+  struct swig_lua_class **bases;
+  const char **base_names;
+} swig_lua_class;
+
+/* this is the struct for wrapping all pointers in SwigLua
+*/
+typedef struct {
+  swig_type_info   *type;
+  int     own;  /* 1 if owned & must be destroyed */
+  void        *ptr;
+} swig_lua_userdata;
+
+/* this is the struct for wrapping arbitrary packed binary data
+(currently it is only used for member function pointers)
+the data ordering is similar to swig_lua_userdata, but it is currently not possible
+to tell the two structures apart within SWIG, other than by looking at the type
+*/
+typedef struct {
+  swig_type_info   *type;
+  int     own;  /* 1 if owned & must be destroyed */
+  char data[1];       /* arbitary amount of data */    
+} swig_lua_rawdata;
+
+/* Common SWIG API */
+#define SWIG_NewPointerObj(L, ptr, type, owner)       SWIG_Lua_NewPointerObj(L, (void *)ptr, type, owner)
+#define SWIG_ConvertPtr(L,idx, ptr, type, flags)    SWIG_Lua_ConvertPtr(L,idx,ptr,type,flags)
+#define SWIG_MustGetPtr(L,idx, type,flags, argnum,fnname)  SWIG_Lua_MustGetPtr(L,idx, type,flags, argnum,fnname)
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(L, idx, ptr, sz, ty)       SWIG_Lua_ConvertPacked(L, idx, ptr, sz, ty)
+#define SWIG_NewMemberObj(L, ptr, sz, type)      SWIG_Lua_NewPackedObj(L, ptr, sz, type)
+
+/* Runtime API */
+#define SWIG_GetModule(clientdata) SWIG_Lua_GetModule((lua_State*)(clientdata))
+#define SWIG_SetModule(clientdata, pointer) SWIG_Lua_SetModule((lua_State*) (clientdata), pointer)
+#define SWIG_MODULE_CLIENTDATA_TYPE lua_State*
+
+/* Contract support */
+#define SWIG_contract_assert(expr, msg)  \
+  if (!(expr)) { SWIG_Lua_pusherrstring(L, (char *) msg); goto fail; } else
+
+
+/* helper #defines */
+#define SWIG_fail {goto fail;}
+#define SWIG_fail_arg(func_name,argnum,type) \
+  {SWIG_Lua_pushferrstring(L,"Error in %s (arg %d), expected '%s' got '%s'",\
+  func_name,argnum,type,SWIG_Lua_typename(L,argnum));\
+  goto fail;}
+#define SWIG_fail_ptr(func_name,argnum,type) \
+  SWIG_fail_arg(func_name,argnum,(type && type->str)?type->str:"void*")
+#define SWIG_check_num_args(func_name,a,b) \
+  if (lua_gettop(L)<a || lua_gettop(L)>b) \
+  {SWIG_Lua_pushferrstring(L,"Error in %s expected %d..%d args, got %d",func_name,a,b,lua_gettop(L));\
+  goto fail;}
+
+
+#define SWIG_Lua_get_table(L,n) \
+  (lua_pushstring(L, n), lua_rawget(L,-2))
+
+#define SWIG_Lua_add_function(L,n,f) \
+  (lua_pushstring(L, n), \
+      lua_pushcfunction(L, f), \
+      lua_rawset(L,-3))
+
+/* special helper for allowing 'nil' for usertypes */
+#define SWIG_isptrtype(L,I) (lua_isuserdata(L,I) || lua_isnil(L,I))
+
+#ifdef __cplusplus
+/* Special helper for member function pointers 
+it gets the address, casts it, then dereferences it */
+//#define SWIG_mem_fn_as_voidptr(a)  (*((char**)&(a)))
+#endif
+
+/* storing/access of swig_module_info */
+SWIGRUNTIME swig_module_info *
+SWIG_Lua_GetModule(lua_State* L) {
+  swig_module_info *ret = 0;
+  lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
+  lua_rawget(L,LUA_REGISTRYINDEX);
+  if (lua_islightuserdata(L,-1))
+    ret=(swig_module_info*)lua_touserdata(L,-1);
+  lua_pop(L,1);  /* tidy */
+  return ret;
+}
+
+SWIGRUNTIME void
+SWIG_Lua_SetModule(lua_State* L, swig_module_info *module) {
+  /* add this all into the Lua registry: */
+  lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME);
+  lua_pushlightuserdata(L,(void*)module);
+  lua_rawset(L,LUA_REGISTRYINDEX);
+}
+
+/* -----------------------------------------------------------------------------
+ * global variable support code: modules
+ * ----------------------------------------------------------------------------- */
+
+/* this function is called when trying to set an immutable.
+default action is to print an error.
+This can removed with a compile flag SWIGLUA_IGNORE_SET_IMMUTABLE */
+SWIGINTERN int SWIG_Lua_set_immutable(lua_State* L)
+{
+/*  there should be 1 param passed in: the new value */
+#ifndef SWIGLUA_IGNORE_SET_IMMUTABLE
+  lua_pop(L,1);  /* remove it */
+  luaL_error(L,"This variable is immutable");
+#endif
+    return 0;   /* should not return anything */
+}
+
+/* the module.get method used for getting linked data */
+SWIGINTERN int SWIG_Lua_module_get(lua_State* L)
+{
+/*  there should be 2 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+  printf("SWIG_Lua_module_get %p(%s) '%s'\n",
+   lua_topointer(L,1),lua_typename(L,lua_type(L,1)),
+   lua_tostring(L,2));
+*/
+  /* get the metatable */
+#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC))
+  assert(lua_isrotable(L,1)); /* just in case */
+#else
+  assert(lua_istable(L,1)); /* default Lua action */
+#endif
+  lua_getmetatable(L,1);  /* get the metatable */
+#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC))
+  assert(lua_isrotable(L,-1));  /* just in case */
+#else
+  assert(lua_istable(L,-1));
+#endif
+  SWIG_Lua_get_table(L,".get");  /* get the .get table */
+  lua_remove(L,3);  /* remove metatable */
+#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC))
+  if (lua_isrotable(L,-1))
+#else
+  if (lua_istable(L,-1))
+#endif
+  {
+    /* look for the key in the .get table */
+    lua_pushvalue(L,2);  /* key */
+    lua_rawget(L,-2);
+    lua_remove(L,3);  /* remove .get */
+    if (lua_iscfunction(L,-1))
+    {  /* found it so call the fn & return its value */
+      lua_call(L,0,1);
+      return 1;
+    }
+    lua_pop(L,1);  /* remove the top */
+  }
+  lua_pop(L,1);  /* remove the .get */
+  lua_pushnil(L);  /* return a nil */
+  return 1;
+}
+
+/* the module.set method used for setting linked data */
+SWIGINTERN int SWIG_Lua_module_set(lua_State* L)
+{
+/*  there should be 3 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+  (3) any for the new value
+*/
+  /* get the metatable */
+#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC))
+  assert(lua_isrotable(L,1));  /* just in case */
+#else
+  assert(lua_istable(L,1)); /* default Lua action */
+#endif
+  lua_getmetatable(L,1);  /* get the metatable */
+#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC))
+  assert(lua_isrotable(L,-1));  /* just in case */
+#else
+  assert(lua_istable(L,-1));
+#endif
+  SWIG_Lua_get_table(L,".set");  /* get the .set table */
+  lua_remove(L,4);  /* remove metatable */
+#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC))
+  if (lua_isrotable(L,-1))
+#else
+  if (lua_istable(L,-1))
+#endif
+  {
+    /* look for the key in the .set table */
+    lua_pushvalue(L,2);  /* key */
+    lua_rawget(L,-2);
+    lua_remove(L,4);  /* remove .set */
+    if (lua_iscfunction(L,-1))
+    {  /* found it so call the fn & return its value */
+      lua_pushvalue(L,3);  /* value */
+      lua_call(L,1,0);
+      return 0;
+    }
+#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) 
+    else {
+      return 0; // Exits stoically if an invalid key is initialized.
+    }
+#endif
+  }
+  lua_settop(L,3);  /* reset back to start */
+  /* we now have the table, key & new value, so just set directly */
+  lua_rawset(L,1);  /* add direct */
+  return 0;
+}
+
+#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC))
+/* registering a module in lua. Pushes the module table on the stack. */
+SWIGINTERN void  SWIG_Lua_module_begin(lua_State* L,const char* name)
+{
+  assert(lua_istable(L,-1));  /* just in case */
+  lua_pushstring(L,name);
+  lua_newtable(L);   /* the table */
+  /* add meta table */
+  lua_newtable(L);    /* the meta table */
+  SWIG_Lua_add_function(L,"__index",SWIG_Lua_module_get);
+  SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_module_set);
+  lua_pushstring(L,".get");
+  lua_newtable(L);    /* the .get table */
+  lua_rawset(L,-3);  /* add .get into metatable */
+  lua_pushstring(L,".set");
+  lua_newtable(L);    /* the .set table */
+  lua_rawset(L,-3);  /* add .set into metatable */
+  lua_setmetatable(L,-2);  /* sets meta table in module */
+#ifdef SWIG_LUA_MODULE_GLOBAL
+  /* If requested, install the module directly into the global namespace. */
+  lua_rawset(L,-3);        /* add module into parent */
+  SWIG_Lua_get_table(L,name);   /* get the table back out */
+#else
+  /* Do not install the module table as global name. The stack top has
+     the module table with the name below. We pop the top and replace
+     the name with it. */
+  lua_replace(L,-2);
+#endif
+}
+
+/* ending the register */
+SWIGINTERN void  SWIG_Lua_module_end(lua_State* L)
+{
+  lua_pop(L,1);       /* tidy stack (remove module) */
+}
+
+/* adding a linked variable to the module */
+SWIGINTERN void SWIG_Lua_module_add_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn)
+{
+  assert(lua_istable(L,-1));  /* just in case */
+  lua_getmetatable(L,-1);  /* get the metatable */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".get"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* should be a table: */
+  SWIG_Lua_add_function(L,name,getFn);
+  lua_pop(L,1);       /* tidy stack (remove table) */
+  if (setFn)  /* if there is a set fn */
+  {
+    SWIG_Lua_get_table(L,".set"); /* find the .set table */
+    assert(lua_istable(L,-1));  /* should be a table: */
+    SWIG_Lua_add_function(L,name,setFn);
+    lua_pop(L,1);       /* tidy stack (remove table) */
+  }
+  lua_pop(L,1);       /* tidy stack (remove meta) */
+}
+#endif
+
+/* adding a function module */
+SWIGINTERN void  SWIG_Lua_module_add_function(lua_State* L,const char* name,lua_CFunction fn)
+{
+  SWIG_Lua_add_function(L,name,fn);
+}
+
+/* -----------------------------------------------------------------------------
+ * global variable support code: namespaces
+ * ----------------------------------------------------------------------------- */
+
+SWIGINTERN int SWIG_Lua_namespace_get(lua_State* L)
+{
+/*  there should be 2 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+*/
+  assert(lua_istable(L,-2));  /* just in case */
+  lua_getmetatable(L,-2);
+  assert(lua_istable(L,-1));
+  SWIG_Lua_get_table(L,".get"); /* find the .get table */
+  assert(lua_istable(L,-1));
+  /* look for the key in the .get table */
+  lua_pushvalue(L,2);  /* key */
+  lua_rawget(L,-2);
+  lua_remove(L,-2); /* stack tidy, remove .get table */
+  if (lua_iscfunction(L,-1))
+  {  /* found it so call the fn & return its value */
+    lua_call(L,0,1);  /* 1 value in (userdata),1 out (result) */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  lua_pop(L,1);  /* remove whatever was there */
+  /* ok, so try the .fn table */
+  SWIG_Lua_get_table(L,".fn"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* just in case */
+  lua_pushvalue(L,2);  /* key */
+  lua_rawget(L,-2);  /* look for the fn */
+  lua_remove(L,-2); /* stack tidy, remove .fn table */
+  if (lua_isfunction(L,-1)) /* note: whether it's a C function or lua function */
+  {  /* found it so return the fn & let lua call it */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  lua_pop(L,1);  /* remove whatever was there */
+  return 0;
+}
+
+SWIGINTERN int SWIG_Lua_namespace_set(lua_State* L)
+{
+/*  there should be 3 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+  (3) any for the new value
+*/
+
+  assert(lua_istable(L,1));
+  lua_getmetatable(L,1);    /* get the meta table */
+  assert(lua_istable(L,-1));
+
+  SWIG_Lua_get_table(L,".set"); /* find the .set table */
+  if (lua_istable(L,-1))
+  {
+    /* look for the key in the .set table */
+    lua_pushvalue(L,2);  /* key */
+    lua_rawget(L,-2);
+    if (lua_iscfunction(L,-1))
+    {  /* found it so call the fn & return its value */
+      lua_pushvalue(L,3);  /* value */
+      lua_call(L,1,0);
+      return 0;
+    }
+    lua_pop(L,1);  /* remove the value */
+  }
+  lua_pop(L,1);  /* remove the value .set table */
+  return 0;
+}
+
+SWIGINTERN void SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]); // forward declaration
+SWIGINTERN void  SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn); // forward declaration
+
+/* helper function - register namespace methods and attributes into namespace */
+SWIGINTERN void SWIG_Lua_add_namespace_details(lua_State* L, swig_lua_namespace* ns)
+{
+  int i = 0;
+  assert(lua_istable(L,-1));
+  /* There must be table at the top of the stack */
+  SWIG_Lua_InstallConstants(L, ns->ns_constants);
+
+  lua_getmetatable(L,-1);
+
+  /* add fns */
+  for(i=0;ns->ns_attributes[i].name;i++){
+    SWIG_Lua_add_class_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod);
+  }
+
+  /* add methods to the metatable */
+  SWIG_Lua_get_table(L,".fn"); /* find the .fn table */
+  assert(lua_istable(L,-1));  /* just in case */
+  for(i=0;ns->ns_methods[i].name;i++){
+    SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].method);
+  }
+  lua_pop(L,1);
+
+  /* clear stack - remove metatble */
+  lua_pop(L,1);
+
+}
+
+/* helper function. creates namespace table and add it to module table */
+SWIGINTERN void SWIG_Lua_namespace_register(lua_State* L, swig_lua_namespace* ns)
+{
+  assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table */
+  lua_checkstack(L,5);
+  lua_pushstring(L, ns->name);
+  lua_newtable(L); /* namespace itself */
+  lua_newtable(L); /* metatable for namespace */
+
+  /* add a table called ".get" */
+  lua_pushstring(L,".get");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+  /* add a table called ".set" */
+  lua_pushstring(L,".set");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+  /* add a table called ".fn" */
+  lua_pushstring(L,".fn");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+
+  /* add accessor fns for using the .get,.set&.fn */
+  SWIG_Lua_add_function(L,"__index",SWIG_Lua_namespace_get);
+  SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_namespace_set);
+
+  lua_setmetatable(L,-2); /* set metatable */
+  lua_rawset(L,-3); /* add namespace to module table */
+}
+/* -----------------------------------------------------------------------------
+ * global variable support code: classes
+ * ----------------------------------------------------------------------------- */
+
+/* the class.get method, performs the lookup of class attributes */
+SWIGINTERN int  SWIG_Lua_class_get(lua_State* L)
+{
+/*  there should be 2 params passed in
+  (1) userdata (not the meta table)
+  (2) string name of the attribute
+*/
+  assert(lua_isuserdata(L,-2));  /* just in case */
+  lua_getmetatable(L,-2);    /* get the meta table */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".get"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* just in case */
+  /* look for the key in the .get table */
+  lua_pushvalue(L,2);  /* key */
+  lua_rawget(L,-2);
+  lua_remove(L,-2); /* stack tidy, remove .get table */
+  if (lua_iscfunction(L,-1))
+  {  /* found it so call the fn & return its value */
+    lua_pushvalue(L,1);  /* the userdata */
+    lua_call(L,1,1);  /* 1 value in (userdata),1 out (result) */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  lua_pop(L,1);  /* remove whatever was there */
+  /* ok, so try the .fn table */
+  SWIG_Lua_get_table(L,".fn"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* just in case */
+  lua_pushvalue(L,2);  /* key */
+  lua_rawget(L,-2);  /* look for the fn */
+  lua_remove(L,-2); /* stack tidy, remove .fn table */
+  if (lua_isfunction(L,-1)) /* note: if its a C function or lua function */
+  {  /* found it so return the fn & let lua call it */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  lua_pop(L,1);  /* remove whatever was there */
+  /* NEW: looks for the __getitem() fn
+  this is a user provided get fn */
+  SWIG_Lua_get_table(L,"__getitem"); /* find the __getitem fn */
+  if (lua_iscfunction(L,-1))  /* if its there */
+  {  /* found it so call the fn & return its value */
+    lua_pushvalue(L,1);  /* the userdata */
+    lua_pushvalue(L,2);  /* the parameter */
+    lua_call(L,2,1);  /* 2 value in (userdata),1 out (result) */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  return 0;  /* sorry not known */
+}
+
+/* the class.set method, performs the lookup of class attributes */
+SWIGINTERN int  SWIG_Lua_class_set(lua_State* L)
+{
+/*  there should be 3 params passed in
+  (1) table (not the meta table)
+  (2) string name of the attribute
+  (3) any for the new value
+printf("SWIG_Lua_class_set %p(%s) '%s' %p(%s)\n",
+      lua_topointer(L,1),lua_typename(L,lua_type(L,1)),
+      lua_tostring(L,2),
+      lua_topointer(L,3),lua_typename(L,lua_type(L,3)));*/
+
+  assert(lua_isuserdata(L,1));  /* just in case */
+  lua_getmetatable(L,1);    /* get the meta table */
+  assert(lua_istable(L,-1));  /* just in case */
+
+  SWIG_Lua_get_table(L,".set"); /* find the .set table */
+  if (lua_istable(L,-1))
+  {
+    /* look for the key in the .set table */
+    lua_pushvalue(L,2);  /* key */
+    lua_rawget(L,-2);
+    if (lua_iscfunction(L,-1))
+    {  /* found it so call the fn & return its value */
+      lua_pushvalue(L,1);  /* userdata */
+      lua_pushvalue(L,3);  /* value */
+      lua_call(L,2,0);
+      return 0;
+    }
+    lua_pop(L,1);  /* remove the value */
+  }
+  lua_pop(L,1);  /* remove the value .set table */
+  /* NEW: looks for the __setitem() fn
+  this is a user provided set fn */
+  SWIG_Lua_get_table(L,"__setitem"); /* find the fn */
+  if (lua_iscfunction(L,-1))  /* if its there */
+  {  /* found it so call the fn & return its value */
+    lua_pushvalue(L,1);  /* the userdata */
+    lua_pushvalue(L,2);  /* the parameter */
+    lua_pushvalue(L,3);  /* the value */
+    lua_call(L,3,0);  /* 3 values in ,0 out */
+    lua_remove(L,-2); /* stack tidy, remove metatable */
+    return 1;
+  }
+  return 0;
+}
+
+/* the class.destruct method called by the interpreter */
+SWIGINTERN int  SWIG_Lua_class_destruct(lua_State* L)
+{
+/*  there should be 1 params passed in
+  (1) userdata (not the meta table) */
+  swig_lua_userdata* usr;
+  swig_lua_class* clss;
+  assert(lua_isuserdata(L,-1));  /* just in case */
+  usr=(swig_lua_userdata*)lua_touserdata(L,-1);  /* get it */
+  /* if must be destroyed & has a destructor */
+  if (usr->own) /* if must be destroyed */
+  {
+    clss=(swig_lua_class*)usr->type->clientdata;  /* get the class */
+    if (clss && clss->destructor)  /* there is a destroy fn */
+    {
+      clss->destructor(usr->ptr);  /* bye bye */
+    }
+  }
+  return 0;
+}
+
+/* the class.__tostring method called by the interpreter and print */
+SWIGINTERN int  SWIG_Lua_class_tostring(lua_State* L)
+{
+/*  there should be 1 param passed in
+  (1) userdata (not the metatable) */
+  assert(lua_isuserdata(L,1));  /* just in case */
+  unsigned long userData = (unsigned long)lua_touserdata(L,1); /* get the userdata address for later */
+  lua_getmetatable(L,1);    /* get the meta table */
+  assert(lua_istable(L,-1));  /* just in case */
+  
+  lua_getfield(L, -1, ".type");
+  const char* className = lua_tostring(L, -1);
+  
+  char output[256];
+  sprintf(output, "<%s userdata: %lX>", className, userData);
+  
+  lua_pushstring(L, (const char*)output);
+  return 1;
+}
+
+/* to manually disown some userdata */
+SWIGINTERN int  SWIG_Lua_class_disown(lua_State* L)
+{
+/*  there should be 1 params passed in
+  (1) userdata (not the meta table) */
+  swig_lua_userdata* usr;
+  assert(lua_isuserdata(L,-1));  /* just in case */
+  usr=(swig_lua_userdata*)lua_touserdata(L,-1);  /* get it */
+  
+  usr->own = 0; /* clear our ownership */
+  return 0;
+}
+
+/* Constructor proxy. Used when class name entry in module is not class constructor,
+but special table instead. */
+SWIGINTERN int SWIG_Lua_constructor_proxy(lua_State* L)
+{
+  /* unlimited number of parameters
+     First one is our proxy table and we should remove it
+     Other we should pass to real constructor
+   */
+   assert(lua_istable(L,1));
+   lua_pushstring(L,".constructor");
+   lua_rawget(L,1);
+   assert(!lua_isnil(L,-1));
+   lua_replace(L,1); /* replace our table with real constructor */
+   lua_call(L,lua_gettop(L)-1,1);
+   return 1;
+}
+
+/* gets the swig class registry (or creates it) */
+SWIGINTERN void  SWIG_Lua_get_class_registry(lua_State* L)
+{
+  /* add this all into the swig registry: */
+  lua_pushstring(L,"SWIG");
+  lua_rawget(L,LUA_REGISTRYINDEX);  /* get the registry */
+  if (!lua_istable(L,-1))  /* not there */
+  {  /* must be first time, so add it */
+    lua_pop(L,1);  /* remove the result */
+    lua_pushstring(L,"SWIG");
+    lua_newtable(L);
+    lua_rawset(L,LUA_REGISTRYINDEX);
+    /* then get it */
+    lua_pushstring(L,"SWIG");
+    lua_rawget(L,LUA_REGISTRYINDEX);
+  }
+}
+
+/* helper fn to get the classes metatable from the register */
+SWIGINTERN void  SWIG_Lua_get_class_metatable(lua_State* L,const char* cname)
+{
+  SWIG_Lua_get_class_registry(L);  /* get the registry */
+  lua_pushstring(L,cname);  /* get the name */
+  lua_rawget(L,-2);    /* get it */
+  lua_remove(L,-2);    /* tidy up (remove registry) */
+}
+
+/* helper add a variable to a registered class */
+SWIGINTERN void  SWIG_Lua_add_class_variable(lua_State* L,const char* name,lua_CFunction getFn,lua_CFunction setFn)
+{
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_get_table(L,".get"); /* find the .get table */
+  assert(lua_istable(L,-1));  /* just in case */
+  SWIG_Lua_add_function(L,name,getFn);
+  lua_pop(L,1);       /* tidy stack (remove table) */
+  if (setFn)
+  {
+    SWIG_Lua_get_table(L,".set"); /* find the .set table */
+    assert(lua_istable(L,-1));  /* just in case */
+    SWIG_Lua_add_function(L,name,setFn);
+    lua_pop(L,1);       /* tidy stack (remove table) */
+  }
+}
+
+/* helper to recursively add class static details (static attributes, operations and constants) */
+SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State* L, swig_lua_class* clss)
+{
+  int i = 0;
+  /* The class namespace table must be on the top of the stack */
+  assert(lua_istable(L,-1));
+  /* call all the base classes first: we can then override these later: */
+  for(i=0;clss->bases[i];i++)
+  {
+    SWIG_Lua_add_class_static_details(L,clss->bases[i]);
+  }
+
+  SWIG_Lua_add_namespace_details(L, &clss->cls_static);
+}
+
+/* helper to recursively add class details (attributes & operations) */
+SWIGINTERN void  SWIG_Lua_add_class_details(lua_State* L,swig_lua_class* clss)
+{
+  int i;
+  /* call all the base classes first: we can then override these later: */
+  for(i=0;clss->bases[i];i++)
+  {
+    SWIG_Lua_add_class_details(L,clss->bases[i]);
+  }
+  /* add fns */
+  for(i=0;clss->attributes[i].name;i++){
+    SWIG_Lua_add_class_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod);
+  }
+  /* add methods to the metatable */
+  SWIG_Lua_get_table(L,".fn"); /* find the .fn table */
+  assert(lua_istable(L,-1));  /* just in case */
+  for(i=0;clss->methods[i].name;i++){
+    SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method);
+  }
+  lua_pop(L,1);       /* tidy stack (remove table) */
+  /*   add operator overloads
+    these look ANY method which start with "__" and assume they
+    are operator overloads & add them to the metatable
+    (this might mess up is someone defines a method __gc (the destructor)*/
+  for(i=0;clss->methods[i].name;i++){
+    if (clss->methods[i].name[0]=='_' && clss->methods[i].name[1]=='_'){
+      SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].method);
+    }
+  }
+}
+
+/* set up the base classes pointers.
+Each class structure has a list of pointers to the base class structures.
+This function fills them.
+It cannot be done at compile time, as this will not work with hireachies
+spread over more than one swig file. 
+Therefore it must be done at runtime, querying the SWIG type system.
+*/
+SWIGINTERN void SWIG_Lua_init_base_class(lua_State* L,swig_lua_class* clss)
+{
+  int i=0;
+  swig_module_info* module=SWIG_GetModule(L);
+  for(i=0;clss->base_names[i];i++)
+  {
+    if (clss->bases[i]==0) /* not found yet */
+    {
+      /* lookup and cache the base class */
+      swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]);
+      if (info) clss->bases[i] = (swig_lua_class *) info->clientdata;
+    }
+  }
+}
+
+/* Register class static methods,attributes etc as well as constructor proxy */
+SWIGINTERN void SWIG_Lua_class_register_static(lua_State* L, swig_lua_class* clss)
+{
+  lua_checkstack(L,5); /* just in case */
+  assert(lua_istable(L,-1));  /* just in case */
+  assert(strcmp(clss->name, clss->cls_static.name) == 0); /* in class those 2 must be equal */
+
+  SWIG_Lua_namespace_register(L,&clss->cls_static);
+
+  SWIG_Lua_get_table(L,clss->name); // Get namespace table back
+  assert(lua_istable(L,-1)); /* just in case */
+
+  /*  add its constructor to module with the name of the class
+  so you can do MyClass(...) as well as new_MyClass(...)
+  BUT only if a constructor is defined
+  (this overcomes the problem of pure virtual classes without constructors)*/
+  if (clss->constructor)
+  {
+    SWIG_Lua_add_function(L,".constructor", clss->constructor);
+    lua_getmetatable(L,-1);
+    assert(lua_istable(L,-1)); /* just in case */
+    SWIG_Lua_add_function(L,"__call", SWIG_Lua_constructor_proxy);
+    lua_pop(L,1);
+  }
+
+  assert(lua_istable(L,-1)); /* just in case */
+  SWIG_Lua_add_class_static_details(L, clss);
+
+  /* clear stack */
+  lua_pop(L,1);
+}
+
+/* performs the entire class registration process */
+SWIGINTERN void  SWIG_Lua_class_register(lua_State* L,swig_lua_class* clss)
+{
+  SWIG_Lua_class_register_static(L,clss);
+
+  SWIG_Lua_get_class_registry(L);  /* get the registry */
+  lua_pushstring(L,clss->name);  /* get the name */
+  lua_newtable(L);    /* create the metatable */
+  /* add string of class name called ".type" */
+  lua_pushstring(L,".type");
+  lua_pushstring(L,clss->name);
+  lua_rawset(L,-3);
+  /* add a table called ".get" */
+  lua_pushstring(L,".get");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+  /* add a table called ".set" */
+  lua_pushstring(L,".set");
+  lua_newtable(L);
+  lua_rawset(L,-3);
+  /* add a table called ".fn" */
+  lua_pushstring(L,".fn");
+  lua_newtable(L);
+  /* add manual disown method */
+  SWIG_Lua_add_function(L,"__disown",SWIG_Lua_class_disown);
+  lua_rawset(L,-3);
+  /* add accessor fns for using the .get,.set&.fn */
+  SWIG_Lua_add_function(L,"__index",SWIG_Lua_class_get);
+  SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_class_set);
+  SWIG_Lua_add_function(L,"__gc",SWIG_Lua_class_destruct);
+  /* add tostring method for better output */
+  SWIG_Lua_add_function(L,"__tostring",SWIG_Lua_class_tostring);
+  /* add it */
+  lua_rawset(L,-3);  /* metatable into registry */
+  lua_pop(L,1);      /* tidy stack (remove registry) */
+
+  SWIG_Lua_get_class_metatable(L,clss->name);
+  SWIG_Lua_add_class_details(L,clss);  /* recursive adding of details (atts & ops) */
+  lua_pop(L,1);      /* tidy stack (remove class metatable) */
+}
+
+/* -----------------------------------------------------------------------------
+ * Class/structure conversion fns
+ * ----------------------------------------------------------------------------- */
+
+/* helper to add metatable to new lua object */
+SWIGINTERN void _SWIG_Lua_AddMetatable(lua_State* L,swig_type_info *type)
+{
+  if (type->clientdata)  /* there is clientdata: so add the metatable */
+  {
+    SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->name);
+    if (lua_istable(L,-1))
+    {
+      lua_setmetatable(L,-2);
+    }
+    else
+    {
+      lua_pop(L,1);
+    }
+  }
+}
+
+/* pushes a new object into the lua stack */
+SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type, int own)
+{
+  swig_lua_userdata* usr;
+  if (!ptr){
+    lua_pushnil(L);
+    return;
+  }
+  usr=(swig_lua_userdata*)lua_newuserdata(L,sizeof(swig_lua_userdata));  /* get data */
+  usr->ptr=ptr;  /* set the ptr */
+  usr->type=type;
+  usr->own=own;
+#if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)
+  _SWIG_Lua_AddMetatable(L,type); /* add metatable */
+#endif
+}
+
+/* takes a object from the lua stack & converts it into an object of the correct type
+ (if possible) */
+SWIGRUNTIME int  SWIG_Lua_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags)
+{
+  swig_lua_userdata* usr;
+  swig_cast_info *cast;
+  if (lua_isnil(L,index)){*ptr=0; return SWIG_OK;}    /* special case: lua nil => NULL pointer */
+  usr=(swig_lua_userdata*)lua_touserdata(L,index);  /* get data */
+  if (usr)
+  {
+    if (flags & SWIG_POINTER_DISOWN) /* must disown the object */
+    {
+        usr->own=0;
+    }
+    if (!type)            /* special cast void*, no casting fn */
+    {
+      *ptr=usr->ptr;
+      return SWIG_OK; /* ok */
+    }
+    cast=SWIG_TypeCheckStruct(usr->type,type); /* performs normal type checking */
+    if (cast)
+    {
+      int newmemory = 0;
+      *ptr=SWIG_TypeCast(cast,usr->ptr,&newmemory);
+      assert(!newmemory); /* newmemory handling not yet implemented */
+      return SWIG_OK;  /* ok */
+    }
+  }
+  return SWIG_ERROR;  /* error */
+}
+
+SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State* L,int index,swig_type_info *type,int flags,
+       int argnum,const char* func_name){
+  void* result;
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,index,&result,type,flags))){
+    luaL_error (L,"Error in %s, expected a %s at argument number %d\n",
+		func_name,(type && type->str)?type->str:"void*",argnum);
+  }
+  return result;
+}
+
+/* pushes a packed userdata. user for member fn pointers only */
+SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State* L,void* ptr,size_t size,swig_type_info *type)
+{
+  swig_lua_rawdata* raw;
+  assert(ptr); /* not acceptable to pass in a NULL value */
+  raw=(swig_lua_rawdata*)lua_newuserdata(L,sizeof(swig_lua_rawdata)-1+size);  /* alloc data */
+  raw->type=type;
+  raw->own=0;
+  memcpy(raw->data,ptr,size); /* copy the data */
+  _SWIG_Lua_AddMetatable(L,type); /* add metatable */
+}
+    
+/* converts a packed userdata. user for member fn pointers only */
+SWIGRUNTIME int  SWIG_Lua_ConvertPacked(lua_State* L,int index,void* ptr,size_t size,swig_type_info *type)
+{
+  swig_lua_rawdata* raw;
+  raw=(swig_lua_rawdata*)lua_touserdata(L,index);  /* get data */
+  if (!raw) return SWIG_ERROR;  /* error */
+  if (type==0 || type==raw->type) /* void* or identical type */
+  {
+    memcpy(ptr,raw->data,size); /* copy it */
+    return SWIG_OK; /* ok */
+  }
+  return SWIG_ERROR;  /* error */
+}
+
+/* a function to get the typestring of a piece of data */
+SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp)
+{
+  swig_lua_userdata* usr;
+  if (lua_isuserdata(L,tp))
+  {
+    usr=(swig_lua_userdata*)lua_touserdata(L,tp);  /* get data */
+    if (usr && usr->type && usr->type->str)
+      return usr->type->str;
+    return "userdata (unknown type)";
+  }
+  return lua_typename(L,lua_type(L,tp));
+}
+
+/* lua callable function to get the userdata's type */
+SWIGRUNTIME int SWIG_Lua_type(lua_State* L)
+{
+  lua_pushstring(L,SWIG_Lua_typename(L,1));
+  return 1;
+}
+
+/* lua callable function to compare userdata's value
+the issue is that two userdata may point to the same thing
+but to lua, they are different objects */
+SWIGRUNTIME int SWIG_Lua_equal(lua_State* L)
+{
+  int result;
+  swig_lua_userdata *usr1,*usr2;
+  if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2))  /* just in case */
+    return 0;  /* nil reply */
+  usr1=(swig_lua_userdata*)lua_touserdata(L,1);  /* get data */
+  usr2=(swig_lua_userdata*)lua_touserdata(L,2);  /* get data */
+  /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/
+  result=(usr1->ptr==usr2->ptr);
+   lua_pushboolean(L,result);
+  return 1;
+}
+
+/* -----------------------------------------------------------------------------
+ * global variable support code: class/struct typemap functions
+ * ----------------------------------------------------------------------------- */
+
+#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC))
+/* Install Constants */
+SWIGINTERN void
+SWIG_Lua_InstallConstants(lua_State* L, swig_lua_const_info constants[]) {
+  int i;
+  for (i = 0; constants[i].type; i++) {
+    switch(constants[i].type) {
+    case SWIG_LUA_INT:
+      lua_pushstring(L,constants[i].name);
+      lua_pushnumber(L,(lua_Number)constants[i].lvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_FLOAT:
+      lua_pushstring(L,constants[i].name);
+      lua_pushnumber(L,(lua_Number)constants[i].dvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_CHAR:
+      lua_pushstring(L,constants[i].name);
+      lua_pushfstring(L,"%c",(char)constants[i].lvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_STRING:
+      lua_pushstring(L,constants[i].name);
+      lua_pushstring(L,(char *) constants[i].pvalue);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_POINTER:
+      lua_pushstring(L,constants[i].name);
+      SWIG_NewPointerObj(L,constants[i].pvalue, *(constants[i]).ptype,0);
+      lua_rawset(L,-3);
+      break;
+    case SWIG_LUA_BINARY:
+      lua_pushstring(L,constants[i].name);
+      SWIG_NewMemberObj(L,constants[i].pvalue,constants[i].lvalue,*(constants[i]).ptype);
+      lua_rawset(L,-3);
+      break;
+    default:
+      break;
+    }
+  }
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * executing lua code from within the wrapper
+ * ----------------------------------------------------------------------------- */
+
+#ifndef SWIG_DOSTRING_FAIL /* Allows redefining of error function */
+#define SWIG_DOSTRING_FAIL(S) fprintf(stderr,"%s\n",S)
+#endif
+/* Executes a C string in Lua which is a really simple way of calling lua from C
+Unfortunately lua keeps changing its APIs, so we need a conditional compile
+In lua 5.0.X its lua_dostring()
+In lua 5.1.X its luaL_dostring()
+*/
+SWIGINTERN int 
+SWIG_Lua_dostring(lua_State *L, const char* str) {
+  int ok,top;
+  if (str==0 || str[0]==0) return 0; /* nothing to do */
+  top=lua_gettop(L); /* save stack */
+#if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501))
+  ok=luaL_dostring(L,str);	/* looks like this is lua 5.1.X or later, good */
+#else
+  ok=lua_dostring(L,str);	/* might be lua 5.0.x, using lua_dostring */
+#endif
+  if (ok!=0) {
+    SWIG_DOSTRING_FAIL(lua_tostring(L,-1));
+  }
+  lua_settop(L,top); /* restore the stack */
+  return ok;
+}    
+
+#ifdef __cplusplus
+}
+#endif
+
+/* ------------------------------ end luarun.swg  ------------------------------ */
+
+
+/* -------- TYPES TABLE (BEGIN) -------- */
+
+#define SWIGTYPE_p_UIControl swig_types[0]
+static swig_type_info *swig_types[2];
+static swig_module_info swig_module = {swig_types, 1, 0, 0, 0, 0};
+#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
+#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
+
+/* -------- TYPES TABLE (END) -------- */
+
+#define SWIG_name      "UIControl"
+#define SWIG_init      luaopen_UIControl
+#define SWIG_init_user luaopen_UIControl_user
+
+#define SWIG_LUACODE   luaopen_UIControl_luacode
+
+namespace swig {
+typedef struct{} LANGUAGE_OBJ;
+}
+
+
+#include "UIControl.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+static int _wrap_UIControl_Show(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  
+  SWIG_check_num_args("UIControl::Show",1,1)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::Show",1,"UIControl *");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_Show",1,SWIGTYPE_p_UIControl);
+  }
+  
+  (arg1)->Show();
+  
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_Focused(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::Focused",1,1)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::Focused",1,"UIControl *");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_Focused",1,SWIGTYPE_p_UIControl);
+  }
+  
+  result = (bool)(arg1)->Focused();
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_OnKey(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  int arg2 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::OnKey",2,2)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::OnKey",1,"UIControl *");
+  if(!lua_isnumber(L,2)) SWIG_fail_arg("UIControl::OnKey",2,"int");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_OnKey",1,SWIGTYPE_p_UIControl);
+  }
+  
+  arg2 = (int)lua_tonumber(L, 2);
+  result = (bool)(arg1)->OnKey(arg2);
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_OnMouseLeftClick(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  int arg2 ;
+  int arg3 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::OnMouseLeftClick",3,3)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::OnMouseLeftClick",1,"UIControl *");
+  if(!lua_isnumber(L,2)) SWIG_fail_arg("UIControl::OnMouseLeftClick",2,"int");
+  if(!lua_isnumber(L,3)) SWIG_fail_arg("UIControl::OnMouseLeftClick",3,"int");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_OnMouseLeftClick",1,SWIGTYPE_p_UIControl);
+  }
+  
+  arg2 = (int)lua_tonumber(L, 2);
+  arg3 = (int)lua_tonumber(L, 3);
+  result = (bool)(arg1)->OnMouseLeftClick(arg2,arg3);
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_OnMouseRightClick(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  int arg2 ;
+  int arg3 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::OnMouseRightClick",3,3)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::OnMouseRightClick",1,"UIControl *");
+  if(!lua_isnumber(L,2)) SWIG_fail_arg("UIControl::OnMouseRightClick",2,"int");
+  if(!lua_isnumber(L,3)) SWIG_fail_arg("UIControl::OnMouseRightClick",3,"int");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_OnMouseRightClick",1,SWIGTYPE_p_UIControl);
+  }
+  
+  arg2 = (int)lua_tonumber(L, 2);
+  arg3 = (int)lua_tonumber(L, 3);
+  result = (bool)(arg1)->OnMouseRightClick(arg2,arg3);
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_OnMouseEnter(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::OnMouseEnter",1,1)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::OnMouseEnter",1,"UIControl *");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_OnMouseEnter",1,SWIGTYPE_p_UIControl);
+  }
+  
+  result = (bool)(arg1)->OnMouseEnter();
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_OnMouseLeave(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::OnMouseLeave",1,1)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::OnMouseLeave",1,"UIControl *");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_OnMouseLeave",1,SWIGTYPE_p_UIControl);
+  }
+  
+  result = (bool)(arg1)->OnMouseLeave();
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_AddControl(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  UIControl *arg2 = (UIControl *) 0 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::AddControl",2,2)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::AddControl",1,"UIControl *");
+  if(!SWIG_isptrtype(L,2)) SWIG_fail_arg("UIControl::AddControl",2,"UIControl *");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_AddControl",1,SWIGTYPE_p_UIControl);
+  }
+  
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,2,(void**)&arg2,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_AddControl",2,SWIGTYPE_p_UIControl);
+  }
+  
+  result = (bool)(arg1)->AddControl(arg2);
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static int _wrap_UIControl_RemoveControl(lua_State* L) {
+  int SWIG_arg = 0;
+  UIControl *arg1 = (UIControl *) 0 ;
+  UIControl *arg2 = (UIControl *) 0 ;
+  bool result;
+  
+  SWIG_check_num_args("UIControl::RemoveControl",2,2)
+  if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("UIControl::RemoveControl",1,"UIControl *");
+  if(!SWIG_isptrtype(L,2)) SWIG_fail_arg("UIControl::RemoveControl",2,"UIControl *");
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_RemoveControl",1,SWIGTYPE_p_UIControl);
+  }
+  
+  
+  if (!SWIG_IsOK(SWIG_ConvertPtr(L,2,(void**)&arg2,SWIGTYPE_p_UIControl,0))){
+    SWIG_fail_ptr("UIControl_RemoveControl",2,SWIGTYPE_p_UIControl);
+  }
+  
+  result = (bool)(arg1)->RemoveControl(arg2);
+  lua_pushboolean(L,(int)(result!=0)); SWIG_arg++;
+  return SWIG_arg;
+  
+  if(0) SWIG_fail;
+  
+fail:
+  lua_error(L);
+  return SWIG_arg;
+}
+
+
+static void swig_delete_UIControl(void *obj) {
+UIControl *arg1 = (UIControl *) obj;
+delete arg1;
+}
+static swig_lua_method swig_UIControl_methods[] = {
+    {"Show", _wrap_UIControl_Show}, 
+    {"Focused", _wrap_UIControl_Focused}, 
+    {"OnKey", _wrap_UIControl_OnKey}, 
+    {"OnMouseLeftClick", _wrap_UIControl_OnMouseLeftClick}, 
+    {"OnMouseRightClick", _wrap_UIControl_OnMouseRightClick}, 
+    {"OnMouseEnter", _wrap_UIControl_OnMouseEnter}, 
+    {"OnMouseLeave", _wrap_UIControl_OnMouseLeave}, 
+    {"AddControl", _wrap_UIControl_AddControl}, 
+    {"RemoveControl", _wrap_UIControl_RemoveControl}, 
+    {0,0}
+};
+static swig_lua_attribute swig_UIControl_attributes[] = {
+    {0,0,0}
+};
+static swig_lua_attribute swig_UIControl_cls_attributes[] = {
+    {0,0,0}
+};
+static swig_lua_method swig_UIControl_cls_methods[] = {
+    {0,0}
+};
+static swig_lua_const_info swig_UIControl_cls_constants[] = {
+    {0,0,0,0,0,0}
+};
+static swig_lua_class *swig_UIControl_bases[] = {0};
+static const char *swig_UIControl_base_names[] = {0};
+static swig_lua_class _wrap_class_UIControl = { "UIControl", &SWIGTYPE_p_UIControl,0, swig_delete_UIControl, swig_UIControl_methods, swig_UIControl_attributes, { "UIControl", swig_UIControl_cls_methods, swig_UIControl_cls_attributes, swig_UIControl_cls_constants }, swig_UIControl_bases, swig_UIControl_base_names };
+
+#ifdef __cplusplus
+}
+#endif
+
+static const struct luaL_Reg swig_commands[] = {
+    {0,0}
+};
+
+static swig_lua_var_info swig_variables[] = {
+    {0,0,0}
+};
+
+static swig_lua_const_info swig_constants[] = {
+    {0,0,0,0,0,0}
+};
+
+/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
+
+static swig_type_info _swigt__p_UIControl = {"_p_UIControl", "UIControl *", 0, 0, (void*)&_wrap_class_UIControl, 0};
+
+static swig_type_info *swig_type_initial[] = {
+  &_swigt__p_UIControl,
+};
+
+static swig_cast_info _swigc__p_UIControl[] = {  {&_swigt__p_UIControl, 0, 0, 0},{0, 0, 0, 0}};
+
+static swig_cast_info *swig_cast_initial[] = {
+  _swigc__p_UIControl,
+};
+
+
+/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
+
+/* -----------------------------------------------------------------------------
+ * Type initialization:
+ * This problem is tough by the requirement that no dynamic
+ * memory is used. Also, since swig_type_info structures store pointers to
+ * swig_cast_info structures and swig_cast_info structures store pointers back
+ * to swig_type_info structures, we need some lookup code at initialization.
+ * The idea is that swig generates all the structures that are needed.
+ * The runtime then collects these partially filled structures.
+ * The SWIG_InitializeModule function takes these initial arrays out of
+ * swig_module, and does all the lookup, filling in the swig_module.types
+ * array with the correct data and linking the correct swig_cast_info
+ * structures together.
+ *
+ * The generated swig_type_info structures are assigned staticly to an initial
+ * array. We just loop through that array, and handle each type individually.
+ * First we lookup if this type has been already loaded, and if so, use the
+ * loaded structure instead of the generated one. Then we have to fill in the
+ * cast linked list. The cast data is initially stored in something like a
+ * two-dimensional array. Each row corresponds to a type (there are the same
+ * number of rows as there are in the swig_type_initial array). Each entry in
+ * a column is one of the swig_cast_info structures for that type.
+ * The cast_initial array is actually an array of arrays, because each row has
+ * a variable number of columns. So to actually build the cast linked list,
+ * we find the array of casts associated with the type, and loop through it
+ * adding the casts to the list. The one last trick we need to do is making
+ * sure the type pointer in the swig_cast_info struct is correct.
+ *
+ * First off, we lookup the cast->type name to see if it is already loaded.
+ * There are three cases to handle:
+ *  1) If the cast->type has already been loaded AND the type we are adding
+ *     casting info to has not been loaded (it is in this module), THEN we
+ *     replace the cast->type pointer with the type pointer that has already
+ *     been loaded.
+ *  2) If BOTH types (the one we are adding casting info to, and the
+ *     cast->type) are loaded, THEN the cast info has already been loaded by
+ *     the previous module so we just ignore it.
+ *  3) Finally, if cast->type has not already been loaded, then we add that
+ *     swig_cast_info to the linked list (because the cast->type) pointer will
+ *     be correct.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* c-mode */
+#endif
+#endif
+
+#if 0
+#define SWIGRUNTIME_DEBUG
+#endif
+
+
+SWIGRUNTIME void
+SWIG_InitializeModule(void *clientdata) {
+  size_t i;
+  swig_module_info *module_head, *iter;
+  int found, init;
+
+  /* check to see if the circular list has been setup, if not, set it up */
+  if (swig_module.next==0) {
+    /* Initialize the swig_module */
+    swig_module.type_initial = swig_type_initial;
+    swig_module.cast_initial = swig_cast_initial;
+    swig_module.next = &swig_module;
+    init = 1;
+  } else {
+    init = 0;
+  }
+
+  /* Try and load any already created modules */
+  module_head = SWIG_GetModule(clientdata);
+  if (!module_head) {
+    /* This is the first module loaded for this interpreter */
+    /* so set the swig module into the interpreter */
+    SWIG_SetModule(clientdata, &swig_module);
+    module_head = &swig_module;
+  } else {
+    /* the interpreter has loaded a SWIG module, but has it loaded this one? */
+    found=0;
+    iter=module_head;
+    do {
+      if (iter==&swig_module) {
+        found=1;
+        break;
+      }
+      iter=iter->next;
+    } while (iter!= module_head);
+
+    /* if the is found in the list, then all is done and we may leave */
+    if (found) return;
+    /* otherwise we must add out module into the list */
+    swig_module.next = module_head->next;
+    module_head->next = &swig_module;
+  }
+
+  /* When multiple interpreters are used, a module could have already been initialized in
+     a different interpreter, but not yet have a pointer in this interpreter.
+     In this case, we do not want to continue adding types... everything should be
+     set up already */
+  if (init == 0) return;
+
+  /* Now work on filling in swig_module.types */
+#ifdef SWIGRUNTIME_DEBUG
+  printf("SWIG_InitializeModule: size %d\n", swig_module.size);
+#endif
+  for (i = 0; i < swig_module.size; ++i) {
+    swig_type_info *type = 0;
+    swig_type_info *ret;
+    swig_cast_info *cast;
+
+#ifdef SWIGRUNTIME_DEBUG
+    printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
+#endif
+
+    /* if there is another module already loaded */
+    if (swig_module.next != &swig_module) {
+      type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
+    }
+    if (type) {
+      /* Overwrite clientdata field */
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: found type %s\n", type->name);
+#endif
+      if (swig_module.type_initial[i]->clientdata) {
+	type->clientdata = swig_module.type_initial[i]->clientdata;
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name);
+#endif
+      }
+    } else {
+      type = swig_module.type_initial[i];
+    }
+
+    /* Insert casting types */
+    cast = swig_module.cast_initial[i];
+    while (cast->type) {
+
+      /* Don't need to add information already in the list */
+      ret = 0;
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: look cast %s\n", cast->type->name);
+#endif
+      if (swig_module.next != &swig_module) {
+        ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
+#ifdef SWIGRUNTIME_DEBUG
+	if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name);
+#endif
+      }
+      if (ret) {
+	if (type == swig_module.type_initial[i]) {
+#ifdef SWIGRUNTIME_DEBUG
+	  printf("SWIG_InitializeModule: skip old type %s\n", ret->name);
+#endif
+	  cast->type = ret;
+	  ret = 0;
+	} else {
+	  /* Check for casting already in the list */
+	  swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type);
+#ifdef SWIGRUNTIME_DEBUG
+	  if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name);
+#endif
+	  if (!ocast) ret = 0;
+	}
+      }
+
+      if (!ret) {
+#ifdef SWIGRUNTIME_DEBUG
+	printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name);
+#endif
+        if (type->cast) {
+          type->cast->prev = cast;
+          cast->next = type->cast;
+        }
+        type->cast = cast;
+      }
+      cast++;
+    }
+    /* Set entry in modules->types array equal to the type */
+    swig_module.types[i] = type;
+  }
+  swig_module.types[i] = 0;
+
+#ifdef SWIGRUNTIME_DEBUG
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+  for (i = 0; i < swig_module.size; ++i) {
+    int j = 0;
+    swig_cast_info *cast = swig_module.cast_initial[i];
+    printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
+    while (cast->type) {
+      printf("SWIG_InitializeModule: cast type %s\n", cast->type->name);
+      cast++;
+      ++j;
+    }
+  printf("---- Total casts: %d\n",j);
+  }
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+#endif
+}
+
+/* This function will propagate the clientdata field of type to
+* any new swig_type_info structures that have been added into the list
+* of equivalent types.  It is like calling
+* SWIG_TypeClientData(type, clientdata) a second time.
+*/
+SWIGRUNTIME void
+SWIG_PropagateClientData(void) {
+  size_t i;
+  swig_cast_info *equiv;
+  static int init_run = 0;
+
+  if (init_run) return;
+  init_run = 1;
+
+  for (i = 0; i < swig_module.size; i++) {
+    if (swig_module.types[i]->clientdata) {
+      equiv = swig_module.types[i]->cast;
+      while (equiv) {
+        if (!equiv->converter) {
+          if (equiv->type && !equiv->type->clientdata)
+            SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
+        }
+        equiv = equiv->next;
+      }
+    }
+  }
+}
+
+#ifdef __cplusplus
+#if 0
+{ /* c-mode */
+#endif
+}
+#endif
+
+
+
+/* Forward declaration of where the user's %init{} gets inserted */
+void SWIG_init_user(lua_State* L );
+    
+#ifdef __cplusplus
+extern "C" {
+#endif
+/* this is the initialization function
+  added at the very end of the code
+  the function is always called SWIG_init, but an earlier #define will rename it
+*/
+#if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC))
+LUALIB_API int SWIG_init(lua_State* L)
+#else
+SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */
+#endif
+{
+#if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) /* valid for both Lua and eLua */
+  int i;
+  /* start with global table */
+  lua_pushglobaltable (L);
+  /* SWIG's internal initalisation */
+  SWIG_InitializeModule((void*)L);
+  SWIG_PropagateClientData();
+#endif
+
+#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC))
+  /* add a global fn */
+  SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type);
+  SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_equal);
+  /* begin the module (its a table with the same name as the module) */
+  SWIG_Lua_module_begin(L,SWIG_name);
+  /* add commands/functions */
+  for (i = 0; swig_commands[i].name; i++){
+    SWIG_Lua_module_add_function(L,swig_commands[i].name,swig_commands[i].func);
+  }
+  /* add variables */
+  for (i = 0; swig_variables[i].name; i++){
+    SWIG_Lua_module_add_variable(L,swig_variables[i].name,swig_variables[i].get,swig_variables[i].set);
+  }
+#endif
+
+#if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)
+  /* set up base class pointers (the hierarchy) */
+  for (i = 0; swig_types[i]; i++){
+    if (swig_types[i]->clientdata){
+      SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata));
+    }
+  }
+  /* additional registration structs & classes in lua */
+  for (i = 0; swig_types[i]; i++){
+    if (swig_types[i]->clientdata){
+      SWIG_Lua_class_register(L,(swig_lua_class*)(swig_types[i]->clientdata));
+    }
+  }
+#endif
+
+#if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC))
+  /* constants */
+  SWIG_Lua_InstallConstants(L,swig_constants);
+#endif
+
+#if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)
+  /* invoke user-specific initialization */
+  SWIG_init_user(L);
+  /* end module */
+  /* Note: We do not clean up the stack here (Lua will do this for us). At this
+     point, we have the globals table and out module table on the stack. Returning
+     one value makes the module table the result of the require command. */
+  return 1;
+#else
+  return 0;
+#endif
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+
+const char* SWIG_LUACODE=
+  "";
+
+void SWIG_init_user(lua_State* L)
+{
+  /* exec Lua code if applicable */
+  SWIG_Lua_dostring(L,SWIG_LUACODE);
+}
+
--- a/mm7_2.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_2.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -406,12 +406,12 @@
   Player *v2; // edi@9
   int v3; // eax@10
   signed int v4; // esi@10
-  signed __int64 v5; // qax@18
+  //signed __int64 v5; // qax@18
   signed int v6; // ebx@34
-  char *v7; // edi@34
+  //char *v7; // edi@34
   int v8; // eax@37
-  int v9; // esi@43
-  int v10; // eax@44
+  //int v9; // esi@43
+  //int v10; // eax@44
   unsigned __int8 v11; // sf@44
   unsigned __int8 v12; // of@44
   signed int v13; // eax@49
@@ -428,7 +428,7 @@
   GUIWindow window; // [sp+D4h] [bp-6Ch]@1
   __int16 monster_ids[6]; // [sp+128h] [bp-18h]@56
   int v26; // [sp+134h] [bp-Ch]@1
-  int v27; // [sp+138h] [bp-8h]@23
+  //int v27; // [sp+138h] [bp-8h]@23
   int num_monsters; // [sp+13Ch] [bp-4h]@17
 
   v26 = 0;
@@ -442,23 +442,19 @@
   if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
     pIndoor->Draw();
   else if ( uCurrentlyLoadedLevelType == LEVEL_Outdoor )
-      pOutdoor->Draw();
+    pOutdoor->Draw();
 
   pRenderer->DrawBillboards_And_MaybeRenderSpecialEffects_And_EndScene();
   pRenderer->BeginScene();
   if ( pRenderer->pRenderD3D )
-    pRenderer->FillRectFast(
-      pViewport->uViewportTL_X,
-      pViewport->uViewportTL_Y,
-      pViewport->uViewportBR_X - pViewport->uViewportTL_X,
-      pViewport->uViewportBR_Y - pViewport->uViewportTL_Y + 1,
-      pRenderer->uTargetGMask | pRenderer->uTargetBMask);
+    pRenderer->FillRectFast(pViewport->uViewportTL_X, pViewport->uViewportTL_Y, pViewport->uViewportBR_X - pViewport->uViewportTL_X,
+      pViewport->uViewportBR_Y - pViewport->uViewportTL_Y + 1, pRenderer->uTargetGMask | pRenderer->uTargetBMask);
 
   Texture* pTex = pIcons_LOD->GetTexture(uTextureID_Leather);
   pRenderer->GetLeather(8, 352 - v0, pTex, pTex->uTextureHeight - v0);
 
-  pRenderer->DrawTextureIndexed(8u, 347 - v0, pTexture_591428);
-  v1 = FitTextInAWindow(pGlobalTXT_LocalizationStrings[575], pFontArrus, &window, 0xDu, 0);
+  pRenderer->DrawTextureIndexed(8, 347 - v0, pTexture_591428);
+  v1 = FitTextInAWindow(pGlobalTXT_LocalizationStrings[575], pFontArrus, &window, 0xDu, 0);//,     . .
   pDialogueWindow->DrawText(pFontArrus, 13, 354 - v0, 0, v1, 0, 0, 0);
   pRenderer->EndScene();
   pRenderer->Present();
@@ -477,43 +473,40 @@
     ++pMessageQueue_50CBD0->uNumMessages;
   }*/
   pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
-  v2 = pParty->pPlayers.data();
-  do
+  //v2 = pParty->pPlayers.data();
+  for ( uint i = 0; i < 4; i++ )
   {
-    v3 = v2->GetActualLevel();
+    v3 = pParty->pPlayers[i].GetActualLevel();
     v4 = v26;
     if ( v3 > v26 )
     {
-      v26 = v2->GetActualLevel();
-      v4 = v26;
+      v26 = pParty->pPlayers[i].GetActualLevel();
+      v4 = pParty->pPlayers[i].GetActualLevel();
     }
-    ++v2;
+    //++v2;
   }
-  while ( (signed int)v2 < (signed int)pParty->pHirelings.data() );
-  if ( uDialogueType == 85 )
+  //while ( (signed int)v2 < (signed int)pParty->pHirelings.data() );
+  if ( uDialogueType == DIALOGUE_ARENA_SELECT_PAGE )
   {
     num_monsters = v4;
     v4 /= 2;
   }
-  else if ( uDialogueType == 86 )
+  else if ( uDialogueType == DIALOGUE_ARENA_SELECT_SQUIRE )
   {
-    v5 = (signed __int64)((double)v26 * 1.5);
-    num_monsters = v5;
+    //v5 = (signed __int64)((double)v26 * 1.5);
+    num_monsters = (int)((double)v26 * 1.5);
     v4 /= 2;
   }
-  else if ( uDialogueType == 87 )
+  else if ( uDialogueType == DIALOGUE_ARENA_SELECT_KNIGHT )
   {
-    LODWORD(v5) = 2 * v4;
-    num_monsters = v5;
+    //LODWORD(v5) = 2 * v4;
+    num_monsters = 2 * v4;
     v4 /= 2;
   }
-  else
+  else if ( uDialogueType == DIALOGUE_ARENA_SELECT_CHAMPION )
   {
-    __debugbreak(); // warning C4700: uninitialized local variable 'v27' used
-    if ( uDialogueType == 88 )
-      num_monsters = 2 * v4;
-    else
-      v4 = v27;
+    num_monsters = 2 * v4;
+    v4 /= 2;
   }
   if ( v4 < 1 )
     v4 = 1;
@@ -526,43 +519,44 @@
   if ( num_monsters < 2 )
     num_monsters = 2;
   v6 = 0;
-  v27 = 1;
-  v7 = (char *)&pMonsterStats->pInfos[1].uLevel;
-  do
+  //v27 = 1;
+  //v7 = (char *)&pMonsterStats->pInfos[1].uLevel;
+  for ( uint i = 1; i <= 258; i++ )
   {
-    if ( v7[8] != 1 )
+    if ( pMonsterStats->pInfos[i].uAIType != 1 )//if ( v7[8] != 1 )
     {
-      if ( !MonsterStats::BelongsToSupertype(*((short *)v7 + 22), MONSTER_SUPERTYPE_8) )
+      if ( !MonsterStats::BelongsToSupertype(pMonsterStats->pInfos[i].uID, MONSTER_SUPERTYPE_8) ) //!MonsterStats::BelongsToSupertype(*((short *)v7 + 22), MONSTER_SUPERTYPE_8)
       {
-        v8 = (unsigned __int8)*v7;
-        if ( v8 >= v4 )
+        //v8 = (unsigned __int8)pMonsterStats->pInfos[i].uLevel;
+        if ( pMonsterStats->pInfos[i].uLevel >= v4 )
         {
-          if ( v8 <= num_monsters )
-            v23[v6++] = v27;
+          if ( pMonsterStats->pInfos[i].uLevel <= num_monsters )
+            v23[v6++] = i;
         }
       }
     }
-    ++v27;
-    v7 += 88;
+   // ++v27;
+    //v7 += 88;
   }
-  while ( (signed int)v7 <= (signed int)&pMonsterStats->pInfos[258].uLevel );
+  //while ( (signed int)v7 <= (signed int)&pMonsterStats->pInfos[258].uLevel );
   num_monsters = 6;
   if ( v6 < 6 )
     num_monsters = v6;
-  v9 = 0;
+  //v9 = 0;
   if ( num_monsters > 0 )
   {
-    do
+    for ( uint i = 0; i < num_monsters; i++ )
     {
-      v10 = rand();
-      ++v9;
-      v12 = __OFSUB__(v9, num_monsters);
-      v11 = v9 - num_monsters < 0;
-      *((short *)&window.pControlsTail + v9 + 1) = v23[v10 % v6];
+      //v10 = rand();
+      //++v9;
+      //v12 = __OFSUB__(v9, num_monsters);
+      //v11 = v9 - num_monsters < 0;
+      //*((short *)&window.pControlsTail + v9 + 1) = v23[rand() % v6];
+      monster_ids[i] = v23[rand() % v6];
     }
-    while ( v11 ^ v12 );
+    //while ( v11 ^ v12 );
   }
-  if ( uDialogueType == 85 )
+  if ( uDialogueType == DIALOGUE_ARENA_SELECT_PAGE )
   {
     v16 = rand();
     v17 = 3;
@@ -571,7 +565,7 @@
     v13 = v22;
     v14 = v18 + 6;
   }
-  else if ( uDialogueType == 86 )
+  else if ( uDialogueType == DIALOGUE_ARENA_SELECT_SQUIRE )
   {
     v16 = rand();
     v17 = 7;
@@ -580,7 +574,7 @@
     v13 = v22;
     v14 = v18 + 6;
   }
-  else if ( uDialogueType == 87 )
+  else if ( uDialogueType == DIALOGUE_ARENA_SELECT_KNIGHT )
   {
     v15 = rand() % 11;
     v13 = 200;
@@ -588,23 +582,23 @@
   }
   else
   {
-    if ( uDialogueType == 88 )
+    if ( uDialogueType == DIALOGUE_ARENA_SELECT_CHAMPION )
     {
       v13 = 500;
       v14 = 20;
     }
-    else
-    {
-      v14 = v27;
-      v13 = gold_transaction_amount;
-    }
+    //else
+    //{
+      //v14 = v27;
+      //v13 = gold_transaction_amount;
+    //}
   }
-  i = 0;
-  for ( gold_transaction_amount = v26 * v13; i < v14; ++i )
+  gold_transaction_amount = v26 * v13;
+  for ( i = 0; i < v14; ++i )
   {
-    monster_y = pMonsterArenaPlacements[i].y;
-    v21 = rand();
-    Actor::_4BBF61_summon_actor((unsigned __int16)monster_ids[v21 % num_monsters], pMonsterArenaPlacements[i].x, monster_y, 1);
+    //monster_y = pMonsterArenaPlacements[i].y;
+    //v21 = rand();
+    Actor::_4BBF61_summon_actor(monster_ids[rand() % num_monsters], pMonsterArenaPlacements[i].x, pMonsterArenaPlacements[i].y, 1);
   }
   pAudioPlayer->PlaySound((SoundID)14060, 0, 0, -1, 0, 0, 0, 0);
 }
@@ -750,15 +744,13 @@
   pWindow.uFrameW = 397;
   pFont = LoadFont("endgame.fnt", "FONTPAL", NULL);
   if ( pParty->IsPartyGood() )
-  {
-    v1 = pGlobalTXT_LocalizationStrings[675];
-  }
+    v1 = pGlobalTXT_LocalizationStrings[675];//"Splendid job!  With the activation of the Gate, a thousand worlds lie at your feet.  Perhaps on one of them you will find the Ancients themselves, and return with the fruits their great civilization has to offer your world and your kingdom."
   else
   {
     result = pParty->IsPartyEvil();
     if ( !(short)result )
       return result;
-    v1 = pGlobalTXT_LocalizationStrings[676];
+    v1 = pGlobalTXT_LocalizationStrings[676];//"Brilliant!  The completion of the Heavenly Forge has provided enough Ancient weapons to crush all resistance to your plans.  Soon the world will bow to your every whim!  Still, you can't help but wonder what was beyond the Gate the other side was trying so hard to build."
   }
   pInString = v1;
   v23 = pParty->uTimePlayed - 138240;
@@ -769,33 +761,19 @@
   if ( !v19 )
     v19 = 1;
   pRenderer->BeginScene();
-  pWindow.DrawTitleText(pFont, 1u, 0x23u, 1u, pGlobalTXT_LocalizationStrings[9], 3u);
-  v3 = pParty->pPlayers.data();//[0].pName;
+  pWindow.DrawTitleText(pFont, 1, 0x23, 1, pGlobalTXT_LocalizationStrings[9], 3);//Congratulations!
   v23 = 0i64;
   v20 = 0;
-  //for ( i = (int)pParty->pPlayers[0].pName; ; v3 = (char *)i )
-  for ( i = pParty->pPlayers.data(); ; v3 = i )
+  for ( uint i = 0; i < 4; i++ )
   {
-	v4 = pClassNames[v3->classType];
-    v5 = v3->GetBaseLevel();
-	sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[129], i->pName, v5, v4);
-    pWindow.DrawTitleText(
-      pFont,
-      1u,
-      v20 * (LOBYTE(pFont->uFontHeight) - 2) + LOBYTE(pFont->uFontHeight) + 46,
-      1u,
-      pTmpBuf.data(),
-      3u);
-	v23 += i->uExperience;//__PAIR__(*(int *)(i - 4), *(int *)(i - 8));
-    ++v20;
-    ++i;
-	if ( i > &pParty->pPlayers[3] )
-      break;
+    sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[129], pParty->pPlayers[i].pName, pParty->pPlayers[i].GetBaseLevel(), pClassNames[pParty->pPlayers[i].classType]);//%s the Level %u %s
+    pWindow.DrawTitleText(pFont, 1, i * (LOBYTE(pFont->uFontHeight) - 2) + LOBYTE(pFont->uFontHeight) + 46, 1, pTmpBuf.data(), 3);
+    v23 += pParty->pPlayers[i].uExperience;//__PAIR__(*(int *)(i - 4), *(int *)(i - 8));
   }
   v23 = (signed __int64)v23 / v19;
-  v6 = FitTextInAWindow(pInString, pFont, &pWindow, 0xCu, 0);
-  pWindow.DrawTitleText(pFont, 1u, 5 * (LOBYTE(pFont->uFontHeight) + 11), 1u, v6, 0);
-  strcpy(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[37]);
+  v6 = FitTextInAWindow(pInString, pFont, &pWindow, 0xC, 0);
+  pWindow.DrawTitleText(pFont, 1, 5 * (LOBYTE(pFont->uFontHeight) + 11), 1, v6, 0);
+  strcpy(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[37]);//Total Time:
   v7 = pGlobalTXT_LocalizationStrings[56];
   if ( v17 != 1 )
     v7 = pGlobalTXT_LocalizationStrings[57];
@@ -809,13 +787,13 @@
   strcat(pTmpBuf.data(), pTmpBuf2.data());
   pWindow.DrawTitleText(pFont, 1u, pWindow.uFrameHeight - 2 * LOBYTE(pFont->uFontHeight) - 5, 1u, pTmpBuf.data(), 3u);
   sprintf(pTmpBuf.data(), pGlobalTXT_LocalizationStrings[94], v23);
-  pWindow.DrawTitleText(pFont, 1u, pWindow.uFrameHeight, 1u, pTmpBuf.data(), 3u);
+  pWindow.DrawTitleText(pFont, 1, pWindow.uFrameHeight, 1u, pTmpBuf.data(), 3);
   dword_6BE364_game_settings_1 |= GAME_SETTINGS_4000;
   pRenderer->EndScene();
   pRenderer->Present();
   if ( pRenderer->pRenderD3D )
     pRenderer->pBeforePresentFunction();
-  pRenderer->_49F1BC("MM7_Win.Pcx");
+  pRenderer->SaveWinnersCertificate("MM7_Win.Pcx");
   free(pFont);
   window_SpeakInHouse->Release();
   window_SpeakInHouse = 0;
@@ -2278,7 +2256,6 @@
   if (val < 1)
     return val;
 
-
     v2 = 0;
     v3 = val;
     result = 0;
@@ -2349,32 +2326,16 @@
 //----- (00452B2E) --------------------------------------------------------
 int __fastcall GetDiceResult(unsigned int uNumDice, unsigned int uDiceSides)
 {
-  signed int v2; // edi@1
   int v3; // esi@1
-  int result; // eax@2
-  unsigned int v5; // ebx@4
-
-  v2 = uDiceSides;
+
   v3 = 0;
   if ( uDiceSides )
   {
-    if ( (signed int)uNumDice > 0 )
-    {
-      v5 = uNumDice;
-      do
-      {
-        --v5;
-        v3 += rand() % v2 + 1;
-      }
-      while ( v5 );
-    }
-    result = v3;
+    for ( uint i = 0; i < uNumDice; ++i)
+      v3 += rand() % uDiceSides + 1;
+    return v3;
   }
-  else
-  {
-    result = 0;
-  }
-  return result;
+  return 0;
 }
 
 //----- (00453F62) --------------------------------------------------------
@@ -2734,37 +2695,36 @@
   pHostileTXT_Raw = NULL;
   pHostileTXT_Raw = (char *)pEvents_LOD->LoadRaw("hostile.txt", 0);
   strtok(pHostileTXT_Raw, "\r");
-  for (i=0; i<89; ++i)
-	  {
-	  test_string = strtok(NULL, "\r") + 1;
-	  break_loop = false;
-	  decode_step=0;
-	  do 
-		  {
-		  c = *(unsigned char*)test_string;
-		  temp_str_len = 0;
-		  while((c!='\t')&&(c>0))
-			  {
-			  ++temp_str_len;
-			  c=test_string[temp_str_len];
-			  }		
-		  tmp_pos=test_string+temp_str_len;
-		  if (*tmp_pos == 0)
-			  break_loop = true;
-		  *tmp_pos = 0;
-		  if (temp_str_len)
-			  {
-			  if ( decode_step >= 1 && decode_step < 90 )
-				  relations[decode_step-1][i] = atoi(test_string);
-			  }
-		  else
-			  { 
-			  break_loop = true;
-			  }
-		  ++decode_step;
-		  test_string=tmp_pos+1;
-		  } while ((decode_step<92)&&!break_loop);
-	  }
+  for ( i=0; i < 89; ++i )
+  {
+     test_string = strtok(NULL, "\r") + 1;
+     break_loop = false;
+     decode_step=0;
+     do 
+     {
+       c = *(unsigned char*)test_string;
+       temp_str_len = 0;
+       while((c!='\t') && (c > 0))
+       {
+         ++temp_str_len;
+         c = test_string[temp_str_len];
+       }
+       tmp_pos=test_string+temp_str_len;
+       if (*tmp_pos == 0)
+         break_loop = true;
+       *tmp_pos = 0;
+       if (temp_str_len)
+       {
+         if ( decode_step >= 1 && decode_step < 90 )
+           relations[decode_step-1][i] = atoi(test_string);
+       }
+       else
+         break_loop = true;
+       ++decode_step;
+       test_string=tmp_pos+1;
+     }
+     while ((decode_step < 92) && !break_loop );
+   }
   if ( pHostileTXT_Raw)
   {
     free(pHostileTXT_Raw);
@@ -2790,40 +2750,35 @@
 unsigned int __fastcall GetSpellColor(signed int a1)
 {
   if ( a1 == 0 )
-    return TargetColor(0, 0, 0);
+    return Color16(0, 0, 0);
   if ( a1 < 12 )
-    return TargetColor(255, 85, 0);
+    return Color16(255, 85, 0);
   if ( a1 < 23 )
-    return TargetColor(150, 212, 255);
+    return Color16(150, 212, 255);
   if ( a1 < 34 )
-    return TargetColor(0, 128, 255);
+    return Color16(0, 128, 255);
   if ( a1 < 45 )
-    return TargetColor(128, 128, 128);
+    return Color16(128, 128, 128);
   if ( a1 < 56 )
-    return TargetColor(225, 225, 225);
+    return Color16(225, 225, 225);
   if ( a1 < 67 )
-    return TargetColor(235, 15, 255);
+    return Color16(235, 15, 255);
   if ( a1 < 78 )
-    return TargetColor(255, 128, 0);
+    return Color16(255, 128, 0);
   if ( a1 < 89 )
-    return TargetColor(255, 255, 155);
+    return Color16(255, 255, 155);
   if ( a1 < 100 )
-    return TargetColor(192, 192, 240);
+    return Color16(192, 192, 240);
 }
 
 //----- (004610AA) --------------------------------------------------------
 void __fastcall PrepareToLoadODM(unsigned int bLoading, ODMRenderParams *a2)
 {
-  unsigned int v2; // edi@1
-  ODMRenderParams *v3; // esi@1
-
-  v2 = bLoading;
-  v3 = a2;
   pGameLoadingUI_ProgressBar->Reset(27);
   pSoundList->_4A9D79(0);
   uCurrentlyLoadedLevelType = LEVEL_Outdoor;
-  ODM_LoadAndInitialize(pCurrentMapName, v3);
-  if ( !v2 )
+  ODM_LoadAndInitialize(pCurrentMapName, a2);
+  if ( !bLoading )
     TeleportToStartingPoint(uLevel_StartingPointType);
   viewparams->_443365();
   PlayLevelMusic();
@@ -2836,7 +2791,7 @@
   //GUIProgressBar *v0; // ebx@1
   //signed int v1; // ebp@1
   //char *v2; // esi@2
-  __int16 v3; // cx@3
+  //__int16 v3; // cx@3
   int v4; // edx@8
   //size_t v5; // edi@14
   signed int v6; // esi@14
@@ -2857,11 +2812,9 @@
   int v21[16]; // [sp+1Ch] [bp-40h]@17
 
   GenerateItemsInChest();
-  //v0 = pGameLoadingUI_ProgressBar;
   pGameLoadingUI_ProgressBar->Progress();
-  pParty->uFlags |= 2u;
+  pParty->uFlags |= 2;
   pParty->field_7B5_in_arena_quest = 0;
-  //v1 = 0;
   dword_5C6DF8 = 1;
   pNPCStats->uNewlNPCBufPos = 0;
   v19 = pMapStats->GetMapInfo(pCurrentMapName);
@@ -2870,42 +2823,42 @@
   for (uint i = 0; i < uNumActors; ++i)
   //if ( (signed int)uNumActors > 0 )
   {
-    Actor* pActor = &pActors[i];
+    //Actor* pActor = &pActors[i];
     //v2 = (char *)&pActors[0].uNPC_ID;
     //do
     //{
-      v3 = pActor->pMonsterInfo.uID;
+      //v3 = pActors[i].pMonsterInfo.uID;
       v17 = 0;
-      if ( pActor->pMonsterInfo.uID >= 115 && pActor->pMonsterInfo.uID <= 186
-        || pActor->pMonsterInfo.uID >= 232 && pActor->pMonsterInfo.uID <= 249 )
+      if ( pActors[i].pMonsterInfo.uID >= 115 && pActors[i].pMonsterInfo.uID <= 186
+        || pActors[i].pMonsterInfo.uID >= 232 && pActors[i].pMonsterInfo.uID <= 249 )
         v17 = 1;
       //v1 = 0;
-      v4 = (v3 - 1) % 3;
+      v4 = (pActors[i].pMonsterInfo.uID - 1) % 3;
       if ( 2 == v4 )
       {
-        if ( pActor->sNPC_ID && pActor->sNPC_ID < 5000 )
+        if ( pActors[i].sNPC_ID && pActors[i].sNPC_ID < 5000 )
           continue;
       }
       else
       {
         if ( v4 != 1 )
         {
-          if ( v4 == 0 && pActor->sNPC_ID == 0 )
-			pActor->sNPC_ID = 0;
-		  continue;
+          if ( v4 == 0 && pActors[i].sNPC_ID == 0 )
+            pActors[i].sNPC_ID = 0;
+          continue;
         }
       }
-      if ( pActor->sNPC_ID > 0 && pActor->sNPC_ID < 5000 )
+      if ( pActors[i].sNPC_ID > 0 && pActors[i].sNPC_ID < 5000 )
         continue;
       if ( v17 )
       {
-        pNPCStats->InitializeAdditionalNPCs(&pNPCStats->pAdditionalNPC[pNPCStats->uNewlNPCBufPos], v3, 0, v19);
+        pNPCStats->InitializeAdditionalNPCs(&pNPCStats->pAdditionalNPC[pNPCStats->uNewlNPCBufPos], pActors[i].pMonsterInfo.uID, 0, v19);
         v14 = LOWORD(pNPCStats->uNewlNPCBufPos) + 5000;
         ++pNPCStats->uNewlNPCBufPos;
-        pActor->sNPC_ID = v14;
+        pActors[i].sNPC_ID = v14;
         continue;
       }
-      pActor->sNPC_ID = 0;
+      pActors[i].sNPC_ID = 0;
       //++v15;
       //v2 += 836;
     //}
@@ -2921,64 +2874,41 @@
 
   for (uint i = 0; i < uNumActors; ++i)
   {
-    Actor* pActor = &pActors[i];
     //v7 = (char *)&pActors[0].pMonsterInfo;
     //do
     //{
-      v8 = 0;
-      if ( v6 > 0 )
-      {
-        do
-        {
-          if ( v21[v8] == pActor->pMonsterInfo.uID - 1 )
-            break;
-          ++v8;
-        }
-        while ( v8 < v6 );
-      }
-
-      if ( v8 == v6 )
-      {
-        v21[v6++] = pActor->pMonsterInfo.uID - 1;
-        v20 = v6;
-        if ( v6 == 16 )
-          break;
-      }
-      //++v16;
-      //v7 += 836;
+    for ( v8 = 0; v8 < v6; ++v8 )
+    {
+      if ( v21[v8] == pActors[i].pMonsterInfo.uID - 1 )
+        break;
+    }
+
+    if ( v8 == v6 )
+    {
+      v21[v6++] = pActors[i].pMonsterInfo.uID - 1;
+      v20 = v6;
+      if ( v6 == 16 )
+        break;
+    }
+    //++v16;
+    //v7 += 836;
     //}
     //while ( v16 < (signed int)v5 );
   }
 
   pGameLoadingUI_ProgressBar->Progress();
 
-  if ( v6 > 0 )
-  {
-    int _v0 = 0;
-    do
+    for ( int _v0 = 0; _v0 < v6; ++_v0 )
     {
-      v9 = v21[_v0];
-      v18 = 4;
-      v10 = &pMonsterStats->pInfos[v9 + 1];
-      //v11 = (int *)pMonsterList->pMonsters[v9].pSoundSampleIDs;
-      MonsterDesc* v11 = &pMonsterList->pMonsters[v9];
-      do
-      {
-        pSoundList->LoadSound(v11->pSoundSampleIDs[4 - v18], 0);
-        //v11 = (int *)((char *)v11 + 2);
-        --v18;
-      }
-      while ( v18 );
+      for ( v18 = 4; v18; --v18 )
+        pSoundList->LoadSound(pMonsterList->pMonsters[v21[_v0]].pSoundSampleIDs[4 - v18], 0);
       v12 = 0;
       do
-        v13 = pSoundList->LoadSound(v12++ + word_4EE088_sound_ids[v10->uSpell1ID], 1);
+        v13 = pSoundList->LoadSound(v12++ + word_4EE088_sound_ids[pMonsterStats->pInfos[v21[_v0] + 1].uSpell1ID], 1);
       while ( v13 );
-      ++_v0;
     }
-    while ( _v0 < v6 );
     //v0 = pGameLoadingUI_ProgressBar;
     //v1 = 0;
-  }
 
   pGameLoadingUI_ProgressBar->Progress();
 
@@ -3475,7 +3405,7 @@
       {
         if ( !RegCreateKeyExA(v7, "1.0", 0, "", 0, 0xF003Fu, 0, &v8, &dwDisposition) )
         {
-          RegSetValueExA(v8, lpValueName, 0, 4u, Data, 4u);
+          RegSetValueExA(v8, lpValueName, 0, 4, Data, 4);
           RegCloseKey(v8);
         }
         RegCloseKey(v7);
@@ -3710,13 +3640,13 @@
   }
   else
   {
-    bool bWindowMode = ReadWindowsRegistryInt("startinwindow", false);
+    //bool bWindowMode = ReadWindowsRegistryInt("startinwindow", false);
     //uint uDefaultDevice = ReadWindowsRegistryInt("D3D Device", 1);
     bool bColoredLights = ReadWindowsRegistryInt("Colored Lights", false);
     uint uLevelOfDetail = ReadWindowsRegistryInt("Detail Level", 1);
     uint bTinting = ReadWindowsRegistryInt("Tinting", 1) != 0;
 
-    if (!pRenderer->Initialize(bWindowMode, window, bColoredLights, uLevelOfDetail, bTinting))
+    if (!pRenderer->Initialize(window, bColoredLights, uLevelOfDetail, bTinting))
     {
       Log::Warning(L"Render failed to initialize");
       return false;
@@ -3987,18 +3917,16 @@
 
 
   
-  if (dword_6BE364_game_settings_1 & 2 || !(dword_6BE368_debug_settings_2 & DEBUG_SETTINGS_RUN_IN_WIDOW))// 
-                                                //   color depth != 16
-                                                // or
-                                                //   not in window
+  if (dword_6BE368_debug_settings_2 & DEBUG_SETTINGS_RUN_IN_WIDOW)
   {
-    window->SetFullscreenMode();
-    pRenderer->InitializeFullscreen();
+    //window->SetWindowedMode(game_width, game_height);
+    pRenderer->SwitchToWindow();
   }
   else
   {
-    //window->SetWindowedMode(game_width, game_height);
-    pRenderer->SwitchToWindow();
+    __debugbreak(); // Nomad
+    window->SetFullscreenMode();
+    pRenderer->InitializeFullscreen();
   }
   sub_4C023F();
   uSoundVolumeMultiplier = ReadWindowsRegistryInt("soundflag", 9);
@@ -4077,9 +4005,12 @@
   pItemsTable->Initialize();
 
   pBitmaps_LOD->dword_011BA8 = 1;
-  pBitmaps_LOD->SetupPalettes(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
-  pIcons_LOD->SetupPalettes(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
-  pPaletteManager->SetColorChannelInfo(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
+  //pBitmaps_LOD->SetupPalettes(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
+  pBitmaps_LOD->SetupPalettes(5, 6, 5);
+  //pIcons_LOD->SetupPalettes(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
+  pIcons_LOD->SetupPalettes(5, 6, 5);
+  //pPaletteManager->SetColorChannelInfo(pRenderer->uTargetRBits, pRenderer->uTargetGBits, pRenderer->uTargetBBits);
+  pPaletteManager->SetColorChannelInfo(5, 6, 5);
 
   pPaletteManager->SetMistColor(128, 128, 128);
   pPaletteManager->RecalculateAll();
@@ -4114,21 +4045,12 @@
     pUIAnims[i]->y = _4E98D0[i][2];
   }
 
-  v5 = 0;
-  if ( (signed int)pObjectList->uNumObjects > 0 )
+  for ( v5 = 0; v5 < (signed int)pObjectList->uNumObjects; ++v5 )
   {
-    v6 = 0;
-    do
-    {
-      BYTE3(v7) = 0;
-      v8 = &pObjectList->pObjects[v6];
-      ++v6;
-      *(short *)((char *)&v7 + 1) = v8->uParticleTrailColorR;
-      LOBYTE(v7) = v8->uParticleTrailColorG;
-      ++v5;
-      v8->uParticleTrailColor = v8->uParticleTrailColorB | (v7 << 8);
-    }
-    while ( v5 < (signed int)pObjectList->uNumObjects );
+    BYTE3(v7) = 0;
+    *(short *)((char *)&v7 + 1) = pObjectList->pObjects[v5].uParticleTrailColorR;
+    LOBYTE(v7) = pObjectList->pObjects[v5].uParticleTrailColorG;
+    pObjectList->pObjects[v5].uParticleTrailColor = pObjectList->pObjects[v5].uParticleTrailColorB | (v7 << 8);
   }
   flt_6BE3A0 = 0.55000001f;
   MainMenuUI_Create();
@@ -4304,7 +4226,7 @@
 bool debug_information = false;
 bool show_picked_face = false;
 bool draw_debug_line = false;
-bool new_speed = true;
+bool new_speed = false;
 int max_flight_height = 4000;
 
 
@@ -4391,8 +4313,7 @@
       uGameState = GAME_STATE_PLAYING;
       while ( 1 )
       {
-        if (uGameState == GAME_FINISHED ||
-            GetCurrentMenuID() == MENU_EXIT_GAME)
+        if (uGameState == GAME_FINISHED || GetCurrentMenuID() == MENU_EXIT_GAME)
         {
           pGame->Deinitialize();
           return true;
@@ -4694,7 +4615,7 @@
   {
     LOBYTE(viewparams->field_20) = 0;
   }
-  pParty->uFlags |= 2u;
+  pParty->uFlags |= 2;
   viewparams->uSomeY = viewparams->uScreen_topL_Y;
   viewparams->uSomeX = viewparams->uScreen_topL_X;
   viewparams->uSomeZ = viewparams->uScreen_BttmR_X;
@@ -4744,22 +4665,15 @@
 int __fastcall _46A6AC_spell_render(int a1, int a2, int a3)
 {
   int result; // eax@2
-  unsigned int v4; // edx@3
   int *v5; // esi@6
   unsigned int v6; // ebx@6
   signed int v7; // edi@9
-  unsigned __int16 v8; // ax@9
   int i; // eax@14
   int v10; // ecx@19
-  int v11; // [sp+0h] [bp-18h]@1
-  unsigned int v12; // [sp+4h] [bp-14h]@3
   unsigned int v13; // [sp+8h] [bp-10h]@4
-  int v14; // [sp+Ch] [bp-Ch]@1
   int *v15; // [sp+10h] [bp-8h]@4
   int v16; // [sp+14h] [bp-4h]@3
 
-  v11 = a2;
-  v14 = a1;
   if ( pRenderer->pRenderD3D )
   {
     result = _46A6AC_spell_render_d3d(a1, a2, a3);
@@ -4768,56 +4682,47 @@
   {
     __debugbreak(); // SW render never called
     v16 = 0;
-    v4 = viewparams->uScreen_topL_X;
-    v12 = viewparams->uScreen_BttmR_X;
     if ( (signed int)viewparams->uScreen_topL_Y < (signed int)viewparams->uScreen_BttmR_Y )
     {
       v15 = &pRenderer->pActiveZBuffer[viewparams->uScreen_topL_X + 640 * viewparams->uScreen_topL_Y];
       v13 = ((viewparams->uScreen_BttmR_Y - viewparams->uScreen_topL_Y - 1) >> 1) + 1;
-      do
+      for ( v13; v13; --v13 )
       {
-        if ( (signed int)v4 < (signed int)v12 )
+        if ( (signed int)viewparams->uScreen_topL_X < (signed int)viewparams->uScreen_BttmR_X )
         {
           v5 = v15;
-          v6 = ((v12 - v4 - 1) >> 1) + 1;
-          do
+          v6 = ((viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X - 1) >> 1) + 1;
+          for ( v6; v6; --v6 )
           {
             if ( PID_TYPE(*(char *)v5) == OBJECT_Actor)
             {
               if ( *v5 <= a3 << 16 )
               {
                 v7 = PID_ID((signed int)(unsigned __int16)*v5);
-                v8 = pActors[v7].uAIState;
-                if ( v8 != 5 )
+                if ( pActors[v7].uAIState != Dead && pActors[v7].uAIState != Dying && pActors[v7].uAIState != Removed
+                  && pActors[v7].uAIState != Summoned && pActors[v7].uAIState != Disabled )
                 {
-                  if ( v8 != 4 && v8 != 11 && v8 != 17 && v8 != 19 )
+                  for ( i = 0; i < v16; ++i )
                   {
-                    for ( i = 0; i < v16; ++i )
+                    if ( *(int *)(a1 + 4 * i) == v7 )
+                      break;
+                  }
+                  if ( i == v16 )
+                  {
+                    if ( i < a2 - 1 )
                     {
-                      if ( *(int *)(v14 + 4 * i) == v7 )
-                        break;
-                    }
-                    if ( i == v16 )
-                    {
-                      if ( i < v11 - 1 )
-                      {
-                        v10 = v16++;
-                        *(int *)(v14 + 4 * v10) = v7;
-                      }
+                      v10 = v16++;
+                      *(int *)(a1 + 4 * v10) = v7;
                     }
                   }
                 }
               }
             }
             v5 += 2;
-            --v6;
           }
-          while ( v6 );
         }
         v15 += 1280;
-        --v13;
       }
-      while ( v13 );
     }
     result = v16;
   }
@@ -4828,67 +4733,42 @@
 int __fastcall _46A6AC_spell_render_d3d(int a1, int a2, int a3)
 {
   unsigned int v3; // eax@2
-  int v4; // ecx@2
   unsigned int v5; // eax@2
   unsigned int v6; // eax@4
-  unsigned int v7; // edi@4
-  unsigned __int16 v8; // ax@4
-  float v9; // ST00_4@9
   int v10; // ecx@11
   unsigned int v12; // [sp+10h] [bp-14h]@1
-  int v13; // [sp+14h] [bp-10h]@1
-  int v14; // [sp+18h] [bp-Ch]@1
   int v15; // [sp+1Ch] [bp-8h]@1
   unsigned int a1a; // [sp+20h] [bp-4h]@1
 
-  v13 = a1;
-  v14 = a2;
   v15 = 0;
-  a1a = 0;
   v12 = pRenderer->GetBillboardDrawListSize();
-  if ( (signed int)v12 > 0 )
+  if ( (signed int)pRenderer->GetBillboardDrawListSize() > 0 )
   {
-    do
+    for ( a1a = 0; (signed int)a1a < (signed int)v12; ++a1a )
     {
       v3 = pRenderer->GetParentBillboardID(a1a);
-      v4 = pBillboardRenderList[v3].sZValue;
       v5 = (unsigned __int16)pBillboardRenderList[v3].object_pid;
       if ( PID_TYPE(v5) == OBJECT_Actor)
       {
-        if ( v4 <= (unsigned int)(a3 << 16) )
+        if ( pBillboardRenderList[v3].sZValue <= (unsigned int)(a3 << 16) )
         {
           v6 = PID_ID(v5);
-          v7 = v6;
-          v8 = pActors[v6].uAIState;
-          if ( v8 != Dead )
+          if ( pActors[v6].uAIState != Dead && pActors[v6].uAIState != Dying && pActors[v6].uAIState != Removed
+            && pActors[v6].uAIState != Disabled && pActors[v6].uAIState != Summoned )
           {
-            if ( v8 != Dying )
+            if ( pGame->pVisInstance->DoesRayIntersectBillboard((double)a3, a1a) )
             {
-              if ( v8 != Removed )
+              if ( v15 < a2 - 1 )
               {
-                if ( v8 != Disabled )
-                {
-                  if ( v8 != Summoned )
-                  {
-                    v9 = (double)a3;
-                    if ( pGame->pVisInstance->DoesRayIntersectBillboard(v9, a1a) )
-                    {
-                      if ( v15 < v14 - 1 )
-                      {
-                        v10 = v15++;
-                        *(int *)(v13 + 4 * v10) = v7;
-                      }
-                    }
-                  }
-                }
+                __debugbreak();// *(int *)(a1 + 4 * v10) = v6;   ?
+                v10 = v15++;
+                *(int *)(a1 + 4 * v10) = v6;
               }
             }
           }
         }
       }
-      ++a1a;
     }
-    while ( (signed int)a1a < (signed int)v12 );
   }
   return v15;
 }
@@ -4896,8 +4776,6 @@
 //----- (0046A89E) --------------------------------------------------------
 int __fastcall _46A89E_immolation_effect(int a1, int a2, int a3)
 {
-  signed int v3; // edi@1
-  Actor *v4; // esi@2
   int v5; // ebx@3
   int v6; // eax@3
   int v7; // ebx@3
@@ -4905,74 +4783,50 @@
   int v9; // edx@4
   unsigned int v10; // edx@6
   unsigned int v11; // edx@8
-  __int16 v12; // ax@10
   int v13; // ecx@15
-  int v15; // [sp+4h] [bp-18h]@1
-  int v16; // [sp+8h] [bp-14h]@1
   int v17; // [sp+Ch] [bp-10h]@3
   int v18; // [sp+10h] [bp-Ch]@3
   int v19; // [sp+18h] [bp-4h]@1
 
-  v3 = 0;
-  v15 = a2;
-  v16 = a1;
   v19 = 0;
-  if ( (signed int)uNumActors > 0 )
+  for ( uint i = 0; i < (signed int)uNumActors; ++i )
   {
-    v4 = pActors.data();//[0].uAIState;
-    do
+    v5 = abs(pActors[i].vPosition.x - pParty->vPosition.x);
+    v17 = abs(pActors[i].vPosition.y - pParty->vPosition.y);
+    v18 = abs(pActors[i].vPosition.z - pParty->vPosition.z);
+    v6 = v5;
+    v7 = v17;
+    v8 = v18;
+    if ( v6 < v17 )
     {
-	  v5 = abs(v4->vPosition.x - pParty->vPosition.x);
-	  v17 = abs(v4->vPosition.y - pParty->vPosition.y);
-	  v18 = abs(v4->vPosition.z - pParty->vPosition.z);
-      v6 = v5;
-      v7 = v17;
-      v8 = v18;
-      if ( v6 < v17 )
-      {
-        v9 = v6;
-        v6 = v17;
-        v7 = v9;
-      }
-      if ( v6 < v18 )
-      {
-        v10 = v6;
-        v6 = v18;
-        v8 = v10;
-      }
-      if ( v7 < (signed int)v8 )
+      v9 = v6;
+      v6 = v17;
+      v7 = v9;
+    }
+    if ( v6 < v18 )
+    {
+      v10 = v6;
+      v6 = v18;
+      v8 = v10;
+    }
+    if ( v7 < (signed int)v8 )
+    {
+      v11 = v8;
+      v8 = v7;
+      v7 = v11;
+    }
+    if ( (signed int)(((unsigned int)(11 * v7) >> 5) + (v8 >> 2) + v6) <= a3 )
+    {
+      if ( pActors[i].uAIState != Dead && pActors[i].uAIState != Dying && pActors[i].uAIState != Removed
+        && pActors[i].uAIState != Disabled && pActors[i].uAIState != Summoned )
       {
-        v11 = v8;
-        v8 = v7;
-        v7 = v11;
+        __debugbreak();// *(int *)(a1 + 4 * v13) = i;   ?
+        v13 = v19++;
+        *(int *)(a1 + 4 * v13) = i;
+        if ( v19 >= a2 - 1 )
+          break;
       }
-      if ( (signed int)(((unsigned int)(11 * v7) >> 5) + (v8 >> 2) + v6) <= a3 )
-      {
-		v12 = v4->uAIState;
-        if ( v4->uAIState != 5 )
-        {
-          if ( v12 != 4 )
-          {
-            if ( v12 != 11 )
-            {
-              if ( v12 != 19 )
-              {
-                if ( v12 != 17 )
-                {
-                  v13 = v19++;
-                  *(int *)(v16 + 4 * v13) = v3;
-                  if ( v19 >= v15 - 1 )
-                    break;
-                }
-              }
-            }
-          }
-        }
-      }
-      ++v3;
-      ++v4;
     }
-    while ( v3 < (signed int)uNumActors );
   }
   return v19;
 }
@@ -5007,19 +4861,13 @@
 //----- (0046BFFA) --------------------------------------------------------
 bool __fastcall _46BFFA_check_object_intercept(unsigned int uLayingItemID, signed int a2)
 {
-  //SpriteObject *v2; // esi@1
-  ObjectDesc *v3; // ebx@1
-  unsigned __int16 v5; // cx@9
-  //unsigned __int16 v6; // cx@14
-  //signed int v7; // edx@14
+  ObjectDesc *object; // ebx@1
   unsigned int v8; // eax@19
-  unsigned int v9; // edi@19
   signed int v10; // ebx@19
   char *v11; // edx@20
   unsigned __int16 v12; // ax@23
   int v13; // eax@27
   unsigned int v14; // ebx@33
-  //unsigned __int16 v15; // ax@35
   int v16; // eax@36
   unsigned int v17; // eax@37
   __int16 v18; // di@37
@@ -5055,7 +4903,6 @@
   int v48; // edx@87
   int v49; // edx@88
   int v50; // edx@89
-  unsigned int v51; // eax@93
   signed int v52; // ebx@93
   char *v53; // edx@94
   unsigned __int16 v54; // ax@98
@@ -5077,11 +4924,6 @@
   char *v70; // edx@125
   unsigned __int16 v71; // ax@128
   unsigned int v72; // ebx@131
-  //int v73; // ST14_4@132
-  //int v74; // ST10_4@132
-  //int v75; // ebx@132
-  //int v76; // ST0C_4@132
-  //unsigned __int16 v77; // ax@132
   int v78; // eax@133
   char v79; // zf@139
   unsigned int v80; // eax@140
@@ -5103,13 +4945,8 @@
   unsigned __int16 v96; // ax@184
   int v97; // eax@185
   unsigned __int16 v98; // ax@191
-  unsigned int v99; // ecx@191
   char v100; // ST18_1@198
-  //int v101; // ST14_4@198
   int v102; // eax@198
-  //int v103; // ST10_4@198
-  //int v104; // ST0C_4@198
-  //unsigned __int16 v105; // ax@200
   signed int v106; // eax@208
   unsigned int v107; // edx@220
   signed int v108; // ebx@225
@@ -5120,7 +4957,6 @@
   unsigned __int16 v113; // si@241
   int v114; // eax@242
   int v115; // eax@245
-  //signed int v116; // eax@245
   unsigned __int16 v117; // ax@251
   unsigned int v118; // ecx@251
   signed int v119; // ebx@251
@@ -5130,14 +4966,7 @@
   char *v123; // edx@261
   int v124; // eax@267
   int v125; // [sp-20h] [bp-4Ch]@28
-  //signed int v126; // [sp-1Ch] [bp-48h]@27
-  //unsigned int v127; // [sp-18h] [bp-44h]@27
-  //signed int v128; // [sp-14h] [bp-40h]@27
-  //signed int v129; // [sp-10h] [bp-3Ch]@27
-  //int v130; // [sp-Ch] [bp-38h]@27
-  //unsigned int v131; // [sp-8h] [bp-34h]@27
   char v132; // [sp-8h] [bp-34h]@131
-  //int v133; // [sp-4h] [bp-30h]@27
   char v134; // [sp-4h] [bp-30h]@131
   signed int v135; // [sp-4h] [bp-30h]@217
   int v136; // [sp+Ch] [bp-20h]@208
@@ -5149,21 +4978,15 @@
   unsigned int v142; // [sp+1Ch] [bp-10h]@158
   signed int v143; // [sp+1Ch] [bp-10h]@172
   char *v144; // [sp+1Ch] [bp-10h]@192
-  signed int v145; // [sp+20h] [bp-Ch]@1
   signed int v146; // [sp+20h] [bp-Ch]@60
   int v147; // [sp+20h] [bp-Ch]@72
   signed int v148; // [sp+20h] [bp-Ch]@158
-  //int v149; // [sp+20h] [bp-Ch]@198
   unsigned __int16 v150; // [sp+20h] [bp-Ch]@208
-  int v151; // [sp+24h] [bp-8h]@1
   signed int v152; // [sp+24h] [bp-8h]@208
-  unsigned int v153; // [sp+28h] [bp-4h]@1
-
-  v153 = uLayingItemID;
-  //v2 = &pSpriteObjects[uLayingItemID];
-  v3 = &pObjectList->pObjects[pSpriteObjects[uLayingItemID].uObjectDescID];
-  v145 = a2;
-  v151 = PID_TYPE(a2);
+
+  //:    
+  object = &pObjectList->pObjects[pSpriteObjects[uLayingItemID].uObjectDescID];
+  //v151 = PID_TYPE(a2);
   if ( PID_TYPE(a2) == OBJECT_Actor)
   {
     if ( PID_TYPE(pSpriteObjects[uLayingItemID].spell_caster_pid) == OBJECT_Actor 
@@ -5177,14 +5000,13 @@
   }
   if ( pParty->bTurnBasedModeOn == 1 )
   {
-    v5 = pSpriteObjects[uLayingItemID].uAttributes;
-    if ( v5 & 4 )
+    if ( pSpriteObjects[uLayingItemID].uAttributes & 4 )
     {
       --pTurnEngine->pending_actions;
-      pSpriteObjects[uLayingItemID].uAttributes = v5 & 0xFFFB;
+      pSpriteObjects[uLayingItemID].uAttributes &= 0xFFFB;
     }
   }
-  if ( v151 == OBJECT_BModel && PID_TYPE(pSpriteObjects[uLayingItemID].spell_caster_pid) != OBJECT_Player)
+  if ( PID_TYPE(a2) == OBJECT_BModel && PID_TYPE(pSpriteObjects[uLayingItemID].spell_caster_pid) != OBJECT_Player)
       {
       if (PID_ID(pSpriteObjects[uLayingItemID].spell_caster_pid) < 500)  //bugfix  PID_ID(v2->spell_caster_pid)==1000
          BYTE2(pActors[PID_ID(pSpriteObjects[uLayingItemID].spell_caster_pid)].uAttributes) |= 4;
@@ -5206,86 +5028,59 @@
           {
             if ( pSpriteObjects[uLayingItemID].uType != 9080 )
               return 0;
-LABEL_191:
-            v98 = pSpriteObjects[uLayingItemID].uType + 1;
-            v99 = pObjectList->uNumObjects;
-            v32 = 0;
-            pSpriteObjects[uLayingItemID].uType = v98;
-            v146 = 0;
-            if ( (signed int)v99 > 0 )
+            v95 = 0;
+            pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 1;
+            for ( v146 = 0; v146 < (signed int)pObjectList->uNumObjects; ++v146 )
             {
-              v144 = (char *)&pObjectList->pObjects->uObjectID;
-              while ( v98 != *(short *)v144 )
-              {
-                ++v146;
-                v144 += 56;
-                if ( v146 >= (signed int)v99 )
-                {
-                  pSpriteObjects[uLayingItemID].uObjectDescID = 0;
-                  if ( !v32 )
-                    SpriteObject::OnInteraction(v153);
-                  v100 = pSpriteObjects[uLayingItemID].field_61;
-                  pSpriteObjects[uLayingItemID].uSpriteFrameID = v32;
-                  v102 = 8 * v153;
-                  LOBYTE(v102) = PID(OBJECT_Item,v153);
-                  pSpriteObjects[uLayingItemID].vVelocity.x = v32;
-                  pSpriteObjects[uLayingItemID].vVelocity.y = v32;
-                  pSpriteObjects[uLayingItemID].vVelocity.z = v32;
-                  AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, v32);
-                  if (v3->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
-                    trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v3->uParticleTrailColor);
-                  if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v32 )
-                    v47 = 0;
-                  else
-                    v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-                  v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-                  pAudioPlayer->PlaySound((SoundID)v125, v102, v32, -1, v32, v47, v32, v32);
-                  return 0;
-                }
-              }
-              pSpriteObjects[uLayingItemID].uObjectDescID = v146;
-              if ( v146 == (short)v32 )
-                SpriteObject::OnInteraction(v153);
-              v100 = pSpriteObjects[uLayingItemID].field_61;
-              pSpriteObjects[uLayingItemID].uSpriteFrameID = v32;
-              v102 = 8 * v153;
-              LOBYTE(v102) = PID(OBJECT_Item,v153);
-              pSpriteObjects[uLayingItemID].vVelocity.x = v32;
-              pSpriteObjects[uLayingItemID].vVelocity.y = v32;
-              pSpriteObjects[uLayingItemID].vVelocity.z = v32;
-              AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, v32);
-              if (v3->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
-                trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v3->uParticleTrailColor);
-              if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v32 )
-                v47 = 0;
-              else
-                v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-              v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-              pAudioPlayer->PlaySound((SoundID)v125, v102, v32, -1, v32, v47, v32, v32);
-              return 0;
+              if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v146].uObjectID )
+                v95 = v146;
             }
-            pSpriteObjects[uLayingItemID].uObjectDescID = 0;
-            if ( !v32 )
-              SpriteObject::OnInteraction(v153);
+            pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+            if ( !v95 )
+              SpriteObject::OnInteraction(uLayingItemID);
             v100 = pSpriteObjects[uLayingItemID].field_61;
-            pSpriteObjects[uLayingItemID].uSpriteFrameID = v32;
-            v102 = 8 * v153;
-            LOBYTE(v102) = PID(OBJECT_Item,v153);
-            pSpriteObjects[uLayingItemID].vVelocity.x = v32;
-            pSpriteObjects[uLayingItemID].vVelocity.y = v32;
-            pSpriteObjects[uLayingItemID].vVelocity.z = v32;
-            AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, v32);
-            if (v3->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
-              trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v3->uParticleTrailColor);
-            if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v32 )
+            pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+            v102 = 8 * uLayingItemID;
+            LOBYTE(v102) = PID(OBJECT_Item, uLayingItemID);
+            pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+            pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+            pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+            AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, 0);
+            if (object->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
+              trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, object->uParticleTrailColor);
+            if ( !pSpriteObjects[uLayingItemID].uSoundID )
               v47 = 0;
             else
               v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
             v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-            pAudioPlayer->PlaySound((SoundID)v125, v102, v32, -1, v32, v47, v32, v32);
+            pAudioPlayer->PlaySound((SoundID)v125, v102, 0, -1, 0, v47, 0, 0);
             return 0;
           }
-          goto LABEL_93;
+          sub_43A97E(uLayingItemID, a2);
+          ++pSpriteObjects[uLayingItemID].uType;
+          v95 = 0;
+          for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+          {
+            if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+              v95 = v52;
+          }
+          pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+          if ( !v95 )
+            SpriteObject::OnInteraction(uLayingItemID);
+          v96 = pSpriteObjects[uLayingItemID].uSoundID;
+          pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+          pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+          pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+          pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+          if ( !v96 )
+            v97 = 0;
+          else
+            v97 = (signed __int16)v96 + 4;
+          v124 = 8 * uLayingItemID;
+          LOBYTE(v124) = v124 | 2;
+          v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+          pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+          return 0;
         }
 LABEL_172:
         v143 = 17030;
@@ -5302,40 +5097,27 @@
             break;
         }
         v138 = 1;
-        if ( v151 != OBJECT_Actor)
+        if ( PID_TYPE(a2) != OBJECT_Actor)
         {
           if ( pSpriteObjects[uLayingItemID].uType != 9030 || pSpriteObjects[uLayingItemID].spell_skill != 4 )
-		  {
-			  SpriteObject::OnInteraction(v153);
-			  return 0;
-		  }
-		  pSpriteObjects[uLayingItemID]._46BEF1_apply_spells_aoe();
+          {
+            SpriteObject::OnInteraction(uLayingItemID);
+            return 0;
+          }
+          pSpriteObjects[uLayingItemID]._46BEF1_apply_spells_aoe();
 LABEL_233:
           if ( !v138 )
           {
-            v109 = pObjectList->uNumObjects;
             ++pSpriteObjects[uLayingItemID].uType;
-            v110 = 0;
-            if ( (signed int)v109 <= 0 )
-            {
-LABEL_238:
-              v112 = 0;
-            }
-            else
+            v112 = 0;
+            for ( v110 = 0; v110 < (signed int)pObjectList->uNumObjects; ++v110 )
             {
-              v111 = (char *)&pObjectList->pObjects->uObjectID;
-              while ( pSpriteObjects[uLayingItemID].uType != *(short *)v111 )
-              {
-                ++v110;
-                v111 += 56;
-                if ( v110 >= (signed int)v109 )
-                  goto LABEL_238;
-              }
-              v112 = v110;
+              if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v110].uObjectID )
+                v112 = v110;
             }
             pSpriteObjects[uLayingItemID].uObjectDescID = v112;
             if ( !v112 )
-              SpriteObject::OnInteraction(v153);
+              SpriteObject::OnInteraction(uLayingItemID);
             pSpriteObjects[uLayingItemID].vVelocity.z = 0;
             pSpriteObjects[uLayingItemID].vVelocity.y = 0;
             pSpriteObjects[uLayingItemID].vVelocity.x = 0;
@@ -5345,16 +5127,16 @@
               v114 = (signed __int16)v113 + 4;
             else
               v114 = 0;
-            v115 = 8 * v153;
-            LOBYTE(v115) = PID(OBJECT_Item,v153);
+            v115 = 8 * uLayingItemID;
+            LOBYTE(v115) = PID(OBJECT_Item, uLayingItemID);
             v125 = v143 + 1;
             pAudioPlayer->PlaySound((SoundID)v125, v115, 0, -1, 0, v114, 0, 0);
             return 0;
           }
-          SpriteObject::OnInteraction(v153);
+          SpriteObject::OnInteraction(uLayingItemID);
           return 0;
         }
-        v106 = v145;
+        v106 = a2;
         v150 = 0;
         v139 = PID_ID(v106);
         v137 = pSpriteObjects[uLayingItemID].spell_level;
@@ -5420,55 +5202,100 @@
         v107 = v135;
         goto LABEL_222;
       }
-      if ( pSpriteObjects[uLayingItemID].uType == 8090 || pSpriteObjects[uLayingItemID].uType == 7030 || pSpriteObjects[uLayingItemID].uType == 7090 || pSpriteObjects[uLayingItemID].uType == 8000 )
-        goto LABEL_93;
+      if ( pSpriteObjects[uLayingItemID].uType == 8090
+        || pSpriteObjects[uLayingItemID].uType == 7030
+        || pSpriteObjects[uLayingItemID].uType == 7090 || pSpriteObjects[uLayingItemID].uType == 8000 )
+      {
+        sub_43A97E(uLayingItemID, a2);
+        ++pSpriteObjects[uLayingItemID].uType;
+        v95 = 0;
+        for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+        {
+          if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+            v95 = v52;
+        }
+        pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+        if ( !v95 )
+          SpriteObject::OnInteraction(uLayingItemID);
+        v96 = pSpriteObjects[uLayingItemID].uSoundID;
+        pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+        pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+        if ( !v96 )
+          v97 = 0;
+        else
+          v97 = (signed __int16)v96 + 4;
+        v124 = 8 * uLayingItemID;
+        LOBYTE(v124) = v124 | 2;
+        v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+        pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+        return 0;
+      }
       if ( pSpriteObjects[uLayingItemID].uType == 8010 )
       {
-        if ( v151 == 3
-          && MonsterStats::BelongsToSupertype(pActors[PID_ID(v145)].pMonsterInfo.uID, MONSTER_SUPERTYPE_UNDEAD) )
-          sub_43A97E(v153, v145);
-        v93 = pObjectList->uNumObjects;
+        if ( PID_TYPE(a2) == 3
+          && MonsterStats::BelongsToSupertype(pActors[PID_ID(a2)].pMonsterInfo.uID, MONSTER_SUPERTYPE_UNDEAD) )
+          sub_43A97E(uLayingItemID, a2);
         ++pSpriteObjects[uLayingItemID].uType;
-        v9 = 0;
-        v52 = 0;
-        if ( (signed int)v93 > 0 )
+        //v9 = 0;
+        v95 = 0;
+        for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
         {
-          v94 = (char *)&pObjectList->pObjects->uObjectID;
-          while ( pSpriteObjects[uLayingItemID].uType != *(short *)v94 )
-          {
-            ++v52;
-            v94 += 56;
-            if ( v52 >= (signed int)v93 )
-              goto LABEL_181;
-          }
-          v95 = v52;
-          pSpriteObjects[uLayingItemID].uObjectDescID = v95;
-			if ( v95 == (short)v9 )
-				SpriteObject::OnInteraction(v153);
-			v96 = pSpriteObjects[uLayingItemID].uSoundID;
-			pSpriteObjects[uLayingItemID].vVelocity.z = v9;
-			pSpriteObjects[uLayingItemID].vVelocity.y = v9;
-			pSpriteObjects[uLayingItemID].vVelocity.x = v9;
-			pSpriteObjects[uLayingItemID].uSpriteFrameID = v9;
-			if ( v96 == (short)v9 )
-				v97 = 0;
-			else
-				v97 = (signed __int16)v96 + 4;
-			v92 = v153;
-            v124 = 8 * v92;
-            LOBYTE(v124) = v124 | 2;
-            v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-            pAudioPlayer->PlaySound((SoundID)v125, v124, v9, -1, v9, v97, v9, v9);
-            return 0;
+          if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+            v95 = v52;
         }
-        goto LABEL_181;
+        pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+        if ( !v95 )
+          SpriteObject::OnInteraction(uLayingItemID);
+        v96 = pSpriteObjects[uLayingItemID].uSoundID;
+         pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+        pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+        if ( !v96 )
+          v97 = 0;
+        else
+          v97 = (signed __int16)v96 + 4;
+        v92 = uLayingItemID;
+        v124 = 8 * v92;
+        LOBYTE(v124) = v124 | 2;
+        v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+        pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+        return 0;
       }
       v79 = pSpriteObjects[uLayingItemID].uType == 8030;
     }
     else
     {
       if ( pSpriteObjects[uLayingItemID].uType == 6090 )
-        goto LABEL_93;
+      {
+        sub_43A97E(uLayingItemID, a2);
+        ++pSpriteObjects[uLayingItemID].uType;
+        v95 = 0;
+        for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+        {
+          if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+            v95 = v52;
+        }
+        pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+        if ( !v95 )
+          SpriteObject::OnInteraction(uLayingItemID);
+        v96 = pSpriteObjects[uLayingItemID].uSoundID;
+        pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+        pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+        if ( !v96 )
+          v97 = 0;
+        else
+          v97 = (signed __int16)v96 + 4;
+        v124 = 8 * uLayingItemID;
+        LOBYTE(v124) = v124 | 2;
+        v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+        pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+        return 0;
+      }
       if ( pSpriteObjects[uLayingItemID].uType <= 4070 )
       {
         if ( pSpriteObjects[uLayingItemID].uType != 4070 )
@@ -5480,81 +5307,75 @@
             if ( v49 )
             {
               v50 = v49 - 908;
-              if ( !v50 )
-                goto LABEL_93;
+              if ( v49 == 908 )
+              {
+                sub_43A97E(uLayingItemID, a2);
+                ++pSpriteObjects[uLayingItemID].uType;
+                v95 = 0;
+                for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+                {
+                  if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+                    v95 = v52;
+                }
+                pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+                if ( !v95 )
+                  SpriteObject::OnInteraction(uLayingItemID);
+                v96 = pSpriteObjects[uLayingItemID].uSoundID;
+                pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+                pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+                pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+                pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+                if ( !v96 )
+                  v97 = 0;
+                else
+                  v97 = (signed __int16)v96 + 4;
+                v124 = 8 * uLayingItemID;
+                LOBYTE(v124) = v124 | 2;
+                v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+                pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+                return 0;
+              }
               v45 = v50 - 30;
               v44 = v45 == 0;
               goto LABEL_91;
             }
-            v54 = pSpriteObjects[uLayingItemID].uType - 1;
-            v55 = pObjectList->uNumObjects;
-            v9 = 0;
-            v56 = 0;
-            v44 = pObjectList->uNumObjects == 0;
-            v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
-            pSpriteObjects[uLayingItemID].uType = v54;
-            if ( v20 | v44 )
+            //v9 = 0;
+            pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType - 1;
+            v58 = 0;
+            for ( v56 = 0; v56 < (signed int)pObjectList->uNumObjects; ++v56 )
             {
-LABEL_102:
-              v58 = 0;
-            }
-            else
-            {
-              v57 = (char *)&pObjectList->pObjects->uObjectID;
-              while ( v54 != *(short *)v57 )
-              {
-                ++v56;
-                v57 += 56;
-                if ( v56 >= (signed int)v55 )
-                  goto LABEL_102;
-              }
-              v58 = v56;
+              if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v56].uObjectID )
+                v58 = v56;
             }
             pSpriteObjects[uLayingItemID].uObjectDescID = v58;
             if ( !v58 )
-              SpriteObject::OnInteraction(v153);
+              SpriteObject::OnInteraction(uLayingItemID);
             pSpriteObjects[uLayingItemID].vVelocity.z = 0;
             pSpriteObjects[uLayingItemID].vVelocity.y = 0;
             pSpriteObjects[uLayingItemID].vVelocity.x = 0;
             pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
-            sub_43A97E(v153, v145);
-            if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v9 )
+            sub_43A97E(uLayingItemID, a2);
+            if ( !pSpriteObjects[uLayingItemID].uSoundID )
               v16 = 0;
             else
               v16 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-            v124 = 8 * v153;
+            v124 = 8 * uLayingItemID;
             LOBYTE(v124) = v124 | 2;
             v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-            pAudioPlayer->PlaySound((SoundID)v125, v124, v9, -1, v9, v16, v9, v9);
+            pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v16, 0, 0);
             return 0;
           }
-          v59 = pSpriteObjects[uLayingItemID].uType + 2;
-          v60 = pObjectList->uNumObjects;
-          v9 = 0;
-          v61 = 0;
-          v44 = pObjectList->uNumObjects == 0;
-          v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
-          pSpriteObjects[uLayingItemID].uType = v59;
-          if ( v20 | v44 )
+          //v9 = 0;
+          pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 2;
+          v63 = 0;
+          for ( v61 = 0; v61 < (signed int)pObjectList->uNumObjects; ++v61 )
           {
-LABEL_111:
-            v63 = 0;
-          }
-          else
-          {
-            v62 = (char *)&pObjectList->pObjects->uObjectID;
-            while ( v59 != *(short *)v62 )
-            {
-              ++v61;
-              v62 += 56;
-              if ( v61 >= (signed int)v60 )
-                goto LABEL_111;
-            }
-            v63 = v61;
+            if ( v59 == pObjectList->pObjects[v61].uObjectID )
+              v63 = v61;
           }
           pSpriteObjects[uLayingItemID].uObjectDescID = v63;
           if ( !v63 )
-            SpriteObject::OnInteraction(v153);
+            SpriteObject::OnInteraction(uLayingItemID);
           v64 = pSpriteObjects[uLayingItemID].uFacing - stru_5C6E00->uIntegerDoublePi;
           v44 = pSpriteObjects[uLayingItemID].spell_skill == 4;
           pSpriteObjects[uLayingItemID].vVelocity.z = 0;
@@ -5568,60 +5389,45 @@
             v141 = v65;
             do
             {
-              v64 += (signed int)stru_5C6E00->uIntegerHalfPi >> 1;
+              v64 += (signed int)stru_5C6E00->uIntegerHalfPi / 2;
               pSpriteObjects[uLayingItemID].Create(v64, 0, 1000, 0);
               --v141;
             }
             while ( v141 );
           }
-          SpriteObject::OnInteraction(v153);
-          if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v9 )
+          SpriteObject::OnInteraction(uLayingItemID);
+          if ( !pSpriteObjects[uLayingItemID].uSoundID )
             v16 = 0;
           else
             v16 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-          v124 = 8 * v153;
+          v124 = 8 * uLayingItemID;
           LOBYTE(v124) = v124 | 2;
           v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-          pAudioPlayer->PlaySound((SoundID)v125, v124, v9, -1, v9, v16, v9, v9);
+          pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v16, 0, 0);
           return 0;
         }
-        if ( v151 == 6 || v151 == 5 || (v66 = 0, !v151) )
+        //v66 = 0;
+        if ( PID_TYPE(a2) == 6 || PID_TYPE(a2) == 5 ||  !PID_TYPE(a2) )
           return 1;
-        v67 = pSpriteObjects[uLayingItemID].uType + 1;
-        v68 = pObjectList->uNumObjects;
-        v69 = 0;
-        v44 = pObjectList->uNumObjects == 0;
-        v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
-        pSpriteObjects[uLayingItemID].uType = v67;
-        if ( v20 | v44 )
+        pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 1;
+        v71 = 0;
+        for ( v69 = 0; v69 < (signed int)pObjectList->uNumObjects; ++v69 )
         {
-LABEL_128:
-          v71 = 0;
-        }
-        else
-        {
-          v70 = (char *)&pObjectList->pObjects->uObjectID;
-          while ( v67 != *(short *)v70 )
-          {
-            ++v69;
-            v70 += 56;
-            if ( v69 >= (signed int)v68 )
-              goto LABEL_128;
-          }
-          v71 = v69;
+          if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v69].uObjectID )
+            v71 = v69;
         }
         pSpriteObjects[uLayingItemID].uObjectDescID = v71;
         if ( !v71 )
-          SpriteObject::OnInteraction(v153);
+          SpriteObject::OnInteraction(uLayingItemID);
         v134 = 0;
-        v72 = v153;
+        v72 = uLayingItemID;
         v132 = 0;
-        pSpriteObjects[uLayingItemID].vVelocity.z = v66;
-        pSpriteObjects[uLayingItemID].vVelocity.y = v66;
-        pSpriteObjects[uLayingItemID].vVelocity.x = v66;
-        pSpriteObjects[uLayingItemID].uSpriteFrameID = v66;
+        pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+        pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
         AttackerInfo.Add(PID(OBJECT_Item,v72), 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v132, v134);
-        if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v66 )
+        if ( !pSpriteObjects[uLayingItemID].uSoundID )
           v78 = 0;
         else
           v78 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
@@ -5631,33 +5437,17 @@
       }
       if ( pSpriteObjects[uLayingItemID].uType == 4090 )
       {
-        v84 = pSpriteObjects[uLayingItemID].uType + 2;
-        v85 = pObjectList->uNumObjects;
-        v9 = 0;
-        v86 = 0;
-        v44 = pObjectList->uNumObjects == 0;
-        v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
-        pSpriteObjects[uLayingItemID].uType = v84;
-        if ( v20 | v44 )
+        //v9 = 0;
+        pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 2;
+        v88 = 0;
+        for ( v86 = 0; v86 < (signed int)pObjectList->uNumObjects; ++v86 )
         {
-LABEL_155:
-          v88 = 0;
-        }
-        else
-        {
-          v87 = (char *)&pObjectList->pObjects->uObjectID;
-          while ( v84 != *(short *)v87 )
-          {
-            ++v86;
-            v87 += 56;
-            if ( v86 >= (signed int)v85 )
-              goto LABEL_155;
-          }
-          v88 = v86;
+          if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v86].uObjectID )
+            v88 = v86;
         }
         pSpriteObjects[uLayingItemID].uObjectDescID = v88;
         if ( !v88 )
-          SpriteObject::OnInteraction(v153);
+          SpriteObject::OnInteraction(uLayingItemID);
         v89 = pSpriteObjects[uLayingItemID].uFacing - stru_5C6E00->uIntegerDoublePi;
         pSpriteObjects[uLayingItemID].vVelocity.z = 0;
         pSpriteObjects[uLayingItemID].vVelocity.y = 0;
@@ -5675,63 +5465,74 @@
           --v148;
         }
         while ( v148 );
-        SpriteObject::OnInteraction(v153);
-        if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v9 )
+        SpriteObject::OnInteraction(uLayingItemID);
+        if ( !pSpriteObjects[uLayingItemID].uSoundID )
           v16 = 0;
         else
           v16 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-        v124 = 8 * v153;
+        v124 = 8 * uLayingItemID;
         LOBYTE(v124) = v124 | 2;
         v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id-1] + 1;
-        pAudioPlayer->PlaySound((SoundID)v125, v124, v9, -1, v9, v16, v9, v9);
+        pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v16, 0, 0);
         return 0;
       }
       if ( pSpriteObjects[uLayingItemID].uType == 4092 )
       {
-        v80 = pObjectList->uNumObjects;
-        v66 = 0;
-        v81 = 0;
-        v44 = pObjectList->uNumObjects == 0;
-        v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
+        //v66 = 0;
         pSpriteObjects[uLayingItemID].uType = 4091;
-        if ( v20 | v44 )
+        v83 = 0;
+        for ( v81 = 0; v81 < (signed int)pObjectList->uNumObjects; ++v81 )
         {
-LABEL_144:
-          v83 = 0;
-        }
-        else
-        {
-          v82 = (char *)&pObjectList->pObjects->uObjectID;
-          while ( *(short *)v82 != 4091 )
-          {
-            ++v81;
-            v82 += 56;
-            if ( v81 >= (signed int)v80 )
-              goto LABEL_144;
-          }
-          v83 = v81;
+          if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v81].uObjectID )
+            v83 = v81;
         }
         pSpriteObjects[uLayingItemID].uObjectDescID = v83;
         if ( !v83 )
-          SpriteObject::OnInteraction(v153);
+          SpriteObject::OnInteraction(uLayingItemID);
         v134 = 0;
-        v72 = v153;
+        //v72 = uLayingItemID;
         v132 = pSpriteObjects[uLayingItemID].field_61;
-        pSpriteObjects[uLayingItemID].vVelocity.z = v66;
-        pSpriteObjects[uLayingItemID].vVelocity.y = v66;
-        pSpriteObjects[uLayingItemID].vVelocity.x = v66;
-        pSpriteObjects[uLayingItemID].uSpriteFrameID = v66;
-        AttackerInfo.Add(PID(OBJECT_Item,v72), 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v132, v134);
-        if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v66 )
+        pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+        pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+        AttackerInfo.Add(PID(OBJECT_Item, uLayingItemID), 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v132, v134);
+        if ( !pSpriteObjects[uLayingItemID].uSoundID )
           v78 = 0;
         else
           v78 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
         v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-        pAudioPlayer->PlaySound((SoundID)v125, pSpriteObjects[uLayingItemID].vPosition.x, v66, -1, v66, v78, v66, v66);
+        pAudioPlayer->PlaySound((SoundID)v125, pSpriteObjects[uLayingItemID].vPosition.x, 0, -1, 0, v78, 0, 0);
         return 0;
       }
       if ( pSpriteObjects[uLayingItemID].uType == 4100 || pSpriteObjects[uLayingItemID].uType == 6010 )
-        goto LABEL_93;
+      {
+        sub_43A97E(uLayingItemID, a2);
+        ++pSpriteObjects[uLayingItemID].uType;
+        v95 = 0;
+        for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+        {
+          if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+            v95 = v52;
+        }
+        pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+        if ( !v95 )
+          SpriteObject::OnInteraction(uLayingItemID);
+        v96 = pSpriteObjects[uLayingItemID].uSoundID;
+        pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+        pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+        pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+        if ( !v96 )
+          v97 = 0;
+        else
+          v97 = (signed __int16)v96 + 4;
+        v124 = 8 * uLayingItemID;
+        LOBYTE(v124) = v124 | 2;
+        v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+        pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+        return 0;
+      }
       v79 = pSpriteObjects[uLayingItemID].uType == 6040;
     }
     if ( !v79 )
@@ -5739,37 +5540,50 @@
     goto LABEL_172;
   }
   if ( pSpriteObjects[uLayingItemID].uType == 3060 )
-    goto LABEL_93;
+  {
+    sub_43A97E(uLayingItemID, a2);
+    ++pSpriteObjects[uLayingItemID].uType;
+    v95 = 0;
+    for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+    {
+      if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+        v95 = v52;
+    }
+    pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+    if ( !v95 )
+      SpriteObject::OnInteraction(uLayingItemID);
+    v96 = pSpriteObjects[uLayingItemID].uSoundID;
+    pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+    pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+    if ( !v96 )
+      v97 = 0;
+    else
+      v97 = (signed __int16)v96 + 4;
+    v124 = 8 * uLayingItemID;
+    LOBYTE(v124) = v124 | 2;
+    v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+    pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+    return 0;
+  }
   if ( pSpriteObjects[uLayingItemID].uType <= 555 )
   {
     if ( pSpriteObjects[uLayingItemID].uType == 555 )
     {
-      sub_43A97E(v153, v145);
-      v23 = pObjectList->uNumObjects;
+      sub_43A97E(uLayingItemID, a2);
       ++pSpriteObjects[uLayingItemID].uType;
       v18 = 0;
-      v24 = 0;
-      if ( (signed int)v23 <= 0 )
-      {
-LABEL_41:
-        v22 = 0;
-      }
-      else
+      v22 = 0;
+      v25 = (char *)&pObjectList->pObjects->uObjectID;
+      for ( v24 = 0; v24 < (signed int)pObjectList->uNumObjects; ++v24 )
       {
-        v25 = (char *)&pObjectList->pObjects->uObjectID;
-        while ( pSpriteObjects[uLayingItemID].uType != *(short *)v25 )
-        {
-          ++v24;
-          v25 += 56;
-          if ( v24 >= (signed int)v23 )
-            goto LABEL_41;
-        }
-        v22 = v24;
+        if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v24].uObjectID )
+          v22 = v24;
       }
-LABEL_42:
       pSpriteObjects[uLayingItemID].uObjectDescID = v22;
       if ( v22 == v18 )
-        SpriteObject::OnInteraction(v153);
+        SpriteObject::OnInteraction(uLayingItemID);
       pSpriteObjects[uLayingItemID].vVelocity.z = v18;
       pSpriteObjects[uLayingItemID].vVelocity.y = v18;
       pSpriteObjects[uLayingItemID].vVelocity.x = v18;
@@ -5788,18 +5602,29 @@
         case 530:
         case 535:
         case 540:
-          sub_43A97E(v153, v145);
-          v8 = pObjectList->uNumObjects;
+          sub_43A97E(uLayingItemID, a2);
           ++pSpriteObjects[uLayingItemID].uType;
-          v9 = 0;
-          v10 = 0;
-          if ( (signed int)v8 <= 0 )
+          v12 = 0;
+          for ( v10 = 0; v10 < (signed int)pObjectList->uNumObjects; ++v10 )
           {
-            v12 = 0;
-            goto LABEL_24;
+            if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v10].uObjectID )
+              v12 = v10;
           }
-          v11 = (char *)&pObjectList->pObjects->uObjectID;
-          break;
+          pSpriteObjects[uLayingItemID].uObjectDescID = v12;
+          if ( !v12 )
+            SpriteObject::OnInteraction(uLayingItemID);
+          v44 = pSpriteObjects[uLayingItemID].uType == 555;
+          pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+          pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+          pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+          pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+          if ( !v44 )
+          {
+            v13 = 8 * uLayingItemID;
+            LOBYTE(v13) = PID(OBJECT_Item, uLayingItemID);
+            pAudioPlayer->PlaySound(SOUND_8, v13, 0, -1, 0, 0, 0, 0);
+          }
+          return 0;
         case 545:
         case 550:
           if ( pSpriteObjects[uLayingItemID].stru_24.uItemID != 405 && pSpriteObjects[uLayingItemID].stru_24.uSpecEnchantmentType != 3 )
@@ -5808,54 +5633,46 @@
             pSpriteObjects[uLayingItemID].vVelocity.y = 0;
             pSpriteObjects[uLayingItemID].vVelocity.x = 0;
             pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
-            sub_43A97E(v153, v145);
-            SpriteObject::OnInteraction(v153);
+            sub_43A97E(uLayingItemID, a2);
+            SpriteObject::OnInteraction(uLayingItemID);
             if ( pSpriteObjects[uLayingItemID].uSoundID == 0 )
               v16 = 0;
             else
               v16 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-            v124 = 8 * v153;
+            v124 = 8 * uLayingItemID;
             LOBYTE(v124) = v124 | 2;
             v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id] + 1;
             pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v16, 0, 0);
             return 0;
           }
-          v17 = pObjectList->uNumObjects;
           v18 = 0;
-          v19 = 0;
-          v44 = pObjectList->uNumObjects == 0;
-          v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
           pSpriteObjects[uLayingItemID].uType = 600;
-          if ( v20 | v44 )
-            goto LABEL_41;
-          v21 = (char *)&pObjectList->pObjects->uObjectID;
-          while ( *(short *)v21 != 600 )
+          v22 = 0;
+          for ( v19 = 0; v19 < (signed int)pObjectList->uNumObjects; ++v19 )
           {
-            ++v19;
-            v21 += 56;
-            if ( v19 >= (signed int)v17 )
-              goto LABEL_41;
+            if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v19].uObjectID )
+              v22 = v19;
           }
-          v22 = v19;
-          goto LABEL_42;
+          pSpriteObjects[uLayingItemID].uObjectDescID = v22;
+          if ( !v22 )
+            SpriteObject::OnInteraction(uLayingItemID);
+          pSpriteObjects[uLayingItemID].vVelocity.z = v18;
+          pSpriteObjects[uLayingItemID].vVelocity.y = v18;
+          pSpriteObjects[uLayingItemID].vVelocity.x = v18;
+          pSpriteObjects[uLayingItemID].uSpriteFrameID = v18;
         default:
           return 0;
       }
-      while ( pSpriteObjects[uLayingItemID].uType != *(short *)v11 )
+      v12 = 0;
+      for ( v10; v10 < (signed int)v8; ++v10 )
       {
-        ++v10;
         v11 += 56;
-        if ( v10 >= (signed int)v8 )
-        {
-          v12 = 0;
-          goto LABEL_24;
-        }
+        if ( pSpriteObjects[uLayingItemID].uType != *(short *)v11 )
+          v12 = v10;
       }
-      v12 = v10;
-LABEL_24:
       pSpriteObjects[uLayingItemID].uObjectDescID = v12;
       if ( !v12 )
-        SpriteObject::OnInteraction(v153);
+        SpriteObject::OnInteraction(uLayingItemID);
       v44 = pSpriteObjects[uLayingItemID].uType == 555;
       pSpriteObjects[uLayingItemID].vVelocity.z = 0;
       pSpriteObjects[uLayingItemID].vVelocity.y = 0;
@@ -5863,9 +5680,9 @@
       pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
       if ( !v44 )
       {
-        v13 = 8 * v153;
-        LOBYTE(v13) = PID(OBJECT_Item,v153);
-        pAudioPlayer->PlaySound(SOUND_8, v13, v9, -1, v9, v9, v9, v9);
+        v13 = 8 * uLayingItemID;
+        LOBYTE(v13) = PID(OBJECT_Item, uLayingItemID);
+        pAudioPlayer->PlaySound(SOUND_8, v13, 0, -1, 0, 0, 0, 0);
         return 0;
       }
     }
@@ -5880,284 +5697,276 @@
     if ( v42 )
     {
       v43 = v42 - 40;
-      if ( !v43 )
-        goto LABEL_59;
+      if ( v42 == 40 )
+      {
+        if ( PID_TYPE(a2) != 3 )
+        {
+          //v32 = 0;
+          pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 1;
+          v46 = 0;
+          for ( v146 = 0; v146 < (signed int)pObjectList->uNumObjects; ++v146 )
+          {
+            if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v146].uObjectID )
+              v46 = v146;
+          }
+          pSpriteObjects[uLayingItemID].uObjectDescID = v46;
+          if ( !v46 )
+            SpriteObject::OnInteraction(uLayingItemID);
+          v100 = pSpriteObjects[uLayingItemID].field_61;
+          pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+          v102 = 8 * uLayingItemID;
+          LOBYTE(v102) = PID(OBJECT_Item, uLayingItemID);
+          pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+          pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+          pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+          AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, 0);
+          if (object->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
+            trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, object->uParticleTrailColor);
+          if ( !pSpriteObjects[uLayingItemID].uSoundID )
+            v47 = 0;
+          else
+            v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
+          v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+          pAudioPlayer->PlaySound((SoundID)v125, v102, 0, -1, 0, v47, 0, 0);
+          return 0;
+        }
+        return 1;
+      }
       v45 = v43 - 910;
       v44 = v45 == 0;
 LABEL_91:
       if ( !v44 && v45 != 20 )
         return 0;
     }
-LABEL_93:
-    sub_43A97E(v153, v145);
-    v51 = pObjectList->uNumObjects;
+    sub_43A97E(uLayingItemID, a2);
     ++pSpriteObjects[uLayingItemID].uType;
-    v9 = 0;
-    v52 = 0;
-    if ( (signed int)v51 > 0 )
+    v95 = 0;
+    for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
     {
-      v53 = (char *)&pObjectList->pObjects->uObjectID;
-      while ( pSpriteObjects[uLayingItemID].uType != *(short *)v53 )
-      {
-        ++v52;
-        v53 += 56;
-        if ( v52 >= (signed int)v51 )
-          goto LABEL_181;
-      }
-      v95 = v52;
+      if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+        v95 = v52;
     }
-	else
-	{
-LABEL_181:
-    v95 = 0;
-	}
     pSpriteObjects[uLayingItemID].uObjectDescID = v95;
-    if ( v95 == (short)v9 )
-      SpriteObject::OnInteraction(v153);
+    if ( !v95 )
+      SpriteObject::OnInteraction(uLayingItemID);
     v96 = pSpriteObjects[uLayingItemID].uSoundID;
-    pSpriteObjects[uLayingItemID].vVelocity.z = v9;
-    pSpriteObjects[uLayingItemID].vVelocity.y = v9;
-    pSpriteObjects[uLayingItemID].vVelocity.x = v9;
-    pSpriteObjects[uLayingItemID].uSpriteFrameID = v9;
-    if ( v96 == (short)v9 )
+    pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+    pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+    if ( !v96 )
       v97 = 0;
     else
       v97 = (signed __int16)v96 + 4;
-    v92 = v153;
+    v124 = 8 * uLayingItemID;
+    LOBYTE(v124) = v124 | 2;
+    v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+    pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+    return 0;
+  }
+  if ( pSpriteObjects[uLayingItemID].uType == 1100 )
+  {
+    sub_43A97E(uLayingItemID, a2);
+    ++pSpriteObjects[uLayingItemID].uType;
+    v95 = 0;
+    for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+    {
+      if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+        v95 = v52;
+    }
+    pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+    if ( !v95 )
+      SpriteObject::OnInteraction(uLayingItemID);
+    v96 = pSpriteObjects[uLayingItemID].uSoundID;
+    pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+    pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+    if ( !v96 )
+      v97 = 0;
+    else
+      v97 = (signed __int16)v96 + 4;
+    v92 = uLayingItemID;
     v124 = 8 * v92;
     LOBYTE(v124) = v124 | 2;
     v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-    pAudioPlayer->PlaySound((SoundID)v125, v124, v9, -1, v9, v97, v9, v9);
+    pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
     return 0;
   }
-  if ( pSpriteObjects[uLayingItemID].uType == 1100 )
-    goto LABEL_93;
   v26 = pSpriteObjects[uLayingItemID].uType - 600;
-  if ( !v26 )
+  if ( pSpriteObjects[uLayingItemID].uType == 600 )
   {
-    v33 = pObjectList->uNumObjects;
-    v34 = 0;
-    v44 = pObjectList->uNumObjects == 0;
-    v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
     pSpriteObjects[uLayingItemID].uType = 601;
-    if ( v20 | v44 )
+    v36 = 0;
+    for ( v34 = 0; v34 < (signed int)pObjectList->uNumObjects; ++v34 )
     {
-LABEL_69:
-      v36 = 0;
-    }
-    else
-    {
-      v35 = (char *)&pObjectList->pObjects->uObjectID;
-      while ( *(short *)v35 != 601 )
-      {
-        ++v34;
-        v35 += 56;
-        if ( v34 >= (signed int)v33 )
-          goto LABEL_69;
-      }
-      v36 = v34;
+      if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v34].uObjectID )
+        v36 = v34;
     }
     pSpriteObjects[uLayingItemID].uObjectDescID = v36;
     if ( !v36 )
-      SpriteObject::OnInteraction(v153);
+      SpriteObject::OnInteraction(uLayingItemID);
     v37 = pSpriteObjects[uLayingItemID].vPosition.z;
     pSpriteObjects[uLayingItemID].vVelocity.z = 0;
-    v38 = 8 * v153;
+    v38 = 8 * uLayingItemID;
     v39 = pSpriteObjects[uLayingItemID].vPosition.y;
-    LOBYTE(v38) = PID(OBJECT_Item,v153);
+    LOBYTE(v38) = PID(OBJECT_Item, uLayingItemID);
     pSpriteObjects[uLayingItemID].vVelocity.y = 0;
     pSpriteObjects[uLayingItemID].vVelocity.x = 0;
     v40 = pSpriteObjects[uLayingItemID].vPosition.x;
     pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
     v147 = v38;
     AttackerInfo.Add(v38, 512, v40, v39, v37, 0, 0);
-    if (v3->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
-      trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v3->uParticleTrailColor);
+    if (object->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
+      trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, object->uParticleTrailColor);
     pAudioPlayer->PlaySound(SOUND_8, v147, 0, -1, 0, 0, 0, 0);
     return 0;
   }
   v27 = v26 - 410;
-  if ( !v27 )
-    goto LABEL_93;
+  if ( v26 == 410 )
+  {
+    sub_43A97E(uLayingItemID, a2);
+    ++pSpriteObjects[uLayingItemID].uType;
+    v95 = 0;
+    for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
+    {
+      if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+        v95 = v52;
+    }
+    pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+    if ( !v95 )
+    SpriteObject::OnInteraction(uLayingItemID);
+    v96 = pSpriteObjects[uLayingItemID].uSoundID;
+    pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+    pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+    if ( !v96 )
+      v97 = 0;
+    else
+      v97 = (signed __int16)v96 + 4;
+    v124 = 8 * uLayingItemID;
+    LOBYTE(v124) = v124 | 2;
+    v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+    pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+    return 0;
+  }
   v28 = v27 - 40;
   if ( !v28 )
-    goto LABEL_191;
+  {
+    v95 = 0;
+    pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 1;
+    for ( v146 = 0; v146 < (signed int)pObjectList->uNumObjects; ++v146 )
+    {
+      if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v146].uObjectID )
+        v95 = v146;
+    }
+    pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+    if ( !v95 )
+      SpriteObject::OnInteraction(uLayingItemID);
+    v100 = pSpriteObjects[uLayingItemID].field_61;
+    pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+    v102 = 8 * uLayingItemID;
+    LOBYTE(v102) = PID(OBJECT_Item, uLayingItemID);
+    pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+    AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, 0);
+    if (object->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
+      trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, object->uParticleTrailColor);
+    if ( !pSpriteObjects[uLayingItemID].uSoundID )
+      v47 = 0;
+    else
+      v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
+    v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+    pAudioPlayer->PlaySound((SoundID)v125, v102, 0, -1, 0, v47, 0, 0);
+    return 0;
+  }
   v29 = v28 - 10;
   if ( v29 )
   {
     if ( v29 != 20 )
       return 0;
-LABEL_59:
-    if ( v151 != 3 )
+    if ( PID_TYPE(a2) != 3 )
     {
-      v30 = pSpriteObjects[uLayingItemID].uType + 1;
-      v31 = pObjectList->uNumObjects;
-      v32 = 0;
-      pSpriteObjects[uLayingItemID].uType = v30;
-      v146 = 0;
-      if ( (signed int)v31 > 0 )
+      //v32 = 0;
+      pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 1;
+      v46 = 0;
+      for ( v146 = 0; v146 < (signed int)pObjectList->uNumObjects; ++v146 )
       {
-        v140 = (char *)&pObjectList->pObjects->uObjectID;
-        while ( v30 != *(short *)v140 )
-        {
-          ++v146;
-          v140 += 56;
-          if ( v146 >= (signed int)v31 )
-          {
-            v46 = 0;
-            pSpriteObjects[uLayingItemID].uObjectDescID = v46;
-            if ( v46 == (short)v32 )
-              SpriteObject::OnInteraction(v153);
-            v100 = pSpriteObjects[uLayingItemID].field_61;
-            pSpriteObjects[uLayingItemID].uSpriteFrameID = v32;
-            v102 = 8 * v153;
-            LOBYTE(v102) = PID(OBJECT_Item,v153);
-            pSpriteObjects[uLayingItemID].vVelocity.x = v32;
-            pSpriteObjects[uLayingItemID].vVelocity.y = v32;
-            pSpriteObjects[uLayingItemID].vVelocity.z = v32;
-            AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, v32);
-            if (v3->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
-              trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v3->uParticleTrailColor);
-            if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v32 )
-              v47 = 0;
-            else
-              v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-            v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-            pAudioPlayer->PlaySound((SoundID)v125, v102, v32, -1, v32, v47, v32, v32);
-            return 0;
-          }
-        }
-        v46 = v146;
-        pSpriteObjects[uLayingItemID].uObjectDescID = v46;
-        if ( v46 == (short)v32 )
-          SpriteObject::OnInteraction(v153);
-        v100 = pSpriteObjects[uLayingItemID].field_61;
-        pSpriteObjects[uLayingItemID].uSpriteFrameID = v32;
-        v102 = 8 * v153;
-        LOBYTE(v102) = PID(OBJECT_Item,v153);
-        pSpriteObjects[uLayingItemID].vVelocity.x = v32;
-        pSpriteObjects[uLayingItemID].vVelocity.y = v32;
-        pSpriteObjects[uLayingItemID].vVelocity.z = v32;
-        AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, v32);
-        if (v3->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
-          trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v3->uParticleTrailColor);
-        if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v32 )
-          v47 = 0;
-        else
-          v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
-        v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-        pAudioPlayer->PlaySound((SoundID)v125, v102, v32, -1, v32, v47, v32, v32);
-        return 0;
+        if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v146].uObjectID )
+          v46 = v146;
       }
-      v46 = 0;
       pSpriteObjects[uLayingItemID].uObjectDescID = v46;
-      if ( v46 == (short)v32 )
-        SpriteObject::OnInteraction(v153);
+      if ( !v46 )
+        SpriteObject::OnInteraction(uLayingItemID);
       v100 = pSpriteObjects[uLayingItemID].field_61;
-      pSpriteObjects[uLayingItemID].uSpriteFrameID = v32;
-      v102 = 8 * v153;
-      LOBYTE(v102) = PID(OBJECT_Item,v153);
-      pSpriteObjects[uLayingItemID].vVelocity.x = v32;
-      pSpriteObjects[uLayingItemID].vVelocity.y = v32;
-      pSpriteObjects[uLayingItemID].vVelocity.z = v32;
-      AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, v32);
-      if (v3->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
-        trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v3->uParticleTrailColor);
-      if ( pSpriteObjects[uLayingItemID].uSoundID == (short)v32 )
+      pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+      v102 = 8 * uLayingItemID;
+      LOBYTE(v102) = PID(OBJECT_Item, uLayingItemID);
+      pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+      pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+      pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+      AttackerInfo.Add(v102, 512, pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, v100, 0);
+      if (object->uFlags & OBJECT_DESC_TRIAL_PARTICLE)
+        trail_particle_generator.GenerateTrailParticles(pSpriteObjects[uLayingItemID].vPosition.x, pSpriteObjects[uLayingItemID].vPosition.y, pSpriteObjects[uLayingItemID].vPosition.z, object->uParticleTrailColor);
+      if ( !pSpriteObjects[uLayingItemID].uSoundID )
         v47 = 0;
       else
         v47 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
       v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-      pAudioPlayer->PlaySound((SoundID)v125, v102, v32, -1, v32, v47, v32, v32);
+      pAudioPlayer->PlaySound((SoundID)v125, v102, 0, -1, 0, v47, 0, 0);
       return 0;
     }
     return 1;
   }
 LABEL_247:
-  if ( v151 == 6 || v151 == 5 || (v9 = 0, !v151) )
+  //v9 = 0;
+  if ( PID_TYPE(a2) == 6 || PID_TYPE(a2) == 5 || !PID_TYPE(a2) )
     return 1;
-  if ( v151 != 2 )
+  if ( PID_TYPE(a2) != 2 )
   {
-    sub_43A97E(v153, v145);
-    v122 = pObjectList->uNumObjects;
+    sub_43A97E(uLayingItemID, a2);
     ++pSpriteObjects[uLayingItemID].uType;
-    v52 = 0;
-    if ( (signed int)v122 > 0 )
+    v95 = 0;
+    for ( v52 = 0; v52 < (signed int)pObjectList->uNumObjects; ++v52 )
     {
-      v123 = (char *)&pObjectList->pObjects->uObjectID;
-      while ( pSpriteObjects[uLayingItemID].uType != *(short *)v123 )
-      {
-        ++v52;
-        v123 += 56;
-        if ( v52 >= (signed int)v122 )
-          goto LABEL_181;
-      }
-      v95 = v52;
-      pSpriteObjects[uLayingItemID].uObjectDescID = v95;
-      if ( v95 == (short)v9 )
-        SpriteObject::OnInteraction(v153);
-      v96 = pSpriteObjects[uLayingItemID].uSoundID;
-      pSpriteObjects[uLayingItemID].vVelocity.z = v9;
-      pSpriteObjects[uLayingItemID].vVelocity.y = v9;
-      pSpriteObjects[uLayingItemID].vVelocity.x = v9;
-      pSpriteObjects[uLayingItemID].uSpriteFrameID = v9;
-      if ( v96 == (short)v9 )
-        v97 = 0;
-      else
-        v97 = (signed __int16)v96 + 4;
-      v92 = v153;
-      v124 = 8 * v92;
-      LOBYTE(v124) = v124 | 2;
-      v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
-      pAudioPlayer->PlaySound((SoundID)v125, v124, v9, -1, v9, v97, v9, v9);
-      return 0;
+      if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v52].uObjectID )
+        v95 = v52;
     }
-    goto LABEL_181;
+    pSpriteObjects[uLayingItemID].uObjectDescID = v95;
+    if ( !v95 )
+      SpriteObject::OnInteraction(uLayingItemID);
+    pSpriteObjects[uLayingItemID].vVelocity.z = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.y = 0;
+    pSpriteObjects[uLayingItemID].vVelocity.x = 0;
+    pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
+    if ( !pSpriteObjects[uLayingItemID].uSoundID )
+      v97 = 0;
+    else
+      v97 = (signed __int16)pSpriteObjects[uLayingItemID].uSoundID + 4;
+    v124 = 8 * uLayingItemID;
+    LOBYTE(v124) = v124 | 2;
+    v125 = word_4EE088_sound_ids[pSpriteObjects[uLayingItemID].spell_id - 1] + 1;
+    pAudioPlayer->PlaySound((SoundID)v125, v124, 0, -1, 0, v97, 0, 0);
+    return 0;
   }
-  v117 = pSpriteObjects[uLayingItemID].uType + 1;
-  v118 = pObjectList->uNumObjects;
-  v119 = 0;
-  v44 = pObjectList->uNumObjects == 0;
-  v20 = (pObjectList->uNumObjects & 0x80000000u) != 0;
-  pSpriteObjects[uLayingItemID].uType = v117;
-  if ( v20 | v44 )
-  {
-    v121 = 0;
-  }
-  else
+  pSpriteObjects[uLayingItemID].uType = pSpriteObjects[uLayingItemID].uType + 1;
+  v121 = 0;
+  for ( v119 = 0; v119 < (signed int)pObjectList->uNumObjects; ++v119 )
   {
-    v120 = (char *)&pObjectList->pObjects->uObjectID;
-    while ( v117 != *(short *)v120 )
-    {
-      ++v119;
-      v120 += 56;
-      if ( v119 >= (signed int)v118 )
-      {
-        v121 = 0;
-        pSpriteObjects[uLayingItemID].uObjectDescID = v121;
-        if ( !v121 )
-          SpriteObject::OnInteraction(v153);
-        pSpriteObjects[uLayingItemID].vVelocity.z = 0;
-        pSpriteObjects[uLayingItemID].vVelocity.y = 0;
-        pSpriteObjects[uLayingItemID].vVelocity.x = 0;
-        pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
-        v13 = 8 * v153;
-        LOBYTE(v13) = PID(OBJECT_Item,v153);
-        pAudioPlayer->PlaySound(SOUND_8, v13, v9, -1, v9, v9, v9, v9);
-        return 0;
-      }
-    }
-    v121 = v119;
+    if ( pSpriteObjects[uLayingItemID].uType == pObjectList->pObjects[v119].uObjectID )
+      v121 = v119;
   }
   pSpriteObjects[uLayingItemID].uObjectDescID = v121;
   if ( !v121 )
-    SpriteObject::OnInteraction(v153);
+    SpriteObject::OnInteraction(uLayingItemID);
   pSpriteObjects[uLayingItemID].vVelocity.z = 0;
   pSpriteObjects[uLayingItemID].vVelocity.y = 0;
   pSpriteObjects[uLayingItemID].vVelocity.x = 0;
   pSpriteObjects[uLayingItemID].uSpriteFrameID = 0;
-  v13 = 8 * v153;
-  LOBYTE(v13) = PID(OBJECT_Item,v153);
-  pAudioPlayer->PlaySound(SOUND_8, v13, v9, -1, v9, v9, v9, v9);
+  v13 = 8 * uLayingItemID;
+  LOBYTE(v13) = PID(OBJECT_Item,uLayingItemID);
+  pAudioPlayer->PlaySound(SOUND_8, v13, 0, -1, 0, 0, 0, 0);
   return 0;
 }
--- a/mm7_3.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_3.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -210,7 +210,7 @@
 
   a11 = ecx0;
 
-  BLVFace f; // [sp+Ch] [bp-7Ch]@1
+  BLVFace face; // [sp+Ch] [bp-7Ch]@1
 
   result = 0;
   for ( a10 = 0; a10 < (signed int)pOutdoor->uNumBModels; ++a10 )
@@ -225,51 +225,51 @@
           && stru_721530.sMaxY <= pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.y2 && stru_721530.sMinY >= pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.y1
           && stru_721530.sMaxZ <= pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.z2 && stru_721530.sMinZ >= pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.z1 )
         {
-          f.pFacePlane_old.vNormal.x = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.vNormal.x;
-          f.pFacePlane_old.vNormal.y = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.vNormal.y;
-          f.pFacePlane_old.vNormal.z = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.vNormal.z;
-          f.pFacePlane_old.dist = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.dist;
-          f.uAttributes = pOutdoor->pBModels[a10].pFaces[v3].uAttributes;
-          f.pBounding.x1 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.x1;
-          f.pBounding.y1 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.y1;
-          f.pBounding.z1 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.z1;
-          f.pBounding.x2 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.x2;
-          f.pBounding.y2 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.y2;
-          f.pBounding.z2 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.z2;
-          f.zCalc1 = pOutdoor->pBModels[a10].pFaces[v3].zCalc1;
-          f.zCalc2 = pOutdoor->pBModels[a10].pFaces[v3].zCalc2;
-          f.zCalc3 = pOutdoor->pBModels[a10].pFaces[v3].zCalc3;
-          f.pXInterceptDisplacements = pOutdoor->pBModels[a10].pFaces[v3].pXInterceptDisplacements;
-          f.pYInterceptDisplacements = pOutdoor->pBModels[a10].pFaces[v3].pYInterceptDisplacements;
-          f.pZInterceptDisplacements = pOutdoor->pBModels[a10].pFaces[v3].pZInterceptDisplacements;
-          f.uPolygonType = (PolygonType)pOutdoor->pBModels[a10].pFaces[v3].uPolygonType;
-          f.uNumVertices = pOutdoor->pBModels[a10].pFaces[v3].uNumVertices;
-          f.uBitmapID = pOutdoor->pBModels[a10].pFaces[v3].uTextureID;
-          f.pVertexIDs = pOutdoor->pBModels[a10].pFaces[v3].pVertexIDs;
-          if ( !f.Ethereal() && !f.Portal() )
+          face.pFacePlane_old.vNormal.x = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.vNormal.x;
+          face.pFacePlane_old.vNormal.y = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.vNormal.y;
+          face.pFacePlane_old.vNormal.z = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.vNormal.z;
+          face.pFacePlane_old.dist = pOutdoor->pBModels[a10].pFaces[v3].pFacePlane.dist;
+          face.uAttributes = pOutdoor->pBModels[a10].pFaces[v3].uAttributes;
+          face.pBounding.x1 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.x1;
+          face.pBounding.y1 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.y1;
+          face.pBounding.z1 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.z1;
+          face.pBounding.x2 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.x2;
+          face.pBounding.y2 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.y2;
+          face.pBounding.z2 = pOutdoor->pBModels[a10].pFaces[v3].pBoundingBox.z2;
+          face.zCalc1 = pOutdoor->pBModels[a10].pFaces[v3].zCalc1;
+          face.zCalc2 = pOutdoor->pBModels[a10].pFaces[v3].zCalc2;
+          face.zCalc3 = pOutdoor->pBModels[a10].pFaces[v3].zCalc3;
+          face.pXInterceptDisplacements = pOutdoor->pBModels[a10].pFaces[v3].pXInterceptDisplacements;
+          face.pYInterceptDisplacements = pOutdoor->pBModels[a10].pFaces[v3].pYInterceptDisplacements;
+          face.pZInterceptDisplacements = pOutdoor->pBModels[a10].pFaces[v3].pZInterceptDisplacements;
+          face.uPolygonType = (PolygonType)pOutdoor->pBModels[a10].pFaces[v3].uPolygonType;
+          face.uNumVertices = pOutdoor->pBModels[a10].pFaces[v3].uNumVertices;
+          face.uBitmapID = pOutdoor->pBModels[a10].pFaces[v3].uTextureID;
+          face.pVertexIDs = pOutdoor->pBModels[a10].pFaces[v3].pVertexIDs;
+          if ( !face.Ethereal() && !face.Portal() )
           {
-            v8 = (f.pFacePlane_old.dist + f.pFacePlane_old.vNormal.x * stru_721530.normal.x
-                                        + f.pFacePlane_old.vNormal.y * stru_721530.normal.y
-                                        + f.pFacePlane_old.vNormal.z * stru_721530.normal.z ) >> 16;
+            v8 = (face.pFacePlane_old.dist + face.pFacePlane_old.vNormal.x * stru_721530.normal.x
+                                        + face.pFacePlane_old.vNormal.y * stru_721530.normal.y
+                                        + face.pFacePlane_old.vNormal.z * stru_721530.normal.z ) >> 16;
             if ( v8 > 0 )
             {
-              v9 = (f.pFacePlane_old.dist + f.pFacePlane_old.vNormal.x * stru_721530.normal2.x
-                                          + f.pFacePlane_old.vNormal.y * stru_721530.normal2.y
-                                          + f.pFacePlane_old.vNormal.z * stru_721530.normal2.z) >> 16;
+              v9 = (face.pFacePlane_old.dist + face.pFacePlane_old.vNormal.x * stru_721530.normal2.x
+                                          + face.pFacePlane_old.vNormal.y * stru_721530.normal2.y
+                                          + face.pFacePlane_old.vNormal.z * stru_721530.normal2.z) >> 16;
               if ( v8 <= stru_721530.prolly_normal_d || v9 <= stru_721530.prolly_normal_d )
               {
                 if ( v9 <= v8 )
                 {
                   a2 = stru_721530.field_6C;
                   if ( sub_4754BF(stru_721530.prolly_normal_d, &a2, stru_721530.normal.x, stru_721530.normal.y, stru_721530.normal.z,
-                            stru_721530.direction.x, stru_721530.direction.y, stru_721530.direction.z, &f, a10, a11) )
+                            stru_721530.direction.x, stru_721530.direction.y, stru_721530.direction.z, &face, a10, a11) )
                   {
                     v10 = a2;
                   }
                   else
                   {
                     a2 = stru_721530.prolly_normal_d + stru_721530.field_6C;
-                    if ( !sub_475F30( &a2, &f, stru_721530.normal.x, stru_721530.normal.y, stru_721530.normal.z,
+                    if ( !sub_475F30( &a2, &face, stru_721530.normal.x, stru_721530.normal.y, stru_721530.normal.z,
                              stru_721530.direction.x, stru_721530.direction.y, stru_721530.direction.z, a10) )
                       goto LABEL_29;
                     v10 = a2 - stru_721530.prolly_normal_d;
@@ -288,21 +288,21 @@
 LABEL_29:
             if ( stru_721530.field_0 & 1 )
             {
-              v15 = (f.pFacePlane_old.dist + f.pFacePlane_old.vNormal.x * stru_721530.position.x
-                                           + f.pFacePlane_old.vNormal.y * stru_721530.position.y
-                                           + f.pFacePlane_old.vNormal.z * stru_721530.position.z) >> 16;
+              v15 = (face.pFacePlane_old.dist + face.pFacePlane_old.vNormal.x * stru_721530.position.x
+                                           + face.pFacePlane_old.vNormal.y * stru_721530.position.y
+                                           + face.pFacePlane_old.vNormal.z * stru_721530.position.z) >> 16;
               if ( v15 > 0 )
               {
-                v16 = (f.pFacePlane_old.dist + f.pFacePlane_old.vNormal.x * stru_721530.field_4C
-                                             + f.pFacePlane_old.vNormal.y * stru_721530.field_50
-                                             + f.pFacePlane_old.vNormal.z * stru_721530.field_54) >> 16;
+                v16 = (face.pFacePlane_old.dist + face.pFacePlane_old.vNormal.x * stru_721530.field_4C
+                                             + face.pFacePlane_old.vNormal.y * stru_721530.field_50
+                                             + face.pFacePlane_old.vNormal.z * stru_721530.field_54) >> 16;
                 if ( v15 <= stru_721530.prolly_normal_d || v16 <= stru_721530.prolly_normal_d )
                 {
                   if ( v16 <= v15 )
                   {
                     a2 = stru_721530.field_6C;
                     if ( sub_4754BF(stru_721530.field_8_radius, &a2, stru_721530.position.x, stru_721530.position.y, stru_721530.position.z,
-                             stru_721530.direction.x, stru_721530.direction.y, stru_721530.direction.z, &f, a10, a11) )
+                             stru_721530.direction.x, stru_721530.direction.y, stru_721530.direction.z, &face, a10, a11) )
                     {
                       if ( a2 < stru_721530.field_7C )
                       {
@@ -315,7 +315,7 @@
                     else
                     {
                       a2 = stru_721530.field_6C + stru_721530.field_8_radius;
-                      if ( sub_475F30(&a2, &f, stru_721530.position.x, stru_721530.position.y, stru_721530.position.z,
+                      if ( sub_475F30(&a2, &face, stru_721530.position.x, stru_721530.position.y, stru_721530.position.z,
                                      stru_721530.direction.x, stru_721530.direction.y, stru_721530.direction.z, a10) )
                       {
                         v21 = a2 - stru_721530.prolly_normal_d;
@@ -371,38 +371,32 @@
   int v10; // ecx@12
   int v11; // esi@13
 
-  if ( (signed int)uNumSpriteObjects > 0 )
+  for ( uint i = 0; i < uNumSpriteObjects; ++i )
   {
-    for ( uint i = 0; i < uNumSpriteObjects; ++i )
+    if ( pSpriteObjects[i].uObjectDescID )
     {
-      if ( pSpriteObjects[i].uObjectDescID )
+      object = &pObjectList->pObjects[pSpriteObjects[i].uObjectDescID];
+      if ( !(object->uFlags & OBJECT_DESC_NO_COLLISION) )
       {
-        object = &pObjectList->pObjects[pSpriteObjects[i].uObjectDescID];
-        if ( !(object->uFlags & OBJECT_DESC_NO_COLLISION) )
+        if ( stru_721530.sMaxX <= pSpriteObjects[i].vPosition.x + object->uRadius && stru_721530.sMinX >= pSpriteObjects[i].vPosition.x - object->uRadius
+          && stru_721530.sMaxY <= pSpriteObjects[i].vPosition.y + object->uRadius && stru_721530.sMinY >= pSpriteObjects[i].vPosition.y - object->uRadius
+          && stru_721530.sMaxZ <= pSpriteObjects[i].vPosition.z + object->uHeight && stru_721530.sMinZ >= pSpriteObjects[i].vPosition.z )
         {
-          if ( stru_721530.sMaxX <= pSpriteObjects[i].vPosition.x + object->uRadius
-            && stru_721530.sMinX >= pSpriteObjects[i].vPosition.x - object->uRadius
-            && stru_721530.sMaxY <= pSpriteObjects[i].vPosition.y + object->uRadius
-            && stru_721530.sMinY >= pSpriteObjects[i].vPosition.y - object->uRadius
-            && stru_721530.sMaxZ <= pSpriteObjects[i].vPosition.z + object->uHeight
-            && stru_721530.sMinZ >= pSpriteObjects[i].vPosition.z )
+          if ( abs(((pSpriteObjects[i].vPosition.x - stru_721530.normal.x) * stru_721530.direction.y
+                  - (pSpriteObjects[i].vPosition.y - stru_721530.normal.y) * stru_721530.direction.x) >> 16)
+                  <= object->uHeight + stru_721530.prolly_normal_d )
           {
-            if ( abs(((pSpriteObjects[i].vPosition.x - stru_721530.normal.x) * stru_721530.direction.y
-                    - (pSpriteObjects[i].vPosition.y - stru_721530.normal.y) * stru_721530.direction.x) >> 16) <= object->uHeight
-                                                                                    + stru_721530.prolly_normal_d )
+            v10 = ((pSpriteObjects[i].vPosition.x - stru_721530.normal.x) * stru_721530.direction.x
+                 + (pSpriteObjects[i].vPosition.y - stru_721530.normal.y) * stru_721530.direction.y) >> 16;
+            if ( v10 > 0 )
             {
-              v10 = ((pSpriteObjects[i].vPosition.x - stru_721530.normal.x) * stru_721530.direction.x
-                   + (pSpriteObjects[i].vPosition.y - stru_721530.normal.y) * stru_721530.direction.y) >> 16;
-              if ( v10 > 0 )
+              v11 = stru_721530.normal.z + ((unsigned __int64)(stru_721530.direction.z * (signed __int64)v10) >> 16);
+              if ( v11 >= pSpriteObjects[i].vPosition.z - stru_721530.prolly_normal_d )
               {
-                v11 = stru_721530.normal.z + ((unsigned __int64)(stru_721530.direction.z * (signed __int64)v10) >> 16);
-                if ( v11 >= pSpriteObjects[i].vPosition.z - stru_721530.prolly_normal_d )
+                if ( v11 <= object->uHeight + stru_721530.prolly_normal_d + pSpriteObjects[i].vPosition.z )
                 {
-                  if ( v11 <= object->uHeight + stru_721530.prolly_normal_d + pSpriteObjects[i].vPosition.z )
-                  {
-                    if ( v10 < stru_721530.field_7C )
-                      sub_46DEF2(_this, i);
-                  }
+                  if ( v10 < stru_721530.field_7C )
+                    sub_46DEF2(_this, i);
                 }
               }
             }
@@ -416,35 +410,29 @@
 //----- (0046EF01) --------------------------------------------------------
 int _46EF01_collision_chech_player(int a1)
 {
-  int v1; // edx@1
   int result; // eax@1
   int v3; // ebx@7
   int v4; // esi@7
   int v5; // edi@8
   int v6; // ecx@9
   int v7; // edi@12
-  int v8; // [sp+Ch] [bp-10h]@1
-  unsigned int v9; // [sp+10h] [bp-Ch]@1
   int v10; // [sp+14h] [bp-8h]@7
   int v11; // [sp+18h] [bp-4h]@7
 
-  v8 = a1;
-  v1 = 2 * pParty->field_14_radius;
   result = pParty->vPosition.x;
-  v9 = pParty->uPartyHeight;
-  if ( stru_721530.sMaxX <= pParty->vPosition.x + v1 && stru_721530.sMinX >= pParty->vPosition.x - v1
-    && stru_721530.sMaxY <= pParty->vPosition.y + v1 && stru_721530.sMinY >= pParty->vPosition.y - v1
-    && stru_721530.sMaxZ <= (signed int)(pParty->vPosition.z + pParty->uPartyHeight)
-    && stru_721530.sMinZ >= pParty->vPosition.z )
+  //v9 = pParty->uPartyHeight;
+  if ( stru_721530.sMaxX <= pParty->vPosition.x + (2 * pParty->field_14_radius) && stru_721530.sMinX >= pParty->vPosition.x - (2 * pParty->field_14_radius)
+    && stru_721530.sMaxY <= pParty->vPosition.y + (2 * pParty->field_14_radius) && stru_721530.sMinY >= pParty->vPosition.y - (2 * pParty->field_14_radius)
+    && stru_721530.sMaxZ <= pParty->vPosition.z + pParty->uPartyHeight && stru_721530.sMinZ >= pParty->vPosition.z )
   {
-    v3 = stru_721530.prolly_normal_d + v1;
+    v3 = stru_721530.prolly_normal_d + (2 * pParty->field_14_radius);
     v11 = pParty->vPosition.x - stru_721530.normal.x;
     v4 = ((pParty->vPosition.x - stru_721530.normal.x) * stru_721530.direction.y
         - (pParty->vPosition.y - stru_721530.normal.y) * stru_721530.direction.x) >> 16;
     v10 = pParty->vPosition.y - stru_721530.normal.y;
     result = abs(((pParty->vPosition.x - stru_721530.normal.x) * stru_721530.direction.y
                 - (pParty->vPosition.y - stru_721530.normal.y) * stru_721530.direction.x) >> 16);
-    if ( result <= stru_721530.prolly_normal_d + v1 )
+    if ( result <= stru_721530.prolly_normal_d + (2 * pParty->field_14_radius) )
     {
       result = v10 * stru_721530.direction.y;
       v5 = (v10 * stru_721530.direction.y + v11 * stru_721530.direction.x) >> 16;
@@ -454,8 +442,8 @@
         result = pParty->vPosition.z;
         if ( v6 >= pParty->vPosition.z )
         {
-          result = v9 + pParty->vPosition.z;
-          if ( v6 <= (signed int)(v9 + pParty->vPosition.z) || v8 )
+          result = pParty->uPartyHeight + pParty->vPosition.z;
+          if ( v6 <= (signed int)(pParty->uPartyHeight + pParty->vPosition.z) || a1 )
           {
             result = integer_sqrt(v3 * v3 - v4 * v4);
             v7 = v5 - integer_sqrt(v3 * v3 - v4 * v4);
@@ -535,35 +523,13 @@
 //----- (0047050A) --------------------------------------------------------
 int stru141_actor_collision_object::_47050A(int dt)
 {
-  //stru141_actor_collision_object *v2; // esi@1
-  //signed int v3; // eax@1
-  //int v4; // ecx@1
-  //int v5; // edx@1
-  //int v6; // edx@1
   int v7; // eax@1
-  //int v8; // eax@3
   signed int result; // eax@4
-  //int v10; // eax@5
-  //int v11; // eax@5
-  //int v12; // ebx@5
-  //int v13; // edx@5
-  //int v14; // edi@5
-  //int v15; // ecx@5
-  //int v16; // eax@5
   int v17; // eax@5
   int v18; // eax@7
-  //int v19; // edx@9
-  //int v20; // edi@9
   int v21; // eax@9
   int v22; // eax@11
-  //int v23; // edx@13
-  //int v24; // eax@13
-  //int v25; // eax@14
-  //int v26; // eax@16
-  //int v27; // eax@17
-  //int v28; // [sp+14h] [bp+8h]@5
-
-  //v2 = this;
+
   int speed = 1 | integer_sqrt(this->velocity.z * this->velocity.z + this->velocity.y * this->velocity.y + this->velocity.x * this->velocity.x);
 
   this->direction.x = 65536 / speed * this->velocity.x;
@@ -681,7 +647,6 @@
   int v71; // [sp+38h] [bp-18h]@62
   int uIsAboveFloor; // [sp+3Ch] [bp-14h]@10
   int v72b;
-  //int v73; // [sp+40h] [bp-10h]@17
   int uIsFlying; // [sp+44h] [bp-Ch]@8
   unsigned int v75; // [sp+48h] [bp-8h]@1
   int uIsOnWater; // [sp+4Ch] [bp-4h]@10
@@ -997,14 +962,10 @@
 void UpdateObjects()
 {
   unsigned int v0; // ebx@0
-  //unsigned int v1; // edi@1
-  //char *v2; // esi@2
-  //__int16 v3; // dx@5
   ObjectDesc *object; // eax@5
   int v5; // ecx@6
   __int16 v6; // cx@7
   signed int v7; // eax@9
-  //unsigned int v10; // ecx@16
   signed int v11; // eax@17
   int v12; // edi@27
   int v13; // eax@27
@@ -1014,103 +975,94 @@
   unsigned int v17; // edx@32
   int v18; // [sp+4h] [bp-10h]@27
   int v19; // [sp+8h] [bp-Ch]@27
-  //signed int v20; // [sp+10h] [bp-4h]@1
-
-  //v1 = 0;
-  //v20 = 0;
+
   for (uint i = 0; i < uNumSpriteObjects; ++i)
   {
-    SpriteObject* item = &pSpriteObjects[i];
-    //v2 = (char *)&item->uSpriteFrameID;
-    //do
-    //{
-      //LOWORD(v0) = item->uAttributes;
-    if (item->uAttributes & OBJECT_40)
-      item->uAttributes &= ~OBJECT_40;
+    if (pSpriteObjects[i].uAttributes & OBJECT_40)
+      pSpriteObjects[i].uAttributes &= ~OBJECT_40;
     else
     {
-      object = &pObjectList->pObjects[item->uObjectDescID];
-      if (item->AttachedToActor())
+      object = &pObjectList->pObjects[pSpriteObjects[i].uObjectDescID];
+      if (pSpriteObjects[i].AttachedToActor())
       {
-          v5 = PID_ID(item->spell_target_pid);
-          item->vPosition.x = pActors[v5].vPosition.x;
-          item->vPosition.y = pActors[v5].vPosition.y;
-          item->vPosition.z = pActors[v5].vPosition.z + pActors[v5].uActorHeight;
-          if ( !item->uObjectDescID )
-            continue;
-          item->uSpriteFrameID += pEventTimer->uTimeElapsed;
-          if ( !(object->uFlags & OBJECT_DESC_TEMPORARY))
-            continue;
-          if ( item->uSpriteFrameID >= 0 )
-          {
-            v7 = object->uLifetime;
-            if (item->uAttributes & ITEM_BROKEN)
-              v7 = item->field_20;
-            if ( item->uSpriteFrameID < v7 )
-              continue;
-          }
-          SpriteObject::OnInteraction(i);
+        v5 = PID_ID(pSpriteObjects[i].spell_target_pid);
+        pSpriteObjects[i].vPosition.x = pActors[v5].vPosition.x;
+        pSpriteObjects[i].vPosition.y = pActors[v5].vPosition.y;
+        pSpriteObjects[i].vPosition.z = pActors[v5].vPosition.z + pActors[v5].uActorHeight;
+        if ( !pSpriteObjects[i].uObjectDescID )
           continue;
-      }
-
-        if ( item->uObjectDescID )
+        pSpriteObjects[i].uSpriteFrameID += pEventTimer->uTimeElapsed;
+        if ( !(object->uFlags & OBJECT_DESC_TEMPORARY))
+          continue;
+        if ( pSpriteObjects[i].uSpriteFrameID >= 0 )
         {
-          item->uSpriteFrameID += pEventTimer->uTimeElapsed;
-          if ( object->uFlags & OBJECT_DESC_TEMPORARY )
-          {
-            if ( item->uSpriteFrameID < 0 )
-            {
-              SpriteObject::OnInteraction(i);
-              continue;
-            }
-            v11 = object->uLifetime;
-            if (item->uAttributes & ITEM_BROKEN)
-              v11 = item->field_20;
-          }
-          if ( !(object->uFlags & OBJECT_DESC_TEMPORARY) || item->uSpriteFrameID < v11 )
-          {
-            if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
-              SpriteObject::UpdateObject_fn0_BLV(i);
-            else
-              SpriteObject::UpdateObject_fn0_ODM(i);
-			if ( pParty->bTurnBasedModeOn != 1 || !(item->uSectorID & 4) )
-              continue;
-			v12 = abs(pParty->vPosition.x - item->vPosition.x);
-			v18 = abs(pParty->vPosition.y - item->vPosition.y);
-			v19 = abs(pParty->vPosition.z - item->vPosition.z);
-            v13 = v12;
-            v14 = v18;
-            v15 = v19;
-            if ( v12 < v18 )
-            {
-              v13 = v18;
-              v14 = v12;
-            }
-            if ( v13 < v19 )
-            {
-              v16 = v13;
-              v13 = v19;
-              v15 = v16;
-            }
-            if ( v14 < (signed int)v15 )
-            {
-              v17 = v15;
-              v15 = v14;
-              v14 = v17;
-            }
-            v0 = (unsigned int)(11 * v14) >> 5;
-            if ( (signed int)(v0 + (v15 >> 2) + v13) <= 5120 )
-              continue;
-            SpriteObject::OnInteraction(i);
-            continue;
-          }
-          if ( !(object->uFlags & OBJECT_DESC_INTERACTABLE) )
+          v7 = object->uLifetime;
+          if (pSpriteObjects[i].uAttributes & ITEM_BROKEN)
+             v7 = pSpriteObjects[i].field_20;
+          if ( pSpriteObjects[i].uSpriteFrameID < v7 )
+             continue;
+        }
+        SpriteObject::OnInteraction(i);
+        continue;
+      }
+      if ( pSpriteObjects[i].uObjectDescID )
+      {
+        pSpriteObjects[i].uSpriteFrameID += pEventTimer->uTimeElapsed;
+        if ( object->uFlags & OBJECT_DESC_TEMPORARY )
+        {
+          if ( pSpriteObjects[i].uSpriteFrameID < 0 )
           {
             SpriteObject::OnInteraction(i);
             continue;
           }
-          _46BFFA_check_object_intercept(i, PID(OBJECT_Item,i));
+          v11 = object->uLifetime;
+          if (pSpriteObjects[i].uAttributes & ITEM_BROKEN)
+            v11 = pSpriteObjects[i].field_20;
         }
+        if ( !(object->uFlags & OBJECT_DESC_TEMPORARY) || pSpriteObjects[i].uSpriteFrameID < v11 )
+        {
+          if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
+            SpriteObject::UpdateObject_fn0_BLV(i);
+          else
+            SpriteObject::UpdateObject_fn0_ODM(i);
+          if ( pParty->bTurnBasedModeOn != 1 || !(pSpriteObjects[i].uSectorID & 4) )
+            continue;
+          v12 = abs(pParty->vPosition.x - pSpriteObjects[i].vPosition.x);
+          v18 = abs(pParty->vPosition.y - pSpriteObjects[i].vPosition.y);
+          v19 = abs(pParty->vPosition.z - pSpriteObjects[i].vPosition.z);
+          v13 = v12;
+          v14 = v18;
+          v15 = v19;
+          if ( v12 < v18 )
+          {
+            v13 = v18;
+            v14 = v12;
+          }
+          if ( v13 < v19 )
+          {
+            v16 = v13;
+            v13 = v19;
+            v15 = v16;
+          }
+          if ( v14 < (signed int)v15 )
+          {
+            v17 = v15;
+            v15 = v14;
+            v14 = v17;
+          }
+          v0 = (unsigned int)(11 * v14) >> 5;
+          if ( (signed int)(v0 + (v15 >> 2) + v13) <= 5120 )
+            continue;
+          SpriteObject::OnInteraction(i);
+          continue;
+        }
+        if ( !(object->uFlags & OBJECT_DESC_INTERACTABLE) )
+        {
+          SpriteObject::OnInteraction(i);
+          continue;
+        }
+        _46BFFA_check_object_intercept(i, PID(OBJECT_Item,i));
+      }
     }
   }
 }
@@ -1118,32 +1070,26 @@
 //----- (0047272C) --------------------------------------------------------
 int collide_against_floor_approximate(int x, int y, int z, unsigned int *pSectorID, unsigned int *pFaceID)
 {
-  signed int v5; // ebx@1
   int result; // eax@1
-  int v7; // [sp+10h] [bp-8h]@1
-  signed int v8; // [sp+14h] [bp-4h]@1
-
-  v5 = x - 2;
-  v7 = x;
-  v8 = y;
+
   *pSectorID = pIndoor->GetSector(x - 2, y, z + 40);
-  result = collide_against_floor(v5, v8, z + 40, pSectorID, pFaceID);
+  result = collide_against_floor(x - 2, y, z + 40, pSectorID, pFaceID);
   if ( result == -30000 || !*pSectorID )
   {
-    *pSectorID = pIndoor->GetSector(v7 + 2, v8, z + 40);
-    result = collide_against_floor(v7 + 2, v8, z + 40, pSectorID, pFaceID);
+    *pSectorID = pIndoor->GetSector(x + 2, y, z + 40);
+    result = collide_against_floor(x + 2, y, z + 40, pSectorID, pFaceID);
     if ( result == -30000 || !*pSectorID )
     {
-      *pSectorID = pIndoor->GetSector(v7, v8 - 2, z + 40);
-      result = collide_against_floor(v7, v8 - 2, z + 40, pSectorID, pFaceID);
+      *pSectorID = pIndoor->GetSector(x, y - 2, z + 40);
+      result = collide_against_floor(x, y - 2, z + 40, pSectorID, pFaceID);
       if ( result == -30000 || !*pSectorID )
       {
-        *pSectorID = pIndoor->GetSector(v7, v8 + 2, z + 40);
-        result = collide_against_floor(v7, v8 + 2, z + 40, pSectorID, pFaceID);
+        *pSectorID = pIndoor->GetSector(x, y + 2, z + 40);
+        result = collide_against_floor(x, y + 2, z + 40, pSectorID, pFaceID);
         if ( result == -30000 || !*pSectorID )
         {
-          *pSectorID = pIndoor->GetSector(v7, v8, z + 140);
-          result = collide_against_floor(v7, v8, z + 140, pSectorID, pFaceID);
+          *pSectorID = pIndoor->GetSector(x, y, z + 140);
+          result = collide_against_floor(x, y, z + 140, pSectorID, pFaceID);
         }
       }
     }
@@ -1272,25 +1218,9 @@
 }
 
 //----- (00475665) --------------------------------------------------------
-int sub_475665(BLVFace *_this, int a2, __int16 a3)
+int sub_475665(BLVFace *face, int a2, __int16 a3)
 {
-  unsigned int v3; // eax@1
-  Vec3_short_ *v4; // edx@3
-  signed int v5; // eax@4
-  int v6; // esi@4
-  signed int v7; // eax@7
-  Vec3_short_ *v8; // edx@8
-  signed int v9; // eax@9
-  int v10; // esi@9
-  signed int v11; // eax@11
-  Vec3_short_ *v12; // edx@12
-  signed int v13; // eax@13
-  int v14; // esi@13
-  int v15; // esi@14
   bool v16; // edi@14
-  int v17; // ecx@16
-  signed int v18; // edx@16
-  int v19; // eax@17
   signed int v20; // ebx@18
   int v21; // edi@20
   signed int v22; // ST14_4@22
@@ -1304,113 +1234,86 @@
   signed int v30; // [sp+30h] [bp+Ch]@11
   signed int v31; // [sp+30h] [bp+Ch]@14
 
-  v3 = _this->uAttributes;
-  if ( BYTE1(v3) & 1 )
+  if ( face->uAttributes & FACE_XY_PLANE )
   {
-    v28 = 0;
     v26 = (signed __int16)a2;
     v27 = SHIWORD(a2);
-    if ( _this->uNumVertices )
+    if ( face->uNumVertices )
     {
-      v4 = pIndoor->pVertices;
-      do
+      for ( v28 = 0; v28 < face->uNumVertices; v28++ )
       {
-        v5 = v28;
-        v6 = 2 * v28;
-        word_720C10_intercepts_xs[2 * v28] = _this->pXInterceptDisplacements[v28] + v4[_this->pVertexIDs[v28]].x;
-        word_720B40_intercepts_zs[2 * v28] = _this->pYInterceptDisplacements[v5] + v4[_this->pVertexIDs[v5]].y;
-        word_720C10_intercepts_xs[2 * v28++ + 1] = _this->pXInterceptDisplacements[v5 + 1]
-                                                 + v4[_this->pVertexIDs[v5 + 1]].x;
-        word_720B40_intercepts_zs[v6 + 1] = _this->pYInterceptDisplacements[v5 + 1] + v4[_this->pVertexIDs[v5 + 1]].y;
+        word_720C10_intercepts_xs[2 * v28] = face->pXInterceptDisplacements[v28] + pIndoor->pVertices[face->pVertexIDs[v28]].x;
+        word_720B40_intercepts_zs[2 * v28] = face->pYInterceptDisplacements[v28] + pIndoor->pVertices[face->pVertexIDs[v28]].y;
+        word_720C10_intercepts_xs[2 * v28 + 1] = face->pXInterceptDisplacements[v28 + 1] + pIndoor->pVertices[face->pVertexIDs[v28 + 1]].x;
+        word_720B40_intercepts_zs[2 * v28 + 1] = face->pYInterceptDisplacements[v28 + 1] + pIndoor->pVertices[face->pVertexIDs[v28 + 1]].y;
       }
-      while ( v28 < _this->uNumVertices );
     }
   }
   else
   {
-    if ( BYTE1(v3) & 2 )
+    if ( face->uAttributes & FACE_XZ_PLANE )
     {
       v26 = (signed __int16)a2;
-      v7 = a3;
-      v29 = 0;
-      v27 = v7;
-      if ( _this->uNumVertices )
+      v27 = a3;
+      if ( face->uNumVertices )
       {
-        v8 = pIndoor->pVertices;
-        do
+        for ( v29 = 0; v29 < face->uNumVertices; v29++ )
         {
-          v9 = v29;
-          v10 = 2 * v29;
-          word_720C10_intercepts_xs[2 * v29] = _this->pXInterceptDisplacements[v29] + v8[_this->pVertexIDs[v29]].x;
-          word_720B40_intercepts_zs[2 * v29] = _this->pZInterceptDisplacements[v9] + v8[_this->pVertexIDs[v9]].z;
-          word_720C10_intercepts_xs[2 * v29++ + 1] = _this->pXInterceptDisplacements[v9 + 1] + v8[_this->pVertexIDs[v9 + 1]].x;
-          word_720B40_intercepts_zs[v10 + 1] = _this->pZInterceptDisplacements[v9 + 1] + v8[_this->pVertexIDs[v9 + 1]].z;
+          word_720C10_intercepts_xs[2 * v29] = face->pXInterceptDisplacements[v29] + pIndoor->pVertices[face->pVertexIDs[v29]].x;
+          word_720B40_intercepts_zs[2 * v29] = face->pZInterceptDisplacements[v29] + pIndoor->pVertices[face->pVertexIDs[v29]].z;
+          word_720C10_intercepts_xs[2 * v29 + 1] = face->pXInterceptDisplacements[v29 + 1] + pIndoor->pVertices[face->pVertexIDs[v29 + 1]].x;
+          word_720B40_intercepts_zs[2 * v29 + 1] = face->pZInterceptDisplacements[v29 + 1] + pIndoor->pVertices[face->pVertexIDs[v29 + 1]].z;
         }
-        while ( v29 < _this->uNumVertices );
       }
     }
     else
     {
       v26 = SHIWORD(a2);
-      v11 = a3;
-      v30 = 0;
-      v27 = v11;
-      if ( _this->uNumVertices )
+      v27 = a3;
+      if ( face->uNumVertices )
       {
-        v12 = pIndoor->pVertices;
-        do
+        for ( v30 = 0; v30 < face->uNumVertices; v30++ )
         {
-          v13 = v30;
-          v14 = 2 * v30;
-          word_720C10_intercepts_xs[2 * v30] = _this->pYInterceptDisplacements[v30] + v12[_this->pVertexIDs[v30]].y;
-          word_720B40_intercepts_zs[2 * v30] = _this->pZInterceptDisplacements[v13] + v12[_this->pVertexIDs[v13]].z;
-          word_720C10_intercepts_xs[2 * v30++ + 1] = _this->pYInterceptDisplacements[v13 + 1] + v12[_this->pVertexIDs[v13 + 1]].y;
-          word_720B40_intercepts_zs[v14 + 1] = _this->pZInterceptDisplacements[v13 + 1] + v12[_this->pVertexIDs[v13 + 1]].z;
+          word_720C10_intercepts_xs[2 * v30] = face->pYInterceptDisplacements[v30] + pIndoor->pVertices[face->pVertexIDs[v30]].y;
+          word_720B40_intercepts_zs[2 * v30] = face->pZInterceptDisplacements[v30] + pIndoor->pVertices[face->pVertexIDs[v30]].z;
+          word_720C10_intercepts_xs[2 * v30 + 1] = face->pYInterceptDisplacements[v30 + 1] + pIndoor->pVertices[face->pVertexIDs[v30 + 1]].y;
+          word_720B40_intercepts_zs[2 * v30 + 1] = face->pZInterceptDisplacements[v30 + 1] + pIndoor->pVertices[face->pVertexIDs[v30 + 1]].z;
         }
-        while ( v30 < _this->uNumVertices );
       }
     }
   }
-  v15 = 2 * _this->uNumVertices;
   v31 = 0;
-  word_720C10_intercepts_xs[2 * _this->uNumVertices] = word_720C10_intercepts_xs[0];
-  word_720B40_intercepts_zs[v15] = word_720B40_intercepts_zs[0];
-  v25 = 0;
+  word_720C10_intercepts_xs[2 * face->uNumVertices] = word_720C10_intercepts_xs[0];
+  word_720B40_intercepts_zs[2 * face->uNumVertices] = word_720B40_intercepts_zs[0];
   v16 = word_720B40_intercepts_zs[0] >= v27;
-  if ( v15 <= 0 )
+  if ( 2 * face->uNumVertices <= 0 )
     return 0;
-  do
+  for ( v25 = 0; v25 < 2 * face->uNumVertices; ++v25 )
   {
     if ( v31 >= 2 )
       break;
-    v17 = v25;
-    v18 = word_720B40_intercepts_zs[v25 + 1];
-    if ( v16 ^ (v18 >= v27) )
+    if ( v16 ^ (word_720B40_intercepts_zs[v25 + 1] >= v27) )
     {
-      v19 = word_720C10_intercepts_xs[v17 + 1];
-      if ( v19 >= v26 )
+      if ( word_720C10_intercepts_xs[v25 + 1] >= v26 )
         v20 = 0;
       else
         v20 = 2;
-      v21 = v20 | (word_720C10_intercepts_xs[v17] < v26);
+      v21 = v20 | (word_720C10_intercepts_xs[v25] < v26);
       if ( v21 != 3 )
       {
+        v22 = word_720C10_intercepts_xs[v25 + 1] - word_720C10_intercepts_xs[v25];
+        LODWORD(v23) = v22 << 16;
+        HIDWORD(v23) = v22 >> 16;
         if ( !v21
-          || (v22 = v19 - word_720C10_intercepts_xs[v17],
-              LODWORD(v23) = v22 << 16,
-              HIDWORD(v23) = v22 >> 16,
-              word_720C10_intercepts_xs[v17]
-            + ((signed int)(((unsigned __int64)(v23
-                                              / (v18 - word_720B40_intercepts_zs[v17])
-                                              * ((v27 - (signed int)word_720B40_intercepts_zs[v17]) << 16)) >> 16)
-                          + 32768) >> 16) >= v26) )
+          || (word_720C10_intercepts_xs[v25] + ((signed int)(((unsigned __int64)(v23
+           / (word_720B40_intercepts_zs[v25 + 1] - word_720B40_intercepts_zs[v25])
+           * ((v27 - (signed int)word_720B40_intercepts_zs[v25]) << 16)) >> 16)
+               + 32768) >> 16) >= v26) )
           ++v31;
       }
     }
-    ++v25;
-    v16 = v18 >= v27;
+    v16 = word_720B40_intercepts_zs[v25 + 1] >= v27;
   }
-  while ( v25 < v15 );
   result = 1;
   if ( v31 != 1 )
     result = 0;
@@ -1418,20 +1321,9 @@
 }
 
 //----- (004759C9) --------------------------------------------------------
-bool __fastcall sub_4759C9(BLVFace *a1, int a2, int a3, __int16 a4)
+bool __fastcall sub_4759C9(BLVFace *face, int a2, int a3, __int16 a4)
 {
-  //unsigned int v4; // eax@1
-  //int v5; // edx@4
-  __int16 v6; // si@4
-  //int v7; // edx@9
-  __int16 v8; // si@9
-  //int v9; // edx@13
-  __int16 v10; // si@13
-  int v11; // esi@14
   bool v12; // edi@14
-  int v13; // ecx@16
-  signed int v14; // edx@16
-  int v15; // eax@17
   signed int v16; // ebx@18
   int v17; // edi@20
   signed int v18; // ST14_4@22
@@ -1441,113 +1333,88 @@
   signed int v22; // [sp+18h] [bp-Ch]@1
   int v23; // [sp+1Ch] [bp-8h]@2
   signed int v24; // [sp+20h] [bp-4h]@2
-  Vec3_int_ **a4a; // [sp+30h] [bp+Ch]@3
-  Vec3_int_ **a4b; // [sp+30h] [bp+Ch]@8
-  Vec3_int_ **a4c; // [sp+30h] [bp+Ch]@12
   signed int a4d; // [sp+30h] [bp+Ch]@14
 
-  //v4 = a1->uAttributes;
-  v22 = 0;
-  if ( BYTE1(a1->uAttributes) & 1 )
+  if ( face->uAttributes & FACE_XY_PLANE )
   {
     v23 = (signed __int16)a3;
     v24 = SHIWORD(a3);
-    if ( a1->uNumVertices )
+    if ( face->uNumVertices )
     {
-      a4a = &pOutdoor->pBModels[a2].pVertices.pVertices;
-      do
+      for ( v22 = 0; v22 < face->uNumVertices; ++v22 )
       {
-        //v5 = 2 * v22;
-        word_720A70_intercepts_xs_plus_xs[2 * v22] = a1->pXInterceptDisplacements[v22] + LOWORD((*a4a)[a1->pVertexIDs[v22]].x);
-        word_7209A0_intercepts_ys_plus_ys[2 * v22] = a1->pYInterceptDisplacements[v22] + LOWORD((*a4a)[a1->pVertexIDs[v22]].y);
-        word_720A70_intercepts_xs_plus_xs[2 * v22 + 1] = a1->pXInterceptDisplacements[v22 + 1] + LOWORD((*a4a)[a1->pVertexIDs[v22 + 1]].x);
-        word_7209A0_intercepts_ys_plus_ys[2 * v22 + 1] = v6 = a1->pYInterceptDisplacements[v22 + 1] + LOWORD((*a4a)[a1->pVertexIDs[v22 + 1]].y);
-        ++v22;
+        word_720A70_intercepts_xs_plus_xs[2 * v22] = face->pXInterceptDisplacements[v22] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22]].x);
+        word_7209A0_intercepts_ys_plus_ys[2 * v22] = face->pYInterceptDisplacements[v22] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22]].y);
+        word_720A70_intercepts_xs_plus_xs[2 * v22 + 1] = face->pXInterceptDisplacements[v22 + 1] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22 + 1]].x);
+        word_7209A0_intercepts_ys_plus_ys[2 * v22 + 1] = face->pYInterceptDisplacements[v22 + 1] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22 + 1]].y);
       }
-      while ( v22 < a1->uNumVertices );
     }
   }
   else
   {
-    if ( BYTE1(a1->uAttributes) & 2 )
+    if ( face->uAttributes & FACE_XZ_PLANE )
     {
       v23 = (signed __int16)a3;
       v24 = a4;
-      if ( a1->uNumVertices )
+      if ( face->uNumVertices )
       {
-        a4b = &pOutdoor->pBModels[a2].pVertices.pVertices;
-        do
+        for ( v22 = 0; v22 < face->uNumVertices; ++v22 )
         {
-          //v7 = 2 * v22;
-          word_720A70_intercepts_xs_plus_xs[2 * v22] = a1->pXInterceptDisplacements[v22] + LOWORD((*a4b)[a1->pVertexIDs[v22]].x);
-          word_7209A0_intercepts_ys_plus_ys[2 * v22] = a1->pZInterceptDisplacements[v22] + LOWORD((*a4b)[a1->pVertexIDs[v22]].z);
-          word_720A70_intercepts_xs_plus_xs[2 * v22 + 1] = a1->pXInterceptDisplacements[v22 + 1] + LOWORD((*a4b)[a1->pVertexIDs[v22 + 1]].x);
-          word_7209A0_intercepts_ys_plus_ys[2 * v22 + 1] = v8 = a1->pZInterceptDisplacements[v22 + 1] + LOWORD((*a4b)[a1->pVertexIDs[v22 + 1]].z);
-          ++v22;
+          word_720A70_intercepts_xs_plus_xs[2 * v22] = face->pXInterceptDisplacements[v22] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22]].x);
+          word_7209A0_intercepts_ys_plus_ys[2 * v22] = face->pZInterceptDisplacements[v22] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22]].z);
+          word_720A70_intercepts_xs_plus_xs[2 * v22 + 1] = face->pXInterceptDisplacements[v22 + 1] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22 + 1]].x);
+          word_7209A0_intercepts_ys_plus_ys[2 * v22 + 1] = face->pZInterceptDisplacements[v22 + 1] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22 + 1]].z);
         }
-        while ( v22 < a1->uNumVertices );
       }
     }
     else
     {
       v23 = SHIWORD(a3);
       v24 = a4;
-      if ( a1->uNumVertices )
+      if ( face->uNumVertices )
       {
-        a4c = &pOutdoor->pBModels[a2].pVertices.pVertices;
-        do
+        for ( v22 = 0; v22 < face->uNumVertices; ++v22 )
         {
-          //v9 = 2 * v22;
-          word_720A70_intercepts_xs_plus_xs[2 * v22] = a1->pYInterceptDisplacements[v22] + LOWORD((*a4c)[a1->pVertexIDs[v22]].y);
-          word_7209A0_intercepts_ys_plus_ys[2 * v22] = a1->pZInterceptDisplacements[v22] + LOWORD((*a4c)[a1->pVertexIDs[v22]].z);
-          word_720A70_intercepts_xs_plus_xs[2 * v22 + 1] = a1->pYInterceptDisplacements[v22 + 1] + LOWORD((*a4c)[a1->pVertexIDs[v22 + 1]].y);
-          word_7209A0_intercepts_ys_plus_ys[2 * v22 + 1] = v10 = a1->pZInterceptDisplacements[v22 + 1] + LOWORD((*a4c)[a1->pVertexIDs[v22 + 1]].z);
-          ++v22;
+          word_720A70_intercepts_xs_plus_xs[2 * v22] = face->pYInterceptDisplacements[v22] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22]].y);
+          word_7209A0_intercepts_ys_plus_ys[2 * v22] = face->pZInterceptDisplacements[v22] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22]].z);
+          word_720A70_intercepts_xs_plus_xs[2 * v22 + 1] = face->pYInterceptDisplacements[v22 + 1] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22 + 1]].y);
+          word_7209A0_intercepts_ys_plus_ys[2 * v22 + 1] = face->pZInterceptDisplacements[v22 + 1] + LOWORD(pOutdoor->pBModels[a2].pVertices.pVertices[face->pVertexIDs[v22 + 1]].z);
         }
-        while ( v22 < a1->uNumVertices );
       }
     }
   }
-  v11 = 2 * a1->uNumVertices;
   a4d = 0;
-  word_720A70_intercepts_xs_plus_xs[2 * a1->uNumVertices] = word_720A70_intercepts_xs_plus_xs[0];
-  word_7209A0_intercepts_ys_plus_ys[v11] = word_7209A0_intercepts_ys_plus_ys[0];
-  v21 = 0;
+  word_720A70_intercepts_xs_plus_xs[2 * face->uNumVertices] = word_720A70_intercepts_xs_plus_xs[0];
+  word_7209A0_intercepts_ys_plus_ys[2 * face->uNumVertices] = word_7209A0_intercepts_ys_plus_ys[0];
   v12 = word_7209A0_intercepts_ys_plus_ys[0] >= v24;
-  if ( v11 <= 0 )
+  if ( 2 * face->uNumVertices <= 0 )
     return 0;
-  do
+  for ( v21 = 0; v21 < 2 * face->uNumVertices; ++v21 )
   {
     if ( a4d >= 2 )
       break;
-    v13 = v21;
-    v14 = word_7209A0_intercepts_ys_plus_ys[v21 + 1];
-    if ( v12 ^ (v14 >= v24) )
+    if ( v12 ^ (word_7209A0_intercepts_ys_plus_ys[v21 + 1] >= v24) )
     {
-      v15 = word_720A70_intercepts_xs_plus_xs[v13 + 1];
-      if ( v15 >= v23 )
+      if ( word_720A70_intercepts_xs_plus_xs[v21 + 1] >= v23 )
         v16 = 0;
       else
         v16 = 2;
-      v17 = v16 | (word_720A70_intercepts_xs_plus_xs[v13] < v23);
+      v17 = v16 | (word_720A70_intercepts_xs_plus_xs[v21] < v23);
       if ( v17 != 3 )
       {
+        v18 = word_720A70_intercepts_xs_plus_xs[v21 + 1] - word_720A70_intercepts_xs_plus_xs[v21];
+        LODWORD(v19) = v18 << 16;
+        HIDWORD(v19) = v18 >> 16;
         if ( !v17
-          || (v18 = v15 - word_720A70_intercepts_xs_plus_xs[v13],
-              LODWORD(v19) = v18 << 16,
-              HIDWORD(v19) = v18 >> 16,
-              word_720A70_intercepts_xs_plus_xs[v13]
-            + ((signed int)(((unsigned __int64)(v19
-                                              / (v14 - word_7209A0_intercepts_ys_plus_ys[v13])
-                                              * ((v24 - (signed int)word_7209A0_intercepts_ys_plus_ys[v13]) << 16)) >> 16)
-                          + 32768) >> 16) >= v23) )
+          || (word_720A70_intercepts_xs_plus_xs[v21] + ((signed int)(((unsigned __int64)(v19
+              / (word_7209A0_intercepts_ys_plus_ys[v21 + 1] - word_7209A0_intercepts_ys_plus_ys[v21])
+              * ((v24 - (signed int)word_7209A0_intercepts_ys_plus_ys[v21]) << 16)) >> 16)
+              + 32768) >> 16) >= v23) )
           ++a4d;
       }
     }
-    ++v21;
-    v12 = v14 >= v24;
+    v12 = word_7209A0_intercepts_ys_plus_ys[v21 + 1] >= v24;
   }
-  while ( v21 < v11 );
   result = 1;
   if ( a4d != 1 )
     result = 0;
@@ -1617,24 +1484,19 @@
 //----- (00475F30) --------------------------------------------------------
 bool __fastcall sub_475F30(int *a1, BLVFace *a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9)
 {
-  //BLVFace *v9; // ebx@1
   int v10; // ST20_4@2
   int v11; // ST28_4@2
   int v12; // ST24_4@2
   char v13; // zf@2
   int v14; // edi@2
-  int v15; // eax@5
   signed int v16; // esi@5
   int v17; // ST20_4@9
   signed __int64 v18; // qtt@10
   int v19; // ST14_4@11
-  //int *v21; // [sp+14h] [bp-10h]@1
   int v22; // [sp+1Ch] [bp-8h]@2
   int v23; // [sp+1Ch] [bp-8h]@10
   signed int v24; // [sp+20h] [bp-4h]@10
 
-  //v9 = a2;
-  //v21 = a1;
   if ( a2->Ethereal()
     || (v10 = (unsigned __int64)(a6 * (signed __int64)a2->pFacePlane_old.vNormal.x) >> 16,
         v11 = (unsigned __int64)(a7 * (signed __int64)a2->pFacePlane_old.vNormal.y) >> 16,
@@ -1645,11 +1507,10 @@
         v13)
     || v14 > 0 && !a2->Portal())
     return 0;
-  v15 = a4 * a2->pFacePlane_old.vNormal.y;
-  v16 = -(a2->pFacePlane_old.dist + v15 + a3 * a2->pFacePlane_old.vNormal.x + a5 * a2->pFacePlane_old.vNormal.z);
+  v16 = -(a2->pFacePlane_old.dist + a4 * a2->pFacePlane_old.vNormal.y + a3 * a2->pFacePlane_old.vNormal.x + a5 * a2->pFacePlane_old.vNormal.z);
   if ( v14 <= 0 )
   {
-    if ( a2->pFacePlane_old.dist + v15 + a3 * a2->pFacePlane_old.vNormal.x + a5 * a2->pFacePlane_old.vNormal.z < 0 )
+    if ( a2->pFacePlane_old.dist + a4 * a2->pFacePlane_old.vNormal.y + a3 * a2->pFacePlane_old.vNormal.x + a5 * a2->pFacePlane_old.vNormal.z < 0 )
       return 0;
   }
   else
@@ -1657,7 +1518,7 @@
     if ( v16 < 0 )
       return 0;
   }
-  v17 = abs(-(a2->pFacePlane_old.dist + v15 + a3 * a2->pFacePlane_old.vNormal.x + a5 * a2->pFacePlane_old.vNormal.z)) >> 14;
+  v17 = abs(-(a2->pFacePlane_old.dist + a4 * a2->pFacePlane_old.vNormal.y + a3 * a2->pFacePlane_old.vNormal.x + a5 * a2->pFacePlane_old.vNormal.z)) >> 14;
   if ( v17 > abs(v14)
     || (LODWORD(v18) = v16 << 16, HIDWORD(v18) = v16 >> 16, v24 = v18 / v22, v23 = v18 / v22, v23 > *a1 << 16)
     || (LOWORD(v19) = a3 + (((unsigned int)((unsigned __int64)(v23 * (signed __int64)a6) >> 16) + 32768) >> 16),
@@ -1726,6 +1587,7 @@
   float v39; // [sp+D0h] [bp-8h]@6
   int *v40; // [sp+D4h] [bp-4h]@2
 
+  __debugbreak();// 
   v2 = (char *)&this->field_64[4 * this->uNumVertices];
   v38 = 0;
   *(int *)v2 = this->field_64[0];
@@ -1873,6 +1735,7 @@
   float v39; // [sp+D0h] [bp-8h]@6
   int *v40; // [sp+D4h] [bp-4h]@2
 
+  __debugbreak();// 
   v2 = (char *)&this->field_64[4 * this->uNumVertices];
   v38 = 0;
   *(int *)v2 = this->field_64[0];
@@ -2022,7 +1885,7 @@
   float v41; // [sp+2Ch] [bp-4h]@6
   float v42; // [sp+2Ch] [bp-4h]@9
 
-  //v1 = this;
+  __debugbreak();// 
   if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
   {
     v2 = 0;
@@ -2133,7 +1996,6 @@
 bool stru6_stru1_indoor_sw_billboard::sub_477F63()
 {
   signed int v1; // ebx@1
-  stru6_stru1_indoor_sw_billboard *v2; // esi@1
   double v3; // st7@2
   int v4; // edx@4
   char *v5; // ecx@5
@@ -2142,10 +2004,8 @@
   signed int v9; // [sp+Ch] [bp-8h]@1
   float v10; // [sp+10h] [bp-4h]@2
 
-  stru6_stru1_indoor_sw_billboard* a1 = this;
-
+  __debugbreak();//  - sw  hw?
   v1 = 0;
-  v2 = a1;
   v9 = 0;
   if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
   {
@@ -2157,15 +2017,14 @@
     v10 = (double)pODMRenderParams->shading_dist_mist;
     v3 = 8.0;
   }
-  v4 = a1->uNumVertices;
+  v4 = this->uNumVertices;
   if ( v4 <= 0 )
   {
-    memcpy(&v2->field_14[40], &v2->field_14[20], 16 * v4);
-    return v2->uNumVertices != 0;
+    memcpy(&this->field_14[40], &this->field_14[20], 16 * v4);
+    return this->uNumVertices != 0;
   }
-  v5 = (char *)&a1->field_14[20];
-  v6 = v4;
-  do
+  v5 = (char *)&this->field_14[20];
+  for ( v6 = v4; v6; --v6 )
   {
     if ( v3 >= *(float *)v5 || *(float *)v5 >= (double)v10 )
     {
@@ -2175,81 +2034,68 @@
         v1 = 1;
     }
     v5 += 16;
-    --v6;
   }
-  while ( v6 );
   if ( !v1 )
   {
     if ( v9 )
     {
-      v2->_477927(v10);
-      return v2->uNumVertices != 0;
+      this->_477927(v10);
+      return this->uNumVertices != 0;
     }
-    memcpy(&v2->field_14[40], &v2->field_14[20], 16 * v4);
-    return v2->uNumVertices != 0;
+    memcpy(&this->field_14[40], &this->field_14[20], 16 * v4);
+    return this->uNumVertices != 0;
   }
   v7 = v3;
   _4775ED(v7);
-  return v2->uNumVertices != 0;
+  return this->uNumVertices != 0;
 }
 
 //----- (0047802A) --------------------------------------------------------
 int stru6_stru1_indoor_sw_billboard::sub_47802A()
 {
   double v6; // st7@4
-  double v12; // st7@16
   signed int v16; // [sp+38h] [bp-Ch]@1
   int a6; // [sp+3Ch] [bp-8h]@5
   int a5; // [sp+40h] [bp-4h]@5
 
-  stru6_stru1_indoor_sw_billboard* a1 = this;
-
+  __debugbreak(); //  this->field_B4[i*4+16]
   v16 = 0;
   if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
   {
-	for(int i = 0; i < a1->uNumVertices; i++)
+    for(int i = 0; i < this->uNumVertices; i++)
     {
-		v6 = (double)pBLVRenderParams->fov_rad_fixpoint * 0.000015258789 / a1->field_B4[i*4];
-		if ( pRenderer->pRenderD3D )
-		{
-			pGame->pIndoorCameraD3D->Project(
-				round(a1->field_B4[i*4]),
-				round(a1->field_B4[i*4+1]),
-				round(a1->field_B4[i*4+2]),
-				&a5,
-				&a6);
-			a1->field_B4[i*4+16] = (double)a5;
-			a1->field_B4[i*4+17] = (double)a6;
-			a1->field_B4[i*4+18] = round(a1->field_B4[i*4]);
-		}
-		else
-		{
-			a1->field_B4[i*4+16] = (double)pBLVRenderParams->uViewportCenterX - v6 * a1->field_B4[i*4+1];
-			a1->field_B4[i*4+17] = (double)pBLVRenderParams->uViewportCenterY - v6 * a1->field_B4[i*4+2];
-			a1->field_B4[i*4+18] = a1->field_B4[i*4];
-		}
-		a1->field_B4[i*4+19] = a1->field_B4[i*4+3];
-		if ( (double)(signed int)pViewport->uViewportTL_X <= a1->field_B4[i*4+16]
-			&& (double)(signed int)pViewport->uViewportBR_X > a1->field_B4[i*4+16]
-			&& (double)(signed int)pViewport->uViewportTL_Y <= a1->field_B4[i*4+17]
-			&& (double)(signed int)pViewport->uViewportBR_Y > a1->field_B4[i*4+17] )
-			v16 = 1;
+      v6 = (double)pBLVRenderParams->fov_rad_fixpoint * 0.000015258789 / this->field_B4[i*4];
+      if ( pRenderer->pRenderD3D )
+      {
+        pGame->pIndoorCameraD3D->Project(round_to_int(this->field_B4[i*4]), round_to_int(this->field_B4[i*4+1]), round_to_int(this->field_B4[i*4+2]),
+           &a5, &a6);
+        this->field_B4[i*4+16] = (double)a5;
+        this->field_B4[i*4+17] = (double)a6;
+        this->field_B4[i*4+18] = round_to_int(this->field_B4[i*4]);
+      }
+      else
+      {
+        this->field_B4[i*4+16] = (double)pBLVRenderParams->uViewportCenterX - v6 * this->field_B4[i*4+1];
+        this->field_B4[i*4+17] = (double)pBLVRenderParams->uViewportCenterY - v6 * this->field_B4[i*4+2];
+        this->field_B4[i*4+18] = this->field_B4[i*4];
+      }
+      this->field_B4[i*4+19] = this->field_B4[i*4+3];
+      if ( (double)(signed int)pViewport->uViewportTL_X <= this->field_B4[i*4+16] && (double)(signed int)pViewport->uViewportBR_X > this->field_B4[i*4+16]
+        && (double)(signed int)pViewport->uViewportTL_Y <= this->field_B4[i*4+17] && (double)(signed int)pViewport->uViewportBR_Y > this->field_B4[i*4+17] )
+        v16 = 1;
     }
   }
   else
   {
-	for(int i = 0; i < a1->uNumVertices; i++)
+    for(int i = 0; i < this->uNumVertices; i++)
     {
-		v12 = (double)pODMRenderParams->int_fov_rad / a1->field_B4[i*4];
-		a1->field_B4[i*4+20] = (double)pViewport->uScreenCenterX - v12 * a1->field_B4[i*4+1];
-		a1->field_B4[i*4+21] = (double)pViewport->uScreenCenterY - v12 * a1->field_B4[i*4+2];
-		*((int *)&a1->field_B4[i*4+22]) = (int)a1->field_B4[i*4];
-		*((int *)&a1->field_B4[i*4+23]) = a1->field_B4[i*4+3];
-		if ( (double)(signed int)pViewport->uViewportTL_X <= a1->field_B4[i*4+20]
-			&& (double)(signed int)pViewport->uViewportBR_X > a1->field_B4[i*4+20]
-			&& (double)(signed int)pViewport->uViewportTL_Y <= a1->field_B4[i*4+21]
-			&& (double)(signed int)pViewport->uViewportBR_Y > a1->field_B4[i*4+21] )
-			v16 = 1;
+       this->field_B4[i*4+20] = (double)pViewport->uScreenCenterX - (double)pODMRenderParams->int_fov_rad / this->field_B4[i*4] * this->field_B4[i*4+1];
+       this->field_B4[i*4+21] = (double)pViewport->uScreenCenterY - (double)pODMRenderParams->int_fov_rad / this->field_B4[i*4] * this->field_B4[i*4+2];
+       *((int *)&this->field_B4[i*4+22]) = (int)this->field_B4[i*4];
+       *((int *)&this->field_B4[i*4+23]) = this->field_B4[i*4+3];
+       if ( (double)(signed int)pViewport->uViewportTL_X <= this->field_B4[i*4+20] && (double)(signed int)pViewport->uViewportBR_X > this->field_B4[i*4+20]
+         && (double)(signed int)pViewport->uViewportTL_Y <= this->field_B4[i*4+21] && (double)(signed int)pViewport->uViewportBR_Y > this->field_B4[i*4+21] )
+         v16 = 1;
     }
   }
   return v16;
@@ -2260,56 +2106,34 @@
 //----- (00479089) --------------------------------------------------------
 bool __fastcall IsBModelVisible(unsigned int uModelID, int *reachable)
 {
-  BSPModel *v2; // eax@1
   int v3; // edi@1
   int v4; // ebx@1
-  int v5; // ST28_4@1
-  int v6; // ecx@1
-  int v7; // ebx@3
-  int v8; // eax@3
   int v9; // eax@3
-  //int v10; // ebx@3
   signed int v11; // esi@6
   int v12; // esi@8
   bool result; // eax@9
-  //unsigned int v14; // [sp+Ch] [bp-20h]@1
-  int v15; // [sp+Ch] [bp-20h]@5
-  //int *v16; // [sp+10h] [bp-1Ch]@1
   int v17; // [sp+1Ch] [bp-10h]@1
-  int v18; // [sp+20h] [bp-Ch]@1
   int v19; // [sp+20h] [bp-Ch]@3
   int angle; // [sp+24h] [bp-8h]@1
-  int v21; // [sp+28h] [bp-4h]@1
-  //int v22; // [sp+28h] [bp-4h]@3
-
-  //v16 = unused;
-  angle = (signed int)(pODMRenderParams->uCameraFovInDegrees << 11) / 360 >> 1;
-  //v14 = uModelID;
-  v2 = &pOutdoor->pBModels[uModelID];
-  v3 = v2->vBoundingCenter.x - pGame->pIndoorCameraD3D->vPartyPos.x;
-  v4 = v2->vBoundingCenter.y - pGame->pIndoorCameraD3D->vPartyPos.y;
-  v5 = stru_5C6E00->Cos(pGame->pIndoorCameraD3D->sRotationY);
-  v21 = stru_5C6E00->Sin(pGame->pIndoorCameraD3D->sRotationY);
-  v18 = stru_5C6E00->Cos(pGame->pIndoorCameraD3D->sRotationX);
+
+  angle = (signed int)(pODMRenderParams->uCameraFovInDegrees << 11) / 360 / 2;
+  v3 = pOutdoor->pBModels[uModelID].vBoundingCenter.x - pGame->pIndoorCameraD3D->vPartyPos.x;
+  v4 = pOutdoor->pBModels[uModelID].vBoundingCenter.y - pGame->pIndoorCameraD3D->vPartyPos.y;
   stru_5C6E00->Sin(pGame->pIndoorCameraD3D->sRotationX);
-  v6 = v5;
-  v17 = v3 * v5 + v4 * v21;
+  v17 = v3 * stru_5C6E00->Cos(pGame->pIndoorCameraD3D->sRotationY) + v4 * stru_5C6E00->Sin(pGame->pIndoorCameraD3D->sRotationY);
   if (pGame->pIndoorCameraD3D->sRotationX)
-    v17 = (unsigned __int64)(v17 * (signed __int64)v18) >> 16;
-  v19 = v4 * v6 - v3 * v21;
-  v7 = abs(v4);
-  v8 = abs(v3);
-  v9 = int_get_vector_length(v8, v7, 0);
+    v17 = (unsigned __int64)(v17 * (signed __int64)stru_5C6E00->Cos(pGame->pIndoorCameraD3D->sRotationX)) >> 16;
+  v19 = v4 * stru_5C6E00->Cos(pGame->pIndoorCameraD3D->sRotationY) - v3 * stru_5C6E00->Sin(pGame->pIndoorCameraD3D->sRotationY);
+  v9 = int_get_vector_length(abs(v3), abs(v4), 0);
   //v10 = v14 * 188;
   //v22 = v9;
   *reachable = false;
   if ( v9 < pOutdoor->pBModels[uModelID].sBoundingRadius + 256 )
     *reachable = true;
-  v15 = stru_5C6E00->Sin(angle);
   if ( v19 >= 0 )
-    v11 = ((unsigned __int64)(v15 * (signed __int64)v17) >> 16) - ((unsigned __int64)(stru_5C6E00->Cos(angle) * (signed __int64)v19) >> 16);
+    v11 = ((unsigned __int64)(stru_5C6E00->Sin(angle) * (signed __int64)v17) >> 16) - ((unsigned __int64)(stru_5C6E00->Cos(angle) * (signed __int64)v19) >> 16);
   else
-    v11 = ((unsigned __int64)(stru_5C6E00->Cos(angle) * (signed __int64)v19) >> 16) + ((unsigned __int64)(v15 * (signed __int64)v17) >> 16);
+    v11 = ((unsigned __int64)(stru_5C6E00->Cos(angle) * (signed __int64)v19) >> 16) + ((unsigned __int64)(stru_5C6E00->Sin(angle) * (signed __int64)v17) >> 16);
   v12 = v11 >> 16;
   if ( v9 <= pODMRenderParams->shading_dist_mist + 2048 )
   {
@@ -2329,28 +2153,25 @@
 //----- (00479295) --------------------------------------------------------
 int Polygon::_479295()
 {
-  ODMFace *v2; // esi@1
   int v3; // ecx@4
   int v4; // eax@4
   int v5; // edx@4
   int v6; // ST14_4@5
-  int v7; // ST04_4@5
-  stru149 *v8; // ecx@5
   Vec3_int_ thisa; // [sp+Ch] [bp-10h]@8
   int v11; // [sp+18h] [bp-4h]@4
 
-  v2 = this->pODMFace;
-  if ( !v2->pFacePlane.vNormal.z )
+  if ( !this->pODMFace->pFacePlane.vNormal.z )
   {
-    v3 = v2->pFacePlane.vNormal.x;
-    v4 = -v2->pFacePlane.vNormal.y;
+    v3 = this->pODMFace->pFacePlane.vNormal.x;
+    v4 = -this->pODMFace->pFacePlane.vNormal.y;
     v5 = 0;
     v11 = 65536;
   }
-  else if ( (v2->pFacePlane.vNormal.x || v2->pFacePlane.vNormal.y) && abs(v2->pFacePlane.vNormal.z) < 59082 )
+  else if ( (this->pODMFace->pFacePlane.vNormal.x || this->pODMFace->pFacePlane.vNormal.y)
+      && abs(this->pODMFace->pFacePlane.vNormal.z) < 59082 )
   {
-    thisa.x = -v2->pFacePlane.vNormal.y;
-    thisa.y = v2->pFacePlane.vNormal.x;
+    thisa.x = -this->pODMFace->pFacePlane.vNormal.y;
+    thisa.y = this->pODMFace->pFacePlane.vNormal.x;
     thisa.z = 0;
     thisa.Normalize_float();
     v4 = thisa.x;
@@ -2365,12 +2186,9 @@
 	  v11 = 0;
 	  v5 = -65536;
   }
-  v6 = v11;
-  sTextureDeltaU = v2->sTextureDeltaU;
-  v7 = v3;
-  v8 = ptr_38;
-  sTextureDeltaV = v2->sTextureDeltaV;
-  v8->_48616B_frustum_odm(v4, v7, 0, 0, v5, v6);
+  sTextureDeltaU = this->pODMFace->sTextureDeltaU;
+  sTextureDeltaV = this->pODMFace->sTextureDeltaV;
+  ptr_38->_48616B_frustum_odm(v4, v3, 0, 0, v5, v11);
   return 1;
 }
 
@@ -3377,21 +3195,14 @@
 //----- (0048257A) --------------------------------------------------------
 int __fastcall GetTerrainHeightsAroundParty2(int a1, int a2, int *pIsOnWater, int bFloatAboveWater)
 {
-  //unsigned int v4; // ebx@1
-  //unsigned int v5; // edi@1
   int result; // eax@9
-  //int v7; // ebx@10
   int v8; // ebx@11
   int v9; // eax@11
   int v10; // ecx@11
-  //int v11; // [sp+Ch] [bp-Ch]@1
-  //int v12; // [sp+10h] [bp-8h]@1
   int v13; // [sp+10h] [bp-8h]@11
   signed int v14; // [sp+14h] [bp-4h]@3
   int v15; // [sp+24h] [bp+Ch]@11
 
-  //v11 = a1;
-  //v12 = a2;
   unsigned int grid_x = WorldPosToGridCellX(a1);
   unsigned int grid_z = WorldPosToGridCellZ(a2) - 1;
 
@@ -3450,10 +3261,6 @@
     return y_x1z1;
 }
 
-
-
-
-
 //----- (00485F53) --------------------------------------------------------
 void  sr_485F53(Vec2_int_ *v)
 {
@@ -3472,15 +3279,14 @@
 //----- (00486089) --------------------------------------------------------
 void Polygon::_normalize_v_18()
 {
-  double v2; // st7@1
-  double v3; // st6@1
-  double v5; // st5@1
-
-  //v1 = this;
-  v2 = (double)this->v_18.x;
-  v3 = (double)this->v_18.y;
-  v5 = (double)this->v_18.z;
-  float len = sqrt(v5 * v5 + v3 * v3 + v2 * v2);
+  //double v2; // st7@1
+  //double v3; // st6@1
+  //double v5; // st5@1
+
+ // v2 = (double)this->v_18.x;
+  //v3 = (double)this->v_18.y;
+ // v5 = (double)this->v_18.z;
+  float len = sqrt((double)this->v_18.z * (double)this->v_18.z + (double)this->v_18.y * (double)this->v_18.y + (double)this->v_18.x * (double)this->v_18.x);
   if (fabsf(len) < 1e-6f)
   {
     v_18.x = 0;
@@ -3489,9 +3295,9 @@
   }
   else
   {
-    v_18.x = round(v2 / len * 65536.0);
-    v_18.y = round(v3 / len * 65536.0);
-    v_18.y = round(v5 / len * 65536.0);
+    v_18.x = round_to_int((double)this->v_18.x / len * 65536.0);
+    v_18.y = round_to_int((double)this->v_18.y / len * 65536.0);
+    v_18.y = round_to_int((double)this->v_18.z / len * 65536.0);
   }
 }
 
@@ -3499,28 +3305,13 @@
 void stru149::_48616B_frustum_odm(int a2, int a3, int a4, int a5, int a6, int a7)
 {
   int v7; // ebx@1
-  //int v8; // esi@1
   int v9; // edi@1
-  //int v10; // eax@1
   int v11; // edx@1
-  //int v12; // esi@2
-  //int v13; // eax@2
-  //int v14; // ST10_4@3
-  //int v15; // esi@3
-  //int v16; // eax@5
   int v17; // ST0C_4@6
-  //int v18; // eax@8
   int v19; // ST0C_4@9
-  //int v20; // eax@10
-  //int v21; // edx@10
-  //int v22; // eax@10
-  //int result; // eax@10
   int v24; // [sp+14h] [bp-14h]@1
   int v25; // [sp+18h] [bp-10h]@1
-  //int v26; // [sp+1Ch] [bp-Ch]@1
   int v27; // [sp+24h] [bp-4h]@1
-  //int v28; // [sp+30h] [bp+8h]@10
-  //int v29; // [sp+3Ch] [bp+14h]@10
 
   v25 = pGame->pIndoorCameraD3D->int_cosine_x;
   v7 = pGame->pIndoorCameraD3D->int_sine_y;
@@ -3939,7 +3730,7 @@
       if ( !pLevelStr[i] )
       {
         pLevelStrOffsets[string_num] = i + 1;
-		++string_num;
+        ++string_num;
         if ( i - prev_string_offset > max_string_length )
           max_string_length = i - prev_string_offset;
         prev_string_offset = i;
@@ -3968,7 +3759,7 @@
   {
     for (uint i = 0; i < uLevelEVT_NumEvents; ++i)
     {
-		test_event=(_evt_raw*)&pLevelEVT[pLevelEVT_Index[i].uEventOffsetInEVT];
+      test_event=(_evt_raw*)&pLevelEVT[pLevelEVT_Index[i].uEventOffsetInEVT];
       if ( test_event->_e_type == EVENT_OnMapLeave )
       {
         EventProcessor(pLevelEVT_Index[i].uEventID, 0, 1, pLevelEVT_Index[i].event_sequence_num);
@@ -3980,161 +3771,150 @@
 //----- (00443FDC) --------------------------------------------------------
 void OnMapLoad()
 {
-	stru176 *v3; // esi@7
-	__int16 v4; // cx@9
-	__int16 v5; // di@9
-	int v6; // eax@9
-	signed __int64 v8; // qax@26
-	unsigned int v9; // ecx@26
-	signed __int64 v10; // qax@26
-	signed __int64 v11; // qax@26
-	int v12; // ST50_4@26
-	signed __int64 v13; // qax@26
-	signed __int64 v14; // qax@26
-	int v15; // ST58_4@26
-	signed __int64 v16; // qax@26
-	int hours; // ebx@26
-	unsigned __int64 v18; // [sp+Ch] [bp-44h]@12
-	signed __int64 seconds; // [sp+14h] [bp-3Ch]@26
-	unsigned __int64 v20; // [sp+1Ch] [bp-34h]@7
-	int minutes; // [sp+2Ch] [bp-24h]@26
-	int years; // [sp+34h] [bp-1Ch]@26
-	int weeks; // [sp+38h] [bp-18h]@26
-	int v26; // [sp+3Ch] [bp-14h]@15
-	int days; // [sp+3Ch] [bp-14h]@26
-	int months; // [sp+40h] [bp-10h]@26
-	__int16 v29; // [sp+46h] [bp-Ah]@9
-	__int16 v30; // [sp+48h] [bp-8h]@9
-	__int16 v31; // [sp+4Ah] [bp-6h]@9
-	__int16 v32; // [sp+4Ch] [bp-4h]@9
-	__int16 v33; // [sp+4Eh] [bp-2h]@9
-
-	for (uint i = 0; i < uLevelEVT_NumEvents; ++i)
-	{
-		EventIndex pEvent = pLevelEVT_Index[i];
-
-		_evt_raw* _evt = (_evt_raw *)(&pLevelEVT[pEvent.uEventOffsetInEVT]);
-
-		if (_evt->_e_type == EVENT_PlaySound)
-		{
-			pSoundList->LoadSound(EVT_DWORD(_evt->v5), 0);
-		}
-		else if (_evt->_e_type == EVENT_OnMapReload)
-		{
-			EventProcessor(pEvent.uEventID, 0, 0, pEvent.event_sequence_num);
-		}
-		else if (_evt->_e_type == EVENT_OnTimer || _evt->_e_type == EVENT_Initialize)
-		{
-			v3 = &array_5B5928_timers[dword_5B65C8_timers_count];
-			v20 = pOutdoor->loc_time.uLastVisitDay;
-			if (uCurrentlyLoadedLevelType == LEVEL_Indoor)
-				v20 = pIndoor->stru1.uLastVisitDay;
-
-			v3->timer_evt_type = _evt->_e_type;
-			v3->timer_evt_ID = pEvent.uEventID;
-			v3->timer_evt_seq_num = pEvent.event_sequence_num;
-
-			v3->field_10 = _evt->v5;
-			v3->field_12 = _evt->v6;
-			v3->field_14 = _evt->v7;
-			v3->field_16 = _evt->v8;
-			v3->field_18 = _evt->v9;
-			v3->field_1A = _evt->v10;
-
-
-			v6 = ((unsigned short)_evt->v12 << 8) + _evt->v11;
-
-			v3->time_left_to_fire = ((unsigned short)_evt->v12 << 8) + _evt->v11;
-            v3->fire_interval = ((unsigned short)_evt->v12 << 8) + _evt->v11;
-			if (v3->timer_evt_type  == EVENT_Initialize && !(short)v6 )
-			{
-				if ( v20 )
-					v18 = pParty->uTimePlayed - v20;
-				else
-					v18 = 0i64;
-				v26 = (signed int)(signed __int64)((double)(signed __int64)v18 * 0.234375) / 60 / 60 / 24;
-
-				if ( v26 / 7 / 4 / 12 )
-				{
-					if ( v3->field_10 )
-					{
-						++dword_5B65C8_timers_count;
-                        v3->next_fire_time = 0;
-						continue;
-					}
-				}
-				if (v26 / 7 / 4 != 0 && v3->field_12 != 0 ||
-					v26 / 7 != 0 && v3->field_14 != 0 ||
-					v26 != 0 || !v20)
-				{
-					++dword_5B65C8_timers_count;
-					v3->next_fire_time = 0;
-					continue;
-				}
-			}
-			else
-			{
-				v8 = (signed __int64)((double)(signed __int64)pParty->uTimePlayed * 0.234375);
-				v9 = v8;
-				v10 = (signed int)v8 / 60;
-				minutes = v10 % 60;
-				v11 = (signed int)(v10 / 60);
-				v12 = v11 % 24;
-				v13 = (signed int)(v11 / 24);
-				days = v13 % 7;
-				v14 = (signed int)(v13 / 7);
-				v15 = v14 % 4;
-				v16 = (signed int)(v14 / 4);
-				years = v16 / 12;
-
-				unsigned __int64 _1 = (unsigned __int64)((double)pParty->uTimePlayed * 0.234375) >> 32;
-				__int64 _2 = ((__int64)v9 << 32) | _1;
-
-				seconds = _2 % 60;
-				//v19 = (signed __int64)__PAIR__((unsigned __int64)(signed __int64)((double)(signed __int64)pParty->uTimePlayed * 0.234375) >> 32,
-				//                        v9)
-				//    % 60;
-
-				hours = v12;
-				weeks = v15;
-				months = v16 % 12;
-				if ( v3->field_10 )
-				{
-					++years;
-				}
-				else
-				{
-					if ( v3->field_12 )
-					{
-						++months;
-					}
-					else
-					{
-						if ( v3->field_14 )
-						{
-							++weeks;
-						}
-						else
-						{
-							++days;
-							minutes = v3->field_18;
-							hours = v3->field_16;
-							seconds = v3->field_1A;
-						}
-					}
-				}
-                v3->next_fire_time = (signed __int64)((double)((seconds
-					+ 60 * minutes
-					+ 3600 * hours
-					+ 0x93A80 * weeks
-					+ 0x15180 * days
-					+ 0x24EA00 * (months + 12i64 * years)) << 7)
-					* 0.033333335);
-
-				++dword_5B65C8_timers_count;
-			}
-		}
-	}
+  __int16 v4; // cx@9
+  __int16 v5; // di@9
+  int v6; // eax@9
+  signed __int64 v8; // qax@26
+  unsigned int v9; // ecx@26
+  signed __int64 v10; // qax@26
+  signed __int64 v11; // qax@26
+  int v12; // ST50_4@26
+  signed __int64 v13; // qax@26
+  signed __int64 v14; // qax@26
+  int v15; // ST58_4@26
+  signed __int64 v16; // qax@26
+  int hours; // ebx@26
+  unsigned __int64 v18; // [sp+Ch] [bp-44h]@12
+  signed __int64 seconds; // [sp+14h] [bp-3Ch]@26
+  unsigned __int64 v20; // [sp+1Ch] [bp-34h]@7
+  int minutes; // [sp+2Ch] [bp-24h]@26
+  int years; // [sp+34h] [bp-1Ch]@26
+  int weeks; // [sp+38h] [bp-18h]@26
+  int v26; // [sp+3Ch] [bp-14h]@15
+  int days; // [sp+3Ch] [bp-14h]@26
+  int months; // [sp+40h] [bp-10h]@26
+  __int16 v29; // [sp+46h] [bp-Ah]@9
+  __int16 v30; // [sp+48h] [bp-8h]@9
+  __int16 v31; // [sp+4Ah] [bp-6h]@9
+  __int16 v32; // [sp+4Ch] [bp-4h]@9
+  __int16 v33; // [sp+4Eh] [bp-2h]@9
+
+  for (uint i = 0; i < uLevelEVT_NumEvents; ++i)
+  {
+    EventIndex pEvent = pLevelEVT_Index[i];
+
+    _evt_raw* _evt = (_evt_raw *)(&pLevelEVT[pEvent.uEventOffsetInEVT]);
+
+    if (_evt->_e_type == EVENT_PlaySound)
+      pSoundList->LoadSound(EVT_DWORD(_evt->v5), 0);
+    else if (_evt->_e_type == EVENT_OnMapReload)
+      EventProcessor(pEvent.uEventID, 0, 0, pEvent.event_sequence_num);
+    else if (_evt->_e_type == EVENT_OnTimer || _evt->_e_type == EVENT_Initialize)
+    {
+      //v3 = &array_5B5928_timers[dword_5B65C8_timers_count];
+      v20 = pOutdoor->loc_time.uLastVisitDay;
+      if (uCurrentlyLoadedLevelType == LEVEL_Indoor)
+        v20 = pIndoor->stru1.uLastVisitDay;
+
+      array_5B5928_timers[dword_5B65C8_timers_count].timer_evt_type = _evt->_e_type;
+      array_5B5928_timers[dword_5B65C8_timers_count].timer_evt_ID = pEvent.uEventID;
+      array_5B5928_timers[dword_5B65C8_timers_count].timer_evt_seq_num = pEvent.event_sequence_num;
+
+      array_5B5928_timers[dword_5B65C8_timers_count].field_10 = _evt->v5;
+      array_5B5928_timers[dword_5B65C8_timers_count].field_12 = _evt->v6;
+      array_5B5928_timers[dword_5B65C8_timers_count].field_14 = _evt->v7;
+      array_5B5928_timers[dword_5B65C8_timers_count].field_16 = _evt->v8;
+      array_5B5928_timers[dword_5B65C8_timers_count].field_18 = _evt->v9;
+      array_5B5928_timers[dword_5B65C8_timers_count].field_1A = _evt->v10;
+
+
+      v6 = ((unsigned short)_evt->v12 << 8) + _evt->v11;
+
+      array_5B5928_timers[dword_5B65C8_timers_count].time_left_to_fire = ((unsigned short)_evt->v12 << 8) + _evt->v11;
+      array_5B5928_timers[dword_5B65C8_timers_count].fire_interval = ((unsigned short)_evt->v12 << 8) + _evt->v11;
+      if (array_5B5928_timers[dword_5B65C8_timers_count].timer_evt_type  == EVENT_Initialize && !(short)v6 )
+      {
+        if ( v20 )
+          v18 = pParty->uTimePlayed - v20;
+        else
+          v18 = 0i64;
+        v26 = (signed int)(signed __int64)((double)(signed __int64)v18 * 0.234375) / 60 / 60 / 24;
+
+        if ( v26 / 7 / 4 / 12 )
+        {
+          if ( array_5B5928_timers[dword_5B65C8_timers_count].field_10 )
+          {
+            ++dword_5B65C8_timers_count;
+            array_5B5928_timers[dword_5B65C8_timers_count].next_fire_time = 0;
+            continue;
+          }
+        }
+        if (v26 / 7 / 4 != 0 && array_5B5928_timers[dword_5B65C8_timers_count].field_12 != 0 ||
+          v26 / 7 != 0 && array_5B5928_timers[dword_5B65C8_timers_count].field_14 != 0 ||
+          v26 != 0 || !v20)
+        {
+          ++dword_5B65C8_timers_count;
+          array_5B5928_timers[dword_5B65C8_timers_count].next_fire_time = 0;
+          continue;
+        }
+      }
+      else
+      {
+        v8 = (signed __int64)((double)(signed __int64)pParty->uTimePlayed * 0.234375);
+        v9 = v8;
+        v10 = (signed int)v8 / 60;
+        minutes = v10 % 60;
+        v11 = (signed int)(v10 / 60);
+        v12 = v11 % 24;
+        v13 = (signed int)(v11 / 24);
+        days = v13 % 7;
+        v14 = (signed int)(v13 / 7);
+        v15 = v14 % 4;
+        v16 = (signed int)(v14 / 4);
+        years = v16 / 12;
+
+        unsigned __int64 _1 = (unsigned __int64)((double)pParty->uTimePlayed * 0.234375) >> 32;
+        __int64 _2 = ((__int64)v9 << 32) | _1;
+
+        seconds = _2 % 60;
+        //v19 = (signed __int64)__PAIR__((unsigned __int64)(signed __int64)((double)(signed __int64)pParty->uTimePlayed * 0.234375) >> 32,
+        //                        v9)
+        //    % 60;
+
+        hours = v12;
+        weeks = v15;
+        months = v16 % 12;
+        if ( array_5B5928_timers[dword_5B65C8_timers_count].field_10 )
+          ++years;
+        else
+        {
+          if ( array_5B5928_timers[dword_5B65C8_timers_count].field_12 )
+            ++months;
+          else
+          {
+            if ( array_5B5928_timers[dword_5B65C8_timers_count].field_14 )
+              ++weeks;
+            else
+            {
+              ++days;
+              minutes = array_5B5928_timers[dword_5B65C8_timers_count].field_18;
+              hours = array_5B5928_timers[dword_5B65C8_timers_count].field_16;
+              seconds = array_5B5928_timers[dword_5B65C8_timers_count].field_1A;
+            }
+          }
+        }
+        array_5B5928_timers[dword_5B65C8_timers_count].next_fire_time = (signed __int64)((double)((seconds
+                    + 60 * minutes
+                    + 3600 * hours
+                    + 0x93A80 * weeks
+                    + 0x15180 * days
+                    + 0x24EA00 * (months + 12i64 * years)) << 7)
+                    * 0.033333335);
+
+        ++dword_5B65C8_timers_count;
+      }
+    }
+  }
 }
 
 //----- (00444360) --------------------------------------------------------
@@ -4154,31 +3934,26 @@
 //----- (00444D80) --------------------------------------------------------
 int GetTravelTime()
 {
-  signed int v0; // esi@1
-
-  v0 = uDefaultTravelTime_ByFoot;
+  signed int new_travel_time; // esi@1
+
+  new_travel_time = uDefaultTravelTime_ByFoot;
   if ( CheckHiredNPCSpeciality(Guide) )
-    --v0;
+    --new_travel_time;
   if ( CheckHiredNPCSpeciality(Tracker) )
-    v0 -= 2;
+    new_travel_time -= 2;
   if ( CheckHiredNPCSpeciality(Pathfinder) )
-    v0 -= 3;
+    new_travel_time -= 3;
   if ( CheckHiredNPCSpeciality(Explorer) )
-    --v0;
-  if ( v0 < 1 )
-    v0 = 1;
-  return v0;
+    --new_travel_time;
+  if ( new_travel_time < 1 )
+    new_travel_time = 1;
+  return new_travel_time;
 }
 // 6BD07C: using guessed type int uDefaultTravelTime_ByFoot;
 
 //----- (004451A8) --------------------------------------------------------
 void __fastcall sub_4451A8_press_any_key(int a1, int a2, int a4)
 {
-  int v3; // esi@1
-  int v4; // edi@1
-
-  v3 = a2;
-  v4 = a1;
   if ( !pGUIWindow2 )
   {
     if ( pParty->uFlags & 2 )
@@ -4186,8 +3961,8 @@
     pAudioPlayer->StopChannels(-1, -1);
     pMiscTimer->Pause();
     pEventTimer->Pause();
-    dword_5C3418 = v4;
-    dword_5C341C = v3;
+    dword_5C3418 = a1;
+    dword_5C341C = a2;
     _591094_decoration = activeLevelDecoration;
     pGUIWindow2 = GUIWindow::Create(0, 0, 640, 480, WINDOW_GreetingNPC, a4, 0);
     pGUIWindow2->CreateButton( 61, 424, 31, 40, 2, 94, UIMSG_SelectCharacter, 1, '1', "", 0);
@@ -4209,7 +3984,7 @@
 }
 
 //----- (004465DF) --------------------------------------------------------
-int sub_4465DF_check_season(int a1)
+bool sub_4465DF_check_season(int a1)
 {
   unsigned int v1; // eax@1
   unsigned int v2; // edx@1
@@ -4219,185 +3994,132 @@
 
   v1 = pParty->uCurrentMonth + 1;
   v2 = pParty->uDaysPlayed + 1;
-  if ( a1 )
+  if ((v1 == (a1 + 1) * 3 && v2 >= 21) || v1 == (a1 + 1) % 4 * 3 + 1 || v1 == (a1 + 1) % 4 * 3 + 2 || (v1 == (a1 + 2) % 4 * 3 && v2 < 21))
+	  return true;
+  return false;
+
+  switch (a1)
   {
-    v3 = a1 - 1;
-    if ( v3 )
-    {
-      v4 = v3 - 1;
-      if ( v4 )
-      {
-        if ( v4 != 1 )
-          return 0;
-        if ( v1 != 12 )
-        {
-          if ( (signed int)v1 >= 1 && (signed int)v1 <= 2 )
-            return 1;
-          v6 = v1 == 3;
-LABEL_24:
-          if ( !v6 || (signed int)v2 >= 21 )
-            return 0;
-          return 1;
-        }
-      }
-      else
-      {
-        if ( v1 != 9 )
-        {
-          if ( (signed int)v1 >= 10 && (signed int)v1 <= 11 )
-            return 1;
-          v6 = v1 == 12;
-          goto LABEL_24;
-        }
-      }
-    }
-    else
-    {
-      if ( v1 != 6 )
-      {
-        if ( (signed int)v1 >= 7 && (signed int)v1 <= 8 )
-          return 1;
-        v6 = v1 == 9;
-        goto LABEL_24;
-      }
-    }
-  }
-  else
-  {
-    if ( v1 != 3 )
-    {
-      if ( (signed int)v1 >= 4 && (signed int)v1 <= 5 )
-        return 1;
-      v6 = v1 == 6;
-      goto LABEL_24;
-    }
+	case 3:
+		if (v1 != 12)//12.21 -> 3.20
+		{
+			if ((signed int)v1 >= 1 && (signed int)v1 <= 2)
+				return true;
+			v6 = v1 == 3;
+			if (!v6 || (signed int)v2 >= 21)
+				return false;
+			return true;
+		}
+		break;
+	case 2:
+		if (v1 != 9)//9.21 -> 12.20
+		{
+			if ((signed int)v1 >= 10 && (signed int)v1 <= 11)
+				return true;
+			v6 = v1 == 12;
+			if (!v6 || (signed int)v2 >= 21)
+				return false;
+			return true;
+		}
+		break;
+	case 1:
+		if (v1 != 6)//6.21 -> 9.20
+		{
+			if ((signed int)v1 >= 7 && (signed int)v1 <= 8)
+				return true;
+			v6 = v1 == 9;
+			if (!v6 || (signed int)v2 >= 21)
+				return false;
+			return true;
+		}
+		break;
+	case 0:
+		if (v1 != 3)//3.21 -> 9.20
+		{
+			if ((signed int)v1 >= 4 && (signed int)v1 <= 5)
+				return true;
+			v6 = v1 == 6;
+			if (!v6 || (signed int)v2 >= 21)
+				return false;
+			return true;
+		}
+		break;
+	default:
+		return false;
   }
   if ( (signed int)v2 >= 21 )
-    return 1;
-  return 0;
+    return true;
+  return false;
 }
 
 //----- (0044861E) --------------------------------------------------------
 void __fastcall sub_44861E_set_texture(unsigned int uFaceCog, const char *pFilename)
 {
-  unsigned int v2; // eax@2
-  unsigned __int16 v3; // di@2
-  signed int v4; // esi@5
-  BLVFace *v5; // eax@7
-  unsigned int *v6; // eax@8
-  char *v7; // eax@9
-  int v8; // edi@16
-  char *v9; // esi@16
-  ODMFace *v10; // eax@17
-  unsigned int *v11; // eax@19
-  unsigned __int16 v12; // [sp+Ch] [bp-18h]@2
-  const char *Str2; // [sp+10h] [bp-14h]@1
-  unsigned int v14; // [sp+14h] [bp-10h]@1
-  signed int v15; // [sp+18h] [bp-Ch]@14
-  int v16; // [sp+1Ch] [bp-8h]@15
-  signed int v17; // [sp+20h] [bp-4h]@4
-  signed int v18; // [sp+20h] [bp-4h]@16
-
-  Str2 = pFilename;
-  v14 = uFaceCog;
+  unsigned int texture; // eax@2
+
   if ( uFaceCog )
   {
-    v2 = pBitmaps_LOD->LoadTexture(pFilename);
-    v3 = v2;
-    v12 = v2;
-    if ( v2 != -1 ? (int)&pBitmaps_LOD->pTextures[v2] : 0 )
+    texture = pBitmaps_LOD->LoadTexture(pFilename);
+    if ( texture != -1 ? (int)&pBitmaps_LOD->pTextures[texture] : 0 )
     {
-      pBitmaps_LOD->pTextures[v2].palette_id2 = pPaletteManager->LoadPalette(pBitmaps_LOD->pTextures[v2].palette_id1);
+      pBitmaps_LOD->pTextures[texture].palette_id2 = pPaletteManager->LoadPalette(pBitmaps_LOD->pTextures[texture].palette_id1);
 
       if ( uCurrentlyLoadedLevelType == 1 )
       {
-        v17 = 1;
         if ( (signed int)pIndoor->uNumFaceExtras > 1 )
         {
-          v4 = 1;
-          do
+          for ( uint i = 1; i < (signed int)pIndoor->uNumFaceExtras; ++i )
           {
-            if ( pIndoor->pFaceExtras[v4].sCogNumber == v14 )
+            if ( pIndoor->pFaceExtras[i].sCogNumber == uFaceCog )
             {
-              v5 = &pIndoor->pFaces[pIndoor->pFaceExtras[v4].field_C];
-              if ( BYTE1(v5->uAttributes) & 0x40 )
+              if ( BYTE1(pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uAttributes) & 0x40 )
               {
-                pIndoor->pFaces[pIndoor->pFaceExtras[v4].field_C].uBitmapID = pTextureFrameTable->FindTextureByName(
-                                                                              Str2);
-                v6 = (unsigned int *)&pIndoor->pFaces[pIndoor->pFaceExtras[v4].field_C].uBitmapID;
-                if ( *(_WORD *)v6 )
+                pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uBitmapID = pTextureFrameTable->FindTextureByName(pFilename);
+                if ( pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uBitmapID)
                 {
-                  pTextureFrameTable->LoadAnimationSequenceAndPalettes(*(_WORD *)v6);
+                  pTextureFrameTable->LoadAnimationSequenceAndPalettes(pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uBitmapID);
                 }
                 else
                 {
-                  *(_WORD *)v6 = v3;
-                  v7 = (char *)&pIndoor->pFaces[pIndoor->pFaceExtras[v4].field_C].uAttributes;
-                  v7[1] &= 0xBFu;
+                  pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uBitmapID = texture;
+                  BYTE1(pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uAttributes) &= 0xBFu;
                 }
               }
               else
               {
-                v5->uBitmapID = v3;
+                pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uBitmapID = texture;
               }
             }
-            ++v17;
-            ++v4;
           }
-          while ( v17 < (signed int)pIndoor->uNumFaceExtras );
         }
-        pParty->uFlags |= 2u;
+        pParty->uFlags |= 2;
       }
       else
       {
-        v15 = 0;
-        if ( (signed int)pOutdoor->uNumBModels > 0 )
+        for ( uint j = 0; j < (unsigned int)pOutdoor->uNumBModels; ++j )
         {
-          v16 = 0;
-          do
+          for ( uint i = 0; i < pOutdoor->pBModels[j].uNumFaces; ++i )
           {
-            v8 = 0;
-            v9 = (char *)&pOutdoor->pBModels[v16].pVertices;
-            v18 = 0;
-            if ( (signed int)pOutdoor->pBModels[v16].uNumFaces > 0 )
+            if ( pOutdoor->pBModels[j].pFaces[i].sCogNumber == uFaceCog )
             {
-              do
+              if ( BYTE1(pOutdoor->pBModels[j].pFaces[i].uAttributes) & 0x40 )
               {
-                v10 = (ODMFace *)(v8 + *((_DWORD *)v9 + 4));
-                if ( v10->sCogNumber == v14 )
+                pOutdoor->pBModels[j].pFaces[i].uTextureID = pTextureFrameTable->FindTextureByName(pFilename);
+                if ( pOutdoor->pBModels[j].pFaces[i].uTextureID )
+                  pTextureFrameTable->LoadAnimationSequenceAndPalettes(pOutdoor->pBModels[j].pFaces[i].uTextureID);
+                else
                 {
-                  if ( BYTE1(v10->uAttributes) & 0x40 )
-                  {
-                    *(_WORD *)(*((_DWORD *)v9 + 4) + v8 + 272) = pTextureFrameTable->FindTextureByName(
-                                                                   Str2);
-                    v11 = (unsigned int *)(*((_DWORD *)v9 + 4) + v8 + 272);
-                    if ( *(_WORD *)v11 )
-                    {
-                      pTextureFrameTable->LoadAnimationSequenceAndPalettes(*(_WORD *)v11);
-                    }
-                    else
-                    {
-                      *(_WORD *)v11 = v12;
-                      *(_BYTE *)(*((_DWORD *)v9 + 4) + v8 + 29) &= 0xBFu;
-                    }
-                  }
-                  else
-                  {
-                    v10->uTextureID = v12;
-                  }
+                  pOutdoor->pBModels[j].pFaces[i].uTextureID = texture;
+                  BYTE1(pOutdoor->pBModels[j].pFaces[i].uAttributes) &= 0xBFu;
                 }
-                ++v18;
-                v8 += 308;
               }
-              while ( v18 < *((_DWORD *)v9 + 2) );
+              else
+                pOutdoor->pBModels[j].pFaces[i].uTextureID = texture;
             }
-            ++v15;
-            ++v16;
           }
-          while ( v15 < (signed int)pOutdoor->uNumBModels );
         }
       }
-      pParty->uFlags |= 2u;
+      pParty->uFlags |= 2;
     }
   }
 }
@@ -4420,7 +4142,7 @@
       else
         pLevelDecorations[i].uFlags |= LEVEL_DECORATION_INVISIBLE;
 
-      pParty->uFlags |= 2u;
+      pParty->uFlags |= 2;
     }
   }
 }
@@ -4428,148 +4150,42 @@
 //----- (0044892E) --------------------------------------------------------
 void __fastcall sub_44892E_set_faces_bit(int sCogNumber, int bit, int on)
 {
-  signed int v3; // esi@2
-  signed int v4; // ecx@4
-  char *v5; // eax@6
-  int v6; // edi@13
-  char *v7; // esi@13
-  signed int v8; // ecx@13
-  ODMFace *v9; // eax@14
-  int v10; // [sp+0h] [bp-Ch]@1
-  signed int v11; // [sp+4h] [bp-8h]@11
-  int v12; // [sp+8h] [bp-4h]@12
-
-  v10 = sCogNumber;
   if ( sCogNumber )
   {
-    v3 = 1;
     if ( uCurrentlyLoadedLevelType == 1 )
     {
-      if ( (signed int)pIndoor->uNumFaceExtras > 1 )
+      for ( uint i = 1; i < (unsigned int)pIndoor->uNumFaceExtras; ++i )
       {
-        v4 = 1;
-        do
+        if ( pIndoor->pFaceExtras[i].sCogNumber == sCogNumber )
         {
-          if ( pIndoor->pFaceExtras[v4].sCogNumber == v10 )
-          {
-            v5 = (char *)&pIndoor->pFaces[pIndoor->pFaceExtras[v4].field_C].uAttributes;
-            if ( on )
-              *(_DWORD *)v5 |= bit;
-            else
-              *(_DWORD *)v5 &= ~bit;
-          }
-          ++v3;
-          ++v4;
+          if ( on )
+            pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uAttributes |= bit;
+          else
+            pIndoor->pFaces[pIndoor->pFaceExtras[i].field_C].uAttributes &= ~bit;
         }
-        while ( v3 < (signed int)pIndoor->uNumFaceExtras );
       }
-      pParty->uFlags |= 2u;
+      pParty->uFlags |= 2;
     }
     else
     {
-      v11 = 0;
-      if ( (signed int)pOutdoor->uNumBModels > 0 )
+      for ( uint j = 0; j < (unsigned int)pOutdoor->uNumBModels; ++j )
       {
-        v12 = 0;
-        do
+        for ( uint i = 0; i < (unsigned int)pOutdoor->pBModels[j].uNumFaces; ++i )
         {
-          v6 = 0;
-          v7 = (char *)&pOutdoor->pBModels[v12].pVertices;
-          v8 = 0;
-          if ( (signed int)pOutdoor->pBModels[v12].uNumFaces > 0 )
+          if ( pOutdoor->pBModels[j].pFaces[i].sCogNumber == sCogNumber )
           {
-            do
-            {
-              v9 = (ODMFace *)(v6 + *((_DWORD *)v7 + 4));
-              if ( v9->sCogNumber == v10 )
-              {
-                if ( on )
-                  v9->uAttributes |= bit;
-                else
-                  v9->uAttributes &= ~bit;
-              }
-              ++v8;
-              v6 += 308;
-            }
-            while ( v8 < *((_DWORD *)v7 + 2) );
+            if ( on )
+              pOutdoor->pBModels[j].pFaces[i].uAttributes |= bit;
+            else
+              pOutdoor->pBModels[j].pFaces[i].uAttributes &= ~bit;
           }
-          ++v11;
-          ++v12;
         }
-        while ( v11 < (signed int)pOutdoor->uNumBModels );
       }
     }
-    pParty->uFlags |= 2u;
+    pParty->uFlags |= 2;
   }
 }
 
-//----- (00448A98) --------------------------------------------------------
-void __fastcall ToggleActorGroupFlag(unsigned int uGroupID, unsigned int uFlag, unsigned int bToggle)
-{
-  unsigned int v3; // ebx@1
-  unsigned int v4; // ebp@1
-  signed int v5; // edi@1
-  Actor *v6; // esi@4
-  size_t v7; // ecx@10
-  Actor *v8; // eax@11
-  unsigned __int16 v9; // dx@14
-
-  v4 = uGroupID;
-  v5 = Standing;
-  v3 = uFlag;
-  if ( uGroupID )
-  {
-    if ( bToggle )
-    {
-      if ( (signed int)uNumActors > Standing )
-      {
-        v6 = pActors.data();//[0].uAttributes;
-        do
-        {
-          if ( v6->uGroup == v4 )
-          {
-            v6->uAttributes |= v3;
-            if ( v3 == 0x10000 )
-            {
-              v6->uAIState = Disabled;
-              v6->UpdateAnimation();
-            }
-          }
-          ++v5;
-          ++v6;
-        }
-        while ( v5 < (signed int)uNumActors );
-      }
-    }
-    else
-    {
-      v7 = uNumActors;
-      if ( (signed int)uNumActors > Standing )
-      {
-        v8 = pActors.data();//[0].uAIState;
-        do
-        {
-          if ( v8->uGroup == v4 )
-          {
-            if ( v3 == 0x10000 )
-            {
-              v9 = v8->uAIState;
-              if ( v8->uAIState != Dead )
-              {
-                if ( v9 != 4 && v9 != 11 )
-                  v8->uAIState = Standing;
-              }
-            }
-			LODWORD(v8->uAttributes) &= ~v3;
-          }
-          ++v8;
-          --v7;
-        }
-        while ( v7 );
-      }
-    }
-  }
-}
 
 //----- (00448B45) --------------------------------------------------------
 void  GameUI_StatusBar_UpdateTimedString(unsigned int bForceHide)
@@ -4652,63 +4268,44 @@
 //----- (00448CF4) --------------------------------------------------------
 void __fastcall sub_448CF4_spawn_monsters(__int16 typeindex, __int16 level, int count, int x, int y, int z, int group, unsigned int uUniqueName)
 {
-  __int16 v8; // di@1
-  __int16 v9; // si@1
-  unsigned int v10; // eax@1
-  size_t v11; // ebx@2
-  signed int v12; // esi@2
-  Actor *pActor;//Actor_uYawAngle_cr *v13; // ebx@3
-  AIDirection a3; // [sp+Ch] [bp-50h]@2
+  unsigned int map_id; // eax@1
+  size_t old_num_actors; // ebx@2
   AIDirection v15; // [sp+28h] [bp-34h]@2
-  //SpawnPointMM7 v16; // [sp+44h] [bp-18h]@1
-
-  v8 = typeindex;
-  v9 = level;
-
-  SpawnPointMM7 v16; // [sp+44h] [bp-18h]@1
-  //SpawnPointMM7::SpawnPointMM7(&v16);
-
-  v16.vPosition.x = x;
-  v16.vPosition.y = y;
-  v16.vPosition.z = z;
-  v16.uGroup = group;
-  v16.uRadius = 32;
-  v16.uKind = 3;
-  v16.uIndex = v8 + 2 * v9 + v9;
-  v10 = pMapStats->GetMapInfo(pCurrentMapName);
-  if ( v10 )
+  SpawnPointMM7 pSpawnPoint; // [sp+44h] [bp-18h]@1
+
+  pSpawnPoint.vPosition.x = x;
+  pSpawnPoint.vPosition.y = y;
+  pSpawnPoint.vPosition.z = z;
+  pSpawnPoint.uGroup = group;
+  pSpawnPoint.uRadius = 32;
+  pSpawnPoint.uKind = 3;
+  pSpawnPoint.uIndex = typeindex + 2 * level + level;
+  map_id = pMapStats->GetMapInfo(pCurrentMapName);
+  if ( map_id )
   {
-    v11 = uNumActors;
-    SpawnEncounter(&pMapStats->pInfos[v10], &v16, 0, count, 0);
-    Actor::GetDirectionInfo(PID(OBJECT_Actor, v11), 4u, &v15, 1);
-    v12 = v11;
-    if ( (signed int)v11 < (signed int)uNumActors )
+    old_num_actors = uNumActors;
+    SpawnEncounter(&pMapStats->pInfos[map_id], &pSpawnPoint, 0, count, 0);
+    Actor::GetDirectionInfo(PID(OBJECT_Actor, old_num_actors), 4, &v15, 1);
+    for ( uint i = (unsigned int)old_num_actors; i < (unsigned int)uNumActors; ++i )
     {
-      for ( pActor = &pActors[v11]; v12 < (signed int)uNumActors; ++pActor )
-      {
-        pActor->PrepareSprites(0);
-        ++v12;
-        pActor->uYawAngle = v15.uYawAngle;
-        pActor->dword_000334_unique_name = uUniqueName;
-      }
+      pActors[i].PrepareSprites(0);
+      pActors[i].uYawAngle = v15.uYawAngle;
+      pActors[i].dword_000334_unique_name = uUniqueName;
     }
   }
 }
 
 
 //----- (0044987B) --------------------------------------------------------
-void sub_44987B(const char *pMapName, MapStartPoint start_point)
+void Transition_StopSound_Autosave(const char *pMapName, MapStartPoint start_point)
 {
-  const char *v2; // edi@1
-
-  v2 = pMapName;
   pAudioPlayer->StopChannels(-1, -1);
   pGameLoadingUI_ProgressBar->Initialize(GUIProgressBar::TYPE_None);
-  if ( _stricmp(pCurrentMapName, v2) )
+  if ( _stricmp(pCurrentMapName, pMapName) )
     SaveGame(1, 0);
 
-  uGameState = GAME_STATE_2;
-  strcpy(pCurrentMapName, v2);
+  uGameState = GAME_STATE_CHANGE_LOCATION;
+  strcpy(pCurrentMapName, pMapName);
   uLevel_StartingPointType = start_point;
 }
 // 6BE35C: using guessed type int uLevel_StartingPointType;
@@ -4716,58 +4313,42 @@
 //----- (004498D5) --------------------------------------------------------
 void TeleportToStartingPoint(MapStartPoint point)
 {
-  //unsigned int v1; // ecx@2
-  //int v2; // ecx@3
-  //int v3; // ecx@4
-  unsigned __int16 v4; // ax@11
-  signed int v5; // ecx@12
-  LevelDecoration *v6; // edx@13
-  signed int v7; // ecx@17
-  int v8; // eax@17
-  int v9; // ecx@17
-  const char *v10; // [sp-4h] [bp-84h]@6
+  const char *model_name; // [sp-4h] [bp-84h]@6
   char pName[128]; // [sp+8h] [bp-78h]@11
 
   switch (point)
   {
-    case MapStartPoint_Party: v10 = "Party Start"; break;
-    case MapStartPoint_North: v10 = "North Start"; break;
-    case MapStartPoint_South: v10 = "South Start"; break;
-    case MapStartPoint_East: v10 = "East Start";  break;
-    case MapStartPoint_West: v10 = "West Start";  break;
+    case MapStartPoint_Party: model_name = "Party Start"; break;
+    case MapStartPoint_North: model_name = "North Start"; break;
+    case MapStartPoint_South: model_name = "South Start"; break;
+    case MapStartPoint_East: model_name = "East Start";  break;
+    case MapStartPoint_West: model_name = "West Start";  break;
     default:
       Error("Invalid enum value: %u", point);
   }
 
-  strcpy(pName, v10);
-  v4 = pDecorationList->GetDecorIdByName(pName);
-  if ( v4 )
+  strcpy(pName, model_name);
+  if ( pDecorationList->GetDecorIdByName(pName) )
   {
-    v5 = 0;
+    
     if ( (signed int)uNumLevelDecorations > 0 )
     {
-      v6 = pLevelDecorations.data();
-      while ( v6->uDecorationDescID != (signed __int16)v4 )
+      for ( uint i = 0; i < (signed int)uNumLevelDecorations; ++i )
       {
-        ++v5;
-        ++v6;
-        if ( v5 >= (signed int)uNumLevelDecorations )
-          goto LABEL_20;
+        if ( pLevelDecorations[i].uDecorationDescID == (signed __int16)pDecorationList->GetDecorIdByName(pName) )
+        {
+          pParty->vPosition.x = pLevelDecorations[i].vPosition.x;
+          pParty->vPosition.y = pLevelDecorations[i].vPosition.y;
+          pParty->vPosition.z = pLevelDecorations[i].vPosition.z;
+          pParty->uFallStartY = pParty->vPosition.z;
+          pParty->sRotationY = (signed int)(stru_5C6E00->uIntegerHalfPi * pLevelDecorations[i].field_1A) / 90;
+          if ( pLevelDecorations[i].field_10_y_rot )
+            pParty->sRotationY = pLevelDecorations[i].field_10_y_rot;
+          pParty->sRotationX = 0;
+          pParty->uFallSpeed = 0;
+        }
       }
-      v7 = v5;
-      pParty->vPosition.x = pLevelDecorations[v7].vPosition.x;
-      pParty->vPosition.y = pLevelDecorations[v7].vPosition.y;
-      pParty->vPosition.z = pLevelDecorations[v7].vPosition.z;
-      pParty->uFallStartY = pParty->vPosition.z;
-      v8 = (signed int)(stru_5C6E00->uIntegerHalfPi * pLevelDecorations[v7].field_1A) / 90;
-      v9 = pLevelDecorations[v7].field_10_y_rot;
-      pParty->sRotationY = v8;
-      if ( v9 )
-        pParty->sRotationY = v9;
-      pParty->sRotationX = 0;
-      pParty->uFallSpeed = 0;
     }
-LABEL_20:
     if ( dword_5B65C0 )
     {
       if ( _5B65A8_npcdata_uflags_or_other )
@@ -4796,96 +4377,6 @@
   }
 }
 
-//----- (00449A49) --------------------------------------------------------
-void Door_switch_animation(unsigned int uDoorID, int a2)
-{
-  int old_state; // eax@1
-  signed int door_id; // esi@2
-
-  if ( !pIndoor->pDoors )
-    return;
-  for ( door_id = 0; door_id < 200; ++door_id )
-  {
-    if ( pIndoor->pDoors[door_id].uDoorID == uDoorID )
-      break;
-  }
-  if ( door_id >= 200 )
-  {
-    Error("Unable to find Door ID: %i!", uDoorID);
-  }
-  old_state = pIndoor->pDoors[door_id].uState;
-  if ( a2 == 2 )
-  {
-    if ( pIndoor->pDoors[door_id].uState == BLVDoor::Closing || pIndoor->pDoors[door_id].uState == BLVDoor::Opening )
-      return;
-    if ( pIndoor->pDoors[door_id].uState )
-    {
-      if ( pIndoor->pDoors[door_id].uState != BLVDoor::Closed && pIndoor->pDoors[door_id].uState != BLVDoor::Closing )
-      {
-        pIndoor->pDoors[door_id].uState = BLVDoor::Closing;
-        if ( old_state == BLVDoor::Open )
-        {
-          pIndoor->pDoors[door_id].uTimeSinceTriggered = 0;
-          return;
-        }
-        if ( pIndoor->pDoors[door_id].uTimeSinceTriggered != 15360 )
-        {
-          pIndoor->pDoors[door_id].uTimeSinceTriggered = (pIndoor->pDoors[door_id].uMoveLength << 7) / pIndoor->pDoors[door_id].uOpenSpeed
-             - ((signed int)(pIndoor->pDoors[door_id].uTimeSinceTriggered * pIndoor->pDoors[door_id].uCloseSpeed)
-             / 128 << 7) / pIndoor->pDoors[door_id].uOpenSpeed;
-          return;
-        }
-        pIndoor->pDoors[door_id].uTimeSinceTriggered = 15360;
-      }
-      return;
-    }
-  }
-  else
-  {
-    if ( a2 == 0 )
-    {
-      if ( pIndoor->pDoors[door_id].uState != BLVDoor::Closed && pIndoor->pDoors[door_id].uState != BLVDoor::Closing )
-      {
-        pIndoor->pDoors[door_id].uState = BLVDoor::Closing;
-        if ( old_state == BLVDoor::Open )
-        {
-          pIndoor->pDoors[door_id].uTimeSinceTriggered = 0;
-          return;
-        }
-        if ( pIndoor->pDoors[door_id].uTimeSinceTriggered != 15360 )
-        {
-          pIndoor->pDoors[door_id].uTimeSinceTriggered = (pIndoor->pDoors[door_id].uMoveLength << 7) / pIndoor->pDoors[door_id].uOpenSpeed
-             - ((signed int)(pIndoor->pDoors[door_id].uTimeSinceTriggered * pIndoor->pDoors[door_id].uCloseSpeed)
-             / 128 << 7) / pIndoor->pDoors[door_id].uOpenSpeed;
-          return;
-        }
-        pIndoor->pDoors[door_id].uTimeSinceTriggered = 15360;
-      }
-      return;
-    }
-    if ( a2 != 1 )
-      return;
-  }
-  if ( old_state != BLVDoor::Open && old_state != BLVDoor::Opening )
-  {
-    pIndoor->pDoors[door_id].uState = BLVDoor::Opening;
-    if ( old_state == BLVDoor::Closed )
-    {
-      pIndoor->pDoors[door_id].uTimeSinceTriggered = 0;
-      return;
-    }
-    if ( pIndoor->pDoors[door_id].uTimeSinceTriggered != 15360 )
-    {
-      pIndoor->pDoors[door_id].uTimeSinceTriggered = (pIndoor->pDoors[door_id].uMoveLength << 7) / pIndoor->pDoors[door_id].uCloseSpeed
-         - ((signed int)(pIndoor->pDoors[door_id].uTimeSinceTriggered * pIndoor->pDoors[door_id].uOpenSpeed)
-         / 128 << 7) / pIndoor->pDoors[door_id].uCloseSpeed;
-      return;
-    }
-    pIndoor->pDoors[door_id].uTimeSinceTriggered = 15360;
-  }
-  return;
-}
-
 //----- (00449B57) --------------------------------------------------------
 bool _449B57_test_bit( unsigned __int8 *a1, __int16 a2 )
 {
@@ -4945,7 +4436,7 @@
   dword_5B65C0 = 0;
 
   pGameLoadingUI_ProgressBar->uType = GUIProgressBar::TYPE_Fullscreen;
-  sub_44987B("nwc.blv", MapStartPoint_Party);
+  Transition_StopSound_Autosave("nwc.blv", MapStartPoint_Party);
   pCurrentScreen = SCREEN_GAME;
   return true;
 }
--- a/mm7_4.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_4.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -45,31 +45,27 @@
 //----- (0046CC4B) --------------------------------------------------------
 void check_event_triggers()
 {
-  LevelDecoration *v1; // esi@2
-
   for (size_t i = 0; i < num_event_triggers; i++)
   {
-    v1 = &pLevelDecorations[event_triggers[i]];
-
-    if (v1->uFlags & LEVEL_DECORATION_TRIGGERED_BY_TOUCH
-        && v1->vPosition.GetDistanceTo(pParty->vPosition) < v1->uTriggerRange)
+    if (pLevelDecorations[event_triggers[i]].uFlags & LEVEL_DECORATION_TRIGGERED_BY_TOUCH
+        && pLevelDecorations[event_triggers[i]].vPosition.GetDistanceTo(pParty->vPosition) < pLevelDecorations[event_triggers[i]].uTriggerRange)
     {
-      EventProcessor(v1->uEventID, PID(OBJECT_Decoration,i), 1);
+      EventProcessor(pLevelDecorations[event_triggers[i]].uEventID, PID(OBJECT_Decoration,i), 1);
     }
-    else if (v1->uFlags & LEVEL_DECORATION_TRIGGERED_BY_MONSTER)
+    else if (pLevelDecorations[event_triggers[i]].uFlags & LEVEL_DECORATION_TRIGGERED_BY_MONSTER)
     {
       for (size_t j = 0; j < uNumActors; j++)
       {
-        if (v1->vPosition.GetDistanceTo(pActors[j].vPosition) < v1->uTriggerRange)
-          EventProcessor(v1->uEventID, 0, 1);
+        if (pLevelDecorations[event_triggers[i]].vPosition.GetDistanceTo(pActors[j].vPosition) < pLevelDecorations[event_triggers[i]].uTriggerRange)
+          EventProcessor(pLevelDecorations[event_triggers[i]].uEventID, 0, 1);
       }
     }
-    else if (v1->uFlags & LEVEL_DECORATION_TRIGGERED_BY_OBJECT)
+    else if (pLevelDecorations[event_triggers[i]].uFlags & LEVEL_DECORATION_TRIGGERED_BY_OBJECT)
     {
       for (size_t j = 0; j < uNumSpriteObjects; j++)
       {
-        if (v1->vPosition.GetDistanceTo(pSpriteObjects[j].vPosition) < v1->uTriggerRange)
-          EventProcessor(v1->uEventID, 0, 1);
+        if (pLevelDecorations[event_triggers[i]].vPosition.GetDistanceTo(pSpriteObjects[j].vPosition) < pLevelDecorations[event_triggers[i]].uTriggerRange)
+          EventProcessor(pLevelDecorations[event_triggers[i]].uEventID, 0, 1);
       }
     }
   }
@@ -90,17 +86,11 @@
 //----- (0046E0B2) --------------------------------------------------------
 void  _46E0B2_collide_against_decorations()
 {
-  BLVSector *v0; // ebp@1
-  LevelDecoration *v1; // edi@2
-  DecorationDesc *v2; // esi@3
-  int v3; // edx@4
-  int v4; // eax@4
-  int v5; // ecx@6
-  int v6; // ebx@8
-  int v7; // esi@8
+  BLVSector *sector; // ebp@1
+  LevelDecoration *decor; // edi@2
+  DecorationDesc *decor_desc; // esi@3
   int v8; // ebx@10
   int v9; // esi@11
-  int v10; // edi@12
   int v11; // eax@12
   int v12; // esi@14
   unsigned int v13; // eax@17
@@ -108,65 +98,44 @@
   int v15; // [sp+8h] [bp-10h]@10
   int v16; // [sp+Ch] [bp-Ch]@10
   int v17; // [sp+10h] [bp-8h]@10
-  int v18; // [sp+14h] [bp-4h]@8
 
-  v0 = &pIndoor->pSectors[stru_721530.uSectorID];
-  for ( i = 0; i < v0->uNumDecorations; ++i )
+  sector = &pIndoor->pSectors[stru_721530.uSectorID];
+  for ( i = 0; i < sector->uNumDecorations; ++i )
   {
-    v1 = &pLevelDecorations[v0->pDecorationIDs[i]];
-    if (!(v1->uFlags & LEVEL_DECORATION_INVISIBLE))
+    decor = &pLevelDecorations[sector->pDecorationIDs[i]];
+    if (!(decor->uFlags & LEVEL_DECORATION_INVISIBLE))
     {
-      v2 = &pDecorationList->pDecorations[v1->uDecorationDescID];
-      if (!v2->CanMoveThrough())
+      decor_desc = &pDecorationList->pDecorations[decor->uDecorationDescID];
+      if (!decor_desc->CanMoveThrough())
       {
-        v3 = v2->uRadius;
-        v4 = v1->vPosition.x;
-        if ( stru_721530.sMaxX <= v4 + v3 )
+        if ( stru_721530.sMaxX <= decor->vPosition.x + decor_desc->uRadius && stru_721530.sMinX >= decor->vPosition.x - decor_desc->uRadius 
+          && stru_721530.sMaxY <= decor->vPosition.y + decor_desc->uRadius && stru_721530.sMinY >= decor->vPosition.y - decor_desc->uRadius 
+          && stru_721530.sMaxZ <= decor->vPosition.z + decor_desc->uDecorationHeight && stru_721530.sMinZ >= decor->vPosition.z )
         {
-          if ( stru_721530.sMinX >= v4 - v3 )
+          v16 = decor->vPosition.x - stru_721530.normal.x;
+          v15 = decor->vPosition.y - stru_721530.normal.y;
+          v8 = stru_721530.prolly_normal_d + decor_desc->uRadius;
+          v17 = ((decor->vPosition.x - stru_721530.normal.x) * stru_721530.direction.y
+              - (decor->vPosition.y - stru_721530.normal.y) * stru_721530.direction.x) >> 16;
+          if ( abs(v17) <= stru_721530.prolly_normal_d + decor_desc->uRadius )
           {
-            v5 = v1->vPosition.y;
-            if ( stru_721530.sMaxY <= v5 + v3 )
+            v9 = (v16 * stru_721530.direction.x + v15 * stru_721530.direction.y) >> 16;
+            if ( v9 > 0 )
             {
-              if ( stru_721530.sMinY >= v5 - v3 )
+              v11 = stru_721530.normal.z + fixpoint_mul(stru_721530.direction.z, v9);
+              if ( v11 >= decor->vPosition.z )
               {
-                v6 = v2->uDecorationHeight;
-                v7 = v1->vPosition.z;
-                v18 = v6;
-                if ( stru_721530.sMaxZ <= v7 + v6 )
+                if ( v11 <= decor_desc->uDecorationHeight + decor->vPosition.z )
                 {
-                  if ( stru_721530.sMinZ >= v7 )
+                  v12 = v9 - integer_sqrt(v8 * v8 - v17 * v17);
+                  if ( v12 < 0 )
+                    v12 = 0;
+                  if ( v12 < stru_721530.field_7C )
                   {
-                    v16 = v4 - stru_721530.normal.x;
-                    v15 = v5 - stru_721530.normal.y;
-                    v8 = stru_721530.prolly_normal_d + v3;
-                    v17 = ((v4 - stru_721530.normal.x) * stru_721530.direction.y
-                         - (v5 - stru_721530.normal.y) * stru_721530.direction.x) >> 16;
-                    if ( abs(v17) <= stru_721530.prolly_normal_d + v3 )
-                    {
-                      v9 = (v16 * stru_721530.direction.x + v15 * stru_721530.direction.y) >> 16;
-                      if ( v9 > 0 )
-                      {
-                        v10 = v1->vPosition.z;
-                        v11 = stru_721530.normal.z + fixpoint_mul(stru_721530.direction.z, v9);
-                        if ( v11 >= v10 )
-                        {
-                          if ( v11 <= v18 + v10 )
-                          {
-                            v12 = v9 - integer_sqrt(v8 * v8 - v17 * v17);
-                            if ( v12 < 0 )
-                              v12 = 0;
-                            if ( v12 < stru_721530.field_7C )
-                            {
-                              stru_721530.field_7C = v12;
-                              v13 = 8 * v0->pDecorationIDs[i];
-                              LOBYTE(v13) = v13 | 5;
-                              stru_721530.uFaceID = v13;
-                            }
-                          }
-                        }
-                      }
-                    }
+                    stru_721530.field_7C = v12;
+                    v13 = 8 * sector->pDecorationIDs[i];
+                    LOBYTE(v13) = v13 | 5;
+                    stru_721530.uFaceID = v13;
                   }
                 }
               }
@@ -203,9 +172,9 @@
     v = v_replace;
   HSV2RGB(&r, &g, &b, h, s, v);
 
-  return (((uint)round(r * 255.0f) & 0xFF) << 16) |
-         (((uint)round(g * 255.0f) & 0xFF) << 8) |
-         (((uint)round(b * 255.0f) & 0xFF));
+  return (((uint)round_to_int(r * 255.0f) & 0xFF) << 16) |
+         (((uint)round_to_int(g * 255.0f) & 0xFF) << 8) |
+         (((uint)round_to_int(b * 255.0f) & 0xFF));
 }
 
 //----- (0048B561) --------------------------------------------------------
@@ -225,95 +194,54 @@
 //----- (00491E3A) --------------------------------------------------------
 void sub_491E3A()
 {
-  Player *v0; // ebx@1
   signed int v1; // esi@3
-  char *v2; // eax@4
   unsigned int v3; // eax@7
   unsigned int v4; // edx@8
-  char *v5; // ecx@9
   int v6; // edi@17
-  Texture *v7; // ebx@18
-  struct IDirect3DTexture2 **v8; // eax@19
-  struct IDirect3DTexture2 *v9; // eax@20
-  struct IDirectDrawSurface **v10; // eax@22
-  struct IDirectDrawSurface *v11; // eax@23
   int v12; // eax@26
 
-  v0 = pParty->pPlayers.data();
-  do
+  __debugbreak();//Ritor1
+  for ( uint pl = 0; pl < 4; pl++ )
   {
     if (SoundSetAction[24][0])
     {
-      v1 = 0;
-      if ( (signed int)pSoundList->sNumSounds <= 0 )
-      {
-LABEL_7:
-        v3 = 0;
-      }
-      else
+      v3 = 0;
+      for ( v1 = 0; v1 < (signed int)pSoundList->sNumSounds; ++v1 )
       {
-        v2 = (char *)&pSoundList->pSounds->uSoundID;
-        while ( *(int *)v2 != 2 * (SoundSetAction[24][0] + 50 * v0->uVoiceID) + 4998 )
-        {
-          ++v1;
-          v2 += 120;
-          if ( v1 >= (signed int)pSoundList->sNumSounds )
-            goto LABEL_7;
-        }
-        v3 = v1;
+        if ( pSoundList->pSL_Sounds[v1].uSoundID == 2 * (SoundSetAction[24][0] + 50 * pParty->pPlayers[pl].uVoiceID) + 4998 )
+          v3 = v1;
       }
       pSoundList->UnloadSound(v3, 1);
-      v4 = 0;
-      if ( (signed int)pSoundList->sNumSounds <= 0 )
-      {
-LABEL_12:
-        v4 = 0;
-      }
-      else
+      for ( v4 = 0; (signed int)v4 < (signed int)pSoundList->sNumSounds; ++v4 )
       {
-        v5 = (char *)&pSoundList->pSounds->uSoundID;
-        while ( *(int *)v5 != 2 * (SoundSetAction[24][0] + 50 * v0->uVoiceID) + 4999 )
-        {
-          ++v4;
-          v5 += 120;
-          if ( (signed int)v4 >= (signed int)pSoundList->sNumSounds )
-            goto LABEL_12;
-        }
+        if ( pSoundList->pSL_Sounds[v4].uSoundID == 2 * (SoundSetAction[24][0] + 50 * pParty->pPlayers[pl].uVoiceID) + 4999 )
+          pSoundList->UnloadSound(v4, 1);
       }
-      pSoundList->UnloadSound(v4, 1);
     }
-    ++v0;
   }
-  while ( (signed int)v0 < (signed int)pParty->pHirelings.data() );
   v6 = pIcons_LOD->uNumLoadedFiles - 1;
   if ( v6 >= pIcons_LOD->pFacesLock )
   {
-    v7 = &pIcons_LOD->pTextures[v6];
     do
     {
-      v7->Release();
-      v8 = pIcons_LOD->pHardwareTextures;
-      if ( v8 )
+      pIcons_LOD->pTextures[v6].Release();
+      if ( pIcons_LOD->pHardwareTextures )
       {
-        v9 = v8[v6];
-        if ( v9 )
+        if ( pIcons_LOD->pHardwareTextures[v6] )
         {
-          v9->Release();
+          pIcons_LOD->pHardwareTextures[v6]->Release();
           pIcons_LOD->pHardwareTextures[v6] = 0;
         }
       }
-      v10 = pIcons_LOD->pHardwareSurfaces;
-      if ( v10 )
+      if ( pIcons_LOD->pHardwareSurfaces )
       {
-        v11 = v10[v6];
-        if ( v11 )
+        if ( pIcons_LOD->pHardwareSurfaces[v6] )
         {
-          v11->Release();
+          pIcons_LOD->pHardwareSurfaces[v6]->Release();
           pIcons_LOD->pHardwareSurfaces[v6] = 0;
         }
       }
       --v6;
-      --v7;
     }
     while ( v6 >= pIcons_LOD->pFacesLock );
   }
@@ -989,36 +917,33 @@
 {
   int v3; // esi@1
   int result; // eax@1
-  stru339_spell_sound *v5; // ebx@1
-  int *v6; // edi@2
+  //stru339_spell_sound *v5; // ebx@1
+  //int *v6; // edi@2
   unsigned int v7; // eax@3
   int v8; // [sp+Ch] [bp-8h]@3
   int v9; // [sp+10h] [bp-4h]@2
   int a2a; // [sp+1Ch] [bp+8h]@1
-  return 0;
+  //return 0;
   v3 = 0;
   result = word_4EE088_sound_ids[uSoundID];
-  v5 = this;
+  //v5 = this;
   a2a = word_4EE088_sound_ids[uSoundID];
-  if ( result )
+  if ( word_4EE088_sound_ids[uSoundID] )
   {
-    v9 = 0;
-    v6 = this->pSoundsOffsets;
-    do
+    //v6 = this->pSoundsOffsets;
+    for ( v9 = 0; v9 < 2; ++v9 )
     {
       v7 = a2a++;
-      result = pSoundList->LoadSound(v7, (char *)v5 + v3, 44744 - v3, &v8, a6);
+      result = pSoundList->LoadSound(v7, (char *)this + v3, 44744 - v3, &v8, a6);
       if ( !result )
         break;
       a6 += 4;
       result = v8 + 256;
-      *v6 = v3;
+      this->pSoundsOffsets[v9] = v3;
       v3 += result;
-      ++v9;
-      *(v6 - 2) = result;
-      ++v6;
+      this->pSoundsSizes[v9] = v8 + 256;
+      //++v6;
     }
-    while ( v9 < 2 );
   }
   return result;
 }
@@ -1027,36 +952,18 @@
 //----- (00494AED) --------------------------------------------------------
 unsigned int PlayerFrameTable::GetFrameIdByExpression(CHARACTER_EXPRESSION_ID expression)
 {
-  unsigned int _uNumFrames; // edx@1
-  unsigned int result; // eax@1
-  PlayerFrame *v4; // ecx@2
-
-  _uNumFrames = this->uNumFrames;
-  result = 0;
-  if ( (signed int)this->uNumFrames <= 0 )
+  for ( uint i = 0; i < this->uNumFrames; i++ )
   {
-    result = 0;
+    if ( this->pFrames[i].expression == expression )
+      return i;
   }
-  else
-  {
-    v4 = this->pFrames;
-    while ( v4->expression != expression )
-    {
-      ++result;
-      ++v4;
-      if ( (signed int)result >= (signed int)_uNumFrames )
-        return 0;
-    }
-  }
-  return result;
+  return 0;
 }
 
 //----- (00494B10) --------------------------------------------------------
 PlayerFrame *PlayerFrameTable::GetFrameBy_x(unsigned int uFramesetID, unsigned int uFrameID)
 {
   unsigned int v3; // esi@1
-  PlayerFrame *v4; // edi@1
-  PlayerFrame *v5; // ecx@1
   __int16 v6; // dx@2
   int v7; // edx@3
   char *i; // eax@3
@@ -1064,12 +971,10 @@
   PlayerFrame *result; // eax@6
 
   v3 = uFramesetID;
-  v4 = this->pFrames;
-  v5 = &v4[uFramesetID];
-  if ( v5->uFlags & 1 && (v6 = v5->uAnimLength) != 0 )
+  if ( this->pFrames[uFramesetID].uFlags & 1 && (v6 = this->pFrames[uFramesetID].uAnimLength) != 0 )
   {
     v7 = ((signed int)uFrameID >> 3) % (unsigned __int16)v6;
-    for ( i = (char *)&v5->uAnimTime; ; i += 10 )
+    for ( i = (char *)&this->pFrames[uFramesetID].uAnimTime; ; i += 10 )
     {
       v9 = *(short *)i;
       if ( v7 <= v9 )
@@ -1077,35 +982,29 @@
       v7 -= v9;
       ++v3;
     }
-    result = &v4[v3];
+    result = &this->pFrames[v3];
   }
   else
-  {
-    result = &v4[uFramesetID];
-  }
+    result = &this->pFrames[uFramesetID];
   return result;
 }
 
 //----- (00494B5E) --------------------------------------------------------
 PlayerFrame *PlayerFrameTable::GetFrameBy_y(int *pFramesetID, int *pAnimTime, int a4)
 {
-  PlayerFrameTable *v4; // edi@1
   int v5; // esi@1
   int v6; // eax@2
 
-  v4 = this;
   v5 = a4 + *pAnimTime;
   if ( v5 < 8 * this->pFrames[*pFramesetID].uAnimTime )
-  {
     *pAnimTime = v5;
-  }
   else
   {
     v6 = rand() % 4 + 21;
     *pFramesetID = v6;
-    *pAnimTime = 8 * v5 % v4->pFrames[v6].uAnimTime;
+    *pAnimTime = 8 * v5 % this->pFrames[v6].uAnimTime;
   }
-  return &v4->pFrames[*pFramesetID];
+  return &this->pFrames[*pFramesetID];
 }
 
 //----- (00494BC3) --------------------------------------------------------
@@ -1122,7 +1021,7 @@
   v3 = v2;
   if ( !v2 )
     Error("Unable to save dpft.bin");
-  fwrite(v1, 4u, 1u, v2);
+  fwrite(v1, 4, 1, v2);
   fwrite(v1->pFrames, 0xAu, v1->uNumFrames, v3);
   fclose(v3);
 }
@@ -1146,7 +1045,7 @@
 //----- (00494C5A) --------------------------------------------------------
 int PlayerFrameTable::FromFileTxt(const char *Args)
 {
-  PlayerFrameTable *v2; // ebx@1
+  //PlayerFrameTable *v2; // ebx@1
   FILE *v3; // eax@1
   int v4; // esi@3
   void *v5; // eax@10
@@ -1162,7 +1061,7 @@
   int v15; // ecx@23
   int v16; // eax@24
   signed int k; // eax@27
-  PlayerFrame *v18; // edx@28
+  //PlayerFrame *v18; // edx@28
   int v19; // esi@28
   int l; // ecx@29
   char Buf; // [sp+Ch] [bp-2F8h]@3
@@ -1173,7 +1072,7 @@
   FILE *File; // [sp+300h] [bp-4h]@1
   int Argsa; // [sp+30Ch] [bp+8h]@28
 
-  v2 = this;
+  __debugbreak();//Ritor1;
   //TileTable::dtor((TileTable *)this);
   v3 = fopen(Args, "r");
   File = v3;
@@ -1199,13 +1098,13 @@
     while ( fgets(&Buf, 490, File) );
     v4 = v25;
   }
-  v2->uNumFrames = v4;
+  this->uNumFrames = v4;
   v5 = malloc(10 * v4);
-  v2->pFrames = (PlayerFrame *)v5;
+  this->pFrames = (PlayerFrame *)v5;
   if ( !v5 )
     Error("PlayerFrameTable::load - Out of Memory!");
   v6 = File;
-  v2->uNumFrames = 0;
+  this->uNumFrames = 0;
   fseek(v6, 0, 0);
   for ( i = fgets(&Buf, 490, File); i; i = fgets(&Buf, 490, File) )
   {
@@ -1213,55 +1112,50 @@
     memcpy(&v24, txt_file_frametable_parser(&Buf, &v23), sizeof(v24));
     if ( v24.uPropCount && *v24.pProperties[0] != 47 )
     {
-      v8 = atoi(v24.pProperties[0]);
-      v9 = v24.pProperties[1];
-      v2->pFrames[v2->uNumFrames].expression = (CHARACTER_EXPRESSION_ID)v8;
-      v10 = atoi(v9);
-      v11 = v24.pProperties[2];
-      v2->pFrames[v2->uNumFrames].uTextureID = v10;
-      v2->pFrames[v2->uNumFrames].uAnimTime = atoi(v11);
-      v2->pFrames[v2->uNumFrames].uAnimLength = 0;
-      v2->pFrames[v2->uNumFrames].uFlags = 0;
+      //v8 = atoi(v24.pProperties[0]);
+      //v9 = v24.pProperties[1];
+      this->pFrames[this->uNumFrames].expression = (CHARACTER_EXPRESSION_ID)atoi(v24.pProperties[0]);
+      //v10 = atoi(v9);
+      //v11 = v24.pProperties[2];
+      this->pFrames[this->uNumFrames].uTextureID = atoi(v24.pProperties[1]);
+      this->pFrames[this->uNumFrames].uAnimTime = atoi(v24.pProperties[2]);
+      this->pFrames[this->uNumFrames].uAnimLength = 0;
+      this->pFrames[this->uNumFrames].uFlags = 0;
       for ( j = 3; j < v24.uPropCount; ++j )
       {
         if ( !_stricmp(v24.pProperties[j], "New") )
-        {
-          v13 = (int)&v2->pFrames[v2->uNumFrames].uFlags;
-          *(char *)v13 |= 4u;
-        }
+          this->pFrames[this->uNumFrames].uFlags |= 4;
       }
-      ++v2->uNumFrames;
+      ++this->uNumFrames;
     }
   }
   fclose(File);
-  v14 = 0;
-  if ( (signed int)(v2->uNumFrames - 1) > 0 )
+  
+  if ( (signed int)(this->uNumFrames - 1) > 0 )
   {
     v15 = 0;
-    do
+    for ( v14 = 0; v14 < this->uNumFrames - 1; ++v14 )
     {
-      v16 = (int)&v2->pFrames[v15];
+      v16 = (int)&this->pFrames[v15];
       if ( !(*(char *)(v16 + 18) & 4) )
-        *(char *)(v16 + 8) |= 1u;
-      ++v14;
+        this->pFrames[v14].uFlags |= 1;
       ++v15;
     }
-    while ( v14 < (signed int)(v2->uNumFrames - 1) );
   }
-  for ( k = 0; k < (signed int)v2->uNumFrames; *(short *)(Argsa + 6) = v19 )
+  for ( k = 0; k < (signed int)this->uNumFrames; *(short *)(Argsa + 6) = v19 )
   {
-    v18 = v2->pFrames;
-    Argsa = (int)&v18[k];
+    //v18 = this->pFrames;
+    Argsa = (int)&this->pFrames[k];
     v19 = *(short *)(Argsa + 4);
-    if ( *(char *)(Argsa + 8) & 1 )
+    if ( this->pFrames[k].uFlags & 1 )
     {
       ++k;
-      for ( l = (int)&v18[k]; *(char *)(l + 8) & 1; l += 10 )
+      for ( l = (int)&this->pFrames[k]; this->pFrames[k].uFlags & 1; l += 10 )
       {
         v19 += *(short *)(l + 4);
         ++k;
       }
-      LOWORD(v19) = v18[k].uAnimTime + v19;
+      LOWORD(v19) = this->pFrames[k].uAnimTime + v19;
     }
     ++k;
   }
@@ -1273,7 +1167,7 @@
 {
   int v2; // edi@1
   int v3; // edx@2
-  int v4; // esi@3
+  //int v4; // esi@3
   int v5; // ebx@5
   signed int v7; // [sp+Ch] [bp-14h]@1
   signed int v8; // [sp+10h] [bp-10h]@1
@@ -1286,40 +1180,33 @@
   v8 = 0;
   v7 = 0;
   if ( dword_AE336C == a1 )
-  {
     v3 = dword_AE3370;
-  }
   else
   {
-    v4 = a2;
+    //v4 = a2;
     dword_AE336C = a1;
-    v10 = 0;
-    if ( (signed int)pNPCStats->uNumNPCNames[v4] <= 0 )
-	{
-		v3 = rand() % (signed int)pNPCStats->uNumNPCNames[v4];
-	}
-	else
-	{
-    v9 = (int **)((char *)pNPCStats->pNPCNames + v4 * 4);
-    do
+    if ( (signed int)pNPCStats->uNumNPCNames[a2] <= 0 )
+      v3 = rand() % (signed int)pNPCStats->uNumNPCNames[a2];
+    else
     {
-      v5 = tolower(*(char *)*v9);
-      if ( v5 == tolower(v2) )
+      v9 = (int **)((char *)pNPCStats->pNPCNames + a2 * 4);
+      for ( v10 = 0; v10 < (signed int)pNPCStats->uNumNPCNames[a2]; ++v10 )
       {
-        if ( v8 )
-          v7 = v10;
-        else
-          v8 = v10;
+        v5 = tolower(*(char *)*v9);
+        if ( v5 == tolower(v2) )
+        {
+          if ( v8 )
+            v7 = v10;
+          else
+            v8 = v10;
+        }
+        v9 += 2;
       }
-      ++v10;
-      v9 += 2;
+      if ( v8 && v8 != v7 )
+        v3 = v8 + rand() % (v7 - v8);
+      else
+        v3 = rand() % (signed int)pNPCStats->uNumNPCNames[a2];
     }
-    while ( v10 < (signed int)pNPCStats->uNumNPCNames[v4] );
-    if ( v8 && v8 != v7 )
-      v3 = v8 + rand() % (v7 - v8);
-    else
-      v3 = rand() % (signed int)pNPCStats->uNumNPCNames[v4];
-	}
   }
   dword_AE3370 = v3;
   return pNPCStats->pNPCNames[0][v11 + 2 * v3];
@@ -1558,7 +1445,7 @@
           break;
         case 17://  
         {
-          uint pay_percentage = pNPCStats->pProfessions[npc->uProfession - 1].uHirePrice / 100;
+          uint pay_percentage = pNPCStats->pProfessions[npc->uProfession].uHirePrice / 100;
           if ( !pay_percentage )
             pay_percentage = 1;
           sprintf(a1, "%lu", pay_percentage);
@@ -1589,7 +1476,7 @@
           i += 2;
           break;
         case 24://   
-          sprintfex(a1, format_4E2D80, TargetColor(255, 255, 155), a3->GetDisplayName());
+          sprintfex(a1, format_4E2D80, Color16(255, 255, 155), a3->GetDisplayName());
           strcat(pTmpBuf2.data(), a1);
           dst = strlen(pTmpBuf2.data());
           i += 2;
@@ -1771,64 +1658,30 @@
 //----- (0049B13D) --------------------------------------------------------
 void stru154::GetFacePlane(ODMFace *pFace, BSPVertexBuffer *pVertices, Vec3_float_ *pOutNormal, float *pOutDist)
 {
-  ODMFace *v5; // ebx@1
-  //int v6; // eax@1
-  //unsigned __int16 *v7; // ebx@2
-  //Vec3_int_ *v8; // eax@3
-  Vec3_int_ *v9; // ecx@3
-  //double v10; // st7@3
-  //int v11; // ecx@3
-  Vec3_int_ *v12; // ecx@3
-  //double v13; // st7@3
-  //double v14; // st6@3
-  //double v15; // st5@3
-  //int v16; // ecx@3
-  Vec3_int_ *v17; // eax@3
-  //double v18; // st5@3
   Vec3_float_ *v19; // eax@3
-  //int result; // eax@8
-  //float v21; // ecx@10
-  //double v22; // st7@10
-  //double v23; // st6@10
   Vec3_float_ v2; // [sp+4h] [bp-64h]@3
-  //float v25; // [sp+18h] [bp-50h]@3
   float v26; // [sp+1Ch] [bp-4Ch]@3
   float v27; // [sp+20h] [bp-48h]@3
   float v28; // [sp+24h] [bp-44h]@3
-  //float v29; // [sp+2Ch] [bp-3Ch]@3
-  //float v30; // [sp+30h] [bp-38h]@3
-  //float v31; // [sp+34h] [bp-34h]@3
-  //float v32; // [sp+38h] [bp-30h]@3
-  //float v33; // [sp+3Ch] [bp-2Ch]@3
   Vec3_float_ v1; // [sp+40h] [bp-28h]@1
-  //float v35; // [sp+4Ch] [bp-1Ch]@3
-  //float v36; // [sp+50h] [bp-18h]@3
-  //float v37; // [sp+54h] [bp-14h]@3
   Vec3_float_ v38; // [sp+58h] [bp-10h]@3
-  //int v39; // [sp+64h] [bp-4h]@1
 
-  //v39 = 0;
   v1.x = 0.0;
-  v5 = pFace;
-  //v6 = pFace->uNumVertices;
   v1.y = 0.0;
   v1.z = 0.0;
 
   if (pFace->uNumVertices >= 2)
   {
-    int i = 0;
-    while ( i < pFace->uNumVertices - 2 )
+    for ( int i = 0; i < pFace->uNumVertices - 2; i++ )
     {
-      v9 = &pVertices->pVertices[pFace->pVertexIDs[i]];
-      v12 = &pVertices->pVertices[pFace->pVertexIDs[i + 1]];
-      v17 = &pVertices->pVertices[pFace->pVertexIDs[i + 2]];
-	  i++;
-      v1.x = v12->x - v9->x;
-      v26 = v17->x - v12->x;
-      v1.y = v12->y - v9->y;
-      v27 = v17->y - v12->y;
-      v1.z = v12->z - v9->z;
-      v28 = v17->z - v12->z;
+      v1.x = pVertices->pVertices[pFace->pVertexIDs[i + 1]].x - pVertices->pVertices[pFace->pVertexIDs[i]].x;
+      v1.y = pVertices->pVertices[pFace->pVertexIDs[i + 1]].y - pVertices->pVertices[pFace->pVertexIDs[i]].y;
+      v1.z = pVertices->pVertices[pFace->pVertexIDs[i + 1]].z - pVertices->pVertices[pFace->pVertexIDs[i]].z;
+
+      v26 = pVertices->pVertices[pFace->pVertexIDs[i + 2]].x - pVertices->pVertices[pFace->pVertexIDs[i + 1]].x;
+      v27 = pVertices->pVertices[pFace->pVertexIDs[i + 2]].y - pVertices->pVertices[pFace->pVertexIDs[i + 1]].y;
+      v28 = pVertices->pVertices[pFace->pVertexIDs[i + 2]].z - pVertices->pVertices[pFace->pVertexIDs[i + 1]].z;
+
       v19 = Vec3_float_::Cross(&v1, &v2, v26, v27, v28);
       v38.x = v19->x;
       v38.y = v19->y;
@@ -1841,28 +1694,28 @@
         pOutNormal->y = v38.y;
         pOutNormal->z = v38.z;
 
-        *pOutDist = -(v9->x * v38.x + v9->y * v38.y + v9->z * v38.z);
+        *pOutDist = -(pVertices->pVertices[pFace->pVertexIDs[i]].x * v38.x
+                    + pVertices->pVertices[pFace->pVertexIDs[i]].y * v38.y
+                    + pVertices->pVertices[pFace->pVertexIDs[i]].z * v38.z);
         return;
       }
     }
   }
 
-  pOutNormal->x = (double)(v5->pFacePlane.vNormal.x & 0xFFFF) / 65535.0f + (double)(v5->pFacePlane.vNormal.x >> 16);
-  pOutNormal->y = (double)(v5->pFacePlane.vNormal.y & 0xFFFF) / 65535.0f + (double)(v5->pFacePlane.vNormal.y >> 16);
-  pOutNormal->z = (double)(v5->pFacePlane.vNormal.z & 0xFFFF) / 65535.0f + (double)(v5->pFacePlane.vNormal.z >> 16);
-  *pOutDist = (double)(v5->pFacePlane.dist & 0xFFFF) / 65535.0f + (double)(v5->pFacePlane.dist >> 16);
+  pOutNormal->x = (double)(pFace->pFacePlane.vNormal.x & 0xFFFF) / 65535.0f + (double)(pFace->pFacePlane.vNormal.x >> 16);
+  pOutNormal->y = (double)(pFace->pFacePlane.vNormal.y & 0xFFFF) / 65535.0f + (double)(pFace->pFacePlane.vNormal.y >> 16);
+  pOutNormal->z = (double)(pFace->pFacePlane.vNormal.z & 0xFFFF) / 65535.0f + (double)(pFace->pFacePlane.vNormal.z >> 16);
+  *pOutDist = (double)(pFace->pFacePlane.dist & 0xFFFF) / 65535.0f + (double)(pFace->pFacePlane.dist >> 16);
 }
 
 //----- (0049D700) --------------------------------------------------------
 unsigned int __fastcall GetMaxMipLevels(unsigned int uDim)
 {
-  unsigned int v1; // eax@1
   int v2; // ecx@1
   unsigned int v3; // eax@1
 
-  v1 = uDim;
   v2 = 0;
-  v3 = v1 - 1;
+  v3 = uDim - 1;
   while ( v3 & 1 )
   {
     v3 >>= 1;
@@ -1913,207 +1766,34 @@
   return LOBYTE(v13) | ((LOBYTE(v11) | (((v6 << 8) | v9) << 8)) << 8);*/
 }
 
-//----- (004A46E6) --------------------------------------------------------
-int __fastcall sr_4A46E6_draw_particle_segment(unsigned int x, signed int y, signed int _z, int a4, unsigned int lightColor)
+void Present32(unsigned __int32 *src, unsigned int src_pitch,
+               unsigned __int32 *dst, unsigned int dst_pitch)
 {
-  int v5; // eax@1
-  int z; // eax@1
-  unsigned int v7; // eax@9
-  unsigned int v8; // ecx@9
-  int v9; // eax@9
-  unsigned int v10; // eax@10
-  int *v11; // esi@10
-  int *v12; // edi@10
-  int v13; // ecx@10
-  int v14; // edx@10
-  unsigned int v15; // eax@22
-  int *v16; // esi@22
-  int *v17; // edi@22
-  int v18; // ecx@22
-  int v19; // edx@22
-  unsigned __int16 *pTarget; // [sp+Ch] [bp-8h]@9
-  int *pTargetZ; // [sp+10h] [bp-4h]@9
-  unsigned int v22; // [sp+1Ch] [bp+8h]@9
-  signed int v23; // [sp+20h] [bp+Ch]@1
+        for (uint y = 0; y < 8; ++y)
+          memcpy(dst + y * dst_pitch,
+                 src + y * src_pitch, src_pitch * sizeof(__int32));
 
-  v5 = a4;
-  v23 = _z >> 16;
-  z = x + v5;
-  if ( z >= (signed int)pViewport->uViewportTL_X
-    && (signed int)x <= (signed int)pViewport->uViewportBR_X
-    && y >= (signed int)pViewport->uViewportTL_Y
-    && y <= (signed int)pViewport->uViewportBR_Y )
-  {
-    if ( (signed int)x < (signed int)pViewport->uViewportTL_X )
-      x = pViewport->uViewportTL_X;
-    if ( z > (signed int)pViewport->uViewportBR_X )
-      z = pViewport->uViewportBR_X;
-    pTarget = &pRenderer->pTargetSurface[x + y * pRenderer->uTargetSurfacePitch];
-    v22 = z - x;
-    pTargetZ = &pRenderer->pActiveZBuffer[x + 640 * y];
-    v7 = lightColor >> 3;
-    v8 = lightColor & 0xF0;
-    v9 = v7 & 0x1E0000;
-    if ( pRenderer->uTargetGBits == 5 )
-    {
-      v10 = (v8 | (((unsigned __int16)(lightColor & 0xF000) | (unsigned int)v9) >> 3)) >> 4;
-      v11 = (int *)pTarget;
-      v12 = pTargetZ;
-      v13 = v22;
-      v14 = (v10 << 16) | v10;
-      z = (unsigned __int8)pTarget & 2;
-      if ( (unsigned __int8)pTarget & 2 )
-      {
-        z = (unsigned int)*pTargetZ >> 16;
-        if ( z > v23 )
-        {
-          z = v14 + ((*pTarget & 0x7BDEu) >> 1);
-          *pTarget = z;
-        }
-        v13 = v22 - 1;
-        v11 = (int *)(pTarget + 1);
-        v12 = pTargetZ + 1;
-      }
-      while ( v13 != 1 )
-      {
-        if ( v13 < 1 )
-          return z;
-        z = (unsigned int)*v12 >> 16;
-        if ( z <= v23 )
-        {
-          v13 -= 2;
-          ++v11;
-          v12 += 2;
-        }
-        else
-        {
-          v12 += 2;
-          z = v14 + ((*v11 & 0x7BDE7BDEu) >> 1);
-          v13 -= 2;
-          *v11 = z;
-          ++v11;
-        }
-      }
-      z = (unsigned int)*v12 >> 16;
-      if ( z > v23 )
-      {
-        z = v14 + ((*(short *)v11 & 0x7BDEu) >> 1);
-        *(short *)v11 = z;
-      }
-    }
-    else
-    {
-      v15 = (v8 | (((unsigned __int16)(lightColor & 0xF800) | (unsigned int)v9) >> 2)) >> 4;
-      v16 = (int *)pTarget;
-      v17 = pTargetZ;
-      v18 = v22;
-      v19 = (v15 << 16) | v15;
-      z = (unsigned __int8)pTarget & 2;
-      if ( (unsigned __int8)pTarget & 2 )
-      {
-        z = (unsigned int)*pTargetZ >> 16;
-        if ( z > v23 )
+        for (uint y = 8; y < 352; ++y)
         {
-          z = v19 + ((*pTarget & 0xF7DEu) >> 1);
-          *pTarget = z;
-        }
-        v18 = v22 - 1;
-        v16 = (int *)(pTarget + 1);
-        v17 = pTargetZ + 1;
-      }
-      while ( v18 != 1 )
-      {
-        if ( v18 < 1 )
-          return z;
-        z = (unsigned int)*v17 >> 16;
-        if ( z <= v23 )
-        {
-          v18 -= 2;
-          ++v16;
-          v17 += 2;
+          memcpy(dst + y * dst_pitch,
+                 src + y * src_pitch, 8 * sizeof(__int32));
+          memcpy(dst + 8 + game_viewport_width + y * dst_pitch,
+                 src + 8 + game_viewport_width + y * src_pitch, 174/*172*/ * sizeof(__int32));
         }
-        else
-        {
-          v17 += 2;
-          z = v19 + ((*v16 & 0xF7DEF7DEu) >> 1);
-          v18 -= 2;
-          *v16 = z;
-          ++v16;
-        }
-      }
-      z = (unsigned int)*v17 >> 16;
-      if ( z > v23 )
-      {
-        z = v19 + ((*(short *)v16 & 0xF7DEu) >> 1);
-        *(short *)v16 = z;
-      }
-    }
-  }
-  return z;
-}
 
-//----- (004A57E9) --------------------------------------------------------
-void  Present_ColorKey()
-{
-  HRESULT v0; // eax@3
-  HRESULT v1; // eax@3
-  HRESULT v2; // eax@3
-  HRESULT v3; // eax@3
-  HRESULT v4; // eax@3
-  RECT a2; // [sp+4h] [bp-14h]@3
-  //CheckHRESULT_stru0 this; // [sp+14h] [bp-4h]@3
+        for (uint y = 352; y < 480; ++y)
+          memcpy(dst + y * dst_pitch,
+                 src + y * src_pitch, src_pitch * sizeof(__int32));
 
-  if ( !pRenderer->uNumSceneBegins )
-  {
-    if ( pRenderer->field_40110 )
-    {
-      a2.bottom = pViewport->uViewportTL_Y;
-      a2.left = 0;
-      a2.top = 0;
-      a2.right = 640;
-      ErrD3D(pRenderer->pBackBuffer4->BltFast(0, 0, pRenderer->pColorKeySurface4, &a2, 16u));
-      a2.right = 640;
-      a2.left = 0;
-      a2.top = pViewport->uViewportBR_Y + 1;
-      a2.bottom = 480;
-      ErrD3D(pRenderer->pBackBuffer4->BltFast(
-             0,
-             pViewport->uViewportBR_Y + 1,
-             pRenderer->pColorKeySurface4,
-             &a2,
-             16u));
-      a2.right = pViewport->uViewportTL_X;
-      a2.bottom = pViewport->uViewportBR_Y + 1;
-      a2.left = 0;
-      a2.top = pViewport->uViewportTL_Y;
-      ErrD3D(pRenderer->pBackBuffer4->BltFast(
-             0,
-             pViewport->uViewportTL_Y,
-             pRenderer->pColorKeySurface4,
-             &a2,
-             16u));
-      a2.left = pViewport->uViewportBR_X;
-      a2.top = pViewport->uViewportTL_Y;
-      a2.right = 640;
-      a2.bottom = pViewport->uViewportBR_Y + 1;
-      ErrD3D(pRenderer->pBackBuffer4->BltFast(
-             pViewport->uViewportBR_X,
-             pViewport->uViewportTL_Y,
-             pRenderer->pColorKeySurface4,
-             &a2,
-             16u));
-      a2.right = pViewport->uViewportBR_X;
-      a2.bottom = pViewport->uViewportBR_Y + 1;
-      a2.left = pViewport->uViewportTL_X;
-      a2.top = pViewport->uViewportTL_Y;
-      ErrD3D(pRenderer->pBackBuffer4->BltFast(
-             pViewport->uViewportTL_X,
-             pViewport->uViewportTL_Y,
-             pRenderer->pColorKeySurface4,
-             &a2,
-             17u));
-    }
-  }
+        for (uint y = pViewport->uViewportTL_Y; y < pViewport->uViewportBR_Y + 1; ++y)
+        {
+          for (uint x = pViewport->uViewportTL_X; x < pViewport->uViewportBR_X; ++x)
+          {
+            //if (src[x + y * src_pitch] != (pRenderer->uTargetGMask | pRenderer->uTargetBMask))
+            if (src[x + y * src_pitch] != 0xFFF8FCF8)  // FFF8FCF8 =  Color32(Color16(g_mask | b_mask))
+              dst[x + y * dst_pitch] = src[x + y * src_pitch];
+          }
+        }
 }
 
 //----- (004A597D) --------------------------------------------------------
@@ -2138,7 +1818,7 @@
   int v17; // eax@16
   HRESULT v18; // eax@22
   DDSURFACEDESC2 Dst; // [sp+Ch] [bp-98h]@3
-  int v20; // [sp+88h] [bp-1Ch]@10
+  //int v20; // [sp+88h] [bp-1Ch]@10
   int v21; // [sp+8Ch] [bp-18h]@10
   __int32 v22; // [sp+90h] [bp-14h]@10
   //unsigned __int32 v23; // [sp+94h] [bp-10h]@10
@@ -2146,21 +1826,24 @@
   //unsigned int _this; // [sp+9Ch] [bp-8h]@10
   //LPVOID v26; // [sp+A0h] [bp-4h]@4
 
+  int r_mask = 0xF800;
+  int g_mask = 0x7E0;
+  int b_mask = 0x1F;
+
   if ( !pRenderer->uNumSceneBegins )
   {
-    if ( pRenderer->field_40110 )
+    if ( pRenderer->using_software_screen_buffer )
     {
       memset(&Dst, 0, 0x7Cu);
       Dst.dwSize = 124;
       if ( pRenderer->LockSurface_DDraw4(pRenderer->pBackBuffer4, &Dst, DDLOCK_WAIT) )
       {
         //v26 = Dst.lpSurface;
-        pRenderer->pCurrentlyLockedSurfaceDataPtr = (unsigned __int16 *)Dst.lpSurface;
-        v24 = pRenderer->uTargetGMask | pRenderer->uTargetBMask |
-              ((pRenderer->uTargetGMask | pRenderer->uTargetBMask) << 16);
-        pRenderer->pCurrentlyLockedSoftSurface = pRenderer->pTargetSurface;
-        pRenderer->uCurrentlyLockedSurfacePitch = Dst.lPitch;
-        v1 = pRenderer->pTargetSurface;
+        //pRenderer->pCurrentlyLockedSurfaceDataPtr = (unsigned __int16 *)Dst.lpSurface;
+        v24 = g_mask | b_mask | ((g_mask | b_mask) << 16);
+        //pRenderer->pCurrentlyLockedSoftSurface = pRenderer->pTargetSurface;
+        //pRenderer->uCurrentlyLockedSurfacePitch = Dst.lPitch;
+        //v1 = pRenderer->pTargetSurface;
         v2 = Dst.lpSurface;
 
 
@@ -2170,8 +1853,12 @@
           for (uint x = 0; x < 640; ++x)
             pDst[x] = pRenderer->uTargetRMask | pRenderer->uTargetBMask;
         }*/
-        
-        ushort* pSrc = pRenderer->pTargetSurface;
+
+        if (!FORCE_16_BITS)
+          Present32((unsigned __int32 *)pRenderer->pTargetSurface, pRenderer->uTargetSurfacePitch, (unsigned __int32 *)Dst.lpSurface, Dst.lPitch / 4);
+        else
+        {        
+        ushort* pSrc = (unsigned short *)pRenderer->pTargetSurface;
         short* pDst = (__int16 *)Dst.lpSurface;
 
         for (uint y = 0; y < 8; ++y)
@@ -2205,7 +1892,7 @@
         //v26 = (LPVOID)(pViewport->uViewportW - pViewport->uViewportY + 1);
         v10 = (int)pSrc_x1y1;
         v11 = (int)pDst_x1y1;
-        int uHalfWidth = v20 = (pViewport->uViewportBR_X - pViewport->uViewportTL_X) / 2;
+        int uHalfWidth = (pViewport->uViewportBR_X - pViewport->uViewportTL_X) / 2;
         v13 = v24;
 
         for (uint y = pViewport->uViewportTL_Y; y < pViewport->uViewportBR_Y + 1; ++y)
@@ -2214,10 +1901,11 @@
           //       pSrc + pViewport->uViewportX + y * 640, (pViewport->uViewportZ - pViewport->uViewportX) * sizeof(__int16));
           for (uint x = pViewport->uViewportTL_X; x < pViewport->uViewportBR_X; ++x)
           {
-            if (pSrc[y * 640 + x] != (pRenderer->uTargetGMask | pRenderer->uTargetBMask))
+            if (pSrc[y * 640 + x] != (g_mask | b_mask))
               pDst[y * Dst.lPitch / 2 + x] = pSrc[y * 640 + x];
           }
         }
+        }
 
               ErrD3D(pRenderer->pBackBuffer4->Unlock(0));
 
@@ -2302,8 +1990,6 @@
   return (a << 24) | (r << 16) | (g << 8) | b;
 }
 
-
-
 //----- (004B1447) --------------------------------------------------------
 void sub_4B1447_party_fine(int a1, int a2, int a3)
 {
@@ -2320,12 +2006,10 @@
       v3 = 2;
     if ( a2 == 2 )
       v3 = 2;
-      goto LABEL_13;
+    goto LABEL_13;
   }
   else
-  {
     v3 = 1;
-  }
   if ( pParty->uFine < 4000000 )
   {
     v4 = a3 + pParty->uFine < 0;
@@ -2423,7 +2107,7 @@
   v7 = pSpellStats->pInfos[v1].pName;
   a1.uFrameZ = a1.uFrameX + a1.uFrameWidth - 1;
   a1.uFrameW = a1.uFrameHeight + a1.uFrameY - 1;
-  v8 = TargetColor(0xFFu, 0xFFu, 0x9Bu);
+  v8 = Color16(0xFFu, 0xFFu, 0x9Bu);
   a1.DrawTitleText(pFontArrus, 0x78u, 0xCu, v8, v7, 3u);
   a1.DrawText(pFontSmallnum, 120, 44, 0, pTmpBuf2.data(), 0, 0, 0);
   a1.uFrameZ = a1.uFrameX + 107;
@@ -2455,28 +2139,29 @@
   uDialogueType = 84;
   current_npc_text = (char *)pNPCTopics[667].pText;
   v0 = _4F0882_evt_VAR_PlayerItemInHands_vals.data();
-  while ( 1 )
+  //while ( 1 )
+  for ( uint i = 0; i <= 53; i++ )
   {
     if ( (unsigned __int16)_449B57_test_bit(pParty->_quest_bits, *v0) )
     {
-      v1 = 0;
-      v2 = pParty->pPlayers.data();
-      do
+      //v1 = 0;
+      //v2 = pParty->pPlayers.data();
+      for ( uint pl = 0; pl < 4; pl++ )
       {
-        LOBYTE(v3) = v2->CompareVariable(VAR_PlayerItemInHands, *(v0+1));
-        if ( v3 )
+        //LOBYTE(v3) = pParty->pPlayers[pl].CompareVariable(VAR_PlayerItemInHands, *(v0+1));
+        if ( pParty->pPlayers[pl].CompareVariable(VAR_PlayerItemInHands, *(v0+1)) )
           break;
-        ++v2;
-        ++v1;
+        //++v2;
+        //++v1;
       }
-      while ( (signed int)v2 < (signed int)pParty->pHirelings.data() );
-      if ( v1 == 4 )
-        break;
+      //while ( (signed int)v2 < (signed int)pParty->pHirelings.data() );
+      //if ( v1 == 4 )
+        //break;
     }
     ++v11;
-    v0 += 2;
-    if ( v0 > &_4F0882_evt_VAR_PlayerItemInHands_vals[53] )
-	  break;
+    //v0 += 2;
+    //if ( v0 > &_4F0882_evt_VAR_PlayerItemInHands_vals[53] )
+	  //break;
   }
   if ( v0 <= &_4F0882_evt_VAR_PlayerItemInHands_vals[53] )
   {
@@ -2488,41 +2173,35 @@
   if ( contract_approved == 601 )
   {
     v5 = 0;
-    v12 = pParty->pPlayers.data();//[0].uClass;
+    //v12 = pParty->pPlayers.data();//[0].uClass;
     v9 = 0;
-    while ( 1 )
+    //while ( 1 )
+    for ( uint i = 0; i < 4; i++ )
     {
-      if ( v12->classType == PLAYER_CLASS_LICH )
+      if ( pParty->pPlayers[i].classType == PLAYER_CLASS_LICH )
       {
         v10 = 0;
-        v6 = pParty->pPlayers.data();//[0].pInventoryItems[0].field_1A;
-        do
+        //v6 = pParty->pPlayers.data();//[0].pInventoryItems[0].field_1A;
+        for ( uint pl = 0; pl < 4; pl++ )
         {
-		  v7 = v6->pInventoryItemList.data();
-          v8 = 138;
-          do
+          for ( v8 = 0; v8 < 126; v8++ )//138
           {
-			if ( v7->uItemID == ITEM_LICH_JAR_FULL )
+            if ( pParty->pPlayers[pl].pInventoryItemList[v8].uItemID == ITEM_LICH_JAR_FULL )
             {
-			  if ( !v7->uHolderPlayer )
-				  v9 = v7;
-			  if ( v7->uHolderPlayer == v5 )
+              if ( !pParty->pPlayers[pl].pInventoryItemList[v8].uHolderPlayer )
+                v9 = &pParty->pPlayers[pl].pInventoryItemList[v8];
+              if ( pParty->pPlayers[pl].pInventoryItemList[v8].uHolderPlayer == v5 )
                 v10 = 1;
             }
-            ++v7;
-            --v8;
           }
-          while ( v8 );
-          ++v6;
         }
-		while ( v6 <= &pParty->pPlayers[3] );
         if ( !v10 )
           break;
       }
-      ++v12;
+//      ++v12;
       ++v5;
-	  if ( v12 > &pParty->pPlayers[3] )
-        return;
+	//  if ( v12 > &pParty->pPlayers[3] )
+      //  return;
     }
     if ( v9 )
 	  v9->uHolderPlayer = v5;
@@ -2543,8 +2222,8 @@
   signed int v9; // esi@8
   int v10; // eax@8
   char *v11; // ecx@8
-  int v12; // edi@9
-  char *v13; // edx@9
+  //int v12; // edi@9
+  //char *v13; // edx@9
   signed int v14; // edi@10
   unsigned int v16; // eax@29
   //int v17; // eax@36
@@ -2603,27 +2282,23 @@
   if ( v6 < v2 + 2 )
   {
     //v8 = v33;
-    v9 = 0;
+    
     v10 = pClassType - pClassType % 4;
     v11 = &byte_4ED970_skill_learn_ability_by_class_table[pClassType - pClassType % 4][v3];
-    do
+    for ( v9 = 0; v9 < 4; ++v9 )
     {
-      v12 = (unsigned __int8)*v11;
-      v13 = &v28[4 * v9];
-      *(int *)v13 = 0;
-      if ( v12 < v34 )
+      v28[4 * v9] = 0;
+      if ( (unsigned __int8)*v11 < v34 )
       {
         v14 = 1;
       }
       else
       {
         v14 = 1;
-        *(int *)v13 = 1;
+        v28[4 * v9] = 1;
       }
-      ++v9;
       v11 += 37;
     }
-    while ( v9 < 4 );
     __debugbreak(); // warning C4700: uninitialized local variable 'v29' used
     if ( v29 == v14 )
     {
@@ -2931,20 +2606,18 @@
 //----- (004B3FE5) --------------------------------------------------------
 void __fastcall _4B3FE5_training_dialogue(int a4)
 {
-  int v1; // edi@1
   const char *v2; // edi@1
-  
+
   __debugbreak();
-  v1 = a4;
   uDialogueType = 78;
   current_npc_text = (char *)pNPCTopics[a4 + 168].pText;
   _4B254D_SkillMasteryTeacher(a4);
   pDialogueWindow->Release();
-  pDialogueWindow = GUIWindow::Create(0, 0, 640, 0x15Eu, WINDOW_MainMenu, v1, 0);
-  v2 = "";
-  pBtn_ExitCancel = pDialogueWindow->CreateButton( 0x1D7u, 0x1BDu, 0xA9u,  0x23u,   1,  0, UIMSG_Escape, 0,   0,
+  pDialogueWindow = GUIWindow::Create(0, 0, 640, 350, WINDOW_MainMenu, a4, 0);
+  pBtn_ExitCancel = pDialogueWindow->CreateButton( 471, 445, 169,  35,   1,  0, UIMSG_Escape, 0,   0,
                  pGlobalTXT_LocalizationStrings[34], pIcons_LOD->GetTexture(uExitCancelTextureId), 0);
   pDialogueWindow->CreateButton(0, 0, 0, 0, 1, 0, UIMSG_BuyInShop_Identify_Repair, 0, 0, "", 0);
+  v2 = "";
   if ( contract_approved )
     v2 = pGlobalTXT_LocalizationStrings[535];
   pDialogueWindow->CreateButton(0x1E0u, 0xA0u, 0x8Cu, 0x1Eu, 1, 0, UIMSG_ClickNPCTopic, 0x4Fu, 0, v2, 0);
@@ -2957,10 +2630,8 @@
 //----- (004B46A5) --------------------------------------------------------
 void __fastcall DrawTextAtStatusBar( const char *Str, int a5 )
 {
-  int v4; // eax@1
   pRenderer->DrawTextureRGB(0, 352, pTexture_StatusBar);
-  v4 = pFontLucida->AlignText_Center(450, Str);
-  pPrimaryWindow->DrawText(pFontLucida, v4 + 11, 357, a5, Str, 0, 0, 0);
+  pPrimaryWindow->DrawText(pFontLucida, pFontLucida->AlignText_Center(450, Str) + 11, 357, a5, Str, 0, 0, 0);
 }
 
 //----- (004B46F8) --------------------------------------------------------
@@ -2978,235 +2649,170 @@
 //----- (004BC49B) --------------------------------------------------------
 void OnSelectNPCDialogueOption(DIALOGUE_TYPE newDialogueType)
 {
-	//unsigned int v1; // esi@1
-    NPCData *speakingNPC; // ebp@1
-    //unsigned int v3; // eax@1
-    int npc_event_id; // ecx@10
-    signed int v5; // edi@14
-    char *v6; // esi@15
-    const char *v7; // ecx@22
-    signed int v8; // edi@37
-    //unsigned int v9; // eax@56
-    unsigned int v10; // ecx@57
-    void *v11; // [sp-Ch] [bp-1Ch]@46
-    int v12; // [sp-8h] [bp-18h]@46
-    char *v13; // [sp-8h] [bp-18h]@60
-    size_t v14; // [sp-4h] [bp-14h]@46
-    const char *v15; // [sp-4h] [bp-14h]@60
-
-    //v1 = _this;
-	speakingNPC = GetNPCData(sDialogue_SpeakingActorNPC_ID);
-    //v3 = v1;
-	uDialogueType = newDialogueType;
-	if (!speakingNPC->uFlags)
-	{
-		speakingNPC->uFlags = 1;
-		//v3 = uDialogueType;
-	}
-
-	if(newDialogueType == DIALOGUE_PROFESSION_DETAILS)
-	{
-		dialogue_show_profession_details = ~dialogue_show_profession_details;
-	}
-	else if(newDialogueType == DIALOGUE_76)
-	{
-		if (speakingNPC->Hired())
-		{
-			v8 = 0;
-			if ( (signed int)pNPCStats->uNumNewNPCs > 0 )
-			{
-				v6 = (char *)pNPCStats->pNewNPCData;
-				while ( !(v6[8] & 0x80) || strcmp(speakingNPC->pName, *(const char **)v6) )
-				{
-					++v8;
-					v6 += 76;
-					if ( v8 >= (signed int)pNPCStats->uNumNewNPCs )
-						break;
-				}
-				if( v8 < (signed int)pNPCStats->uNumNewNPCs )
-					v6[8] &= 0x7Fu;
-			}
-			if ( pParty->pHirelings[0].pName && !_stricmp(pParty->pHirelings[0].pName, speakingNPC->pName) )
-			{
-				v11 = pParty->pHirelings.data();
-				memset(v11, 0, sizeof(NPCData));
-			}
-			else if ( pParty->pHirelings[1].pName && !_stricmp(pParty->pHirelings[1].pName, speakingNPC->pName) )
-			{
-				v11 = &pParty->pHirelings[1];
-				memset(v11, 0, sizeof(NPCData));
-			}
-			pParty->hirelingScrollPosition = 0;
-			pParty->CountHirelings();
-			dword_591084 = 0;
-			pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
-			dword_7241C8 = 0;
-			return;
-		}
-		if ( pParty->pHirelings[0].pName && pParty->pHirelings[1].pName )
-		{
-			v7 = pGlobalTXT_LocalizationStrings[533]; // ""I cannot join you, you're party is full""
-			ShowStatusBarString(v7, 2u);
-		}
-		else
-		{
-			//v9 = v2->uProfession;
-			if ( speakingNPC->uProfession != 51 )
-			{
-				v10 = pNPCStats->pProfessions[speakingNPC->uProfession - 1].uHirePrice;
-																	if ( pParty->uNumGold < v10 )
-			{
-				ShowStatusBarString(pGlobalTXT_LocalizationStrings[155], 2u);// "You don't have enough gold"
-				dialogue_show_profession_details = false;
-				uDialogueType = 13;
-				if ( uActiveCharacter )
-					pPlayers[uActiveCharacter]->PlaySound(SPEECH_NotEnoughGold, 0);
-				v7 = pGlobalTXT_LocalizationStrings[155];
-				ShowStatusBarString(pGlobalTXT_LocalizationStrings[155], 2u);
-				if ( !dword_7241C8 )
-					pGame->Draw();
-				dword_7241C8 = 0;
-				return;
-			}
-				Party::TakeGold(v10);
-			}
-			LOBYTE(speakingNPC->uFlags) |= 0x80u;
-			if ( pParty->pHirelings[0].pName )
-			{
-				memcpy(&pParty->pHirelings[1], speakingNPC, sizeof(pParty->pHirelings[1]));
-				v15 = speakingNPC->pName;
-				v13 = pParty->pHireling2Name;
-			}
-			else
-			{
-				memcpy(pParty->pHirelings.data(), speakingNPC, 0x4Cu);
-				v15 = speakingNPC->pName;
-				v13 = pParty->pHireling1Name;
-			}
-			strcpy(v13, v15);
-			pParty->hirelingScrollPosition = 0;
-			pParty->CountHirelings();
+  NPCData *speakingNPC; // ebp@1
+  int npc_event_id; // ecx@10
+  char *v13; // [sp-8h] [bp-18h]@60
 
-			pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
-
-			if ( sDialogue_SpeakingActorNPC_ID >= 0 )
-				pDialogue_SpeakingActor->uAIState = Removed;
-			if ( uActiveCharacter )
-				pPlayers[uActiveCharacter]->PlaySound(SPEECH_61, 0);
-		}
-	}
-	else if ( (signed int)newDialogueType > 84 && (signed int)newDialogueType <= 88 )
-	{
-		ArenaFight();
-		return;
-	}
-	else if(newDialogueType == DIALOGUE_USE_NPC_ABILITY)
-	{
-		if (UseNPCSkill((NPCProf)speakingNPC->uProfession) == 0)
-		{
-			if ( speakingNPC->uProfession != GateMaster )
-				speakingNPC->bHasUsedTheAbility = 1;
-
-			pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
-		}
-		else
-			ShowStatusBarString(pGlobalTXT_LocalizationStrings[140], 2); //"Your packs are already full!"
-	}
-	else if(newDialogueType == DIALOGUE_13)
-	{
-		if (!speakingNPC->Hired())
-		{
-			sub_4B3E1E();
-			dialogue_show_profession_details = false;
-		}
-		else
-		{
-			v5 = 0;
-			if ( (signed int)pNPCStats->uNumNewNPCs > 0 )
-			{
-				v6 = (char *)pNPCStats->pNewNPCData;
-				while ( !(v6[8] & 0x80) || strcmp(speakingNPC->pName, *(const char **)v6) )
-				{
-					++v5;
-					v6 += 76;
-					if ( v5 >= (signed int)pNPCStats->uNumNewNPCs )
-						break;
-				}
-				if ( v5 < (signed int)pNPCStats->uNumNewNPCs )
-					v6[8] &= 0x7Fu;
-			}
-			if ( pParty->pHirelings[0].pName && !_stricmp(pParty->pHirelings[0].pName, speakingNPC->pName) )
-			{
-				v11 = pParty->pHirelings.data();
-				memset(v11, 0, sizeof(NPCData));
-			}
-			else if ( pParty->pHirelings[1].pName && !_stricmp(pParty->pHirelings[1].pName, speakingNPC->pName) )
-			{
-				v11 = &pParty->pHirelings[1];
-				memset(v11, 0, sizeof(NPCData));
-			}
-			pParty->hirelingScrollPosition = 0;
-			pParty->CountHirelings();
-			dword_591084 = 0;
-			pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
-			dword_7241C8 = 0;
-			return;
-		}
-	}
-	else if(newDialogueType >= 19 && newDialogueType <= 24)
-	{
-		switch(newDialogueType)
-		{
-			case DIALOGUE_19:  npc_event_id = speakingNPC->evt_A; break;
-			case DIALOGUE_20:  npc_event_id = speakingNPC->evt_B; break;
-			case DIALOGUE_21:  npc_event_id = speakingNPC->evt_C; break;
-			case DIALOGUE_22:	 npc_event_id = speakingNPC->evt_D; break;
-			case DIALOGUE_23:  npc_event_id = speakingNPC->evt_E; break;
-			case DIALOGUE_24:	 npc_event_id = speakingNPC->evt_F; break;
-		}
-		if ( (npc_event_id >= 200) && (npc_event_id <= 310) )
-			_4B3FE5_training_dialogue(npc_event_id); //200-310
-		else if (( npc_event_id >= 400) && (npc_event_id <= 410) )
-		{ //400-410
-			dword_F8B1D8 = newDialogueType;
-			DrawJoinGuildWindow(npc_event_id - 400);
-		}
-		else
-		{
-			switch ( npc_event_id )
-			{
-				case 139:
-					OracleDialogue();
-					break;
-				case 311:
-					CheckBountyRespawnAndAward();
-					break;
-				case 399:
-					Arena_SelectionFightLevel();
-					break;
-				default:
-					activeLevelDecoration = (LevelDecoration*)1;
-					current_npc_text = 0;
-					EventProcessor(npc_event_id, 0, 1);
-					activeLevelDecoration = NULL;
-					break;
-			}
-		}
-	}
-	if ( !dword_7241C8 )
-		pGame->Draw();
-	dword_7241C8 = 0;
+  speakingNPC = GetNPCData(sDialogue_SpeakingActorNPC_ID);
+  uDialogueType = newDialogueType;
+  if (!speakingNPC->uFlags)
+    speakingNPC->uFlags = 1;
+  if(newDialogueType == DIALOGUE_PROFESSION_DETAILS)
+    dialogue_show_profession_details = ~dialogue_show_profession_details;
+  else if(newDialogueType == DIALOGUE_76)
+  {
+    if (speakingNPC->Hired())
+    {
+      if ( (signed int)pNPCStats->uNumNewNPCs > 0 )
+      {
+        for ( uint i = 0; i < (unsigned int)pNPCStats->uNumNewNPCs; ++i )
+        {
+          if ( pNPCStats->pNewNPCData[i].uFlags & 0x80 && !strcmp(speakingNPC->pName, pNPCStats->pNewNPCData[i].pName) )
+            pNPCStats->pNewNPCData[i].uFlags &= 0x7Fu;
+        }
+      }
+      if ( pParty->pHirelings[0].pName && !_stricmp(pParty->pHirelings[0].pName, speakingNPC->pName) )
+        memset(&pParty->pHirelings[0], 0, sizeof(NPCData));
+      else if ( pParty->pHirelings[1].pName && !_stricmp(pParty->pHirelings[1].pName, speakingNPC->pName) )
+        memset(&pParty->pHirelings[1], 0, sizeof(NPCData));
+      pParty->hirelingScrollPosition = 0;
+      pParty->CountHirelings();
+      dword_591084 = 0;
+      pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
+      dword_7241C8 = 0;
+      return;
+    }
+    if ( pParty->pHirelings[0].pName && pParty->pHirelings[1].pName )
+      ShowStatusBarString(pGlobalTXT_LocalizationStrings[533], 2);// ""I cannot join you, you're party is full""
+    else
+    {
+      if ( speakingNPC->uProfession != 51 ) //burglars have no hiring price
+      {
+        if ( pParty->uNumGold < pNPCStats->pProfessions[speakingNPC->uProfession].uHirePrice )
+        {
+          ShowStatusBarString(pGlobalTXT_LocalizationStrings[155], 2);// "You don't have enough gold"
+          dialogue_show_profession_details = false;
+          uDialogueType = 13;
+          if ( uActiveCharacter )
+            pPlayers[uActiveCharacter]->PlaySound(SPEECH_NotEnoughGold, 0);
+          if ( !dword_7241C8 )
+            pGame->Draw();
+          dword_7241C8 = 0;
+          return;
+        }
+        Party::TakeGold(pNPCStats->pProfessions[speakingNPC->uProfession].uHirePrice);
+      }
+      LOBYTE(speakingNPC->uFlags) |= 0x80u;
+      if ( pParty->pHirelings[0].pName )
+      {
+        memcpy(&pParty->pHirelings[1], speakingNPC, sizeof(pParty->pHirelings[1]));
+        v13 = pParty->pHireling2Name;
+      }
+      else
+      {
+        memcpy(&pParty->pHirelings[0], speakingNPC, sizeof(pParty->pHirelings[0]));
+        v13 = pParty->pHireling1Name;
+      }
+      strcpy(v13, speakingNPC->pName);
+      pParty->hirelingScrollPosition = 0;
+      pParty->CountHirelings();
+      pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
+      if ( sDialogue_SpeakingActorNPC_ID >= 0 )
+        pDialogue_SpeakingActor->uAIState = Removed;
+      if ( uActiveCharacter )
+        pPlayers[uActiveCharacter]->PlaySound(SPEECH_61, 0);
+    }
+  }
+  else if ( (signed int)newDialogueType > DIALOGUE_84 && (signed int)newDialogueType <= DIALOGUE_ARENA_SELECT_CHAMPION ) //   
+  {
+    ArenaFight();
+    return;
+  }
+  else if(newDialogueType == DIALOGUE_USE_NPC_ABILITY)
+  {
+    if (UseNPCSkill((NPCProf)speakingNPC->uProfession) == 0)
+    {
+      if ( speakingNPC->uProfession != GateMaster )
+        speakingNPC->bHasUsedTheAbility = 1;
+      pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
+    }
+    else
+      ShowStatusBarString(pGlobalTXT_LocalizationStrings[140], 2); //"Your packs are already full!"
+  }
+  else if(newDialogueType == DIALOGUE_13)
+  {
+    if (!speakingNPC->Hired())
+    {
+      sub_4B3E1E();
+      dialogue_show_profession_details = false;
+    }
+    else
+    {
+      for ( uint i = 0; i < (signed int)pNPCStats->uNumNewNPCs; ++i )
+      {
+        if ( pNPCStats->pNewNPCData[i].uFlags & 0x80 && !strcmp(speakingNPC->pName, pNPCStats->pNewNPCData[i].pName) )
+          pNPCStats->pNewNPCData[i].uFlags &= 0x7Fu;
+      }
+      if ( pParty->pHirelings[0].pName && !_stricmp(pParty->pHirelings[0].pName, speakingNPC->pName) )
+        memset(&pParty->pHirelings[0], 0, sizeof(NPCData));
+      else if ( pParty->pHirelings[1].pName && !_stricmp(pParty->pHirelings[1].pName, speakingNPC->pName) )
+        memset(&pParty->pHirelings[1], 0, sizeof(NPCData));
+      pParty->hirelingScrollPosition = 0;
+      pParty->CountHirelings();
+      dword_591084 = 0;
+      pMessageQueue_50CBD0->AddMessage(UIMSG_Escape, 1, 0);
+      dword_7241C8 = 0;
+      return;
+    }
+  }
+  else if(newDialogueType >= DIALOGUE_EVT_A && newDialogueType <= DIALOGUE_EVT_F)
+  {
+    switch(newDialogueType)
+    {
+      case DIALOGUE_EVT_A:  npc_event_id = speakingNPC->evt_A; break;
+      case DIALOGUE_EVT_B:  npc_event_id = speakingNPC->evt_B; break;
+      case DIALOGUE_EVT_C:  npc_event_id = speakingNPC->evt_C; break;
+      case DIALOGUE_EVT_D:  npc_event_id = speakingNPC->evt_D; break;
+      case DIALOGUE_EVT_E:  npc_event_id = speakingNPC->evt_E; break;
+      case DIALOGUE_EVT_F:  npc_event_id = speakingNPC->evt_F; break;
+    }
+    if ( (npc_event_id >= 200) && (npc_event_id <= 310) )
+      _4B3FE5_training_dialogue(npc_event_id); //200-310
+    else if (( npc_event_id >= 400) && (npc_event_id <= 410) )
+    { //400-410
+      dword_F8B1D8 = newDialogueType;
+      DrawJoinGuildWindow(npc_event_id - 400);
+    }
+    else
+    {
+      switch ( npc_event_id )
+      {
+        case 139:
+          OracleDialogue();
+          break;
+        case 311:
+          CheckBountyRespawnAndAward();
+          break;
+        case 399:
+          Arena_SelectionFightLevel();
+          break;
+        default:
+          activeLevelDecoration = (LevelDecoration*)1;
+          current_npc_text = 0;
+          EventProcessor(npc_event_id, 0, 1);
+          activeLevelDecoration = NULL;
+          break;
+      }
+    }
+  }
+  if ( !dword_7241C8 )
+    pGame->Draw();
+  dword_7241C8 = 0;
 }
 
 //----- (004BDAAF) --------------------------------------------------------
 bool MerchandiseTest(ItemGen *item, int _2da_idx)
 {
-  int v6; // edx@8
-  int v7; // edx@9
-  int v8; // edx@10
-  unsigned __int8 v9; // zf@16
-  char v10; // sf@16
-  unsigned __int8 v11; // of@16
   bool test;
 
   if ( (p2DEvents[_2da_idx - 1].uType != 4 || (signed int)item->uItemID < 740 || (signed int)item->uItemID > 771)
--- a/mm7_5.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_5.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -100,7 +100,7 @@
         {
           v10 = pParty->vPosition.y - AttackerInfo.pYs[attacker_id];
           a1 = pParty->vPosition.x - AttackerInfo.pXs[attacker_id];
-          v48 = v10;
+          v48 = pParty->vPosition.y - AttackerInfo.pYs[attacker_id];
           if ( a1 * a1 + v10 * v10
              + ((signed int)(pParty->vPosition.z + pParty->uPartyHeight) >> (1 - AttackerInfo.pZs[attacker_id]))
              * ((signed int)(pParty->vPosition.z + pParty->uPartyHeight) >> (1 - AttackerInfo.pZs[attacker_id]))
@@ -149,7 +149,7 @@
       v23 = pParty->vPosition.y - AttackerInfo.pYs[attacker_id];
       v24 = ((signed int)pParty->uPartyHeight >> 1) - AttackerInfo.pZs[attacker_id];
       a1 = pParty->vPosition.x - AttackerInfo.pXs[attacker_id];
-      v48 = v23;
+      v48 = pParty->vPosition.y - AttackerInfo.pYs[attacker_id];
       if ( a1 * a1 + v23 * v23 + (pParty->vPosition.z + v24) * (pParty->vPosition.z + v24) < (unsigned int)((AttackerInfo.field_324[attacker_id] + 32) * (AttackerInfo.field_324[attacker_id] + 32)) )
       {//party damage ( )
         attacker_coord.x = AttackerInfo.pXs[attacker_id];
@@ -199,7 +199,7 @@
                       ActorDamageFromMonster(AttackerInfo.pIDs[attacker_id], actorID, &AttackerInfo.vec_4B4[attacker_id], v36->field_61);
                     break;
                   case OBJECT_Item:
-                    sub_43B057(AttackerInfo.pIDs[attacker_id], actorID, &AttackerInfo.vec_4B4[attacker_id]);
+                    ItemDamageFromActor(AttackerInfo.pIDs[attacker_id], actorID, &AttackerInfo.vec_4B4[attacker_id]);
                     break;
                 }
               }
@@ -241,7 +241,7 @@
         DamageMonsterFromParty(PID(OBJECT_Item, uLayingItemID), PID_ID(a2), &layingitem_vel_50FDFC);
         break;
       case OBJECT_Item:
-        sub_43B057(PID(OBJECT_Item, uLayingItemID), PID_ID(a2), &layingitem_vel_50FDFC);
+        ItemDamageFromActor(PID(OBJECT_Item, uLayingItemID), PID_ID(a2), &layingitem_vel_50FDFC);
         break;
     }
   }
@@ -250,21 +250,17 @@
 //----- (0043AE12) --------------------------------------------------------
 double __fastcall sub_43AE12(signed int a1)
 {
-  signed int v1; // ST00_4@1
+  //signed int v1; // ST00_4@1
   signed int v2; // ecx@1
   double v3; // st7@1
   double result; // st7@6
 
-  v1 = a1;
-  v2 = 0;
-  v3 = (double)v1;
-  do
+  v3 = (double)a1;
+  for ( v2 = 0; v2 < 5; ++v2 )
   {
     if ( v3 < flt_4E4A80[v2 + 5] )
       break;
-    ++v2;
   }
-  while ( v2 < 5 );
   if ( v2 <= 0 || v2 >= 5 )
   {
     if ( v2 )
@@ -273,62 +269,48 @@
       result = flt_4E4A80[0];
   }
   else
-  {
     result = (flt_4E4A80[v2] - flt_4E4A80[v2 - 1]) * (v3 - flt_4E4A80[v2 + 4]) / (flt_4E4A80[v2 + 5] - flt_4E4A80[v2 + 4]) + flt_4E4A80[v2];
-  }
   return result;
 }
 
 //----- (0043B057) --------------------------------------------------------
-void __fastcall sub_43B057(unsigned int uObjID, unsigned int uActorID, Vec3_int_ *pVelocity)
+void ItemDamageFromActor(unsigned int uObjID, unsigned int uActorID, Vec3_int_ *pVelocity)
 {
-  Actor *pActor; // esi@1
-  SpriteObject *v4; // eax@3
-  int v5; // ecx@3
   int v6; // eax@4
-  int v7; // edi@4
-  unsigned int uActorIDa; // [sp+8h] [bp-8h]@1
-  unsigned int a2; // [sp+Ch] [bp-4h]@1
+  int damage; // edi@4
   int a2a; // [sp+Ch] [bp-4h]@8
 
-  uActorIDa = uActorID;
-  pActor = &pActors[uActorID];
-  a2 = uObjID;
   if ( !pActors[uActorID].IsNotAlive() )
   {
-    if ( PID_TYPE(a2) == OBJECT_Item)
+    if ( PID_TYPE(uObjID) == OBJECT_Item)
     {
-      v4 = &pSpriteObjects[PID_ID(a2)];
-      v5 = v4->spell_id;
-      if ( v5 )
+      if ( pSpriteObjects[PID_ID(uObjID)].spell_id )
       {
-        v6 = _43AFE3_calc_spell_damage(v5, v4->spell_level, v4->spell_skill, pActor->sCurrentHP);
-        v7 = stru_50C198.CalcMagicalDamageToActor(pActor, 0, v6);
-        pActor->sCurrentHP -= v7;
-        if ( v7 )
+        v6 = _43AFE3_calc_spell_damage(pSpriteObjects[PID_ID(uObjID)].spell_id, pSpriteObjects[PID_ID(uObjID)].spell_level, pSpriteObjects[PID_ID(uObjID)].spell_skill, pActors[uActorID].sCurrentHP);
+        damage = stru_50C198.CalcMagicalDamageToActor(&pActors[uActorID], 0, v6);
+        pActors[uActorID].sCurrentHP -= damage;
+        if ( damage )
         {
-          if ( pActor->sCurrentHP > 0 )
-            Actor::AI_Stun(uActorIDa, a2, 0);
+          if ( pActors[uActorID].sCurrentHP > 0 )
+            Actor::AI_Stun(uActorID, uObjID, 0);
           else
-            Actor::Die(uActorIDa);
-          a2a = 20 * v7 / (signed int)pActor->pMonsterInfo.uHP;
-          if ( 20 * v7 / (signed int)pActor->pMonsterInfo.uHP > 10 )
+            Actor::Die(uActorID);
+          a2a = 20 * damage / (signed int)pActors[uActorID].pMonsterInfo.uHP;
+          if ( 20 * damage / (signed int)pActors[uActorID].pMonsterInfo.uHP > 10 )
             a2a = 10;
-          if ( !MonsterStats::BelongsToSupertype(pActor->pMonsterInfo.uID, MONSTER_SUPERTYPE_TREANT) )
+          if ( !MonsterStats::BelongsToSupertype(pActors[uActorID].pMonsterInfo.uID, MONSTER_SUPERTYPE_TREANT) )
           {
             pVelocity->x = (unsigned __int64)(a2a * (signed __int64)pVelocity->x) >> 16;
             pVelocity->y = (unsigned __int64)(a2a * (signed __int64)pVelocity->y) >> 16;
             pVelocity->z = (unsigned __int64)(a2a * (signed __int64)pVelocity->z) >> 16;
-            pActor->vVelocity.x = 50 * LOWORD(pVelocity->x);
-            pActor->vVelocity.y = 50 * LOWORD(pVelocity->y);
-            pActor->vVelocity.z = 50 * LOWORD(pVelocity->z);
+            pActors[uActorID].vVelocity.x = 50 * LOWORD(pVelocity->x);
+            pActors[uActorID].vVelocity.y = 50 * LOWORD(pVelocity->y);
+            pActors[uActorID].vVelocity.z = 50 * LOWORD(pVelocity->z);
           }
-          Actor::AddBloodsplatOnDamageOverlay(uActorIDa, 1, v7);
+          Actor::AddBloodsplatOnDamageOverlay(uActorID, 1, damage);
         }
         else
-        {
-          Actor::AI_Stun(uActorIDa, a2, 0);
-        }
+          Actor::AI_Stun(uActorID, uObjID, 0);
       }
     }
   }
@@ -338,17 +320,11 @@
 void ActorDamageFromMonster(signed int attacker_id, unsigned int actor_id, Vec3_int_ *pVelocity, signed int a4)
 {
   int v4; // ebx@1
-  //SpriteObject *v5; // eax@2
   int v6; // eax@3
-  //Actor *v7; // esi@4
-  //Actor *v8; // edi@4
-  char v9; // zf@5
   __int64 v10; // qax@8
-  signed __int16 v11; // cx@9
   signed int v12; // ecx@20
   int v13; // ecx@22
   int v14; // edi@30
-  //unsigned int uActorID; // [sp+Ch] [bp-8h]@1
   signed int v17; // [sp+10h] [bp-4h]@1
   int v18; // [sp+20h] [bp+Ch]@34
 
@@ -364,101 +340,79 @@
     v6 = pActors[actor_id].IsNotAlive();
     if ( !v6 )
     {
-      v9 = pActors[actor_id].uAIState == 7;
       pActors[actor_id].uLastCharacterIDToHit = v17;
-      if ( v9 )
-        BYTE2(pActors[actor_id].uAttributes) |= 2u;
-      v6 = pActors[PID_ID(v17)]._4273BB_DoesHitOtherActor(&pActors[actor_id], v4, 0);
-      if ( v6 )
+      if ( pActors[actor_id].uAIState == Fleeing )
+        BYTE2(pActors[actor_id].uAttributes) |= 2;
+      if ( pActors[PID_ID(v17)]._4273BB_DoesHitOtherActor(&pActors[actor_id], v4, 0) )
       {
         v10 = (unsigned int)pActors[PID_ID(v17)]._43B3E0_CalcDamage(a4);
         if ( (signed __int64)pActors[PID_ID(v17)].pActorBuffs[ACTOR_BUFF_SHRINK].uExpireTime > 0 )
         {
-          v11 = pActors[PID_ID(v17)].pActorBuffs[ACTOR_BUFF_SHRINK].uPower;
-          if ( v11 )
-            v10 = (signed int)v10 / (unsigned __int16)v11;
+          if ( pActors[PID_ID(v17)].pActorBuffs[ACTOR_BUFF_SHRINK].uPower )
+            v10 = (signed int)v10 / (unsigned __int16)pActors[PID_ID(v17)].pActorBuffs[ACTOR_BUFF_SHRINK].uPower;
         }
         if ( SHIDWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_STONED].uExpireTime) >= SHIDWORD(v10)
           && (SHIDWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_STONED].uExpireTime) > SHIDWORD(v10)
            || LODWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_STONED].uExpireTime) > HIDWORD(v10)) )
           LODWORD(v10) = 0;
-        if ( a4 != HIDWORD(v10) )
+        if ( a4 == HIDWORD(v10) )
+          v12 = pActors[PID_ID(v17)].pMonsterInfo.uAttack1Type;
+        else if ( a4 - HIDWORD(v10) == 1 )
         {
-          if ( a4 - HIDWORD(v10) == 1 )
-          {
-            v12 = pActors[PID_ID(v17)].pMonsterInfo.uAttack2Type;
-            if ( SHIDWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_SHIELD].uExpireTime) >= SHIDWORD(v10)
-              && (SHIDWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_SHIELD].uExpireTime) > SHIDWORD(v10)
-               || LODWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_SHIELD].uExpireTime) > HIDWORD(v10)) )
-              LODWORD(v10) = (signed int)v10 >> 1;
-            goto LABEL_30;
-          }
-          if ( a4 - HIDWORD(v10) == 2 )
-          {
-            v13 = pActors[actor_id].pMonsterInfo.uSpell1ID;
-          }
+          v12 = pActors[PID_ID(v17)].pMonsterInfo.uAttack2Type;
+          if ( SHIDWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_SHIELD].uExpireTime) >= SHIDWORD(v10)
+            && (SHIDWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_SHIELD].uExpireTime) > SHIDWORD(v10)
+             || LODWORD(pActors[actor_id].pActorBuffs[ACTOR_BUFF_SHIELD].uExpireTime) > HIDWORD(v10)) )
+            LODWORD(v10) = (signed int)v10 / 2;
+        }
+        else if ( a4 - HIDWORD(v10) == 2 )
+          v12 = LOBYTE(pSpellStats->pInfos[pActors[actor_id].pMonsterInfo.uSpell1ID].uSchool);
+        else if ( a4 - HIDWORD(v10) == 3 )
+          v12 = LOBYTE(pSpellStats->pInfos[pActors[actor_id].pMonsterInfo.uSpell2ID].uSchool);
+        else if ( a4 - HIDWORD(v10) == 4 )
+          v12 = pActors[PID_ID(v17)].pMonsterInfo.field_3C_some_special_attack;
+        else
+          v12 = 4;
+        v14 = stru_50C198.CalcMagicalDamageToActor(&pActors[actor_id], v12, v10);
+        pActors[actor_id].sCurrentHP -= v14;
+        if ( v14 )
+        {
+          if ( pActors[actor_id].sCurrentHP > 0 )
+            Actor::AI_Stun(actor_id, v17, 0);
           else
+            Actor::Die(actor_id);
+          Actor::AggroSurroundingPeasants(actor_id, 0);
+          v18 = 20 * v14 / (signed int)pActors[actor_id].pMonsterInfo.uHP;
+          if ( 20 * v14 / (signed int)pActors[actor_id].pMonsterInfo.uHP > 10 )
+            v18 = 10;
+          if ( !MonsterStats::BelongsToSupertype(pActors[actor_id].pMonsterInfo.uID, MONSTER_SUPERTYPE_TREANT) )
           {
-            if ( a4 - HIDWORD(v10) != 3 )
-            {
-              if ( a4 - HIDWORD(v10) == 4 )
-                v12 = pActors[PID_ID(v17)].pMonsterInfo.field_3C_some_special_attack;
-              else
-                v12 = 4;
-LABEL_30:
-              v14 = stru_50C198.CalcMagicalDamageToActor(&pActors[actor_id], v12, v10);
-              pActors[actor_id].sCurrentHP -= v14;
-              if ( v14 )
-              {
-                if ( pActors[actor_id].sCurrentHP > 0 )
-                  Actor::AI_Stun(actor_id, v17, 0);
-                else
-                  Actor::Die(actor_id);
-                Actor::AggroSurroundingPeasants(actor_id, 0);
-                v18 = 20 * v14 / (signed int)pActors[actor_id].pMonsterInfo.uHP;
-                if ( 20 * v14 / (signed int)pActors[actor_id].pMonsterInfo.uHP > 10 )
-                  v18 = 10;
-                if ( !MonsterStats::BelongsToSupertype(pActors[actor_id].pMonsterInfo.uID, MONSTER_SUPERTYPE_TREANT) )
-                {
-                  pVelocity->x = (unsigned __int64)(v18 * (signed __int64)pVelocity->x) >> 16;
-                  pVelocity->y = (unsigned __int64)(v18 * (signed __int64)pVelocity->y) >> 16;
-                  pVelocity->z = (unsigned __int64)(v18 * (signed __int64)pVelocity->z) >> 16;
-                  pActors[actor_id].vVelocity.x = 50 * LOWORD(pVelocity->x);
-                  pActors[actor_id].vVelocity.y = 50 * LOWORD(pVelocity->y);
-                  pActors[actor_id].vVelocity.z = 50 * LOWORD(pVelocity->z);
-                }
-                Actor::AddBloodsplatOnDamageOverlay(actor_id, 1, v14);
-              }
-              else
-              {
-                Actor::AI_Stun(actor_id, v17, 0);
-              }
-              return;
-            }
-            v13 = pActors[actor_id].pMonsterInfo.uSpell2ID;
+            pVelocity->x = (unsigned __int64)(v18 * (signed __int64)pVelocity->x) >> 16;
+            pVelocity->y = (unsigned __int64)(v18 * (signed __int64)pVelocity->y) >> 16;
+            pVelocity->z = (unsigned __int64)(v18 * (signed __int64)pVelocity->z) >> 16;
+            pActors[actor_id].vVelocity.x = 50 * LOWORD(pVelocity->x);
+            pActors[actor_id].vVelocity.y = 50 * LOWORD(pVelocity->y);
+            pActors[actor_id].vVelocity.z = 50 * LOWORD(pVelocity->z);
           }
-          v12 = LOBYTE(pSpellStats->pInfos[v13].uSchool);
-          goto LABEL_30;
+          Actor::AddBloodsplatOnDamageOverlay(actor_id, 1, v14);
         }
-        v12 = pActors[PID_ID(v17)].pMonsterInfo.uAttack1Type;
-        goto LABEL_30;
+        else
+          Actor::AI_Stun(actor_id, v17, 0);
+        return;
       }
     }
   }
 }
 
-
 //----- (0043F515) --------------------------------------------------------
 void FindBillboardsLightLevels_BLV()
 {
   for (uint i = 0; i < uNumBillboardsToDraw; ++i)
   {
-    RenderBillboard* p = &pBillboardRenderList[i];
-
-    if (p->field_1E & 2 || uCurrentlyLoadedLevelType == LEVEL_Indoor && !p->uIndoorSectorID)
-      p->dimming_level = 0;
+    if (pBillboardRenderList[i].field_1E & 2 || uCurrentlyLoadedLevelType == LEVEL_Indoor && !pBillboardRenderList[i].uIndoorSectorID)
+      pBillboardRenderList[i].dimming_level = 0;
     else
-      p->dimming_level = _43F55F_get_billboard_light_level(p, -1);
+      pBillboardRenderList[i].dimming_level = _43F55F_get_billboard_light_level(&pBillboardRenderList[i], -1);
   }
 }
 
@@ -468,9 +422,7 @@
   signed int v3; // ecx@2
 
   if ( uCurrentlyLoadedLevelType == LEVEL_Indoor )
-  {
     v3 = pIndoor->pSectors[a1->uIndoorSectorID].uMinAmbientLightLevel;
-  }
   else
   {
     if ( uBaseLightLevel == -1 )
@@ -759,7 +711,7 @@
       obj2_x = pParty->vPosition.x;
       obj2_z = pParty->sEyelevel + pParty->vPosition.z;
       obj2_y = pParty->vPosition.y;
-	  obj2_sector = pIndoor->GetSector(obj2_x, obj2_y, obj2_z);
+	  obj2_sector = pIndoor->GetSector(pParty->vPosition.x, pParty->vPosition.y, pParty->sEyelevel + pParty->vPosition.z);
       break;
 	case OBJECT_Actor:
       obj2_y = pActors[v12].vPosition.y;
@@ -885,15 +837,10 @@
 		v58 = fixpoint_div(v38,v59);
 
 		if( v58 < 0 )
-		{
-			continue;
-		}
+          continue;
 
-		if(!sub_4075DB(
-				obj1_x + ((fixpoint_mul(v49,v58) + 32768) >> 16),
-				obj1_y + ((fixpoint_mul(v48,v58) + 32768) >> 16),
-				obj1_z + ((fixpoint_mul(v47,v58) + 32768) >> 16),
-				v29) )
+		if(!sub_4075DB(obj1_x + ((fixpoint_mul(v49,v58) + 32768) >> 16), obj1_y + ((fixpoint_mul(v48,v58) + 32768) >> 16),
+				obj1_z + ((fixpoint_mul(v47,v58) + 32768) >> 16), v29) )
 		{
 			continue;
 		}
@@ -906,9 +853,7 @@
 
 		//no more portals, quit
 		if ( next_sector == current_sector )
-		{
-			break;
-		}
+          break;
 
 		++sectors_visited;
 		current_sector = next_sector;
@@ -937,28 +882,11 @@
 }
 
 //----- (004075DB) --------------------------------------------------------
-bool __fastcall sub_4075DB(int x, int y, int z, BLVFace *a4)
+bool __fastcall sub_4075DB(int x, int y, int z, BLVFace *face)
 {
-  unsigned int v5; // esi@1
-  char v7; // zf@2
   int v8; // edi@2
-  Vec3_short_ *v9; // ecx@3
-  int v10; // edx@4
-  Vec3_short_ *v12; // ecx@8
-  int v13; // edx@9
-  Vec3_short_ *v15; // ecx@12
-  int v16; // edx@13
-  bool v18; // esi@14
-  int v19; // ecx@14
-  int v20; // ecx@16
-  int v21; // edx@16
-  int v22; // eax@17
-  signed int v23; // ebx@18
-  int v24; // esi@20
   signed int v25; // eax@22
-  signed __int64 v26; // qtt@22
   bool result; // eax@25
-  int v29; // [sp+10h] [bp-Ch]@14
   signed int a3a; // [sp+24h] [bp+8h]@14
   int a4a; // [sp+28h] [bp+Ch]@2
 
@@ -967,44 +895,42 @@
 
   //__debugbreak();
 
-  v5 = a4->uAttributes;
-  v9 = pIndoor->pVertices;
-  if ( v5 & FACE_XY_PLANE )
+  if ( face->uAttributes & FACE_XY_PLANE )
   {
     a4a = x;
     v8 = y;
-    for(int i = 0; i < a4->uNumVertices; i++)
+    for(int i = 0; i < face->uNumVertices; i++)
 	{
-        dword_4F5D98_xs[i] = v9[a4->pVertexIDs[i]].x;
-        dword_4F5CC8_ys[i] = v9[a4->pVertexIDs[i]].y;
+        dword_4F5D98_xs[i] = pIndoor->pVertices[face->pVertexIDs[i]].x;
+        dword_4F5CC8_ys[i] = pIndoor->pVertices[face->pVertexIDs[i]].y;
 	}
   }
   else
   {
     v8 = z;
-    if ( v5 & FACE_XZ_PLANE )
+    if ( face->uAttributes & FACE_XZ_PLANE )
     {
       a4a = x;
-      for(int i = 0; i < a4->uNumVertices; i++)
+      for(int i = 0; i < face->uNumVertices; i++)
 	  {
-		dword_4F5D98_xs[i] = v9[a4->pVertexIDs[i]].x;
-		dword_4F5CC8_ys[i] = v9[a4->pVertexIDs[i]].z;
+		dword_4F5D98_xs[i] = pIndoor->pVertices[face->pVertexIDs[i]].x;
+		dword_4F5CC8_ys[i] = pIndoor->pVertices[face->pVertexIDs[i]].z;
 	  }
     }
     else
     {
       a4a = y;
-      for(int i = 0; i < a4->uNumVertices; i++)
+      for(int i = 0; i < face->uNumVertices; i++)
 	  {
-		dword_4F5D98_xs[i] = v9[a4->pVertexIDs[i]].y;
-		dword_4F5CC8_ys[i] = v9[a4->pVertexIDs[i]].z;
+		dword_4F5D98_xs[i] = pIndoor->pVertices[face->pVertexIDs[i]].y;
+		dword_4F5CC8_ys[i] = pIndoor->pVertices[face->pVertexIDs[i]].z;
 	  }
     }
   }
   a3a = 0;
-  dword_4F5D98_xs[a4->uNumVertices] = dword_4F5D98_xs[0];
-  dword_4F5CC8_ys[a4->uNumVertices] = dword_4F5CC8_ys[0];
-  for(int i = 0; i < a4->uNumVertices && a3a < 2; i++)
+  dword_4F5D98_xs[face->uNumVertices] = dword_4F5D98_xs[0];
+  dword_4F5CC8_ys[face->uNumVertices] = dword_4F5CC8_ys[0];
+  for(int i = 0; i < face->uNumVertices && a3a < 2; i++)
   {
     if ( dword_4F5CC8_ys[i] >= v8 ^ (dword_4F5CC8_ys[i + 1] >= v8) )
     {
@@ -1019,7 +945,7 @@
 		  else
 		  {
 			v25 = fixpoint_div(dword_4F5D98_xs[i + 1] - dword_4F5D98_xs[i], dword_4F5CC8_ys[i + 1] - dword_4F5CC8_ys[i]);
-			if( dword_4F5D98_xs[i] + (fixpoint_mul(v25, (v8 - dword_4F5CC8_ys[i]) << 16) + 32768 >> 16) >= a4a)
+			if( dword_4F5D98_xs[i] + (fixpoint_mul(v25, (v8 - dword_4F5CC8_ys[i]) << 16) + 0x8000 >> 16) >= a4a)
 				++a3a;
 		  }
       }
@@ -1032,75 +958,51 @@
 }
 
 //----- (004077F1) --------------------------------------------------------
-bool __fastcall sub_4077F1(int a1, int a2, int a3, ODMFace *a4, BSPVertexBuffer *a5)
+bool __fastcall sub_4077F1(int a1, int a2, int a3, ODMFace *face, BSPVertexBuffer *a5)
 {
-  //ODMFace *v5; // eax@1
-  Vec3_int_ *v9;
-  unsigned int v5; // esi@1
-  signed int v7; // edi@1
-  //char v8; // zf@2
-  //unsigned __int16 *v9; // edx@3
-  int v10; // ecx@4
-  unsigned __int16 *v11; // edx@8
-  int v12; // ecx@9
-  int v13; // edx@12
-  int v14; // ecx@13
-  int v15; // esi@14
-  bool v16; // edi@14
-  int v17; // ecx@16
-  int v18; // edx@16
-  int v19; // eax@17
-  signed int v20; // ebx@18
-  int v21; // edi@20
-  signed int v22; // eax@22
-  signed __int64 v23; // qtt@22
-  //bool result; // eax@25
-  //int v25; // [sp+14h] [bp-8h]@14
   int a4a; // [sp+28h] [bp+Ch]@2
   signed int a5a; // [sp+2Ch] [bp+10h]@14
 
   std::array<int, 52> dword_4F5B24_ys; // idb
   std::array<int, 52> dword_4F5BF4_xs; // idb
-  
+
   //__debugbreak();	//     
 
-  v5 = a4->uAttributes;
-  v9 = a5->pVertices;
-  if ( v5 & FACE_XY_PLANE )
+  if ( face->uAttributes & FACE_XY_PLANE )
   {
     a4a = a1;
     a3 = a2;
-    for(int i = 0; i < a4->uNumVertices; i++)
+    for(int i = 0; i < face->uNumVertices; i++)
 	{
-        dword_4F5BF4_xs[i+1] = v9[a4->pVertexIDs[i]].x;
-        dword_4F5B24_ys[i+1] = v9[a4->pVertexIDs[i]].y;
+        dword_4F5BF4_xs[i+1] = a5->pVertices[face->pVertexIDs[i]].x;
+        dword_4F5B24_ys[i+1] = a5->pVertices[face->pVertexIDs[i]].y;
 	}
   }
   else
   {
-    if ( v5 & FACE_XY_PLANE )
+    if ( face->uAttributes & FACE_XY_PLANE )
     {
       a4a = a1;
-      for(int i = 0; i < a4->uNumVertices; i++)
+      for(int i = 0; i < face->uNumVertices; i++)
 	  {
-		dword_4F5BF4_xs[i+1] = v9[a4->pVertexIDs[i]].x;
-		dword_4F5B24_ys[i+1] = v9[a4->pVertexIDs[i]].z;
+		dword_4F5BF4_xs[i+1] = a5->pVertices[face->pVertexIDs[i]].x;
+		dword_4F5B24_ys[i+1] = a5->pVertices[face->pVertexIDs[i]].z;
 	  }
     }
     else
     {
       a4a = a2;
-      for(int i = 0; i < a4->uNumVertices; i++)
+      for(int i = 0; i < face->uNumVertices; i++)
 	  {
-		dword_4F5BF4_xs[i+1] = v9[a4->pVertexIDs[i]].y;
-		dword_4F5B24_ys[i+1] = v9[a4->pVertexIDs[i]].z;
+		dword_4F5BF4_xs[i+1] = a5->pVertices[face->pVertexIDs[i]].y;
+		dword_4F5B24_ys[i+1] = a5->pVertices[face->pVertexIDs[i]].z;
 	  }
     }
   }
   a5a = 0;
-  dword_4F5BF4_xs[a4->uNumVertices + 1] = dword_4F5BF4_xs[1];
-  dword_4F5B24_ys[a4->uNumVertices + 1] = dword_4F5B24_ys[1];
-  for(int i = 0; i < a4->uNumVertices; i++)
+  dword_4F5BF4_xs[face->uNumVertices + 1] = dword_4F5BF4_xs[1];
+  dword_4F5B24_ys[face->uNumVertices + 1] = dword_4F5B24_ys[1];
+  for(int i = 0; i < face->uNumVertices; i++)
   {
     if ( a5a >= 2 )
       break;
@@ -1112,11 +1014,11 @@
             ++a5a;
           else
           {
-              v23 = (__int64)(dword_4F5BF4_xs[i + 2] - dword_4F5BF4_xs[i + 1]) << 16;
+              //v23 = (__int64)(dword_4F5BF4_xs[i + 2] - dword_4F5BF4_xs[i + 1]) << 16;
               __int64 _a = dword_4F5B24_ys[i + 2] - dword_4F5B24_ys[i + 1];
               __int64 _b = (__int64)(a3 - dword_4F5B24_ys[i + 1]) << 16;
 
-              if (dword_4F5BF4_xs[i + 1] + ((((v23 / _a * _b) >> 16) + 32768) >> 16) >= a4a)
+              if (dword_4F5BF4_xs[i + 1] + ((((((__int64)(dword_4F5BF4_xs[i + 2] - dword_4F5BF4_xs[i + 1]) << 16) / _a * _b) >> 16) + 0x8000) >> 16) >= a4a)
                 ++a5a;
           }
 	  }
@@ -1132,28 +1034,14 @@
 //----- (004088E9) --------------------------------------------------------
 int __fastcall sub_4088E9(int x1, int y1, int x2, int y2, int x3, int y3)
 {
-  int v8; // eax@1
   signed int result; // eax@1
-  int v11; // [sp+18h] [bp+8h]@1
 
-  v11 = abs(x2 - x1);
-  v8 = abs(y2 - y1);
-  result = integer_sqrt(v11 * v11 + v8 * v8);
+  result = integer_sqrt(abs(x2 - x1) * abs(x2 - x1) + abs(y2 - y1) * abs(y2 - y1));
   if ( result )
     result = abs(((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / result);
   return result;
 }
 
-//----- (0040DEF3) --------------------------------------------------------
-unsigned short TargetColor( unsigned __int16 r, unsigned __int16 g, unsigned __int16 b )
-{
-  return ((unsigned int)b >> (8 - LOBYTE(pRenderer->uTargetBBits))) | pRenderer->uTargetGMask & (g << (LOBYTE(pRenderer->uTargetGBits) + 
-                           LOBYTE(pRenderer->uTargetBBits) - 8)) | pRenderer->uTargetRMask & (r << (LOBYTE(pRenderer->uTargetGBits) + 
-                           LOBYTE(pRenderer->uTargetRBits) + LOBYTE(pRenderer->uTargetBBits) - 8));
-}
-
-
-
 //----- (0040F82D) --------------------------------------------------------
 void __fastcall ZBuffer_Fill(int *pZBuffer, int uTextureId, int iZValue)
 {
@@ -1161,95 +1049,69 @@
   ZBuffer_DoFill(pZBuffer, pIcons_LOD->GetTexture(uTextureId), iZValue);
 }
 
-
-
 //----- (0040F89C) --------------------------------------------------------
 void __fastcall ZBuffer_DoFill(int *pZBuffer, Texture *pTex, int uZValue)
-{
+{//    
   void *v3; // eax@3
-  void *v4; // esi@5
-  int *v5; // edi@5
-  int v6; // eax@5
+  //void *v4; // esi@5
+  //int *v5; // edi@5
+  //int v6; // eax@5
   int v7; // ecx@6
-  Texture *v8; // [sp+Ch] [bp-14h]@1
-  int *v9; // [sp+10h] [bp-10h]@1
-  int v10; // [sp+14h] [bp-Ch]@1
   int v11; // [sp+18h] [bp-8h]@1
-  void *v12; // [sp+1Ch] [bp-4h]@5
+  //void *v12; // [sp+1Ch] [bp-4h]@5
 
-  v10 = pTex->uTextureWidth;
-  v8 = pTex;
-  v9 = pZBuffer;
-  v11 = pTex->uTextureHeight;
   if ( pIcons_LOD->dword_011BA4 && pTex->uDecompressedSize )
     v3 = pTex->UnzipPalette();
   else
     v3 = pTex->pLevelOfDetail0_prolly_alpha_mask;
-  v12 = v3;
-  v4 = v3;
-  v5 = v9;
-  v6 = 0;
-  do
+  //v12 = v3;
+  //v4 = v3;
+  //v5 = pZBuffer;
+  //v6 = 0;
+  for ( uint i = 0; i < pTex->uTextureHeight; i++ )
   {
-    v7 = v10;
-    do
+    for ( uint j = 0; j < pTex->uTextureWidth; j++ )
     {
-      LOBYTE(v6) = *(char *)v4;
-      v4 = (char *)v4 + 1;
-      if ( v6 )
-        *v5 = uZValue;
-      ++v5;
-      --v7;
+      //LOBYTE(v6) = *(char *)v4;
+      //v4 = (char *)v4 + 1;
+      //if ( v6 )
+        *pZBuffer = uZValue;
+      ++pZBuffer;
     }
-    while ( v7 );
-    v5 += 640 - v10;
-    --v11;
+    pZBuffer += 640 - pTex->uTextureWidth;
   }
-  while ( v11 );
   if ( pIcons_LOD->dword_011BA4 )
   {
-    if ( v8->uDecompressedSize )
-      free(v12);
+    if ( pTex->uDecompressedSize )
+      free(v3);
   }
 }
 
 //----- (0040F92A) --------------------------------------------------------
 void __fastcall ZBuffer_DoFill2(int *pZBuffer, Texture *a2, int a3)
-{
-  Texture *v3; // esi@1
+{//    
   void *v4; // eax@3
-  int *v5; // edi@5
+  //int *v5; // edi@5
   int v6; // ecx@6
-  int *v7; // [sp+Ch] [bp-10h]@1
-  int v8; // [sp+10h] [bp-Ch]@1
   int v9; // [sp+18h] [bp-4h]@1
 
-  v3 = a2;
-  v7 = pZBuffer;
-  v8 = a2->uTextureWidth;
-  v9 = a2->uTextureHeight;
   if ( pIcons_LOD->dword_011BA4 && a2->uDecompressedSize )
     v4 = a2->UnzipPalette();
   else
     v4 = a2->pLevelOfDetail0_prolly_alpha_mask;
-  v5 = v7;
-  do
+  //v5 = pZBuffer;
+  for ( uint i = 0; i < a2->uTextureHeight; i++ )
   {
-    v6 = v8;
-    do
+    for ( uint j = 0; j < a2->uTextureWidth; j++ )
     {
-      *v5 = a3;
-      ++v5;
-      --v6;
+      *pZBuffer = a3;
+      ++pZBuffer;
     }
-    while ( v6 );
-    v5 += 640 - v8;
-    --v9;
+    pZBuffer += 640 - a2->uTextureWidth;
   }
-  while ( v9 );
   if ( pIcons_LOD->dword_011BA4 )
   {
-    if ( v3->uDecompressedSize )
+    if ( a2->uDecompressedSize )
       free(v4);
   }
 }
@@ -1262,6 +1124,7 @@
   const char **v3; // esi@2
   char *v4; // ebx@2
 
+  __debugbreak();//Ritor1
   v1 = a1;
   v2 = 1;
   if ( _stricmp(pMapStats->pInfos[1].pFilename, (const char *)&pGames_LOD->pSubIndices[a1]) )
--- a/mm7_6.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_6.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -52,8 +52,6 @@
   int v7; // esi@8
   int v8; // eax@9
   int v9; // edx@11
-  int v10; // edx@13
-  int v11; // esi@13
   unsigned __int8 v12; // sf@13
   unsigned __int8 v13; // of@13
   int v14; // edx@14
@@ -77,27 +75,25 @@
   if ( a3 == 2 )
   {
     v14 = a4 + v9;
-    v15 = ((v7 + 15) >> 1) + v7 + 15;
-	v13 = __OFSUB__(v14, v15);
+    v15 = ((v7 + 15) / 2) + v7 + 15;
+    v13 = __OFSUB__(v14, v15);
     v12 = v14 - v15 < 0;
   }
-  else
+  else if ( a3 == 3 )
   {
-    if ( a3 != 3 )
-    {
-      v10 = a4 + v9;
-      v11 = v7 + 15;
-      v13 = __OFSUB__(v10, v11);
-      v12 = v10 - v11 < 0;
-    }
-	else
-	{
-      v14 = a4 + v9;
-      v15 = 2 * v7 + 30;
-	  v13 = __OFSUB__(v14, v15);
-      v12 = v14 - v15 < 0;
-	}
+    v14 = a4 + v9;
+    v15 = 2 * v7 + 30;
+    v13 = __OFSUB__(v14, v15);
+    v12 = v14 - v15 < 0;
   }
+  else 
+  {
+    v14 = a4 + v9;
+    v15 = v7 + 15;
+    v13 = __OFSUB__(v14, v15);
+    v12 = v14 - v15 < 0;
+  }
+
   if ( v12 ^ v13 )
     result = 0;
   else
@@ -439,11 +435,7 @@
 
     DamageMonsterFromParty(PID(OBJECT_Player, uActiveCharacter - 1), target_id, &a3);
     if (player->WearsItem(ITEM_ARTIFACT_SPLITTER, EQUIP_TWO_HANDED) || player->WearsItem(ITEM_ARTIFACT_SPLITTER, EQUIP_SINGLE_HANDED))
-          _42FA66_do_explosive_impact(
-            actor->vPosition.x,
-            actor->vPosition.y,
-            actor->vPosition.z + actor->uActorHeight / 2,
-            0, 512, uActiveCharacter);
+          _42FA66_do_explosive_impact(actor->vPosition.x, actor->vPosition.y, actor->vPosition.z + actor->uActorHeight / 2, 0, 512, uActiveCharacter);
   }
   else if (bow_idx)
   {
@@ -464,7 +456,6 @@
     player->SetRecoveryTime(flt_6BE3A4_debug_recmod1 * (double)recovery * 2.133333333333333);
   }
 
-  
   int v34 = 0;
   if (shooting_wand)
     return;
@@ -507,10 +498,10 @@
   int *v9; // edx@8
   signed int v10; // ebx@10
   int v11; // edi@11
-  Actor *v12; // esi@12
-  unsigned __int16 v13; // ax@12
+  //Actor *v12; // esi@12
+  //unsigned __int16 v13; // ax@12
   int v14; // eax@22
-  char v15; // zf@30
+  //char v15; // zf@30
   int v16; // esi@32
   int v17; // ecx@34
   stru319 *v18; // eax@39
@@ -518,17 +509,18 @@
   int v20; // ecx@41
   unsigned __int16 v21; // ax@42
   unsigned int v22; // [sp+8h] [bp-24h]@11
-  unsigned int v23; // [sp+Ch] [bp-20h]@7
+  //unsigned int v23; // [sp+Ch] [bp-20h]@7
   stru319 *v24; // [sp+10h] [bp-1Ch]@1
   unsigned int v25; // [sp+14h] [bp-18h]@8
   int *v26; // [sp+18h] [bp-14h]@8
   int v27; // [sp+1Ch] [bp-10h]@10
   int *v28; // [sp+20h] [bp-Ch]@10
-  unsigned int v29; // [sp+24h] [bp-8h]@7
+  //unsigned int v29; // [sp+24h] [bp-8h]@7
   int v30; // [sp+28h] [bp-4h]@6
   int i; // [sp+38h] [bp+Ch]@33
   signed int v32; // [sp+3Ch] [bp+10h]@32
 
+  //__debugbreak();//Ritor1
   v4 = 0;
   v5 = this;
   v24 = this;
@@ -547,49 +539,39 @@
     v30 = 0;
     if ( pRenderer->pActiveZBuffer )
     {
-      v29 = viewparams->uScreen_topL_X;
-      v23 = viewparams->uScreen_BttmR_X;
       if ( (signed int)viewparams->uScreen_topL_Y < (signed int)viewparams->uScreen_BttmR_Y )
       {
-        v25 = viewparams->uScreen_BttmR_Y - viewparams->uScreen_topL_Y;
         v9 = &pRenderer->pActiveZBuffer[viewparams->uScreen_topL_X + 640 * viewparams->uScreen_topL_Y];
         v26 = &pRenderer->pActiveZBuffer[viewparams->uScreen_topL_X + 640 * viewparams->uScreen_topL_Y];
-        do
+        for ( v25 = viewparams->uScreen_BttmR_Y - viewparams->uScreen_topL_Y; v25; --v25 )
         {
-          if ( (signed int)v29 < (signed int)v23 )
+          if ( (signed int)viewparams->uScreen_topL_X < (signed int)viewparams->uScreen_BttmR_X )
           {
             v28 = v9;
             v10 = v4;
-            v27 = v23 - v29;
-            do
+            for ( v27 = viewparams->uScreen_BttmR_X - viewparams->uScreen_topL_X; v27; --v27 )
             {
               v22 = *v28;
               v11 = *v28 & 0xFFFF;
               if (PID_TYPE(v11) == OBJECT_Actor)
               {
-                v12 = &pActors[PID_ID(v11)];
-                v13 = v12->uAIState;
-                if ( v13 != 5 )
+                if ( pActors[PID_ID(v11)].uAIState != Dead )
                 {
-                  if ( v13 != 4
-                    && v13 != 11
-                    && v13 != 19
-                    && v13 != 17
+                  if ( pActors[PID_ID(v11)].uAIState != Dying && pActors[PID_ID(v11)].uAIState != Removed
+                    && pActors[PID_ID(v11)].uAIState != Summoned && pActors[PID_ID(v11)].uAIState != Disabled
                     && (!a3 || pActors[PID_ID(v11)].GetActorsRelation(0)) )
                   {
-                    if ( (!a4 || MonsterStats::BelongsToSupertype(v12->pMonsterInfo.uID, MONSTER_SUPERTYPE_UNDEAD))
+                    if ( (!a4 || MonsterStats::BelongsToSupertype(pActors[PID_ID(v11)].pMonsterInfo.uID, MONSTER_SUPERTYPE_UNDEAD))
                       && v22 <= pick_depth << 16 )
                     {
                       v14 = 0;
                       if ( v10 > 0 )
                       {
-                        do
+                        for ( v14; v14 < v30; ++v14 )
                         {
                           if ( dword_50BDA0[v14] == v11 )
                             break;
-                          ++v14;
                         }
-                        while ( v14 < v30 );
                       }
                       if ( v14 == v30 && v10 < 100 )
                       {
@@ -603,49 +585,39 @@
                 }
               }
               ++v28;
-              --v27;
             }
-            while ( v27 );
             v4 = v30;
             v5 = v24;
           }
           v9 = v26 + 640;
-          v15 = v25-- == 1;
           v26 += 640;
         }
-        while ( !v15 );
       }
       if ( v4 > 0 )
       {
-        v32 = 1;
         v16 = (int)dword_50BC10.data();
-        do
+        for ( v32 = 1; v32 - 1 < v4; ++v32 )
         {
           for ( i = v32; i < v4; ++i )
           {
             v17 = dword_50BC10[i];
-            if ( v17 < *(int *)v16 )
+            if ( dword_50BC10[i] < *(int *)v16 )
             {
               dword_50BC10[i] = *(int *)v16;
               *(int *)v16 = v17;
             }
           }
-          ++v32;
           v16 += 4;
         }
-        while ( v32 - 1 < v4 );
         v5 = v24;
         if ( v4 > 0 )
         {
           v18 = v24;
-          v19 = v4;
-          do
+          for ( v19 = v4; v19; --v19 )
           {
             *(int *)&v18->field_0 = (*(int *)&v18[(char *)dword_50BC10.data() - (char *)v24].field_0 >> 3) & 0x1FFF;
             v18 += 4;
-            --v19;
           }
-          while ( v19 );
         }
       }
       v20 = 0;
@@ -708,16 +680,11 @@
   pSpellObject.spell_id = 0;
   pSpellObject.field_54 = 0;
   pSpellObject.uType = uSpriteID;
-  if ( (signed int)pObjectList->uNumObjects <= 0 )
-    pObjectDescID = 0;
-  else
+  pObjectDescID = 0;
+  for ( uint i = 0; i < (signed int)pObjectList->uNumObjects; ++i )
   {
-    pObjectDescID = 0;
-    for ( uint i = 0; i < (signed int)pObjectList->uNumObjects; ++i )
-    {
-      if ( (short)uSpriteID == pObjectList->pObjects[i].uObjectID )
-        pObjectDescID = i;
-    }
+    if ( (short)uSpriteID == pObjectList->pObjects[i].uObjectID )
+      pObjectDescID = i;
   }
   pSpellObject.uObjectDescID = pObjectDescID;
   pSpellObject.vPosition.x = x;
@@ -770,52 +737,32 @@
 //----- (0042F960) --------------------------------------------------------
 void __fastcall sub_42F960_create_object(int x, int y, int z)
 {
-  int v3; // ebx@1
-  int v4; // edi@1
-  signed int v5; // edx@1
-  char *v6; // ecx@2
   unsigned __int16 v7; // ax@5
   signed int v8; // eax@6
   signed int v9; // eax@7
-  //SpriteObject a1; // [sp+Ch] [bp-70h]@1
 
-  v3 = x;
-  v4 = y;
-  
   SpriteObject a1; // [sp+Ch] [bp-70h]@1
   //SpriteObject::SpriteObject(&a1);
   a1.stru_24.Reset();
 
-  v5 = 0;
   a1.spell_skill = 0;
   a1.spell_level = 0;
   a1.spell_id = 0;
   a1.field_54 = 0;
   a1.uType = 800;
-  if ( (signed int)pObjectList->uNumObjects <= 0 )
-  {
-LABEL_5:
-    v7 = 0;
-  }
-  else
+  v7 = 0;
+  for ( uint i = 0; i < (signed int)pObjectList->uNumObjects; ++i )
   {
-    v6 = (char *)&pObjectList->pObjects->uObjectID;
-    while ( *(short *)v6 != 800 )
-    {
-      ++v5;
-      v6 += 56;
-      if ( v5 >= (signed int)pObjectList->uNumObjects )
-        goto LABEL_5;
-    }
-    v7 = v5;
+    if ( a1.uType == pObjectList->pObjects[i].uObjectID  )
+      v7 = i;
   }
   a1.uObjectDescID = v7;
-  a1.vPosition.x = v3;
-  a1.vPosition.y = v4;
+  a1.vPosition.x = x;
+  a1.vPosition.y = y;
   a1.vPosition.z = z;
   a1.uSoundID = 0;
   a1.uAttributes = 0;
-  a1.uSectorID = pIndoor->GetSector(v3, v4, z);
+  a1.uSectorID = pIndoor->GetSector(x, y, z);
   a1.uSpriteFrameID = 0;
   a1.spell_caster_pid = 0;
   a1.spell_target_pid = 0;
@@ -828,23 +775,11 @@
   }
 }
 
-
-
 //----- (0042FA66) --------------------------------------------------------
 void _42FA66_do_explosive_impact(int a1, int a2, int a3, int a4, __int16 a5, signed int a6)
 {
-  int v6; // edi@1
-  int v7; // esi@1
-  char *v8; // ecx@2
   unsigned __int16 v9; // ax@5
-  //int v10; // eax@10
-  //signed int result; // eax@11
-  //__int16 v12; // ax@12
-  //SpriteObject a1a; // [sp+Ch] [bp-74h]@1
-  int v14; // [sp+7Ch] [bp-4h]@1
 
-  v6 = a1;
-  v7 = a2;
   SpriteObject a1a; // [sp+Ch] [bp-74h]@1
   //SpriteObject::SpriteObject(&a1a);
   a1a.uType = 600;
@@ -853,43 +788,27 @@
   a1a.spell_id = SPELL_FIRE_FIREBALL;
   a1a.spell_level = 8;
   a1a.spell_skill = 3;
-  v14 = 0;
-  if ( (signed int)pObjectList->uNumObjects <= 0 )
-  {
-LABEL_5:
-    v9 = 0;
-  }
-  else
+  v9 = 0;
+  for ( uint i = 0; i < pObjectList->uNumObjects; ++i )
   {
-    v8 = (char *)&pObjectList->pObjects->uObjectID;
-    while ( (short)a1a.uType != *(short *)v8 )
-    {
-      ++v14;
-      v8 += 56;
-      if ( v14 >= (signed int)pObjectList->uNumObjects )
-        goto LABEL_5;
-    }
-    v9 = v14;
+    if ( a1a.uType == pObjectList->pObjects[i].uObjectID )
+      v9 = i;
   }
   a1a.uObjectDescID = v9;
-  a1a.vPosition.x = v6;
-  a1a.vPosition.y = v7;
+  a1a.vPosition.x = a1;
+  a1a.vPosition.y = a2;
   a1a.vPosition.z = a3;
   a1a.uAttributes = 0;
-  a1a.uSectorID = pIndoor->GetSector(v6, v7, a3);
+  a1a.uSectorID = pIndoor->GetSector(a1, a2, a3);
   a1a.uSpriteFrameID = 0;
   a1a.spell_target_pid = 0;
   a1a.field_60_distance_related_prolly_lod = 0;
   a1a.uFacing = 0;
   a1a.uSoundID = 0;
   if ( a6 >= 1 || a6 <= 4 )
-  {
     a1a.spell_caster_pid = PID(OBJECT_Player, a6 - 1);
-  }
   else
-  {
     a1a.spell_caster_pid = 0;
-  }
 
   int id = a1a.Create(0, 0, 0, 0);
   if (id != -1)
@@ -898,63 +817,22 @@
 }
 
 //----- (0042FB5C) --------------------------------------------------------
-bool _42FB5C_check_spell(signed int a1)
+bool _42FB5C_check_spell(signed int spell_id)
 {
-  int v1; // ecx@3
-  int v2; // ecx@4
-  int v3; // ecx@5
-  int v4; // ecx@6
-  int v5; // ecx@7
-  int v6; // ecx@8
-  char v7; // zf@9
-
-  if ( a1 > 39 )
+  if ( spell_id > 39 )
   {
-    if ( a1 > 77 )
-    {
-      if ( a1 == 80 )
-        return 0;
-      if ( a1 > 84 )
-      {
-        if ( a1 <= 86 )
-          return 0;
-        v7 = a1 == 95;
-        goto LABEL_20;
-      }
-    }
-    else
-    {
-      if ( a1 == 77 )
-        return 0;
-      if ( a1 >= 46 )
-      {
-        if ( a1 <= 47 || a1 == 51 )
-          return 0;
-        v7 = a1 == 73;
-        goto LABEL_20;
-      }
-    }
-    return 1;
+    if ( spell_id == SPELL_SPIRIT_BLESS || spell_id == SPELL_SPIRIT_FATE || spell_id == SPELL_SPIRIT_HEROISM || spell_id == SPELL_BODY_HAMMERHANDS
+      || spell_id == SPELL_BODY_POWER_CURE ||spell_id == SPELL_LIGHT_DISPEL_MAGIC || spell_id == SPELL_LIGHT_DAY_OF_PROTECTION
+      || spell_id == SPELL_LIGHT_HOUR_OF_POWER || spell_id == SPELL_DARK_PAIN_REFLECTION)
+      return false;
+    return true;
   }
-  if ( a1 == 39 || (v1 = a1 - 2) == 0 )
-    return 1;
-  v2 = v1 - 3;
-  if ( !v2 )
-    return 0;
-  v3 = v2 - 1;
-  if ( !v3 || (v4 = v3 - 3) == 0 )
-    return 1;
-  v5 = v4 - 8;
-  if ( !v5 )
-    return 0;
-  v6 = v5 - 1;
-  if ( !v6 )
-    return 1;
-  v7 = v6 == 20;
-LABEL_20:
-  if ( !v7 )
-    return 1;
-  return 0;
+  if ( spell_id == SPELL_FIRE_FIRE_BOLT || spell_id == SPELL_FIRE_FIREBALL || spell_id == SPELL_FIRE_METEOR_SHOWER
+    || spell_id == SPELL_AIR_LIGHNING_BOLT || spell_id == SPELL_EARTH_BLADES )
+    return true;
+  if ( spell_id == SPELL_FIRE_HASTE || spell_id == SPELL_AIR_SHIELD || spell_id == SPELL_EARTH_STONESKIN )
+    return false;
+  return true;
 }
 
 //----- (0042FBDD) --------------------------------------------------------
@@ -977,14 +855,14 @@
 void ProcessInputActions()
 {
   char v4; // al@9
-  char v8; // bl@100
+  //char v8; // bl@100
   unsigned __int16 v9; // ax@102
-  int v10; // eax@103
+  int spell_price; // eax@103
   char v14; // al@159
   unsigned int v15; // eax@168
   PartyAction partyAction; // [sp-14h] [bp-1Ch]@20
   InputAction inputAction; // [sp+0h] [bp-8h]@7
-  int v24; // [sp+4h] [bp-4h]@87
+  //int v24; // [sp+4h] [bp-4h]@87
 
   pGame->pKeyboardInstance->EnterCriticalSection();
   Keyboard* pKeyboard = pGame->pKeyboardInstance;
@@ -1153,9 +1031,7 @@
             }
             pPartyActionQueue->Add(partyAction);
             if (uCurrentlyLoadedLevelType == LEVEL_Outdoor && pWeather->bRenderSnow)
-            {
               pWeather->OnPlayerTurn(10);
-            }
             break;
           case INPUT_TurnRight:
             if (pCurrentScreen != SCREEN_GAME)
@@ -1179,9 +1055,7 @@
             }
             pPartyActionQueue->Add(partyAction);
             if (uCurrentlyLoadedLevelType == LEVEL_Outdoor && pWeather->bRenderSnow)
-            {
               pWeather->OnPlayerTurn(-10);
-            }
             break;
           case INPUT_Jump:
             if (pCurrentScreen != SCREEN_GAME || pParty->bTurnBasedModeOn)
@@ -1208,9 +1082,8 @@
             {
               if ( !pPlayers[uActiveCharacter]->uTimeToRecovery )
               {
-                v24 = pPlayers[uActiveCharacter]->GetAttackRecoveryTime(false);
                 if ( !pParty->bTurnBasedModeOn )
-                  pPlayers[uActiveCharacter]->SetRecoveryTime((signed __int64)(flt_6BE3A4_debug_recmod1 * (double)v24 * 2.133333333333333));
+                  pPlayers[uActiveCharacter]->SetRecoveryTime((signed __int64)(flt_6BE3A4_debug_recmod1 * (double)pPlayers[uActiveCharacter]->GetAttackRecoveryTime(false) * 2.133333333333333));
                 CastSpellInfoHelpers::_427D48();
                 pTurnEngine->ApplyPlayerAction();
               }
@@ -1244,24 +1117,21 @@
             }
             if ( !uActiveCharacter )
               break;
-            v8 = pPlayers[uActiveCharacter]->uQuickSpell;
-            if ( !v8
-              || bUnderwater
-              || ((v9 = pPlayers[uActiveCharacter]->pActiveSkills[(unsigned __int8)v8 / 11 + 12], !(HIBYTE(v9) & 1)) ? 
-                 ((v9 & 0x80u) == 0 ? (!(v9 & 0x40) ? (v10 = *(&pSpellDatas[0].uNormalLevelMana + 10 * (unsigned __int8)v8)) : 
-                 (v10 = *(&pSpellDatas[0].uExpertLevelMana + 10 * (unsigned __int8)v8))) : 
-                 (v10 = *(&pSpellDatas[0].uMasterLevelMana + 10 * (unsigned __int8)v8))) : 
-                 (v10 = *(&pSpellDatas[0].uMagisterLevelMana + 10 * (unsigned __int8)v8)),
-                  v10 > pPlayers[uActiveCharacter]->sMana) )
+            v9 = pPlayers[uActiveCharacter]->pActiveSkills[(unsigned __int8)pPlayers[uActiveCharacter]->uQuickSpell / 11 + 12];
+            if ( !pPlayers[uActiveCharacter]->uQuickSpell || bUnderwater
+              || (( !(HIBYTE(v9) & 1)) ? 
+                 ((v9 & 0x80) == 0 ? 
+                 ((v9 & 0x40) == 0 ? spell_price = pSpellDatas[pPlayers[uActiveCharacter]->uQuickSpell].uNormalLevelMana : spell_price = pSpellDatas[pPlayers[uActiveCharacter]->uQuickSpell].uExpertLevelMana) : 
+                 spell_price = pSpellDatas[pPlayers[uActiveCharacter]->uQuickSpell].uMasterLevelMana) : 
+                 spell_price = pSpellDatas[pPlayers[uActiveCharacter]->uQuickSpell].uMagisterLevelMana,
+                 spell_price > pPlayers[uActiveCharacter]->sMana) )
             {
               pPartyActionQueue = pPartyActionQueue;
               pMessageQueue_50CBD0->AddMessage(UIMSG_Attack, 0, 0);
               break;
             }
             else
-            {
-            pMessageQueue_50C9E8->AddMessage(UIMSG_CastQuickSpell, 0, 0);
-            }
+              pMessageQueue_50C9E8->AddMessage(UIMSG_CastQuickSpell, 0, 0);
             break;
           case INPUT_Attack:
             if (pCurrentScreen != SCREEN_GAME)
--- a/mm7_7.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_7.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -29,7 +29,7 @@
   dword_4F8580[0] = 1;
   return result;
   */
-
+	__debugbreak();//Ritor1
   for( int i = 0; i < 62; i++ )
   {
 	  dword_4F8580[i] = 0;
@@ -41,18 +41,9 @@
 //----- (00423B4A) --------------------------------------------------------
 void  sub_423B4A()
 {
-  float *v0; // eax@1
-  signed int v1; // ecx@1
-
-  v0 = &array_507D30[0].flt_2C;
-  v1 = 50;
-  do
-  {
-    *v0 = 0.0;
-    v0 += 12;
-    --v1;
-  }
-  while ( v1 );
+	__debugbreak();//Ritor1
+  for ( uint i = 0; i < 50; i++ )
+    array_507D30[i].flt_2C = 0.0;
 }
 
 /*
--- a/mm7_data.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_data.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -809,7 +809,7 @@
 
 int dword_4EED78; // weak
 _UNKNOWN unk_4EED80; // weak
-int dword_4EFA80; // weak
+int ScreenshotFileNumber; // dword_4EFA80
 int dword_4EFA84; // weak
 void *off_4EFDB0; // weak
 int dword_4F031C[777]; // weak
@@ -841,7 +841,30 @@
 std::array<int, 11> price_for_membership={100, 100, 50, 50, 50, 50, 50, 50, 50, 1000, 1000}; // weak
 
 
-std::array<Vec2_int_, 20> pMonsterArenaPlacements;
+std::array<Vec2_int_, 20> pMonsterArenaPlacements = 
+  {{
+    Vec2_int_(0x5F4, 0x208C),
+    Vec2_int_(0x88A, 0x228C),
+    Vec2_int_(0xC93, 0x247B),
+    Vec2_int_(0x1194, 0x247B),
+    Vec2_int_(0x14CB, 0x232C),
+    Vec2_int_(0x177D, 0x2098),
+    Vec2_int_(0x50B, 0x1E15),
+    Vec2_int_(0x18FF, 0x1E15),
+    Vec2_int_(0x50B, 0xD69),
+    Vec2_int_(0x18FF, 0x1B15),
+    Vec2_int_(0x50B, 0x1021),
+    Vec2_int_(0x18FF, 0x1848),
+    Vec2_int_(0x50B, 0x12D7),
+    Vec2_int_(0x18FF, 0x15A3),
+    Vec2_int_(0x50B, 0x14DB),
+    Vec2_int_(0x18FF, 0x12D7),
+    Vec2_int_(0x50B, 0x1848),
+    Vec2_int_(0x18FF, 0x1021),
+    Vec2_int_(0x50B, 0x1B15),
+    Vec2_int_(0x18FF, 0xD69),
+  }}
+;
 std::array<__int16, 32> word_4F0F30 ={{ 4, 7, 10, 11,                                              
 						   4, 7, 10, 11,
 					       4, 7, 10, 11,
@@ -1005,7 +1028,6 @@
 std::array<char, 54> party_has_equipment;
 std::array<char, 17> byte_5111F6;
 
-std::array<std::array<unsigned __int16, 137>, 117> pOdmMinimap;
 unsigned int uNumBlueFacesInBLVMinimap;
 std::array<unsigned __int16, 50> pBlueFacesInBLVMinimapIDs;
 std::array<int, 14> pTextureIDs_PartyBuffIcons;
@@ -1190,6 +1212,7 @@
 float fTurnSpeedMultiplier = 1.0f; // weak
 float flt_6BE150_look_up_down_dangle = 1.0f; // weak
 //HWND hWnd; // idb
+bool FORCE_16_BITS = false;
 class OSWindow *window = nullptr;
 char pCurrentMapName[32]; // idb
 unsigned int uLevelMapStatsID;
--- a/mm7_data.h	Thu Jan 02 09:11:01 2014 +0600
+++ b/mm7_data.h	Thu Jan 02 09:11:28 2014 +0600
@@ -482,7 +482,7 @@
 extern std::array<short, 28> word_4EE150;
 extern int dword_4EED78; // weak
 extern _UNKNOWN unk_4EED80; // weak
-extern int dword_4EFA80; // weak
+extern int ScreenshotFileNumber; // dword_4EFA80
 extern int dword_4EFA84; // weak
 extern void *off_4EFDB0; // weak
 extern int dword_4F031C[]; // weak
@@ -652,7 +652,6 @@
 
 extern int bRingsShownInCharScreen; // weak
 
-extern std::array<std::array<unsigned __int16, 137>, 117> pOdmMinimap;
 extern unsigned int uNumBlueFacesInBLVMinimap;
 extern std::array<unsigned __int16, 50> pBlueFacesInBLVMinimapIDs;
 extern std::array<int, 14> pTextureIDs_PartyBuffIcons;
@@ -843,7 +842,7 @@
 extern char pCurrentMapName[32]; // idb
 extern unsigned int uLevelMapStatsID;
 
-
+extern bool FORCE_16_BITS; // related to GAME_SETTINGS_INVALID_RESOLUTION
 #define GAME_SETTINGS_0001                            0x0001
 #define GAME_SETTINGS_INVALID_RESOLUTION              0x0002
 #define GAME_SETTINGS_NO_INTRO                        0x0004
@@ -1063,8 +1062,8 @@
 int MakeActorAIList_BLV();
 void UpdateActorAI();
 bool __fastcall sub_4070EF_prolly_detect_player(unsigned int uObjID, unsigned int uObj2ID);
-bool __fastcall sub_4075DB(int a1, int a2, int a3, struct BLVFace *a4);
-bool __fastcall sub_4077F1(int a1, int a2, int a3, struct ODMFace *a4, struct BSPVertexBuffer *a5);
+bool __fastcall sub_4075DB(int a1, int a2, int a3, struct BLVFace *face);
+bool __fastcall sub_4077F1(int a1, int a2, int a3, struct ODMFace *face, struct BSPVertexBuffer *a5);
 bool __fastcall sub_407A1C(int x, int z, int y, struct Vec3_int_ v); // idb
 void InitializeActors();
 void InitializeSpriteObjects();
@@ -1074,7 +1073,6 @@
 unsigned int SearchActorByGroup(unsigned int *pTotalActors, unsigned int uGroup);
 unsigned int SearchActorByID(unsigned int *pTotalActors, unsigned int a2);
 void PrepareArcomage();
-unsigned short TargetColor(unsigned __int16 r, unsigned __int16 g, unsigned __int16 b); // idb
 void DoBlt_Copy(unsigned __int16 *pPixels); // idb
 void __fastcall ZBuffer_Fill(int *pZBuffer, int uTextureId, int iZValue);
 void __fastcall ZBuffer_DoFill(int *pZBuffer, struct Texture *pTex, int uZValue);
@@ -1110,7 +1108,7 @@
 bool PortalFrustrum(int pNumVertices, struct BspRenderer_PortalViewportData *a2, struct BspRenderer_PortalViewportData *near_portal, int uFaceID);
 int ODM_NearClip(unsigned int uVertexID); // idb
 int ODM_FarClip(unsigned int uNumVertices);
-bool __fastcall sub_427769_spell(unsigned int uSpellID);
+bool sub_427769_isSpellQuickCastableOnShiftClick(unsigned int uSpellID);
 void _42777D_CastSpell_UseWand_ShootArrow(int a1, unsigned int uPlayerID, unsigned int a4, __int16 a5, int a6);
 void _42ECB5_PlayerAttacksActor();
 void  InitializeTurnBasedAnimations(void *);
@@ -1118,7 +1116,7 @@
 void __fastcall sub_42F960_create_object(int x, int y, int z); // idb
 void CompactLayingItemsList();
 void _42FA66_do_explosive_impact(int a1, int a2, int a3, int a4, __int16 a5, signed int a6);
-bool _42FB5C_check_spell(signed int a1);
+bool _42FB5C_check_spell(signed int spell_id);
 void sub_42FBDD();
 void CloseWindowBackground();
 void ProcessInputActions();
@@ -1132,7 +1130,7 @@
 void __fastcall sub_43A97E(unsigned int uLayingItemID, signed int a2); // idb
 double __fastcall sub_43AE12(signed int a1);
 int __fastcall _43AFE3_calc_spell_damage(int a1, int a2, signed int a3, int a4);
-void __fastcall sub_43B057(unsigned int uObjID, unsigned int uActorID, struct Vec3_int_ *pVelocity);
+void ItemDamageFromActor(unsigned int uObjID, unsigned int uActorID, struct Vec3_int_ *pVelocity);
 void ActorDamageFromMonster(signed int attacker_id, unsigned int actor_id, struct Vec3_int_ *pVelocity, signed int a4);
 void CharacterUI_LoadPaperdollTextures();
 int __fastcall GetItemTextureFilename(char *pOut, signed int item_id, int index, int shoulder);
@@ -1266,8 +1264,6 @@
 bool AreRenderSurfacesOk();
 unsigned int BlendColors(unsigned int c1, unsigned int c2); // weak
 void DoRenderBillboards_D3D();
-int __fastcall sr_4A46E6_draw_particle_segment(unsigned int x, signed int y, signed int z, int a4, unsigned int lightColor);
-void Present_ColorKey();
 void Present_NoColorKey();
 unsigned int ModulateColor(unsigned int diffuse, float multiplier); // idb
 struct SoundHeader *FindSound_BinSearch(unsigned int uStart, unsigned int uEnd, const char *pName);
@@ -1314,8 +1310,8 @@
 void ODM_ProcessPartyActions();
 bool sub_47531C(int a1, int *a2, int pos_x, int pos_y, int pos_z, int dir_x, int dir_y, int dir_z, struct BLVFace *face, int a10);
 bool sub_4754BF(int a1, int *a2, int X, int Y, int Z, int dir_x, int dir_y, int dir_z, struct BLVFace *face, int a10, int a11);
-int sub_475665(struct BLVFace *_this, int a2, __int16 a3);
-bool __fastcall sub_4759C9(struct BLVFace *a1, int a2, int a3, __int16 a4);
+int sub_475665(struct BLVFace *face, int a2, __int16 a3);
+bool __fastcall sub_4759C9(struct BLVFace *face, int a2, int a3, __int16 a4);
 bool __fastcall sub_475D85(Vec3_int_ *a1, Vec3_int_ *a2, int *a3, struct BLVFace *a4);
 bool __fastcall sub_475F30(int *a1, struct BLVFace *a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9);
 void sub_4452BB();
@@ -1326,7 +1322,7 @@
 void  DialogueEnding();
 void PrepareHouse(enum HOUSE_ID house); // idb
 bool EnterHouse(enum HOUSE_ID uHouseID);
-int sub_4465DF_check_season(int a1);
+bool sub_4465DF_check_season(int a1);
 int __fastcall IsActorAlive(unsigned int uType, unsigned int uParam, unsigned int uNumAlive); // idb
 int NPC_EventProcessor(int npc_event_id, int entry_line = 0);
 void __fastcall sub_448518_npc_set_item(int npc, unsigned int item, int a3);
@@ -1356,7 +1352,7 @@
 int __fastcall MakeColorMaskFromBitDepth(int a1);
 void __fastcall fill_pixels_fast(unsigned int a1, unsigned __int16 *pPixels, unsigned int uNumPixels);
 int __fastcall GetDiceResult(unsigned int uNumDice, unsigned int uDiceSides); // idb
-inline int round(float x) { return (int)floor(x + 0.5f); }
+inline int round_to_int(float x) { return (int)floor(x + 0.5f); }
 inline void __fastcall memset32(void *ptr, unsigned __int32 value, int count)
 {
   unsigned __int32* p = (unsigned __int32 *)ptr;
--- a/stru10.cpp	Thu Jan 02 09:11:01 2014 +0600
+++ b/stru10.cpp	Thu Jan 02 09:11:28 2014 +0600
@@ -118,7 +118,7 @@
     int c;
   } v46[40]; //[sp+0C];
 
-  if (pFace->uAttributes & 0x0100)
+  if (pFace->uAttributes & FACE_XY_PLANE)
   {
     for (uint i = 0; i < pFace->uNumVertices; ++i)
     {
@@ -127,7 +127,7 @@
       v46[i].c = i;
     }
   }
-  if (pFace->uAttributes & 0x0200)
+  if (pFace->uAttributes & FACE_XZ_PLANE)
   {
     for (uint i = 0; i < pFace->uNumVertices; ++i)
     {
@@ -136,7 +136,7 @@
       v46[i].c = i;
     }
   }
-  if (pFace->uAttributes & 0x0400)
+  if (pFace->uAttributes & FACE_YZ_PLANE)
   {
     for (uint i = 0; i < pFace->uNumVertices; ++i)
     {
@@ -282,7 +282,7 @@
   float a3;
   float var_8;
 
-  if (pFace->uAttributes & 0x0100)
+  if (pFace->uAttributes & FACE_XY_PLANE)
   {
     face_center_x = (pFaceLimits[0].vWorldPosition.x + pFaceLimits[2].vWorldPosition.x) / 2;
     face_center_y = (pFaceLimits[3].vWorldPosition.y + pFaceLimits[1].vWorldPosition.y) / 2;
@@ -291,7 +291,7 @@
     a3 = face_center_x - pFaceLimits[0].vWorldPosition.x;
     var_8 = face_center_y - pFaceLimits[1].vWorldPosition.y;
   }
-  if (pFace->uAttributes & 0x0200)
+  if (pFace->uAttributes & FACE_XZ_PLANE)
   {
     face_center_x = (pFaceLimits[0].vWorldPosition.x + pFaceLimits[2].vWorldPosition.x) / 2;//  
     face_center_y = (pFaceLimits[0].vWorldPosition.y + pFaceLimits[2].vWorldPosition.y) / 2;
@@ -303,7 +303,7 @@
     if (pFace->uPolygonType == POLYGON_VerticalWall)
       a3 /= a1.x;
   }
-  if (pFace->uAttributes & 0x0400)
+  if (pFace->uAttributes & FACE_YZ_PLANE)
   {
     face_center_x = (pFaceLimits[0].vWorldPosition.x + pFaceLimits[2].vWorldPosition.x) / 2;
     face_center_y = (pFaceLimits[0].vWorldPosition.y + pFaceLimits[2].vWorldPosition.y) / 2;