merge xymeng's gsoc engine with a few updates (and further checks on symbol definitions) webgl
authorkoda
Sun, 11 Nov 2012 17:15:19 +0100
branchwebgl
changeset 8026 4a4f21070479
parent 8023 7de85783b823
child 8029 7ba43d7e54e7
merge xymeng's gsoc engine with a few updates (and further checks on symbol definitions)
hedgewars/CMakeLists.txt
hedgewars/GSHandlers.inc
hedgewars/LuaPas.pas
hedgewars/SDLh.pas
hedgewars/VGSHandlers.inc
hedgewars/adler32.pas
hedgewars/hwengine.pas
hedgewars/options.inc
hedgewars/pas2cRedo.pas
hedgewars/pas2cSystem.pas
hedgewars/uAI.pas
hedgewars/uAIAmmoTests.pas
hedgewars/uAIMisc.pas
hedgewars/uAmmos.pas
hedgewars/uCaptions.pas
hedgewars/uChat.pas
hedgewars/uCommandHandlers.pas
hedgewars/uConsts.pas
hedgewars/uCursor.pas
hedgewars/uFloat.pas
hedgewars/uGears.pas
hedgewars/uGearsHedgehog.pas
hedgewars/uGearsList.pas
hedgewars/uGearsRender.pas
hedgewars/uGearsUtils.pas
hedgewars/uIO.pas
hedgewars/uLand.pas
hedgewars/uLandGenMaze.pas
hedgewars/uLandGraphics.pas
hedgewars/uLandObjects.pas
hedgewars/uLandTemplates.pas
hedgewars/uLandTexture.pas
hedgewars/uLocale.pas
hedgewars/uMatrix.pas
hedgewars/uMisc.pas
hedgewars/uMobile.pas
hedgewars/uRandom.pas
hedgewars/uRender.pas
hedgewars/uRenderUtils.pas
hedgewars/uScript.pas
hedgewars/uSound.pas
hedgewars/uStats.pas
hedgewars/uStore.pas
hedgewars/uTeams.pas
hedgewars/uTypes.pas
hedgewars/uUtils.pas
hedgewars/uVariables.pas
hedgewars/uVisualGears.pas
hedgewars/uWeb.pas
hedgewars/uWorld.pas
--- a/hedgewars/CMakeLists.txt	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/CMakeLists.txt	Sun Nov 11 17:15:19 2012 +0100
@@ -52,6 +52,7 @@
     uLandTemplates.pas
     uLandTexture.pas
     uLocale.pas
+    uMatrix.pas
     uMisc.pas
     uMobile.pas
     uRandom.pas
--- a/hedgewars/GSHandlers.inc	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/GSHandlers.inc	Sun Nov 11 17:15:19 2012 +0100
@@ -173,7 +173,7 @@
     land: word;
 begin
     // clip velocity at 2 - over 1 per pixel, but really shouldn't cause many actual problems.
-{$IFNDEF WEB}
+{$IFNDEF WEBGL}
     if Gear^.dX.Round > 2 then
         Gear^.dX.QWordValue:= 8589934592;
     if Gear^.dY.Round > 2 then
@@ -999,7 +999,8 @@
 
 procedure doStepBulletWork(Gear: PGear);
 var 
-    i, x, y: LongWord;
+    i: LongInt;
+    x, y: LongWord;
     oX, oY: hwFloat;
     VGear: PVisualGear;
 begin
@@ -2741,6 +2742,7 @@
 procedure doStepSeductionWork(Gear: PGear);
 var i: LongInt;
     hogs: PGearArrayS;
+    len: Integer;
 begin
     AllInactive := false;
     hogs := GearsNear(Gear^.X, Gear^.Y, gtHedgehog, Gear^.Radius);
@@ -3513,7 +3515,9 @@
     i: LongInt;
 begin
     AllInactive := false;
+    {$IFNDEF PAS2C}
     Gear^.dX := Gear^.dX;
+    {$ENDIF}
     doStepFallingGear(Gear);
     //    CheckGearDrowning(Gear); // already checked for in doStepFallingGear
     CalcRotationDirAngle(Gear);
@@ -4614,6 +4618,7 @@
     resgear: PGear;
     hh: PHedgehog;
     i: LongInt;
+    len: Integer;
 begin
     if (TurnTimeLeft > 0) then
         dec(TurnTimeLeft);
@@ -4705,6 +4710,7 @@
 var
     graves: PGearArrayS;
     i: LongInt;
+    len: Integer;
 begin
     AllInactive := false;
     graves := GearsNear(Gear^.X, Gear^.Y, gtGrave, Gear^.Radius);
@@ -5028,12 +5034,14 @@
 A frozen hog will animate differently.  To be decided, but possibly in a similar fashion to a grave when it comes to explosions.  The hog might (possibly) not be damaged by explosions.  This might make freezing potentially useful for friendlies in a bad position.  It might be better to allow damage though.
 A frozen hog stays frozen for a certain number of turns. Each turn the frozen overlay becomes fainter, until it fades and the hog animates normally again.
 *)
+
 procedure doStepIceGun(Gear: PGear);
 var
     HHGear: PGear;
     ndX, ndY: hwFloat;
     i, t, gX, gY: LongInt;
     hogs: PGearArrayS;
+    len: Integer;
 begin
     HHGear := Gear^.Hedgehog^.Gear;
     if (Gear^.Health = 0) or (HHGear = nil) or (HHGear^.Damage <> 0) then
--- a/hedgewars/LuaPas.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/LuaPas.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -54,12 +54,14 @@
 @* of a function in debug information.
 ** CHANGE it if you want a different size.
 *)
+
 const
     LUA_IDSIZE = 60;
 
 (*
 @@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
 *)
+
 const
     LUAL_BUFFERSIZE = 1024;
 
@@ -69,6 +71,7 @@
 ** CHANGE them if you want different prompts. (You can also change the
 ** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.)
 *)
+
 const
     LUA_PROMPT  = '> ';
     LUA_PROMPT2 = '>> ';
@@ -112,6 +115,7 @@
 ** See Copyright Notice at the end of this file
 *)
 
+
 const
     LUA_VERSION     = 'Lua 5.1';
     LUA_VERSION_NUM = 501;
@@ -131,8 +135,10 @@
     LUA_ENVIRONINDEX  = -10001;
     LUA_GLOBALSINDEX  = -10002;
 
+   
 function lua_upvalueindex(idx : LongInt) : LongInt;   // a marco
 
+
 const
    (* thread status; 0 is OK *)
     LUA_YIELD_    = 1;     // Note: the ending underscore is needed in Pascal
@@ -141,6 +147,7 @@
     LUA_ERRMEM    = 4;
     LUA_ERRERR    = 5;
 
+   
 type
    lua_CFunction = function(L : Plua_State) : LongInt; cdecl;
 
@@ -155,6 +162,7 @@
   *)
   lua_Alloc = function (ud, ptr : Pointer; osize, nsize : size_t) : Pointer; cdecl;
 
+
 const
     (*
     ** basic types
@@ -180,6 +188,7 @@
     (* type for integer functions *)
     lua_Integer = LUA_INTEGER_;
 
+   
 (*
 ** state manipulation
 *)
@@ -240,10 +249,9 @@
     
 function lua_type(L : Plua_State; idx : LongInt) : LongInt;
     cdecl; external LuaLibName;
-    
+
 function lua_typename(L : Plua_State; tp : LongInt) : PChar;
     cdecl; external LuaLibName;
-
     
 function lua_equal(L : Plua_State; idx1, idx2 : LongInt) : LongBool;
     cdecl; external LuaLibName;
@@ -263,10 +271,9 @@
 function lua_toboolean(L : Plua_State; idx : LongInt) : LongBool;
     cdecl; external LuaLibName;
     
-    
 function lua_tolstring(L : Plua_State; idx : LongInt; len : Psize_t) : PChar;
     cdecl; external LuaLibName;
-    
+
 function lua_objlen(L : Plua_State; idx : LongInt) : size_t;
     cdecl; external LuaLibName;
     
@@ -294,14 +301,13 @@
     
 procedure lua_pushinteger(L : Plua_State; n : lua_Integer);
     cdecl; external LuaLibName;
-    
+
 procedure lua_pushlstring(L : Plua_State; const s : PChar; ls : size_t);
     cdecl; external LuaLibName;
     
 procedure lua_pushstring(L : Plua_State; const s : PChar);
     cdecl; external LuaLibName;
     
-    
 function  lua_pushvfstring(L : Plua_State;
     const fmt : PChar; argp : Pointer) : PChar;
     cdecl; external LuaLibName;
@@ -327,10 +333,10 @@
 *)
 procedure lua_gettable(L : Plua_State ; idx : LongInt);
     cdecl; external LuaLibName;
-    
+
 procedure lua_getfield(L : Plua_State; idx : LongInt; k : PChar);
     cdecl; external LuaLibName;
-    
+
 procedure lua_rawget(L : Plua_State; idx : LongInt);
     cdecl; external LuaLibName;
     
@@ -355,10 +361,10 @@
 *)
 procedure lua_settable(L : Plua_State; idx : LongInt);
     cdecl; external LuaLibName;
-    
+
 procedure lua_setfield(L : Plua_State; idx : LongInt; const k : PChar);
     cdecl; external LuaLibName;
-    
+
 procedure lua_rawset(L : Plua_State; idx : LongInt);
     cdecl; external LuaLibName;
     
@@ -406,6 +412,7 @@
 (*
 ** garbage-collection functions and options
 *)
+
 const
     LUA_GCSTOP       = 0;
     LUA_GCRESTART    = 1;
@@ -415,7 +422,7 @@
     LUA_GCSTEP       = 5;
     LUA_GCSETPAUSE   = 6;
     LUA_GCSETSTEPMUL = 7;
-
+   
 function lua_gc(L : Plua_State; what, data : LongInt) : LongInt;
     cdecl; external LuaLibName;
 
--- a/hedgewars/SDLh.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/SDLh.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -244,7 +244,11 @@
     SDL_SRCCOLORKEY = $00001000;
     SDL_RLEACCEL    = $00004000;
     SDL_SRCALPHA    = $00010000;
+ {$IFDEF PAS2C}
+    SDL_ANYFORMAT   = $10000000;
+ {$ELSE}
     SDL_ANYFORMAT   = $00100000;
+ {$ENDIF}
     SDL_HWPALETTE   = $20000000;
     SDL_DOUBLEBUF   = $40000000;
     SDL_FULLSCREEN  = $80000000;
@@ -387,7 +391,7 @@
 {$ENDIF}
         end;
 
-    TSDL_eventaction = (SDL_ADDEVENT, SDL_PEEPEVENT, SDL_GETEVENT);
+    TSDL_eventaction = (SDL_ADDEVENT, SDL_PEEKEVENT, SDL_GETEVENT);
 
     PSDL_Surface = ^TSDL_Surface;
     TSDL_Surface = record
@@ -397,6 +401,16 @@
         pitch : {$IFDEF SDL13}LongInt{$ELSE}Word{$ENDIF};
         pixels: Pointer;
         offset: LongInt;
+{$IFDEF PAS2C}
+	hwdata:Pointer;
+	clip_rect:TSDL_Rect;
+        unsed1:LongWord;
+        locked:LongWord;
+        map:Pointer;
+        format_version:Longword;
+        refcount:LongInt;
+{$ELSE}
+		      
 {$IFDEF SDL13}
         userdata: Pointer;
         locked: LongInt;
@@ -405,6 +419,7 @@
         map: Pointer;
         refcount: LongInt;
 {$ENDIF}
+{$ENDIF}
         end;
 
 
@@ -747,6 +762,7 @@
 
     TByteArray = array[0..65535] of Byte;
     PByteArray = ^TByteArray;
+
     TLongWordArray = array[0..16383] of LongWord;
     PLongWordArray = ^TLongWordArray;
 
@@ -1109,22 +1125,31 @@
     SDL_EnableKeyRepeat:= 0;
 end;
 {$ELSE}
-const conversionFormat: TSDL_PixelFormat = (
+const convFormat:TSDL_PixelFormat = (
         palette: nil; BitsPerPixel: 32; BytesPerPixel: 4;
         Rloss: 0; Gloss: 0; Bloss: 0; Aloss: 0;
         Rshift: RShift; Gshift: GShift; Bshift: BShift; Ashift: AShift;
+
+        //TODO: FIXME in pas2c
+        {$IFDEF WEBGL}
+        Rmask: RMask; Gmask: GMask; Bmask: BMask; Amask: AMask;
+        {$ELSE}
         RMask: RMask; GMask: GMask; BMask: BMask; AMask: AMask;
-        colorkey: 0; alpha: 255);
+        colorkey: 0; alpha: 255
+        {$ENDIF}
+        );
 
 function SDL_AllocFormat(format: LongWord): PSDL_PixelFormat;
 begin
     format:= format;
-    SDL_AllocFormat:= @conversionFormat;
+    SDL_AllocFormat:= @convFormat;
 end;
 
 procedure SDL_FreeFormat(pixelformat: PSDL_PixelFormat);
 begin
+   {$IFNDEF PAS2C}
     pixelformat:= pixelformat;  // avoid hint
+   {$ENDIF}
 end;
 {$ENDIF}
 
@@ -1134,7 +1159,7 @@
 {$IFDEF SDL13}
         ((surface^.flags and SDL_RLEACCEL) <> 0)
 {$ELSE}
-        ( surface^.offset <> 0 ) or (( surface^.flags and (SDL_HWSURFACE or SDL_ASYNCBLIT or SDL_RLEACCEL)) <> 0)
+        {$IFNDEF WEBGL}( surface^.offset <> 0 ) or {$ENDIF}(( surface^.flags and (SDL_HWSURFACE or SDL_ASYNCBLIT or SDL_RLEACCEL)) <> 0)
 {$ENDIF}
 end;
 
--- a/hedgewars/VGSHandlers.inc	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/VGSHandlers.inc	Sun Nov 11 17:15:19 2012 +0100
@@ -197,7 +197,9 @@
 ////////////////////////////////////////////////////////////////////////////////
 procedure doStepLineTrail(Gear: PVisualGear; Steps: Longword);
 begin
+{$IFNDEF PAS2C}
 Steps := Steps;
+{$ENDIF}
 if Gear^.Timer <= Steps then
     DeleteVisualGear(Gear)
 else
@@ -464,7 +466,9 @@
     b: boolean;
     t: LongInt;
 begin
+{$IFNDEF PAS2C}
 Steps:= Steps; // avoid compiler hint
+{$ENDIF}
 
 for t:= 0 to Pred(TeamsCount) do
     with thexchar[t] do
@@ -532,7 +536,10 @@
 
 procedure doStepSpeechBubble(Gear: PVisualGear; Steps: Longword);
 begin
+
+{$IFNDEF PAS2C}
 Steps:= Steps; // avoid compiler hint
+{$ENDIF}
 
 with Gear^.Hedgehog^ do
     if SpeechGear <> nil then
--- a/hedgewars/adler32.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/adler32.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -2,8 +2,8 @@
 
 {ZLib - Adler32 checksum function}
 
-
 interface
+uses uTypes;
 
 (*************************************************************************
 
@@ -66,7 +66,7 @@
 Also, the structure was removed to simplify C conversion
 *)
 
-function Adler32Update ( var adler     :longint; Msg     :pointer; Len     :longint ) : longint;
+function Adler32Update (var adler : longint; Msg     :Pointer; Len     :longint ) : longint;
 
 implementation
 
@@ -124,17 +124,19 @@
 end;
 *)
 
-function Adler32Update(var adler: longint; Msg: pointer; Len :longint) : longint;
+function Adler32Update(var adler:longint; Msg: Pointer; Len :longint) : longint;
     {-update Adler32 with Msg data}
     const
         BASE = 65521; {max. prime < 65536 }
         NMAX = 3854; {max. n with 255n(n+1)/2 + (n+1)(BASE-1) < 2^31}
     var
-        s1, s2: longint;
-        i, n: integer;
+        s1, s2 : longint;
+        i, n   : integer;
+       m       : PByte;
     begin
-        s1 := adler and $FFFF;
-        s2 := adler shr 16;
+        m  := PByte(Msg);
+        s1 := Longword(adler) and $FFFF;
+        s2 := Longword(adler) shr 16;
         while Len>0 do
             begin
             if Len<NMAX then
@@ -144,8 +146,8 @@
 
             for i := 1 to n do
                 begin
-                inc(s1, pByte(Msg)^);
-                inc(Msg);
+                inc(s1, m^);
+                inc(m);
                 inc(s2, s1);
                 end;
             s1 := s1 mod BASE;
--- a/hedgewars/hwengine.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/hwengine.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -19,7 +19,7 @@
 {$INCLUDE "options.inc"}
 
 {$IFDEF WIN32}
-{$R res/hwengine.rc}
+{$R hwengine.rc}
 {$ENDIF}
 
 {$IFDEF HWLIBRARY}
@@ -30,14 +30,14 @@
 {$ENDIF}
 
 uses SDLh, uMisc, uConsole, uGame, uConsts, uLand, uAmmos, uVisualGears, uGears, uStore, uWorld, uInputHandler,
-     uSound, uScript, uTeams, uStats, uIO, uLocale, uChat, uAI, uAIMisc, uAILandMarks, uLandTexture, uCollisions,
-     SysUtils, uTypes, uVariables, uCommands, uUtils, uCaptions, uDebug, uCommandHandlers, uLandPainted
+     uSound, uScript, uTeams, uStats, uIO, uLocale, uChat, uAI, uAIMisc, uLandTexture, uCollisions, uAILandMarks,
+     SysUtils, uTypes, uVariables, uCommands, uUtils, uCaptions, uDebug, uCommandHandlers, uLandPainted, uFloat
      {$IFDEF USE_VIDEO_RECORDING}, uVideoRec {$ENDIF}
+     {$IFDEF WEBGL}, uWeb{$ENDIF}
      {$IFDEF USE_TOUCH_INTERFACE}, uTouch {$ENDIF}
      {$IFDEF ANDROID}, GLUnit{$ENDIF}
      ;
 
-
 {$IFDEF HWLIBRARY}
 procedure preInitEverything();
 procedure initEverything(complete:boolean);
@@ -52,9 +52,23 @@
 procedure freeEverything(complete:boolean); forward;
 {$ENDIF}
 
+{$IFDEF WEBGL}
+procedure playFile(path: PChar); forward;
+function isEngineRunning():Integer; forward;
+procedure shutdown();forward;
+function getRealTicks():Integer; forward;
+procedure mainhook(); forward;
+var
+    args: array[0..3] of PChar;
+    PrevTime, CurrTime: LongInt;
+    isTerminated: boolean;
+    prevFocusState: boolean;
+    isRunning : boolean;
+{$ENDIF}
+
 ///////////////////////////////////////////////////////////////////////////////
 function DoTimer(Lag: LongInt): boolean;
-var s: shortstring;
+var s : shortstring;
 begin
     DoTimer:= false;
     inc(RealTicks, Lag);
@@ -90,7 +104,11 @@
             end;
         gsConfirm, gsGame:
             begin
-            DrawWorld(Lag);
+{$IFDEF WEBGL}
+            drawworld_hook();
+{$ELSE}
+            DrawWorld(Lag); // never place between ProcessKbd and DoGameTick - bugs due to /put cmd and isCursorVisible
+{$ENDIF}
             DoGameTick(Lag);
             ProcessVisualGears(Lag);
             end;
@@ -143,18 +161,26 @@
 ///////////////////////////////////////////////////////////////////////////////
 procedure MainLoop;
 var event: TSDL_Event;
-    PrevTime, CurrTime: Longword;
+{$IFNDEF WEBGL}
+    PrevTime, CurrTime: LongInt;
     isTerminated: boolean;
 {$IFDEF SDL13}
     previousGameState: TGameState;
 {$ELSE}
     prevFocusState: boolean;
 {$ENDIF}
+
+{$ENDIF}
+
 begin
+
+{$IFNDEF WEBGL}
     isTerminated:= false;
     PrevTime:= SDL_GetTicks;
     while isTerminated = false do
     begin
+{$ENDIF}
+
         SDL_PumpEvents();
  
         while SDL_PeepEvents(@event, 1, SDL_GETEVENT, {$IFDEF SDL13}SDL_FIRSTEVENT, SDL_LASTEVENT{$ELSE}SDL_ALLEVENTS{$ENDIF}) > 0 do
@@ -271,12 +297,24 @@
         CurrTime:= SDL_GetTicks();
         if PrevTime + longword(cTimerInterval) <= CurrTime then
         begin
-            isTerminated := isTerminated or DoTimer(CurrTime - PrevTime);
-            PrevTime:= CurrTime
+            isTerminated:= isTerminated or DoTimer(CurrTime - PrevTime);
+            PrevTime:= CurrTime;
+            {$IFDEF WEBGL}
+            if not isTerminated then
+                mainloop_hook();
+            else
+            begin
+                freeEverything(true);
+                isRunning := false;
+            end
+            {$ENDIF}
         end
-        else SDL_Delay(1);
+        else {$IFNDEF WEBGL}SDL_Delay(1){$ELSE}mainloop_hook(){$ENDIF};
         IPCCheckSock();
+
+{$IFNDEF WEBGL}
     end;
+{$ENDIF}
 end;
 
 {$IFDEF USE_VIDEO_RECORDING}
@@ -317,6 +355,10 @@
 var p: TPathType;
     s: shortstring;
     i: LongInt;
+{$IFDEF WEBGL}
+    l:TResourceList;
+{$ENDIF}
+
 begin
 {$IFDEF HWLIBRARY}
     preInitEverything();
@@ -409,7 +451,7 @@
     ScriptOnGameInit;
     s:= 'eproto ' + inttostr(cNetProtoVersion);
     SendIPCRaw(@s[0], Length(s) + 1); // send proto version
-
+	
     InitTeams();
     AssignStores();
 
@@ -424,13 +466,27 @@
 
 {$IFDEF USE_VIDEO_RECORDING}
     if GameType = gmtRecord then
-        RecorderMainLoop()
-    else
+    begin
+        RecorderMainLoop();
+        freeEverything(true);
+        exit;
+    end;
 {$ENDIF}
-        MainLoop();
-
+	
+{$IFDEF WEBGL}
+    l := generateResourceList();
+    clear_filelist_hook();
+    for i:= 0 to l.count - 1 do
+    add_file_hook(PChar(l.files[i] + '.png'));
+    isTerminated := false;
+    isRunning := true;
+    PrevTime := SDL_GetTicks();
+    idb_loader_hook();
+{$ELSE}
+    MainLoop;
     // clean up all the memory allocated
     freeEverything(true);
+{$ENDIF}
 end;
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -604,7 +660,18 @@
 ///////////////////////////////////////////////////////////////////////////////
 /////////////////////////////////// m a i n ///////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////
+{$IFDEF WEBGL}
+procedure hwmain(argc:Integer; argv:PPChar);
+{$ENDIF}
 begin
+{$IFDEF PAS2C}
+    // workaround for pascal's ParamStr and ParamCount
+    init(argc, argv);
+{$IFDEF WEBGL}
+    // patch emscripten's SDL implementation
+    SDL_InitPatch();
+{$ENDIF}
+{$ENDIF}
     preInitEverything();
     GetParams();
 
@@ -615,6 +682,62 @@
     else Game();
 
     // return 1 when engine is not called correctly
-    halt(LongInt(GameType = gmtSyntax));
+    {$IFDEF PAS2C}
+       {$IFNDEF WEBGL}
+       exit(LongInt(GameType = gmtSyntax));
+       {$ENDIF}
+    {$ELSE}
+       halt(LongInt(GameType = gmtSyntax));
+    {$ENDIF}
+
+
+{$IFDEF WEBGL}
+end;
+
+// hook
+procedure playFile(path: PChar);
+begin
+    args[0] := PChar('');
+    args[1] := PChar('');
+    args[2] := PChar('Data');
+    args[3] := path;
+    hwmain(4, args);
+end;
+
+// hook
+function isEngineRunning:Integer;
+begin
+    isEngineRunning := isRunning;
+end;
+
+// hook
+procedure shutdown;
+begin
+    GameState := gsExit;
+end;
+
+// hook
+function getRealTicks():Integer;
+begin
+    getRealTicks := RealTicks;
+end;
+
+// main
+begin
+    isRunning := false;
+
+    // avoid hooks to be eliminated by optimizer
+    if argc = 1234 then
+    begin
+        mainhook();
+        isRunning := isEngineRunning();
+        playFile(argv);
+        argc := getRealTicks();
+        DrawWorld(argc);
+        MainLoop;
+        shutdown;
+    end
+{$ENDIF}
+
 {$ENDIF}
 end.
--- a/hedgewars/options.inc	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/options.inc	Sun Nov 11 17:15:19 2012 +0100
@@ -29,6 +29,13 @@
 
 {$DEFINE USE_LUA_SCRIPT}
 
+{$IF DEFINED(WEBGL) AND NOT DEFINED(PAS2C)}
+{$UNDEF WEBGL}
+{$ENDIF}
+
+{$IFDEF WEBGL}
+{$DEFINE GL2}
+{$ENDIF}
 
 {$IFDEF ANDROID}
     {$DEFINE MOBILE}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hedgewars/pas2cRedo.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -0,0 +1,111 @@
+redo;
+{This file contains functions that are re-implemented}
+{pas2c will add prefix fpcrtl_ to all these functions}
+type 
+    uinteger = uinteger;
+    Integer = integer;
+    LongInt = integer;
+    LongWord = uinteger;
+    Cardinal = uinteger;
+    PtrInt = integer;
+    Word = uinteger;
+    Byte = integer;
+    SmallInt = integer;
+    ShortInt = integer;
+    QWord = uinteger;
+    GLint = integer;
+    GLuint = integer;
+    int = integer;
+    size_t = integer;
+
+    pointer = pointer;
+
+    float = float;
+    single = float;
+    double = float;
+    real = float;
+    extended = float;
+    GLfloat = float;
+
+    boolean = boolean;
+    LongBool = boolean;
+
+    string = string;
+    shortstring = string;
+    ansistring = string;
+    widechar = string;
+
+    char = char;
+    PChar = ^char;
+    PPChar = ^Pchar;
+    
+    PByte = ^Byte;
+    PLongInt = ^LongInt;
+    PLongWord = ^LongWord;
+    PInteger = ^Integer;
+    
+    Handle = integer;
+
+var
+    write, writeLn, read, readLn, flush: procedure;
+
+    halt:procedure;
+
+    GetEnumName:function:shortstring;
+    TypeInfo:function:Integer;
+
+    lo:function:Integer;
+
+    init:procedure;
+
+    StrLen:function : integer;
+    odd, even : function : boolean;
+
+    Length : function : integer;
+
+    Now : function : integer;
+
+    new, dispose, FillChar, Move : procedure;
+
+    trunc, round : function : integer;
+    abs, sqr : function : integer;
+
+    StrPas, FormatDateTime, copy, delete, str, pos, PosS, trim, LowerCase : function : shortstring;
+    StrToInt : function : integer;
+    SetLength, val : procedure;
+    _pchar : function : PChar;
+    pchar2str : function : string;
+    memcpy : procedure;
+
+	     min, max:function:integer;
+    assign, rewrite, rewrite_2, reset, reset_2, flush, BlockWrite, BlockRead, close : procedure;
+    FileExists, DirectoryExists, eof : function : boolean;
+    ExtractFileName : function : string;
+    
+    ParamCount : function : integer;
+    ParamStr : function : string;
+
+    arctan2, power: function : float;
+
+    //TypeInfo, GetEnumName : function : shortstring;
+
+    UTF8ToUnicode, WrapText: function : shortstring;
+
+    GetMem : function : pointer;
+    FreeMem : procedure;
+
+    BeginThread, ThreadSwitch : procedure;
+    InterlockedIncrement, InterlockedDecrement : procedure;
+
+    random : function : integer;
+    randomize : procedure;
+    
+    Assigned : function : boolean;
+
+    //EnumToStr : function : string;
+
+    initParams : procedure;
+    
+    Load_GL_VERSION_2_0 : procedure;
+
+
--- a/hedgewars/pas2cSystem.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/pas2cSystem.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -1,18 +1,21 @@
 system;
 
 type 
+    uinteger = uinteger;
     Integer = integer;
     LongInt = integer;
-    LongWord = integer;
-    Cardinal = integer;
+    LongWord = uinteger;
+    Cardinal = uinteger;
     PtrInt = integer;
-    Word = integer;
+    Word = uinteger;
     Byte = integer;
     SmallInt = integer;
     ShortInt = integer;
-    QWord = integer;
+    QWord = uinteger;
     GLint = integer;
     GLuint = integer;
+    GLenum = integer;
+
     int = integer;
     size_t = integer;
 
@@ -51,51 +54,22 @@
 var 
     false, true: boolean;
     
-    write, writeLn, read, readLn: procedure;
-    
-    StrLen, ord, Succ, Pred : function : integer;
+    ord, Succ, Pred : function : integer;
     inc, dec, Low, High, Lo, Hi : function : integer;
-    odd, even : function : boolean;
-
-    Now : function : integer;
-
-    new, dispose, FillChar, Move : procedure;
 
-    trunc, round : function : integer;
-    abs, sqr : function : integer;
-
-    StrPas, FormatDateTime, copy, delete, str, pos, trim, LowerCase : function : shortstring;
-    Length, StrToInt : function : integer;
-    SetLength, val : procedure;
-    _pchar : function : PChar;
-    pchar2str : function : string;
-    memcpy : procedure;
-
-    assign, rewrite, reset, flush, BlockWrite, BlockRead, close : procedure;
     IOResult : integer;
     exit, break, halt, continue : procedure;
-    TextFile, file : Handle;
+
+    TextFile, File : Handle;
     FileMode : integer;
-    FileExists, DirectoryExists, eof : function : boolean;
-    ExtractFileName : function : string;
     exitcode : integer;
     stdout, stderr : Handle;
-    
-    ParamCount : function : integer;
-    ParamStr : function : string;
 
-    sqrt, arctan2, cos, sin, power : function : float;
+    sqrt, cos, sin: function : float;
     pi : float;
 
-    TypeInfo, GetEnumName : function : shortstring;
-
-    UTF8ToUnicode, WrapText: function : shortstring;
-
     sizeof : function : integer;
 
-    GetMem : function : pointer;
-    FreeMem : procedure;
-   
     glGetString : function : pchar;
  
     glBegin, glBindTexture, glBlendFunc, glClear, glClearColor,
@@ -110,7 +84,15 @@
     glDeleteFramebuffersEXT, glGenFramebuffersEXT,
     glGenRenderbuffersEXT, glBindFramebufferEXT, 
     glBindRenderbufferEXT, glRenderbufferStorageEXT,
-    glFramebufferRenderbufferEXT, glFramebufferTexture2DEXT : procedure;
+    glFramebufferRenderbufferEXT, glFramebufferTexture2DEXT,
+    glUniformMatrix4fv, glVertexAttribPointer, glCreateShader,
+    glShaderSource, glCompileShader, glGetShaderiv, glGetShaderInfoLog,
+    glCreateProgram, glAttachShader, glBindAttribLocation, glLinkProgram,
+    glDeleteShader, glGetProgramiv, glGetProgramInfoLog, glUseProgram,
+    glUniform1i, glGetUniformLocation, glEnableVertexAttribArray,
+    glGetError, glDeleteProgram, glDeleteBuffers,
+    glGenBuffers, glBufferData, glBindBuffer, glewInit,
+    glUniform4f, glDisableVertexAttribArray : procedure;
 
     GL_BGRA, GL_BLEND, GL_CLAMP_TO_EDGE, GL_COLOR_ARRAY,
     GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_DEPTH_COMPONENT,
@@ -124,16 +106,12 @@
     GL_TEXTURE_WRAP_T, GL_TRIANGLE_FAN, GL_TRUE, GL_VENDOR,
     GL_VERSION, GL_VERTEX_ARRAY, GLenum,  GL_FRAMEBUFFER_EXT,
     GL_RENDERBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
-    GL_COLOR_ATTACHMENT0_EXT, GL_FLOAT, GL_UNSIGNED_BYTE : integer;
+    GL_COLOR_ATTACHMENT0_EXT, GL_FLOAT, GL_UNSIGNED_BYTE, GL_COMPILE_STATUS,
+    GL_INFO_LOG_LENGTH, GL_LINK_STATUS, GL_VERTEX_SHADER, GL_FRAGMENT_SHADER,
+    GL_NO_ERROR, GL_ARRAY_BUFFER, GL_STATIC_DRAW, GLEW_OK,
+    GL_AUX_BUFFERS: integer;
 
     TThreadId : function : integer;
-    BeginThread, ThreadSwitch : procedure;
-    InterlockedIncrement, InterlockedDecrement : procedure;
-    
-    random : function : integer;
-    randomize : procedure;
-    
-    Assigned : function : boolean;
     
     _strconcat, _strappend, _strprepend, _chrconcat : function : string;
     _strcompare, _strncompare, _strcomparec : function : boolean;
@@ -144,5 +122,7 @@
     png_write_row, png_set_ihdr, png_write_info,
     png_write_end : procedure;
 
-    EnumToStr : function : string;
+    clear_filelist_hook, add_file_hook, idb_loader_hook, mainloop_hook, drawworld_hook : procedure;
+    SDL_InitPatch : procedure;
 
+  
--- a/hedgewars/uAI.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uAI.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -33,6 +33,11 @@
     uAmmos, SysUtils{$IFNDEF USE_SDLTHREADS} {$IFDEF UNIX}, cthreads{$ENDIF} {$ENDIF}, uTypes,
     uVariables, uCommands, uUtils, uDebug, uAILandMarks;
 
+{$IFDEF AI_MAINTHREAD}
+const
+    mainThreadMaxThinkTime:Integer = 1500;
+{$ENDIF}
+
 var BestActions: TActions;
     CanUseAmmo: array [TAmmoType] of boolean;
     StopThinking: boolean;
@@ -42,7 +47,7 @@
     ThinkThread: TThreadID;
 {$ENDIF}
     hasThread: LongInt;
-    StartTicks: Longword;
+    StartTicks: LongInt;
 
 procedure FreeActionsList;
 begin
@@ -330,7 +335,7 @@
                 end;
 
             // 'not CanGO' means we can't go straight, possible jumps are checked above
-            if not CanGo then
+            if (not CanGo) then
                 break;
             
              inc(steps);
@@ -357,6 +362,15 @@
                 
             if GoInfo.FallPix >= FallPixForBranching then
                 Push(ticks, Actions, Me^, Me^.Message xor 3); // aia_Left xor 3 = aia_Right
+
+{$IFDEF AI_MAINTHREAD}
+            if StartTicks < (SDL_GetTicks() - mainThreadMaxThinkTime) then
+                StopThinking := true;
+{$ELSE}
+            if (StartTicks > GameTicks - 1500) and (not StopThinking) then
+                SDL_Delay(1000);
+{$ENDIF}
+
             end {while};
 
         if BestRate > BaseRate then
@@ -368,12 +382,18 @@
 function Think(Me: Pointer): ptrint;
 var BackMe, WalkMe: TGear;
     switchCount: LongInt;
-    StartTicks, currHedgehogIndex, itHedgehog, switchesNum, i: Longword;
+    currHedgehogIndex, itHedgehog, switchesNum, i: Longword;
     switchImmediatelyAvailable: boolean;
     Actions: TActions;
 begin
 InterlockedIncrement(hasThread);
+
+{$IFDEF AI_MAINTHREAD}
+StartTicks:= SDL_GetTicks();
+{$ELSE}
 StartTicks:= GameTicks;
+{$ENDIF}
+
 currHedgehogIndex:= CurrentTeam^.CurrHedgehog;
 itHedgehog:= currHedgehogIndex;
 switchesNum:= 0;
@@ -383,7 +403,7 @@
     switchCount:= HHHasAmmo(PGear(Me)^.Hedgehog^, amSwitch)
 else switchCount:= 0;
 
-if (PGear(Me)^.State and gstAttacked) = 0 then
+if (PGear(Me)^.State and gstAttacking) = 0 then
     if Targets.Count > 0 then
         begin
         // iterate over current team hedgehogs
@@ -395,7 +415,7 @@
             Actions.Score:= 0;
             if switchesNum > 0 then
                 begin
-                if not switchImmediatelyAvailable  then
+                if (not switchImmediatelyAvailable)  then
                     begin
                     // when AI has to use switcher, make it cost smth unless they have a lot of switches
                     if (switchCount < 10) then Actions.Score:= (-27+switchCount*3)*4000;
@@ -420,8 +440,13 @@
             or (itHedgehog = currHedgehogIndex)
             or BestActions.isWalkingToABetterPlace;
 
-        if (StartTicks > GameTicks - 1500) and (not StopThinking) then
-            SDL_Delay(1000);
+            {$IFDEF AI_MAINTHREAD}
+                if StartTicks < (SDL_GetTicks() - mainThreadMaxThinkTime) then
+                    StopThinking := true;
+            {$ELSE}
+                if (StartTicks > GameTicks - 1500) and (not StopThinking) then
+                    SDL_Delay(1000);
+            {$ENDIF}
 
         if (BestActions.Score < -1023) and (not BestActions.isWalkingToABetterPlace) then
             begin
@@ -433,22 +458,29 @@
 else
     begin
     BackMe:= PGear(Me)^;
+    
+//{$IFNDEF AI_MAINTHREAD}
     while (not StopThinking) and (BestActions.Count = 0) do
         begin
+
 (*
         // Maybe this would get a bit of movement out of them? Hopefully not *toward* water. Need to check how often he'd choose that strategy
         if SuddenDeathDmg and ((hwRound(BackMe.Y)+cWaterRise*2) > cWaterLine) then
             AddBonus(hwRound(BackMe.X), hwRound(BackMe.Y), 250, -40);
 *)
+
         FillBonuses(true);
         WalkMe:= BackMe;
         Actions.Count:= 0;
         Actions.Pos:= 0;
         Actions.Score:= 0;
         Walk(@WalkMe, Actions);
-        if not StopThinking then
+{$IFNDEF AI_MAINTHREAD}
+        if (not StopThinking) then
             SDL_Delay(100)
+{$ENDIF}
         end
+//{$ENDIF}
     end;
 
 PGear(Me)^.State:= PGear(Me)^.State and (not gstHHThinking);
@@ -484,12 +516,17 @@
 
 FillBonuses((Me^.State and gstAttacked) <> 0);
 AddFileLog('Enter Think Thread');
+
+{$IFDEF AI_MAINTHREAD}
+Think(Me);
+{$ELSE}
 {$IFDEF USE_SDLTHREADS}
 ThinkThread := SDL_CreateThread(@Think{$IFDEF SDL13}, nil{$ENDIF}, Me);
 {$ELSE}
 BeginThread(@Think, Me, ThinkThread);
 {$ENDIF}
 AddFileLog('Thread started');
+{$ENDIF}
 end;
 
 //var scoreShown: boolean = false;
@@ -536,7 +573,9 @@
 begin
     hasThread:= 0;
     StartTicks:= 0;
+{$IFNDEF PAS2C}
     ThinkThread:= ThinkThread;
+{$ENDIF}
 end;
 
 procedure freeModule;
--- a/hedgewars/uAIAmmoTests.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uAIAmmoTests.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -704,7 +704,7 @@
     Targ:= Targ; // avoid compiler hint
 
     if Level < 3 then trackFall:= afTrackFall
-    else trackFall:= 0;
+        else trackFall:= 0;
 
     ap.ExplR:= 0;
     ap.Time:= 0;
@@ -1047,7 +1047,7 @@
             begin
             maxTop := Targ.Y - cHHRadius * 2;
             
-            while not TestColl(Targ.X, maxTop, cHHRadius) and (maxTop > topY + cHHRadius * 2 + 1) do
+            while (not TestColl(Targ.X, maxTop, cHHRadius)) and (maxTop > topY + cHHRadius * 2 + 1) do
                 dec(maxTop, cHHRadius*2);
             if not TestColl(Targ.X, maxTop + cHHRadius, cHHRadius) then
                 begin
--- a/hedgewars/uAIMisc.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uAIMisc.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -49,7 +49,17 @@
     X, Y: LongInt;
     Radius: LongInt;
     Score: LongInt;
-    end;
+	 end;
+
+Tbonuses = record
+	      Count : Longword;
+	      ar    : array[0..Pred(MAXBONUS)] of TBonus;
+	   end;
+
+Twalkbonuses =  record
+        Count: Longword;
+        ar: array[0..Pred(MAXBONUS div 8)] of TBonus;  // don't use too many
+        end;
 
 procedure initModule;
 procedure freeModule;
@@ -77,15 +87,9 @@
 var ThinkingHH: PGear;
     Targets: TTargets;
 
-    bonuses: record
-        Count: Longword;
-        ar: array[0..Pred(MAXBONUS)] of TBonus;
-        end;
+    bonuses: Tbonuses;
 
-    walkbonuses: record
-        Count: Longword;
-        ar: array[0..Pred(MAXBONUS div 8)] of TBonus;  // don't use too many
-        end;
+    walkbonuses: Twalkbonuses;
 
 const KillScore = 200;
 var friendlyfactor: LongInt = 300;
@@ -353,7 +357,7 @@
         y:= y + dY;
         dY:= dY + cGravityf;
         skipLandCheck:= skipLandCheck and (r <> 0) and (abs(eX-x) + abs(eY-y) < r) and ((abs(eX-x) < rCorner) or (abs(eY-y) < rCorner));
-        if not skipLandCheck and TestCollWithLand(trunc(x), trunc(y), cHHRadius) then
+        if (not skipLandCheck) and TestCollWithLand(trunc(x), trunc(y), cHHRadius) then
         begin
             if 0.4 < dY then
             begin
--- a/hedgewars/uAmmos.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uAmmos.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -257,7 +257,7 @@
             Ammo^[Slot, ami]:= Ammo^[Slot, ami + 1];
             Ammo^[Slot, ami + 1].Count:= 0
             end;
-    until not b;
+    until (not b);
 AmmoMenuInvalidated:= true;
 end;
 
--- a/hedgewars/uCaptions.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uCaptions.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -30,8 +30,6 @@
 procedure initModule;
 procedure freeModule;
 
-implementation
-uses uTextures, uRenderUtils, uVariables, uRender;
 
 type TCaptionStr = record
     Tex: PTexture;
@@ -42,8 +40,13 @@
 var
     Captions: array[TCapGroup] of TCaptionStr;
 
+implementation
+uses uTextures, uRenderUtils, uVariables, uRender;
+
 procedure AddCaption(s: shortstring; Color: Longword; Group: TCapGroup);
 begin
+    if Length(s) = 0 then
+        exit;
     if Captions[Group].Text <> s then
         begin
         FreeTexture(Captions[Group].Tex);
--- a/hedgewars/uChat.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uChat.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -211,7 +211,7 @@
 else if (s[1] = '-') and (s[Length(s)] = '-') then
     x:= 3;
     
-if not CurrentTeam^.ExtDriven and (x <> 0) then
+if (not CurrentTeam^.ExtDriven) and (x <> 0) then
     for c:= 0 to Pred(TeamsCount) do
         if (TeamsArray[c] = CurrentTeam) then
             t:= c;
--- a/hedgewars/uCommandHandlers.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uCommandHandlers.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -185,37 +185,37 @@
 
 procedure chCurD_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 CursorMovementY:= 0;
 end;
 
 procedure chCurL_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 CursorMovementX:= -1;
 end;
 
 procedure chCurL_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 CursorMovementX:= 0;
 end;
 
 procedure chCurR_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 CursorMovementX:= 1;
 end;
 
 procedure chCurR_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 CursorMovementX:= 0;
 end;
 
 procedure chLeft_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -228,7 +228,7 @@
 
 procedure chLeft_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH then
     exit;
 if not isExternalSource then
@@ -240,7 +240,7 @@
 
 procedure chRight_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -253,7 +253,7 @@
 
 procedure chRight_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH then
     exit;
 if not isExternalSource then
@@ -265,7 +265,7 @@
 
 procedure chUp_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -278,7 +278,7 @@
 
 procedure chUp_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH then
     exit;
 if not isExternalSource then
@@ -290,7 +290,7 @@
 
 procedure chDown_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -303,7 +303,7 @@
 
 procedure chDown_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH then
     exit;
 if not isExternalSource then
@@ -315,7 +315,7 @@
 
 procedure chPrecise_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -328,7 +328,7 @@
 
 procedure chPrecise_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH then
     exit;
 if not isExternalSource then
@@ -340,7 +340,7 @@
 
 procedure chLJump(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -353,7 +353,7 @@
 
 procedure chHJump(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -366,7 +366,7 @@
 
 procedure chAttack_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 bShowFinger:= false;
@@ -386,7 +386,7 @@
 
 procedure chAttack_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH then
     exit;
 with CurrentHedgehog^.Gear^ do
@@ -401,7 +401,7 @@
 
 procedure chSwitch(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 if not isExternalSource then
@@ -413,9 +413,10 @@
 end;
 
 procedure chNextTurn(var s: shortstring);
-var gi: PGear;
+var i  : Longword;
+    gi : PGear;
 begin
-    s:= s; // avoid compiler hint
+    s:=s; // avoid compiler hint
 
     TryDo(AllInactive, '/nextturn called when not all gears are inactive', true);
 
@@ -522,13 +523,13 @@
 
 procedure chPut(var s: shortstring);
 begin
-    s:= s; // avoid compiler hint
+    s:=s; // avoid compiler hint
     doPut(0, 0, false);
 end;
 
 procedure chCapture(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 flagMakeCapture:= true
 end;
 
@@ -586,7 +587,7 @@
 
 procedure chAmmoMenu(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH then
     bShowAmmoMenu:= true
 else
@@ -611,19 +612,19 @@
 
 procedure chVol_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 inc(cVolumeDelta, 3)
 end;
 
 procedure chVol_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 dec(cVolumeDelta, 3)
 end;
 
 procedure chFindhh(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if CheckNoTeamOrHH or isPaused then
     exit;
 
@@ -645,7 +646,7 @@
 
 procedure chPause(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if gameType <> gmtNet then
     isPaused:= not isPaused;
 
@@ -657,7 +658,7 @@
 
 procedure chRotateMask(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 if ((GameFlags and gfInvulnerable) = 0) then
     cTagsMask:= cTagsMasks[cTagsMask]
 else
@@ -666,34 +667,34 @@
 
 procedure chSpeedup_p(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 SpeedStart:= RealTicks;
 isSpeed:= true
 end;
 
 procedure chSpeedup_m(var s: shortstring);
 begin
-s:= s; // avoid compiler hint
+s:=s; // avoid compiler hint
 isSpeed:= false
 end;
 
 procedure chZoomIn(var s: shortstring);
 begin
-    s:= s; // avoid compiler hint
+    s:=s; // avoid compiler hint
     if ZoomValue < cMinZoomLevel then
         ZoomValue:= ZoomValue + cZoomDelta;
 end;
 
 procedure chZoomOut(var s: shortstring);
 begin
-    s:= s; // avoid compiler hint
+    s:=s; // avoid compiler hint
     if ZoomValue > cMaxZoomLevel then
         ZoomValue:= ZoomValue - cZoomDelta;
 end;
 
 procedure chZoomReset(var s: shortstring);
 begin
-    s:= s; // avoid compiler hint
+    s:=s; // avoid compiler hint
     ZoomValue:= cDefaultZoomLevel;
 end;
 
--- a/hedgewars/uConsts.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uConsts.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -149,7 +149,7 @@
     cBlowTorchC    = 6;
     cakeDmg =   75;
 
-    cKeyMaxIndex = 1023;
+    cKeyMaxIndex = 1600;
     cKbdMaxIndex = 65536;//need more room for the modifier keys
 
     cHHFileName = 'Hedgehog';
--- a/hedgewars/uCursor.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uCursor.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -9,6 +9,10 @@
 
 uses SDLh, uVariables;
 
+{$IFDEF WEBGL}
+var offsetx, offsety : Integer;
+{$ENDIF}
+
 procedure init;
 begin
     SDL_WarpMouse(cScreenWidth div 2, cScreenHeight div 2);
@@ -16,16 +20,33 @@
 
 procedure updatePosition;
 var x, y: LongInt;
+{$IFDEF WEBGL}
+    tx, ty : LongInt;
+{$ENDIF}
 begin
     SDL_GetMouseState(@x, @y);
 
+{$IFDEF WEBGL}
+    tx := x;
+    ty := y;
+    x := x + offsetx;
+    y := y + offsety;
+{$ENDIF}
+
     if(x <> cScreenWidth div 2) or (y <> cScreenHeight div 2) then
         begin
         CursorPoint.X:= CursorPoint.X + x - cScreenWidth div 2;
         CursorPoint.Y:= CursorPoint.Y - y + cScreenHeight div 2;
 
         if cHasFocus then
+            begin
+            {$IFNDEF WEBGL}
             SDL_WarpMouse(cScreenWidth div 2, cScreenHeight div 2);
+            {$ELSE}
+            offsetx := cScreenWidth div 2 - tx;
+            offsety := cScreenHeight div 2 - ty;
+            {$ENDIF}
+            end;
         end
 end;
 
--- a/hedgewars/uFloat.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uFloat.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -55,7 +55,7 @@
     1: (QWordValue : QWord);
     end;
 {$ENDIF}
-
+		  
 // Returns an hwFloat that represents the value of integer parameter i
 function int2hwFloat (const i: LongInt) : hwFloat; inline;
 function hwFloat2Float (const i: hwFloat) : extended; inline;
@@ -221,7 +221,7 @@
     hwFloat2Float:= -hwFloat2Float;
 end;
 
-{$IFNDEF WEB}
+{$IFNDEF WEBGL}
 operator = (const z1, z2: hwFloat) z : boolean; inline;
 begin
     z:= (z1.isNegative = z2.isNegative) and (z1.QWordValue = z2.QWordValue);
@@ -301,7 +301,7 @@
         b:= (z1.QWordValue > z2.QWordValue) <> z2.isNegative
 end;
 {$ENDIF}
-{$IFDEF WEB}
+{$IFDEF WEBGL}
 (*
     Mostly to be kind to JS as of 2012-08-27 where there is no int64/uint64.  This may change though.
 *)
--- a/hedgewars/uGears.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uGears.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -54,7 +54,6 @@
 function  GearByUID(uid : Longword) : PGear;
 procedure doStepDrowningGear(Gear: PGear);
 
-
 implementation
 uses uStore, uSound, uTeams, uRandom, uCollisions, uIO, uLandGraphics,
     uLocale, uAI, uAmmos, uStats, uVisualGears, uScript, GLunit, uMobile, uVariables,
@@ -600,6 +599,7 @@
 var i,rx, ry: Longword;
     rdx, rdy: hwFloat;
     Gear: PGear;
+    temp: Longword;
 begin
 AddGear(0, 0, gtATStartGame, 0, _0, _0, 2000);
 
@@ -643,6 +643,7 @@
 
 if (GameFlags and gfArtillery) <> 0 then
     cArtillery:= true;
+
 for i:= GetRandom(10)+30 downto 0 do
     begin
     rx:= GetRandom(rightX-leftX)+leftX;
@@ -931,7 +932,7 @@
 var GearsNearArray : TPGearArray;
 function GearsNear(X, Y: hwFloat; Kind: TGearType; r: LongInt): PGearArrayS;
 var
-    t: PGear;
+    t  : PGear;
     s: Longword;
 begin
     r:= r*r;
@@ -948,7 +949,7 @@
             GearsNearArray[s - 1] := t;
             end;
         t := t^.NextGear;
-    end;
+	end;
 
     GearsNear.size:= s;
     GearsNear.ar:= @GearsNearArray
--- a/hedgewars/uGearsHedgehog.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uGearsHedgehog.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -1114,7 +1114,7 @@
     exit
     end;
 
-    if not isInMultiShoot and (Hedgehog^.Gear <> nil) then
+    if (not isInMultiShoot) and (Hedgehog^.Gear <> nil) then
         begin
         if GHStepTicks > 0 then
             dec(GHStepTicks);
--- a/hedgewars/uGearsList.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uGearsList.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -83,8 +83,10 @@
 var gear: PGear;
 begin
 inc(GCounter);
+
 AddFileLog('AddGear: #' + inttostr(GCounter) + ' (' + inttostr(x) + ',' + inttostr(y) + '), d(' + floattostr(dX) + ',' + floattostr(dY) + ') type = ' + EnumToStr(Kind));
 
+   
 New(gear);
 FillChar(gear^, sizeof(TGear), 0);
 gear^.X:= int2hwFloat(X);
@@ -525,7 +527,7 @@
             begin
             t:= max(Gear^.Damage, Gear^.Health);
             Gear^.Damage:= t;
-            if ((not SuddenDeathDmg and (WaterOpacity < $FF)) or (SuddenDeathDmg and (WaterOpacity < $FF)))
+            if (((not SuddenDeathDmg) and (WaterOpacity < $FF)) or (SuddenDeathDmg and (WaterOpacity < $FF)))
             and (hwRound(Gear^.Y) < cWaterLine + 256) then
                 spawnHealthTagForHH(Gear, t);
             end;
--- a/hedgewars/uGearsRender.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uGearsRender.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -23,18 +23,21 @@
 interface
 uses uTypes, uConsts, GLunit, uFloat, SDLh;
 
+type
+   Tar	       = record
+		    X, Y: hwFloat;
+		    dLen: hwFloat;
+		    b : boolean;
+		 end; 
+   TRopePoints = record
+		    Count     : Longword;
+		    HookAngle : GLfloat;
+		    ar	      : array[0..MAXROPEPOINTS] of Tar;
+		    rounded   : array[0..MAXROPEPOINTS + 2] of TVertex2f;
+		 end;	      
 procedure RenderGear(Gear: PGear; x, y: LongInt);
 
-var RopePoints: record
-                Count: Longword;
-                HookAngle: GLfloat;
-                ar: array[0..MAXROPEPOINTS] of record
-                                X, Y: hwFloat;
-                                dLen: hwFloat;
-                                b: boolean;
-                                end;
-                rounded: array[0..MAXROPEPOINTS + 2] of TVertex2f;
-                end;
+var RopePoints: TRopePoints;
 
 implementation
 uses uRender, uUtils, uVariables, uAmmos, Math, uVisualGears;
@@ -82,6 +85,7 @@
     if (X1 = X2) and (Y1 = Y2) then
         begin
         //OutError('WARNING: zero length rope line!', false);
+	DrawRopeLine := 0;
         exit
         end;
     eX:= 0;
@@ -1165,7 +1169,7 @@
                         begin
                         if isInLag and (Gear^.FlightTime < 256) then
                             inc(Gear^.FlightTime, 8)
-                        else if not isInLag and (Gear^.FlightTime > 0) then
+                        else if (not isInLag) and (Gear^.FlightTime > 0) then
                             dec(Gear^.FlightTime, 8);
                         if Gear^.FlightTime > 0 then
                             Tint($FF, $FF, $FF, $FF-min(255,Gear^.FlightTime));
--- a/hedgewars/uGearsUtils.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uGearsUtils.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -557,6 +557,7 @@
     y, sy: LongInt;
     ar: array[0..1023] of TPoint;
     ar2: array[0..2047] of TPoint;
+    temp: TPoint;
     cnt, cnt2: Longword;
     delta: LongInt;
     ignoreNearObjects, ignoreOverlap, tryAgain: boolean;
@@ -579,7 +580,7 @@
                 repeat
                     inc(y, 2);
                 until (y >= cWaterLine) or
-                        (not ignoreOverlap and (CountNonZeroz(x, y, Gear^.Radius - 1, 1, $FFFF) = 0)) or 
+                        ((not ignoreOverlap) and (CountNonZeroz(x, y, Gear^.Radius - 1, 1, $FFFF) = 0)) or 
                         (ignoreOverlap and (CountNonZeroz(x, y, Gear^.Radius - 1, 1, $FF00) = 0));
 
                 sy:= y;
@@ -587,7 +588,7 @@
                 repeat
                     inc(y);
                 until (y >= cWaterLine) or
-                        (not ignoreOverlap and (CountNonZeroz(x, y, Gear^.Radius - 1, 1, $FFFF) <> 0)) or 
+                        ((not ignoreOverlap) and (CountNonZeroz(x, y, Gear^.Radius - 1, 1, $FFFF) <> 0)) or 
                         (ignoreOverlap and (CountNonZeroz(x, y, Gear^.Radius - 1, 1, $FF00) <> 0)); 
 
                 if (y - sy > Gear^.Radius * 2)
@@ -613,12 +614,15 @@
                 end;
 
             if cnt > 0 then
-                with ar[GetRandom(cnt)] do
+	    begin
+	       temp := ar[GetRandom(cnt)];
+               with temp do
                     begin
                     ar2[cnt2].x:= x;
                     ar2[cnt2].y:= y;
                     inc(cnt2)
-                    end
+		    end
+	       end
         until (x + Delta > Right);
 
         dec(Delta, 60)
@@ -632,12 +636,15 @@
     end;
 
 if cnt2 > 0 then
-    with ar2[GetRandom(cnt2)] do
+    begin
+    temp := ar2[GetRandom(cnt2)];
+    with temp do
         begin
         Gear^.X:= int2hwFloat(x);
         Gear^.Y:= int2hwFloat(y);
         AddFileLog('Assigned Gear coordinates (' + inttostr(x) + ',' + inttostr(y) + ')');
         end
+    end
     else
     begin
     OutError('Can''t find place for Gear', false);
--- a/hedgewars/uIO.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uIO.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -20,7 +20,7 @@
 
 unit uIO;
 interface
-uses SDLh, uTypes;
+uses SDLh, uTypes, uMisc;
 
 procedure initModule;
 procedure freeModule;
@@ -114,6 +114,7 @@
 procedure ParseIPCCommand(s: shortstring);
 var loTicks: Word;
 begin
+
 case s[1] of
      '!': begin AddFileLog('Ping? Pong!'); isPonged:= true; end;
      '?': SendIPC(_S'!');
@@ -168,10 +169,11 @@
 end;
 
 procedure LoadRecordFromFile(fileName: shortstring);
-var f: file;
-    ss: shortstring = '';
-    i: LongInt;
-    s: shortstring;
+var f  : File;
+    ss : shortstring = '';
+    i  : LongInt;
+    s  : shortstring;
+   t, tt   : string;
 begin
 
 // set RDNLY on file open
@@ -179,7 +181,6 @@
 {$I-}
 assign(f, fileName);
 reset(f, 1);
-
 tryDo(IOResult = 0, 'Error opening file ' + fileName, true);
 
 i:= 0; // avoid compiler hints
@@ -187,13 +188,13 @@
 repeat
     BlockRead(f, s[1], 255 - Length(ss), i);
     if i > 0 then
-        begin
+    begin
         s[0]:= char(i);
         ss:= ss + s;
         while (Length(ss) > 1)and(Length(ss) > byte(ss[1])) do
             begin
             ParseIPCCommand(copy(ss, 2, byte(ss[1])));
-            Delete(ss, 1, Succ(byte(ss[1])))
+	       Delete(ss, 1, Succ(byte(ss[1])));
             end
         end
 until i = 0;
@@ -222,7 +223,8 @@
     SDLNet_Write16(GameTicks, @s[Succ(byte(s[0]))]);
     AddFileLog('[IPC out] '+ s[1]);
     inc(s[0], 2);
-    SDLNet_TCP_Send(IPCSock, @s, Succ(byte(s[0])))
+       SDLNet_TCP_Send(IPCSock, @s, Succ(byte(s[0])));
+       //log('SendIPC');
     end
 end;
 
@@ -376,7 +378,7 @@
 if CheckNoTeamOrHH or isPaused then
     exit;
 bShowFinger:= false;
-if not CurrentTeam^.ExtDriven and bShowAmmoMenu then
+if (not CurrentTeam^.ExtDriven) and bShowAmmoMenu then
     begin
     bSelected:= true;
     exit
@@ -429,6 +431,7 @@
     
     hiTicks:= 0;
     SendEmptyPacketTicks:= 0;
+
 end;
 
 procedure freeModule;
@@ -437,6 +440,7 @@
     SDLNet_FreeSocketSet(fds);
     SDLNet_TCP_Close(IPCSock);
     SDLNet_Quit();
+
 end;
 
 end.
--- a/hedgewars/uLand.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uLand.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -240,6 +240,7 @@
     rightX:= (playWidth + ((LAND_WIDTH - playWidth) div 2)) - 1;
     topY:= LAND_HEIGHT - playHeight;
 
+    
     // HACK: force to only cavern even if a cavern map is invertable if cTemplateFilter = 4 ?
     if (cTemplateFilter = 4)
     or (Template.canInvert and (getrandom(2) = 0))
@@ -458,7 +459,9 @@
 begin
 tmpsurf:= LoadDataImage(ptMapCurrent, 'mask', ifAlpha or ifTransparent or ifIgnoreCaps);
 if tmpsurf = nil then
-    begin
+    tmpsurf:= LoadImage(Pathz[ptMapCurrent] + '/mask', ifAlpha or ifTransparent or ifIgnoreCaps);
+if tmpsurf = nil then
+begin
     mapName:= ExtractFileName(Pathz[ptMapCurrent]);
     tmpsurf:= LoadDataImage(ptMissionMaps, mapName + '/mask', ifAlpha or ifTransparent or ifIgnoreCaps);
     end;
@@ -524,9 +527,11 @@
 end;
 
 procedure LoadMap;
-var tmpsurf: PSDL_Surface;
-    s: shortstring;
-    mapName: shortstring = '';
+var tmpsurf : PSDL_Surface;
+    s	    : shortstring;
+    f	    : textfile;
+    mapName : shortstring = '';
+
 begin
 WriteLnToConsole('Loading land from file...');
 AddProgress;
@@ -542,6 +547,29 @@
 ResizeLand(tmpsurf^.w, tmpsurf^.h);
 LoadMapConfig;
 
+// unC0Rr - should this be passed from the GUI? I am not sure which layer does what
+s:= UserPathz[ptMapCurrent] + '/map.cfg';
+if not FileExists(s) then
+    s:= Pathz[ptMapCurrent] + '/map.cfg';
+WriteLnToConsole('Fetching map HH limit');
+{$I-}
+Assign(f, s);
+filemode:= 0; // readonly
+Reset(f);
+if IOResult <> 0 then
+    begin
+    s:= Pathz[ptMissionMaps] + '/' + mapName + '/map.cfg';
+    Assign(f, s);
+    Reset(f);
+    end;
+Readln(f);
+if not eof(f) then
+    Readln(f, MaxHedgehogs);
+   
+{$I+}
+if (MaxHedgehogs = 0) then
+    MaxHedgehogs:= 18;
+
 playHeight:= tmpsurf^.h;
 playWidth:= tmpsurf^.w;
 leftX:= (LAND_WIDTH - playWidth) div 2;
@@ -555,9 +583,11 @@
     LAND_HEIGHT - tmpsurf^.h,
     tmpsurf^.w,
     tmpsurf);
+   
 SDL_FreeSurface(tmpsurf);
 
 LoadMask;
+
 end;
 
 procedure DrawBottomBorder; // broken out from other borders for doing a floor-only map, or possibly updating bottom during SD
@@ -580,9 +610,9 @@
 end;
 
 procedure GenMap;
-var x, y, w, c: Longword;
+var x, y, w, c : Longword;
     usermap, usermask, map, mask: shortstring;
-    maskOnly: boolean;
+    maskOnly : boolean;
 begin
     hasBorder:= false;
     maskOnly:= false;
@@ -625,7 +655,6 @@
         MakeFortsMap;
 
     AddProgress;
-
 // check for land near top
 c:= 0;
 if (GameFlags and gfBorder) <> 0 then
@@ -776,7 +805,7 @@
                 if t > 8 then
                     Preview[y, x]:= Preview[y, x] or ($80 shr bit);
             end;
-        end;
+	end;
 end;
 
 
@@ -790,11 +819,13 @@
 end;
 
 procedure chSendLandDigest(var s: shortstring);
-var adler, i: LongInt;
+var adler, i : LongInt;
 begin
     adler:= 1;
-    for i:= 0 to LAND_HEIGHT-1 do
+     for i:= 0 to LAND_HEIGHT-1 do
+       begin
         adler:= Adler32Update(adler, @Land[i,0], LAND_WIDTH);
+       end;
     s:= 'M' + IntToStr(adler) + cScriptName;
 
     chLandCheck(s);
@@ -823,9 +854,13 @@
 
 procedure freeModule;
 begin
-    SetLength(Land, 0, 0);
-    SetLength(LandPixels, 0, 0);
-    SetLength(LandDirty, 0, 0);
+
+   SetLength(LandPixels, 0, 0);
+   
+   SetLength(Land, 0, 0);
+ 
+   SetLength(LandDirty, 0, 0);
+
 end;
 
 end.
--- a/hedgewars/uLandGenMaze.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uLandGenMaze.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -14,6 +14,10 @@
     DIR_S: direction = (x: 0; y: 1);
     DIR_W: direction = (x: -1; y: 0);
 
+{xymeng : make all dynamic arrays static }
+const max_num_cells_x = 4096 div 128;
+   max_num_cells_y    = 4096 div 128;
+   max_num_steps      = 3;
 
 operator = (const a, b: direction) c: Boolean;
 begin
@@ -25,28 +29,43 @@
     large_cell_size = 256;
     braidness = 10;
 
-var x, y: LongInt;
-    cellsize: LongInt; //selected by the user in the gui
-    seen_cells_x, seen_cells_y: LongInt; //number of cells that can be visited by the generator, that is every second cell in x and y direction. the cells between there are walls that will be removed when we move from one cell to another
-    num_edges_x, num_edges_y: LongInt; //number of resulting edges that need to be vertexificated
-    num_cells_x, num_cells_y: LongInt; //actual number of cells, depending on cell size
-    seen_list: array of array of LongInt;
-    xwalls: array of array of Boolean;
-    ywalls: array of array of Boolean;
-    x_edge_list: array of array of Boolean;
-    y_edge_list: array of array of Boolean;
-    maze: array of array of Boolean;
-    pa: TPixAr;
-    num_vertices: LongInt;
-    off_y: LongInt;
-    num_steps: LongInt;
-    current_step: LongInt;
-    step_done: array of Boolean;
-    done: Boolean;
-    last_cell: array of record x, y: LongInt; end;
-    came_from: array of array of record x, y: LongInt; end;
+type
+   cell_t = record x,y	       : LongInt
+	    end;
+   
+var x, y		       : LongInt;
+    cellsize		       : LongInt; //selected by the user in the gui
+    seen_cells_x, seen_cells_y : LongInt; //number of cells that can be visited by the generator, that is every second cell in x and y direction. the cells between there are walls that will be removed when we move from one cell to another
+    num_edges_x, num_edges_y   : LongInt; //number of resulting edges that need to be vertexificated
+    num_cells_x, num_cells_y   : LongInt; //actual number of cells, depending on cell size
+
+
+    seen_list		       : array of array of LongInt;
+    xwalls		       : array of array of Boolean;
+    ywalls		       : array of array of Boolean;
+    x_edge_list		       : array of array of Boolean;
+    y_edge_list		       : array of array of Boolean;
+    maze		       : array of array of Boolean;
+
+    pa			       : TPixAr;
+    num_vertices	       : LongInt;
+    off_y		       : LongInt;
+    num_steps		       : LongInt;
+    current_step	       : LongInt;
+   
+    step_done		       : array of Boolean;
+   
+    done		       : Boolean;
+
+{   last_cell		       : array 0..3 of record x, y :LongInt ; end;
+    came_from		       : array of array of record x, y: LongInt; end;
+    came_from_pos	       : array of LongInt;
+}
+    last_cell : array of cell_t;
+    came_from : array of array of cell_t;
     came_from_pos: array of LongInt;
-    maze_inverted: Boolean;
+   
+    maze_inverted					   : Boolean;
 
 function when_seen(x: LongInt; y: LongInt): LongInt;
 begin
@@ -102,7 +121,7 @@
     begin
         //we have already seen the target cell, decide if we should remove the wall anyway
         //(or put a wall there if maze_inverted, but we are not doing that right now)
-        if not maze_inverted and (GetRandom(braidness) = 0) then
+        if (not maze_inverted) and (GetRandom(braidness) = 0) then
         //or just warn that inverted+braid+indestructible terrain != good idea
         begin
             case dir.x of
@@ -178,7 +197,7 @@
     came_from_pos[current_step] := came_from_pos[current_step] - 1;
     
     if came_from_pos[current_step] >= 0 then
-        see_cell
+        see_cell()
         
     else
         step_done[current_step] := true;
@@ -336,14 +355,18 @@
 SetLength(last_cell, num_steps);
 SetLength(came_from_pos, num_steps);
 SetLength(came_from, num_steps, num_cells_x*num_cells_y);
+
 done := false;
 
 for current_step := 0 to num_steps - 1 do
+begin
     step_done[current_step] := false;
     came_from_pos[current_step] := 0;
-    
+end;
+
 current_step := 0;
 
+
 SetLength(seen_list, seen_cells_x, seen_cells_y);
 SetLength(xwalls, seen_cells_x, seen_cells_y - 1);
 SetLength(ywalls, seen_cells_x - 1, seen_cells_y);
@@ -351,6 +374,7 @@
 SetLength(y_edge_list, num_cells_x, num_edges_y);
 SetLength(maze, num_cells_x, num_cells_y);
 
+   
 num_vertices := 0;
 
 playHeight := num_cells_y * cellsize;
--- a/hedgewars/uLandGraphics.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uLandGraphics.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -208,7 +208,7 @@
 t:= y + dy;
 if (t and LAND_HEIGHT_MASK) = 0 then
     for i:= Max(x - dx, 0) to Min(x + dx, LAND_WIDTH - 1) do
-        if ((Land[t, i] and lfIndestructible) = 0) and (not disableLandBack or (Land[t, i] > 255))  then
+        if ((Land[t, i] and lfIndestructible) = 0) and ((not disableLandBack) or (Land[t, i] > 255))  then
             if (cReducedQuality and rqBlurryLand) = 0 then
                 LandPixels[t, i]:= 0
             else
@@ -217,7 +217,7 @@
 t:= y - dy;
 if (t and LAND_HEIGHT_MASK) = 0 then
     for i:= Max(x - dx, 0) to Min(x + dx, LAND_WIDTH - 1) do
-        if ((Land[t, i] and lfIndestructible) = 0) and (not disableLandBack or (Land[t, i] > 255))  then
+        if ((Land[t, i] and lfIndestructible) = 0) and ((not disableLandBack) or (Land[t, i] > 255))  then
             if (cReducedQuality and rqBlurryLand) = 0 then
                 LandPixels[t, i]:= 0
             else
@@ -226,7 +226,7 @@
 t:= y + dx;
 if (t and LAND_HEIGHT_MASK) = 0 then
     for i:= Max(x - dy, 0) to Min(x + dy, LAND_WIDTH - 1) do
-        if ((Land[t, i] and lfIndestructible) = 0) and (not disableLandBack or (Land[t, i] > 255))  then
+        if ((Land[t, i] and lfIndestructible) = 0) and ((not disableLandBack) or (Land[t, i] > 255))  then
             if (cReducedQuality and rqBlurryLand) = 0 then
                 LandPixels[t, i]:= 0
             else
@@ -235,7 +235,7 @@
 t:= y - dx;
 if (t and LAND_HEIGHT_MASK) = 0 then
     for i:= Max(x - dy, 0) to Min(x + dy, LAND_WIDTH - 1) do
-        if ((Land[t, i] and lfIndestructible) = 0) and (not disableLandBack or (Land[t, i] > 255))  then
+        if ((Land[t, i] and lfIndestructible) = 0) and ((not disableLandBack) or (Land[t, i] > 255))  then
             if (cReducedQuality and rqBlurryLand) = 0 then
                 LandPixels[t, i]:= 0
             else
--- a/hedgewars/uLandObjects.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uLandObjects.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -66,6 +66,8 @@
     ThemeObjects: TThemeObjects;
     SprayObjects: TSprayObjects;
 
+
+
 procedure BlitImageAndGenerateCollisionInfo(cpX, cpY, Width: Longword; Image: PSDL_Surface); inline;
 begin
     BlitImageAndGenerateCollisionInfo(cpX, cpY, Width, Image, 0);
@@ -442,7 +444,7 @@
 SprayObjects.Count:= 0;
 
 while not eof(f) do
-    begin
+begin
     Readln(f, s);
     if Length(s) = 0 then
         continue;
--- a/hedgewars/uLandTemplates.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uLandTemplates.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -24,20 +24,20 @@
 
 const NTPX = Low(SmallInt);
 
-type TPointArray = array[0..64] of TSDL_Rect;
-     PPointArray = ^TPointArray;
+type TPointArray   = array[0..64] of TSDL_Rect;
+     PPointArray   = ^TPointArray;
      TEdgeTemplate = record
-                     BasePoints: PPointArray;
-                     BasePointsCount: Longword;
-                     FillPoints: PPointArray;
-                     FillPointsCount: Longword;
-                     BezierizeCount: Longword;
-                     RandPassesCount: Longword;
-                     TemplateHeight, TemplateWidth: Longword;
-                     canMirror, canFlip, isNegative, canInvert: boolean;
-                     hasGirders: boolean;
-                     MaxHedgeHogs: Longword;
-                     end;
+			BasePoints				  : PPointArray;		  
+			BasePointsCount				  : Longword;
+			FillPoints				  : PPointArray;
+			FillPointsCount				  : Longword;
+			BezierizeCount				  : Longword;
+			RandPassesCount				  : Longword;
+			TemplateHeight, TemplateWidth		  : Longword;
+			canMirror, canFlip, isNegative, canInvert : boolean;
+			hasGirders				  : boolean;
+			MaxHedgeHogs				  : Longword;
+		     end;					  
 ///////////////////////// ORIGINAL SET //////////////////////////////
 /// Area expanded to 2848x1424 at Tiys request to move out border ///
 /////////////////////////////////////////////////////////////////////
@@ -63,9 +63,9 @@
        (x: 2134; y: 1424; w:    1; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template0FPoints: array[0..0] of TPoint =
+      Template0FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template1Points: array[0..15] of TSDL_Rect =
@@ -87,9 +87,9 @@
        (x: 1860; y: 1424; w:   25; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template1FPoints: array[0..0] of TPoint =
+      Template1FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template2Points: array[0..21] of TSDL_Rect =
@@ -117,9 +117,9 @@
        (x: 2004; y: 1424; w:    1; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template2FPoints: array[0..0] of TPoint =
+      Template2FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template3Points: array[0..16] of TSDL_Rect =
@@ -142,9 +142,9 @@
        (x: 1834; y:  622; w:  254; h:  116),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template3FPoints: array[0..0] of TPoint =
+      Template3FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template4Points: array[0..22] of TSDL_Rect =
@@ -173,9 +173,9 @@
        (x: 2150; y:  552; w:   86; h:  220),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template4FPoints: array[0..0] of TPoint =
+      Template4FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template5Points: array[0..15] of TSDL_Rect =
@@ -197,9 +197,9 @@
        (x: 2012; y: 1424; w:    1; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
        );
-      Template5FPoints: array[0..0] of TPoint =
+      Template5FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template6Points: array[0..13] of TSDL_Rect =
@@ -219,9 +219,9 @@
        (x: 2046; y: 1420; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
        );
-      Template6FPoints: array[0..0] of TPoint =
+      Template6FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template7Points: array[0..5] of TSDL_Rect =
@@ -233,9 +233,9 @@
        (x: 1830; y: 1424; w:  454; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template7FPoints: array[0..0] of TPoint =
+      Template7FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 
@@ -262,9 +262,9 @@
        (x: 2030; y: 1424; w:   20; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template8FPoints: array[0..0] of TPoint =
+      Template8FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template9Points: array[0..31] of TSDL_Rect =
@@ -302,9 +302,9 @@
        (x: 2080; y: 1424; w:    1; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template9FPoints: array[0..0] of TPoint =
+      Template9FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template10Points: array[0..13] of TSDL_Rect =
@@ -324,9 +324,9 @@
        (x: 2182; y: 1424; w:    2; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template10FPoints: array[0..0] of TPoint =
+      Template10FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template11Points: array[0..9] of TSDL_Rect =
@@ -342,9 +342,9 @@
        (x: 1984; y: 1424; w:  136; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template11FPoints: array[0..0] of TPoint =
+      Template11FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template12Points: array[0..13] of TSDL_Rect =
@@ -364,9 +364,9 @@
        (x: 2088; y: 1424; w:  176; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template12FPoints: array[0..0] of TPoint =
+      Template12FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template13Points: array[0..15] of TSDL_Rect =
@@ -388,9 +388,9 @@
        (x: 1844; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template13FPoints: array[0..0] of TPoint =
+      Template13FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template14Points: array[0..13] of TSDL_Rect =
@@ -410,9 +410,9 @@
        (x: 2008; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template14FPoints: array[0..0] of TPoint =
+      Template14FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template15Points: array[0..23] of TSDL_Rect =
@@ -442,9 +442,9 @@
        (x: 2056; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template15FPoints: array[0..0] of TPoint =
+      Template15FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template16Points: array[0..28] of TSDL_Rect =
@@ -479,9 +479,9 @@
        (x: 2098; y: 1424; w:   52; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template16FPoints: array[0..0] of TPoint =
+      Template16FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template17Points: array[0..13] of TSDL_Rect =
@@ -501,9 +501,9 @@
        (x: 1998; y: 1424; w:   42; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template17FPoints: array[0..0] of TPoint =
+      Template17FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 1023; Y:    0)
+       (X: 1023; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 //////////////////// MIXING AND MATCHING ORIGINAL //////////////////////////////////////
 const Template18Points: array[0..32] of TSDL_Rect =
@@ -542,9 +542,9 @@
        (x: 3598; y: 1424; w:   42; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template18FPoints: array[0..0] of TPoint =
+      Template18FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template19Points: array[0..44] of TSDL_Rect =
@@ -595,9 +595,9 @@
        (x: 3398; y: 1424; w:   52; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template19FPoints: array[0..0] of TPoint =
+      Template19FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template20Points: array[0..45] of TSDL_Rect =
@@ -649,9 +649,9 @@
        (x: 3456; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template20FPoints: array[0..0] of TPoint =
+      Template20FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template21Points: array[0..30] of TSDL_Rect =
@@ -688,9 +688,9 @@
        (x: 3258; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template21FPoints: array[0..0] of TPoint =
+      Template21FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template22Points: array[0..38] of TSDL_Rect =
@@ -735,9 +735,9 @@
        (x: 3244; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template22FPoints: array[0..0] of TPoint =
+      Template22FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template23Points: array[0..29] of TSDL_Rect =
@@ -773,9 +773,9 @@
        (x: 3438; y: 1424; w:  176; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
        );
-      Template23FPoints: array[0..0] of TPoint =
+      Template23FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template24Points: array[0..23] of TSDL_Rect =
@@ -805,9 +805,9 @@
        (x: 3346; y: 1420; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
        );
-      Template24FPoints: array[0..0] of TPoint =
+      Template24FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template25Points: array[0..19] of TSDL_Rect =
@@ -833,9 +833,9 @@
        (x: 3532; y: 1424; w:    2; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template25FPoints: array[0..0] of TPoint =
+      Template25FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 
@@ -894,9 +894,9 @@
        (x: 3480; y: 1424; w:    1; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template26FPoints: array[0..0] of TPoint =
+      Template26FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template27Points: array[0..42] of TSDL_Rect =
@@ -945,9 +945,9 @@
        (x: 3556; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template27FPoints: array[0..0] of TPoint =
+      Template27FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template28Points: array[0..29] of TSDL_Rect =
@@ -983,9 +983,9 @@
        (x: 3308; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template28FPoints: array[0..0] of TPoint =
+      Template28FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template29Points: array[0..37] of TSDL_Rect =
@@ -1029,9 +1029,9 @@
        (x: 3094; y: 1424; w:    2; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template29FPoints: array[0..0] of TPoint =
+      Template29FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template30Points: array[0..30] of TSDL_Rect =
@@ -1068,9 +1068,9 @@
        (x: 3288; y: 1424; w:  176; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template30FPoints: array[0..0] of TPoint =
+      Template30FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template31Points: array[0..32] of TSDL_Rect =
@@ -1109,9 +1109,9 @@
        (x: 3584; y: 1424; w:  136; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template31FPoints: array[0..0] of TPoint =
+      Template31FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template32Points: array[0..29] of TSDL_Rect =
@@ -1147,9 +1147,9 @@
        (x: 3682; y: 1424; w:    2; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template32FPoints: array[0..0] of TPoint =
+      Template32FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-         (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template33Points: array[0..45] of TSDL_Rect =
@@ -1201,9 +1201,9 @@
        (x: 3480; y: 1424; w:    1; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template33FPoints: array[0..0] of TPoint =
+      Template33FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template34Points: array[0..25] of TSDL_Rect =
@@ -1235,9 +1235,9 @@
        (x: 3230; y: 1424; w:   20; h:    1),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template34FPoints: array[0..0] of TPoint =
+      Template34FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 const Template35Points: array[0..48] of TSDL_Rect =
@@ -1292,9 +1292,9 @@
        (x: 3498; y: 1424; w:   52; h:    2),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template35FPoints: array[0..0] of TPoint =
+      Template35FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 ///////////////////////// CAVERNS ///////////////////////////////////
@@ -1320,9 +1320,9 @@
        (x:  576; y:  976; w:   16; h:   28),
        (x: NTPX; y:    0; w:    1; h:    1)
       );
-      Template36FPoints: array[0..0] of TPoint =
+      Template36FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 ////////////////////////////// ... Silly ...  ////////////////////////////////
 /// Ok. Tiy does not care for these.  Perhaps they could be saved.
@@ -1361,9 +1361,9 @@
        (x: 2250; y: 1200; w: 25; h: 25),
        (x: NTPX; y:    0; w:  1; h:  1)
       );
-      Template37FPoints: array[0..0] of TPoint =
+      Template37FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 // attempt to make a series of moderate hills/valleys - was before I really figured out the whole probabilities thing
 const Template38Points: array[0..16] of TSDL_Rect =
@@ -1386,9 +1386,9 @@
        (x: 3700; y: 2100; w:   1; h:    1),
        (x: NTPX; y:    0; w:   1; h:    1)
       );
-      Template38FPoints: array[0..0] of TPoint =
+      Template38FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 // 8 tiny islands
@@ -1435,9 +1435,9 @@
        (x: 1430; y: 520; w:   1; h:   1),
        (x: NTPX; y:   0; w:   1; h:   1)
       );
-      Template39FPoints: array[0..0] of TPoint =
+      Template39FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 512; Y:    0)
+       (X: 512; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 const Template40Points: array[0..7] of TSDL_Rect =
       (
@@ -1450,9 +1450,9 @@
        (x:  900; y: 1050; w:    1; h:   1),
        (x: NTPX; y:    0; w:    1; h:   1)
       );
-      Template40FPoints: array[0..0] of TPoint =
+      Template40FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 512; Y:    0)
+       (X: 512; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 // Many islands
 const Template41Points: array[0..86] of TSDL_Rect =
@@ -1545,9 +1545,9 @@
        (x: 4050; y: 125; w:  50; h:  75),
        (x: NTPX; y:   0; w:   1; h:   1)
       );
-      Template41FPoints: array[0..0] of TPoint =
+      Template41FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 2047; Y:    0)
+       (X: 2047; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 // 2 tiny islands
 const Template42Points: array[0..13] of TSDL_Rect =
@@ -1567,9 +1567,9 @@
        (x: 1430; y: 520; w:   1; h:   1),
        (x: NTPX; y:   0; w:   1; h:   1)
       );
-      Template42FPoints: array[0..0] of TPoint =
+      Template42FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 512; Y:    0)
+       (X: 512; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 // Many islands
 const Template43Points: array[0..173] of TSDL_Rect =
@@ -1749,9 +1749,9 @@
        (x: 4050; y:2173; w:  50; h:  75),
        (x: NTPX; y:2048; w:   1; h:   1)
       );
-      Template43FPoints: array[0..0] of TPoint =
+      Template43FPoints: array[0..{$IFDEF PAS2C}1{$ELSE}0{$ENDIF}] of TPoint =
       (
-       (X: 4095; Y:    0)
+       (X: 4095; Y:    0){$IFDEF PAS2C},(X:0;Y:9){$ENDIF}
       );
 
 // 3 large caverns
@@ -1775,12 +1775,12 @@
       );
       Template44FPoints: array[0..5] of TSDL_Rect =
       (
-       (X:   1; Y:  90; w:   0; h:   0),
-       (X:   1; Y: 500; w:   0; h:   0),
-       (X:4095; Y: 500; w:   0; h:   0),
-       (X:   1; Y:1200; w:   0; h:   0),
-       (X:4095; Y:1200; w:   0; h:   0),
-       (X:   1; Y:2010; w:   0; h:   0)
+       (x:   1; y:  90; w:   0; h:   0),
+       (x:   1; y: 500; w:   0; h:   0),
+       (x:4095; y: 500; w:   0; h:   0),
+       (x:   1; y:1200; w:   0; h:   0),
+       (x:4095; y:1200; w:   0; h:   0),
+       (x:   1; y:2010; w:   0; h:   0)
       );
 
 // large caverns with an island
@@ -1801,9 +1801,9 @@
       );
       Template45FPoints: array[0..2] of TSDL_Rect =
       (
-       (X:   1; Y:   1; w:   0; h:   0),
-       (X:   1; Y:2047; w:   0; h:   0),
-       (X:1005; Y: 805; w:   0; h:   0)
+       (x:   1; y:   1; w:   0; h:   0),
+       (x:   1; y:2047; w:   0; h:   0),
+       (x:1005; y: 805; w:   0; h:   0)
       );
 
 ////////////////////////////////////////////////////////////////////////
@@ -1812,7 +1812,7 @@
        (BasePoints: @Template0Points;
         BasePointsCount: Succ(High(Template0Points));
         FillPoints: @Template0FPoints;
-        FillPointsCount: Succ(High(Template0FPoints));
+        FillPointsCount: Succ(High(Template0FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1823,7 +1823,7 @@
        (BasePoints: @Template1Points;
         BasePointsCount: Succ(High(Template1Points));
         FillPoints: @Template1FPoints;
-        FillPointsCount: Succ(High(Template1FPoints));
+        FillPointsCount: Succ(High(Template1FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1834,7 +1834,7 @@
        (BasePoints: @Template2Points;
         BasePointsCount: Succ(High(Template2Points));
         FillPoints: @Template2FPoints;
-        FillPointsCount: Succ(High(Template2FPoints));
+        FillPointsCount: Succ(High(Template2FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1845,7 +1845,7 @@
        (BasePoints: @Template3Points;
         BasePointsCount: Succ(High(Template3Points));
         FillPoints: @Template3FPoints;
-        FillPointsCount: Succ(High(Template3FPoints));
+        FillPointsCount: Succ(High(Template3FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 4;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1856,7 +1856,7 @@
        (BasePoints: @Template4Points;
         BasePointsCount: Succ(High(Template4Points));
         FillPoints: @Template4FPoints;
-        FillPointsCount: Succ(High(Template4FPoints));
+        FillPointsCount: Succ(High(Template4FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 4;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1867,7 +1867,7 @@
        (BasePoints: @Template5Points;
         BasePointsCount: Succ(High(Template5Points));
         FillPoints: @Template5FPoints;
-        FillPointsCount: Succ(High(Template5FPoints));
+        FillPointsCount: Succ(High(Template5FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1878,7 +1878,7 @@
        (BasePoints: @Template6Points;
         BasePointsCount: Succ(High(Template6Points));
         FillPoints: @Template6FPoints;
-        FillPointsCount: Succ(High(Template6FPoints));
+        FillPointsCount: Succ(High(Template6FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 5;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1889,7 +1889,7 @@
        (BasePoints: @Template7Points;
         BasePointsCount: Succ(High(Template7Points));
         FillPoints: @Template7FPoints;
-        FillPointsCount: Succ(High(Template7FPoints));
+        FillPointsCount: Succ(High(Template7FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 4;
         RandPassesCount: 4;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1900,7 +1900,7 @@
        (BasePoints: @Template8Points;
         BasePointsCount: Succ(High(Template8Points));
         FillPoints: @Template8FPoints;
-        FillPointsCount: Succ(High(Template8FPoints));
+        FillPointsCount: Succ(High(Template8FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1911,7 +1911,7 @@
        (BasePoints: @Template9Points;
         BasePointsCount: Succ(High(Template9Points));
         FillPoints: @Template9FPoints;
-        FillPointsCount: Succ(High(Template9FPoints));
+        FillPointsCount: Succ(High(Template9FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 1;
         RandPassesCount: 5;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1922,7 +1922,7 @@
        (BasePoints: @Template10Points;
         BasePointsCount: Succ(High(Template10Points));
         FillPoints: @Template10FPoints;
-        FillPointsCount: Succ(High(Template10FPoints));
+        FillPointsCount: Succ(High(Template10FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1933,7 +1933,7 @@
        (BasePoints: @Template11Points;
         BasePointsCount: Succ(High(Template11Points));
         FillPoints: @Template11FPoints;
-        FillPointsCount: Succ(High(Template11FPoints));
+        FillPointsCount: Succ(High(Template11FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 1;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1944,7 +1944,7 @@
        (BasePoints: @Template12Points;
         BasePointsCount: Succ(High(Template12Points));
         FillPoints: @Template12FPoints;
-        FillPointsCount: Succ(High(Template12FPoints));
+        FillPointsCount: Succ(High(Template12FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1955,7 +1955,7 @@
        (BasePoints: @Template13Points;
         BasePointsCount: Succ(High(Template13Points));
         FillPoints: @Template13FPoints;
-        FillPointsCount: Succ(High(Template13FPoints));
+        FillPointsCount: Succ(High(Template13FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 5;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1966,7 +1966,7 @@
        (BasePoints: @Template14Points;
         BasePointsCount: Succ(High(Template14Points));
         FillPoints: @Template14FPoints;
-        FillPointsCount: Succ(High(Template14FPoints));
+        FillPointsCount: Succ(High(Template14FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1977,7 +1977,7 @@
        (BasePoints: @Template15Points;
         BasePointsCount: Succ(High(Template15Points));
         FillPoints: @Template15FPoints;
-        FillPointsCount: Succ(High(Template15FPoints));
+        FillPointsCount: Succ(High(Template15FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1988,7 +1988,7 @@
        (BasePoints: @Template16Points;
         BasePointsCount: Succ(High(Template16Points));
         FillPoints: @Template16FPoints;
-        FillPointsCount: Succ(High(Template16FPoints));
+        FillPointsCount: Succ(High(Template16FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -1999,7 +1999,7 @@
        (BasePoints: @Template17Points;
         BasePointsCount: Succ(High(Template17Points));
         FillPoints: @Template17FPoints;
-        FillPointsCount: Succ(High(Template17FPoints));
+        FillPointsCount: Succ(High(Template17FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 2848;
@@ -2010,7 +2010,7 @@
        (BasePoints: @Template18Points;
         BasePointsCount: Succ(High(Template18Points));
         FillPoints: @Template18FPoints;
-        FillPointsCount: Succ(High(Template18FPoints));
+        FillPointsCount: Succ(High(Template18FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2021,7 +2021,7 @@
        (BasePoints: @Template19Points;
         BasePointsCount: Succ(High(Template19Points));
         FillPoints: @Template19FPoints;
-        FillPointsCount: Succ(High(Template19FPoints));
+        FillPointsCount: Succ(High(Template19FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2032,7 +2032,7 @@
        (BasePoints: @Template20Points;
         BasePointsCount: Succ(High(Template20Points));
         FillPoints: @Template20FPoints;
-        FillPointsCount: Succ(High(Template20FPoints));
+        FillPointsCount: Succ(High(Template20FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2043,7 +2043,7 @@
        (BasePoints: @Template21Points;
         BasePointsCount: Succ(High(Template21Points));
         FillPoints: @Template21FPoints;
-        FillPointsCount: Succ(High(Template21FPoints));
+        FillPointsCount: Succ(High(Template21FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 4;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2054,7 +2054,7 @@
        (BasePoints: @Template22Points;
         BasePointsCount: Succ(High(Template22Points));
         FillPoints: @Template22FPoints;
-        FillPointsCount: Succ(High(Template22FPoints));
+        FillPointsCount: Succ(High(Template22FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 4;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2065,7 +2065,7 @@
        (BasePoints: @Template23Points;
         BasePointsCount: Succ(High(Template23Points));
         FillPoints: @Template23FPoints;
-        FillPointsCount: Succ(High(Template23FPoints));
+        FillPointsCount: Succ(High(Template23FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2076,7 +2076,7 @@
        (BasePoints: @Template24Points;
         BasePointsCount: Succ(High(Template24Points));
         FillPoints: @Template24FPoints;
-        FillPointsCount: Succ(High(Template24FPoints));
+        FillPointsCount: Succ(High(Template24FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 5;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2087,7 +2087,7 @@
        (BasePoints: @Template25Points;
         BasePointsCount: Succ(High(Template25Points));
         FillPoints: @Template25FPoints;
-        FillPointsCount: Succ(High(Template25FPoints));
+        FillPointsCount: Succ(High(Template25FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 4;
         RandPassesCount: 4;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2098,7 +2098,7 @@
        (BasePoints: @Template26Points;
         BasePointsCount: Succ(High(Template26Points));
         FillPoints: @Template26FPoints;
-        FillPointsCount: Succ(High(Template26FPoints));
+        FillPointsCount: Succ(High(Template26FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2109,7 +2109,7 @@
        (BasePoints: @Template27Points;
         BasePointsCount: Succ(High(Template27Points));
         FillPoints: @Template27FPoints;
-        FillPointsCount: Succ(High(Template27FPoints));
+        FillPointsCount: Succ(High(Template27FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 1;
         RandPassesCount: 5;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2120,7 +2120,7 @@
        (BasePoints: @Template28Points;
         BasePointsCount: Succ(High(Template28Points));
         FillPoints: @Template28FPoints;
-        FillPointsCount: Succ(High(Template28FPoints));
+        FillPointsCount: Succ(High(Template28FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2131,7 +2131,7 @@
        (BasePoints: @Template29Points;
         BasePointsCount: Succ(High(Template29Points));
         FillPoints: @Template29FPoints;
-        FillPointsCount: Succ(High(Template29FPoints));
+        FillPointsCount: Succ(High(Template29FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 1;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2142,7 +2142,7 @@
        (BasePoints: @Template30Points;
         BasePointsCount: Succ(High(Template30Points));
         FillPoints: @Template30FPoints;
-        FillPointsCount: Succ(High(Template30FPoints));
+        FillPointsCount: Succ(High(Template30FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 8;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2153,7 +2153,7 @@
        (BasePoints: @Template31Points;
         BasePointsCount: Succ(High(Template31Points));
         FillPoints: @Template31FPoints;
-        FillPointsCount: Succ(High(Template31FPoints));
+        FillPointsCount: Succ(High(Template31FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 5;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2164,7 +2164,7 @@
        (BasePoints: @Template32Points;
         BasePointsCount: Succ(High(Template32Points));
         FillPoints: @Template32FPoints;
-        FillPointsCount: Succ(High(Template32FPoints));
+        FillPointsCount: Succ(High(Template32FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2175,7 +2175,7 @@
        (BasePoints: @Template33Points;
         BasePointsCount: Succ(High(Template33Points));
         FillPoints: @Template33FPoints;
-        FillPointsCount: Succ(High(Template33FPoints));
+        FillPointsCount: Succ(High(Template33FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2186,7 +2186,7 @@
        (BasePoints: @Template34Points;
         BasePointsCount: Succ(High(Template34Points));
         FillPoints: @Template34FPoints;
-        FillPointsCount: Succ(High(Template34FPoints));
+        FillPointsCount: Succ(High(Template34FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 6;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2197,7 +2197,7 @@
        (BasePoints: @Template35Points;
         BasePointsCount: Succ(High(Template35Points));
         FillPoints: @Template35FPoints;
-        FillPointsCount: Succ(High(Template35FPoints));
+        FillPointsCount: Succ(High(Template35FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 7;
         TemplateHeight: 1424; TemplateWidth: 3900;
@@ -2208,7 +2208,7 @@
        (BasePoints: @Template36Points;
         BasePointsCount: Succ(High(Template36Points));
         FillPoints: @Template36FPoints;
-        FillPointsCount: Succ(High(Template36FPoints));
+        FillPointsCount: Succ(High(Template36FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 4;
         RandPassesCount: 12;
         TemplateHeight: 1024; TemplateWidth: 4096;
@@ -2219,7 +2219,7 @@
        (BasePoints: @Template37Points;
         BasePointsCount: Succ(High(Template37Points));
         FillPoints: @Template37FPoints;
-        FillPointsCount: Succ(High(Template37FPoints));
+        FillPointsCount: Succ(High(Template37FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 3;
         TemplateHeight: 2048; TemplateWidth: 4096;
@@ -2230,7 +2230,7 @@
        (BasePoints: @Template38Points;
         BasePointsCount: Succ(High(Template38Points));
         FillPoints: @Template38FPoints;
-        FillPointsCount: Succ(High(Template38FPoints));
+        FillPointsCount: Succ(High(Template38FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 4;
         RandPassesCount: 4;
         TemplateHeight: 2048; TemplateWidth: 4096;
@@ -2241,7 +2241,7 @@
        (BasePoints: @Template39Points;
         BasePointsCount: Succ(High(Template39Points));
         FillPoints: @Template39FPoints;
-        FillPointsCount: Succ(High(Template39FPoints));
+        FillPointsCount: Succ(High(Template39FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 3;
         TemplateHeight: 512; TemplateWidth: 1536;
@@ -2252,7 +2252,7 @@
        (BasePoints: @Template40Points;
         BasePointsCount: Succ(High(Template40Points));
         FillPoints: @Template40FPoints;
-        FillPointsCount: Succ(High(Template40FPoints));
+        FillPointsCount: Succ(High(Template40FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 3;
         TemplateHeight: 1024; TemplateWidth: 1024;
@@ -2263,7 +2263,7 @@
        (BasePoints: @Template41Points;
         BasePointsCount: Succ(High(Template41Points));
         FillPoints: @Template41FPoints;
-        FillPointsCount: Succ(High(Template41FPoints));
+        FillPointsCount: Succ(High(Template41FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 9;
         TemplateHeight: 2048; TemplateWidth: 4096;
@@ -2274,7 +2274,7 @@
        (BasePoints: @Template42Points;
         BasePointsCount: Succ(High(Template42Points));
         FillPoints: @Template42FPoints;
-        FillPointsCount: Succ(High(Template42FPoints));
+        FillPointsCount: Succ(High(Template42FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 3;
         RandPassesCount: 3;
         TemplateHeight: 512; TemplateWidth: 1536;
@@ -2285,7 +2285,7 @@
        (BasePoints: @Template43Points;
         BasePointsCount: Succ(High(Template43Points));
         FillPoints: @Template43FPoints;
-        FillPointsCount: Succ(High(Template43FPoints));
+        FillPointsCount: Succ(High(Template43FPoints)){$IFDEF PAS2C}-1{$ENDIF};
         BezierizeCount: 2;
         RandPassesCount: 9;
         TemplateHeight: 4096; TemplateWidth: 4096;
--- a/hedgewars/uLandTexture.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uLandTexture.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -39,10 +39,11 @@
             tex: PTexture;
             end;
 
-var LandTextures: array of array of TLandRecord;
-    tmpPixels: array [0..TEXSIZE - 1, 0..TEXSIZE - 1] of LongWord;
-    LANDTEXARW: LongWord;
-    LANDTEXARH: LongWord;
+var
+    LandTextures : array of array of TLandRecord;
+    tmpPixels	 : array [0..TEXSIZE - 1, 0..TEXSIZE - 1] of LongWord;
+    LANDTEXARW	 : LongWord;
+    LANDTEXARH	 : LongWord;
 
 function Pixels(x, y: Longword): Pointer;
 var ty: Longword;
@@ -196,7 +197,6 @@
         LANDTEXARW:= (LAND_WIDTH div TEXSIZE) div 2;
         LANDTEXARH:= (LAND_HEIGHT div TEXSIZE) div 2;
         end;
-
     SetLength(LandTextures, LANDTEXARW, LANDTEXARH);
 end;
 
--- a/hedgewars/uLocale.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uLocale.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -61,8 +61,8 @@
 if loaded then
     begin
     while not eof(f) do
-        begin
-        readln(f, s);
+    begin
+       readln(f, s);
         if Length(s) = 0 then
             continue;
         if (s[1] < '0') or (s[1] > '9') then
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hedgewars/uMatrix.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -0,0 +1,268 @@
+(*
+ * Hedgewars, a free turn based strategy game
+ * Copyright (c) 2004-2012 Andrey Korotaev <unC0Rr@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; version 2 of the License
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
+ *)
+
+{$INCLUDE "options.inc"}
+
+unit uMatrix;
+
+interface
+
+uses uTypes {$IFNDEF PAS2C}, gl{$ENDIF};
+
+const
+    MATRIX_MODELVIEW:Integer = 0;
+    MATRIX_PROJECTION:Integer = 1;
+  
+procedure MatrixLoadIdentity(out Result: TMatrix4x4f);
+procedure MatrixMultiply(out Result: TMatrix4x4f; const lhs, rhs: TMatrix4x4f);
+
+procedure hglMatrixMode(t: Integer);
+procedure hglLoadIdentity();
+procedure hglPushMatrix();
+procedure hglPopMatrix();
+procedure hglMVP(var res : TMatrix4x4f);
+procedure hglScalef(x: GLfloat; y: GLfloat; z: GLfloat);
+procedure hglTranslatef(x: GLfloat; y: GLfloat; z: GLfloat);
+procedure hglRotatef(a:GLfloat; x:GLfloat; y:GLfloat; z:GLfloat);
+procedure initModule();
+procedure freeModule();
+
+implementation
+
+const
+    MATRIX_STACK_SIZE = 10;
+
+type
+    TMatrixStack = record
+        top:Integer;
+        stack: array[0..9] of TMatrix4x4f;
+        end;
+var
+    MatrixStacks : array[0..1] of TMatrixStack;
+    CurMatrix: integer;
+
+procedure MatrixLoadIdentity(out Result: TMatrix4x4f);
+begin
+    Result[0,0]:= 1.0; Result[1,0]:=0.0; Result[2,0]:=0.0; Result[3,0]:=0.0;
+    Result[0,1]:= 0.0; Result[1,1]:=1.0; Result[2,1]:=0.0; Result[3,1]:=0.0;
+    Result[0,2]:= 0.0; Result[1,2]:=0.0; Result[2,2]:=1.0; Result[3,2]:=0.0;
+    Result[0,3]:= 0.0; Result[1,3]:=0.0; Result[2,3]:=0.0; Result[3,3]:=1.0;
+end;
+
+procedure hglMatrixMode(t: Integer);
+begin
+    CurMatrix := t;
+end;
+
+procedure hglLoadIdentity();
+begin
+    MatrixLoadIdentity(MatrixStacks[CurMatrix].stack[MatrixStacks[CurMatrix].top]);
+end;
+
+procedure hglScalef(x: GLfloat; y: GLfloat; z: GLfloat);
+var
+    m:TMatrix4x4f;
+    t:TMatrix4x4f;
+begin
+    m[0,0]:=x;m[1,0]:=0;m[2,0]:=0;m[3,0]:=0;
+    m[0,1]:=0;m[1,1]:=y;m[2,1]:=0;m[3,1]:=0;
+    m[0,2]:=0;m[1,2]:=0;m[2,2]:=z;m[3,2]:=0;
+    m[0,3]:=0;m[1,3]:=0;m[2,3]:=0;m[3,3]:=1;
+
+    MatrixMultiply(t, MatrixStacks[CurMatrix].stack[MatrixStacks[CurMatrix].top], m);
+    MatrixStacks[CurMatrix].stack[MatrixStacks[CurMatrix].top] := t; 
+end;
+
+procedure hglTranslatef(x: GLfloat; y: GLfloat; z: GLfloat);
+var
+    m:TMatrix4x4f;
+    t:TMatrix4x4f;
+begin
+    m[0,0]:=1;m[1,0]:=0;m[2,0]:=0;m[3,0]:=x;
+    m[0,1]:=0;m[1,1]:=1;m[2,1]:=0;m[3,1]:=y;
+    m[0,2]:=0;m[1,2]:=0;m[2,2]:=1;m[3,2]:=z;
+    m[0,3]:=0;m[1,3]:=0;m[2,3]:=0;m[3,3]:=1;
+
+    MatrixMultiply(t, MatrixStacks[CurMatrix].stack[MatrixStacks[CurMatrix].top], m);
+    MatrixStacks[CurMatrix].stack[MatrixStacks[CurMatrix].top] := t;
+end;
+
+procedure hglRotatef(a:GLfloat; x:GLfloat; y:GLfloat; z:GLfloat);
+var
+    m:TMatrix4x4f;
+    t:TMatrix4x4f;
+    c:GLfloat;
+    s:GLfloat;
+    xn, yn, zn:GLfloat;
+    l:GLfloat;
+begin
+    a:=a * 3.14159265368 / 180;
+    c:=cos(a);
+    s:=sin(a);
+    
+    l := 1.0 / sqrt(x * x + y * y + z * z);
+    xn := x * l;
+    yn := y * l;
+    zn := z * l;
+
+    m[0,0]:=c + xn * xn * (1 - c);
+    m[1,0]:=xn * yn * (1 - c) - zn * s;
+    m[2,0]:=xn * zn * (1 - c) + yn * s;
+    m[3,0]:=0;
+
+
+    m[0,1]:=yn * xn * (1 - c) + zn * s;
+    m[1,1]:=c + yn * yn * (1 - c);
+    m[2,1]:=yn * zn * (1 - c) - xn * s;
+    m[3,1]:=0;
+
+    m[0,2]:=zn * xn * (1 - c) - yn * s;
+    m[1,2]:=zn * yn * (1 - c) + xn * s;
+    m[2,2]:=c + zn * zn * (1 - c);
+    m[3,2]:=0;
+
+    m[0,3]:=0;m[1,3]:=0;m[2,3]:=0;m[3,3]:=1;
+
+    MatrixMultiply(t, MatrixStacks[CurMatrix].stack[MatrixStacks[CurMatrix].top], m);
+    MatrixStacks[CurMatrix].stack[MatrixStacks[CurMatrix].top] := t;
+end;
+
+procedure hglMVP(var res: TMatrix4x4f);
+begin
+    MatrixMultiply(res, 
+                   MatrixStacks[MATRIX_PROJECTION].stack[MatrixStacks[MATRIX_PROJECTION].top], 
+                   MatrixStacks[MATRIX_MODELVIEW].stack[MatrixStacks[MATRIX_MODELVIEW].top]);
+end;
+
+procedure hglPushMatrix();
+var
+    t: Integer;
+begin
+    t := MatrixStacks[CurMatrix].top;
+    MatrixStacks[CurMatrix].stack[t + 1] := MatrixStacks[CurMatrix].stack[t];
+    inc(t);
+    MatrixStacks[CurMatrix].top := t;
+end;
+
+procedure hglPopMatrix();
+var
+    t: Integer;
+begin
+    t := MatrixStacks[CurMatrix].top;
+    dec(t);
+    MatrixStacks[CurMatrix].top := t;
+end;
+
+procedure initModule();
+begin
+    MatrixStacks[MATRIX_MODELVIEW].top := 0;
+    MatrixStacks[MATRIX_Projection].top := 0;
+    MatrixLoadIdentity(MatrixStacks[MATRIX_MODELVIEW].stack[0]);
+    MatrixLoadIdentity(MatrixStacks[MATRIX_PROJECTION].stack[0]);
+end;
+
+procedure freeModule();
+begin
+end;
+
+procedure MatrixMultiply(out Result: TMatrix4x4f; const lhs, rhs: TMatrix4x4f);
+var
+    test: TMatrix4x4f;
+    i, j: Integer;
+    error: boolean;
+begin
+    Result[0,0]:=lhs[0,0]*rhs[0,0] + lhs[1,0]*rhs[0,1] + lhs[2,0]*rhs[0,2] + lhs[3,0]*rhs[0,3];
+    Result[0,1]:=lhs[0,1]*rhs[0,0] + lhs[1,1]*rhs[0,1] + lhs[2,1]*rhs[0,2] + lhs[3,1]*rhs[0,3];
+    Result[0,2]:=lhs[0,2]*rhs[0,0] + lhs[1,2]*rhs[0,1] + lhs[2,2]*rhs[0,2] + lhs[3,2]*rhs[0,3];
+    Result[0,3]:=lhs[0,3]*rhs[0,0] + lhs[1,3]*rhs[0,1] + lhs[2,3]*rhs[0,2] + lhs[3,3]*rhs[0,3];
+
+    Result[1,0]:=lhs[0,0]*rhs[1,0] + lhs[1,0]*rhs[1,1] + lhs[2,0]*rhs[1,2] + lhs[3,0]*rhs[1,3];
+    Result[1,1]:=lhs[0,1]*rhs[1,0] + lhs[1,1]*rhs[1,1] + lhs[2,1]*rhs[1,2] + lhs[3,1]*rhs[1,3];
+    Result[1,2]:=lhs[0,2]*rhs[1,0] + lhs[1,2]*rhs[1,1] + lhs[2,2]*rhs[1,2] + lhs[3,2]*rhs[1,3];
+    Result[1,3]:=lhs[0,3]*rhs[1,0] + lhs[1,3]*rhs[1,1] + lhs[2,3]*rhs[1,2] + lhs[3,3]*rhs[1,3];
+
+    Result[2,0]:=lhs[0,0]*rhs[2,0] + lhs[1,0]*rhs[2,1] + lhs[2,0]*rhs[2,2] + lhs[3,0]*rhs[2,3];
+    Result[2,1]:=lhs[0,1]*rhs[2,0] + lhs[1,1]*rhs[2,1] + lhs[2,1]*rhs[2,2] + lhs[3,1]*rhs[2,3];
+    Result[2,2]:=lhs[0,2]*rhs[2,0] + lhs[1,2]*rhs[2,1] + lhs[2,2]*rhs[2,2] + lhs[3,2]*rhs[2,3];
+    Result[2,3]:=lhs[0,3]*rhs[2,0] + lhs[1,3]*rhs[2,1] + lhs[2,3]*rhs[2,2] + lhs[3,3]*rhs[2,3];
+
+    Result[3,0]:=lhs[0,0]*rhs[3,0] + lhs[1,0]*rhs[3,1] + lhs[2,0]*rhs[3,2] + lhs[3,0]*rhs[3,3];
+    Result[3,1]:=lhs[0,1]*rhs[3,0] + lhs[1,1]*rhs[3,1] + lhs[2,1]*rhs[3,2] + lhs[3,1]*rhs[3,3];
+    Result[3,2]:=lhs[0,2]*rhs[3,0] + lhs[1,2]*rhs[3,1] + lhs[2,2]*rhs[3,2] + lhs[3,2]*rhs[3,3];
+    Result[3,3]:=lhs[0,3]*rhs[3,0] + lhs[1,3]*rhs[3,1] + lhs[2,3]*rhs[3,2] + lhs[3,3]*rhs[3,3];
+
+{
+    Result[0,0]:=lhs[0,0]*rhs[0,0] + lhs[1,0]*rhs[0,1] + lhs[2,0]*rhs[0,2] + lhs[3,0]*rhs[0,3];
+    Result[0,1]:=lhs[0,0]*rhs[1,0] + lhs[1,0]*rhs[1,1] + lhs[2,0]*rhs[1,2] + lhs[3,0]*rhs[1,3];
+    Result[0,2]:=lhs[0,0]*rhs[2,0] + lhs[1,0]*rhs[2,1] + lhs[2,0]*rhs[2,2] + lhs[3,0]*rhs[2,3];
+    Result[0,3]:=lhs[0,0]*rhs[3,0] + lhs[1,0]*rhs[3,1] + lhs[2,0]*rhs[3,2] + lhs[3,0]*rhs[3,3];
+  
+    Result[1,0]:=lhs[0,1]*rhs[0,0] + lhs[1,1]*rhs[0,1] + lhs[2,1]*rhs[0,2] + lhs[3,1]*rhs[0,3];
+    Result[1,1]:=lhs[0,1]*rhs[1,0] + lhs[1,1]*rhs[1,1] + lhs[2,1]*rhs[1,2] + lhs[3,1]*rhs[1,3];
+    Result[1,2]:=lhs[0,1]*rhs[2,0] + lhs[1,1]*rhs[2,1] + lhs[2,1]*rhs[2,2] + lhs[3,1]*rhs[2,3];
+    Result[1,3]:=lhs[0,1]*rhs[3,0] + lhs[1,1]*rhs[3,1] + lhs[2,1]*rhs[3,2] + lhs[3,1]*rhs[3,3];
+
+    Result[2,0]:=lhs[0,2]*rhs[0,0] + lhs[1,2]*rhs[0,1] + lhs[2,2]*rhs[0,2] + lhs[3,2]*rhs[0,3];
+    Result[2,1]:=lhs[0,2]*rhs[1,0] + lhs[1,2]*rhs[1,1] + lhs[2,2]*rhs[1,2] + lhs[3,2]*rhs[1,3];
+    Result[2,2]:=lhs[0,2]*rhs[2,0] + lhs[1,2]*rhs[2,1] + lhs[2,2]*rhs[2,2] + lhs[3,2]*rhs[2,3];
+    Result[2,3]:=lhs[0,2]*rhs[3,0] + lhs[1,2]*rhs[3,1] + lhs[2,2]*rhs[3,2] + lhs[3,2]*rhs[3,3];
+
+    Result[3,0]:=lhs[0,3]*rhs[0,0] + lhs[1,3]*rhs[0,1] + lhs[2,3]*rhs[0,2] + lhs[3,3]*rhs[0,3];
+    Result[3,1]:=lhs[0,3]*rhs[1,0] + lhs[1,3]*rhs[1,1] + lhs[2,3]*rhs[1,2] + lhs[3,3]*rhs[1,3];
+    Result[3,2]:=lhs[0,3]*rhs[2,0] + lhs[1,3]*rhs[2,1] + lhs[2,3]*rhs[2,2] + lhs[3,3]*rhs[2,3];
+    Result[3,3]:=lhs[0,3]*rhs[3,0] + lhs[1,3]*rhs[3,1] + lhs[2,3]*rhs[3,2] + lhs[3,3]*rhs[3,3];
+}
+
+    {$IFNDEF PAS2C}
+    glPushMatrix;
+    glLoadMatrixf(@lhs[0, 0]);
+    glMultMatrixf(@rhs[0, 0]);
+    glGetFloatv(GL_MODELVIEW_MATRIX, @test[0, 0]);
+    glPopMatrix;
+
+    error:=false;
+    for i:=0 to 3 do
+      for j:=0 to 3 do
+        if Abs(test[i, j] - Result[i, j]) > 0.000001 then
+          error:=true;
+
+    if error then
+    begin
+        writeln('shall:');
+        for i:=0 to 3 do
+        begin
+          for j:=0 to 3 do
+            write(test[i, j]);
+          writeln;
+        end;
+
+        writeln('is:');
+        for i:=0 to 3 do
+        begin
+          for j:=0 to 3 do
+            write(Result[i, j]);
+          writeln;
+        end;
+        halt(0);
+    end;
+    {$ENDIF}
+
+end;
+
+
+end.
--- a/hedgewars/uMisc.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uMisc.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -49,7 +49,7 @@
          size: QWord;
          end;
 
-var conversionFormat: PSDL_PixelFormat;
+var conversionFormat : PSDL_PixelFormat;
 
 procedure movecursor(dx, dy: LongInt);
 var x, y: LongInt;
@@ -68,7 +68,7 @@
 var i: LongInt;
     png_ptr: ^png_struct;
     info_ptr: ^png_info;
-    f: file;
+    f: File;
     image: PScreenshot;
 begin
 image:= PScreenshot(screenshot);
@@ -141,6 +141,7 @@
     );
     image: PScreenshot;
     size: QWord;
+    writeResult:LongInt;
 begin
 image:= PScreenshot(screenshot);
 
@@ -168,8 +169,8 @@
 Rewrite(f, 1);
 if IOResult = 0 then
     begin
-    BlockWrite(f, head, sizeof(head));
-    BlockWrite(f, image^.buffer^, size);
+    BlockWrite(f, head, sizeof(head), writeResult);
+    BlockWrite(f, image^.buffer^, size, writeResult);
     Close(f);
     end
 else
@@ -275,6 +276,7 @@
 var convertedSurf: PSDL_Surface;
 begin
     doSurfaceConversion:= tmpsurf;
+{$IFNDEF WEBGL}
     if ((tmpsurf^.format^.bitsperpixel = 32) and (tmpsurf^.format^.rshift > tmpsurf^.format^.bshift)) or
        (tmpsurf^.format^.bitsperpixel = 24) then
     begin
@@ -282,6 +284,7 @@
         SDL_FreeSurface(tmpsurf);
         doSurfaceConversion:= convertedSurf;
     end;
+{$ENDIF}
 end;
 
 {$IFDEF SDL13}
@@ -314,4 +317,4 @@
     SDL_FreeFormat(conversionFormat);
 end;
 
-end.
+end.		
--- a/hedgewars/uMobile.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uMobile.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -73,7 +73,7 @@
 end;
 
 // this function should make the device vibrate in some way
-procedure PerformRumble; inline;
+procedure performRumble; inline;
 {$IFDEF IPHONEOS}const kSystemSoundID_Vibrate = $00000FFF;{$ENDIF}
 begin
     // do not vibrate while synchronising a demo/save
--- a/hedgewars/uRandom.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uRandom.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -31,7 +31,7 @@
 uses uFloat;
 
 procedure SetRandomSeed(Seed: shortstring); // Sets the seed that should be used for generating pseudo-random values.
-function  GetRandomf: hwFloat; overload; // Returns a pseudo-random hwFloat.
+function  GetRandomf: hwFloat; // Returns a pseudo-random hwFloat.
 function  GetRandom(m: LongWord): LongWord; overload; inline; // Returns a positive pseudo-random integer smaller than m.
 procedure AddRandomness(r: LongWord); inline;
 function  rndSign(num: hwFloat): hwFloat; // Returns num with a random chance of having a inverted sign.
@@ -45,10 +45,11 @@
 procedure AddRandomness(r: LongWord); inline;
 begin
 n:= (n + 1) and $3F;
-cirbuf[n]:= cirbuf[n] xor r
+   cirbuf[n]:= cirbuf[n] xor r;
 end;
 
 function GetNext: Longword; inline;
+var s : string;
 begin
 n:= (n + 1) and $3F;
 cirbuf[n]:=
@@ -56,7 +57,8 @@
             cirbuf[(n +  9) and $3F])            {n - 55 mod 64}
             and $7FFFFFFF;                       {mod 2^31}
 
-GetNext:= cirbuf[n]
+   GetNext:= cirbuf[n];
+   str(GetNext, s);
 end;
 
 procedure SetRandomSeed(Seed: shortstring);
@@ -74,7 +76,7 @@
     cirbuf[i]:= $A98765 + 68; // odd number
 
 for i:= 0 to 1023 do
-    GetNext
+   GetNext;
 end;
 
 function GetRandomf: hwFloat;
@@ -84,7 +86,7 @@
 GetRandomf.QWordValue:= GetNext
 end;
 
-function GetRandom(m: LongWord): LongWord; inline;
+function GetRandom(m: LongWord): LongWord; overload; inline;
 begin
 GetNext;
 GetRandom:= GetNext mod m
--- a/hedgewars/uRender.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uRender.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -17,12 +17,13 @@
  *)
 
 {$INCLUDE "options.inc"}
+{$IF GLunit = GL}{$DEFINE GLunit:=GL,GLext}{$ENDIF}
 
 unit uRender;
 
 interface
 
-uses SDLh, uTypes, GLunit, uConsts;
+uses SDLh, uTypes, GLunit, uConsts, uStore, uMatrix;
 
 procedure DrawSprite            (Sprite: TSprite; X, Y, Frame: LongInt);
 procedure DrawSprite            (Sprite: TSprite; X, Y, FrameX, FrameY: LongInt);
@@ -51,7 +52,6 @@
 procedure Tint                  (r, g, b, a: Byte); inline;
 procedure Tint                  (c: Longword); inline;
 
-
 implementation
 uses uVariables;
 
@@ -68,7 +68,7 @@
 begin
 DrawTextureFromRect(X, Y, r^.w, r^.h, r, SourceTexture)
 end;
-
+{
 procedure DrawTextureFromRect(X, Y, W, H: LongInt; r: PSDL_Rect; SourceTexture: PTexture);
 var rr: TSDL_Rect;
     _l, _r, _t, _b: real;
@@ -115,6 +115,63 @@
 
 glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
 glTexCoordPointer(2, GL_FLOAT, 0, @TextureBuffer[0]);
+glDrawArrays(GL_TRIANGLE_FAN, 0, High(VertexBuffer) - Low(VertexBuffer) + 1);
+end;
+}
+
+procedure DrawTextureFromRect(X, Y, W, H: LongInt; r: PSDL_Rect; SourceTexture: PTexture);
+var 
+    rr: TSDL_Rect;
+    VertexBuffer, TextureBuffer: array [0..3] of TVertex2f;
+    //VertexBuffer, TextureBuffer: TVertexRect;
+    _l, _r, _t, _b: GLfloat;
+begin
+if (SourceTexture^.h = 0) or (SourceTexture^.w = 0) then
+    exit;
+
+// do not draw anything outside the visible screen space (first check fixes some sprite drawing, e.g. hedgehogs)
+if (abs(X) > W) and ((abs(X + W / 2) - W / 2) > cScreenWidth / cScaleFactor) then
+    exit;
+if (abs(Y) > H) and ((abs(Y + H / 2 - (0.5 * cScreenHeight)) - H / 2) > cScreenHeight / cScaleFactor) then
+    exit;
+
+rr.x:= X;
+rr.y:= Y;
+rr.w:= W;
+rr.h:= H;
+
+_l:= r^.x / SourceTexture^.w * SourceTexture^.rx;
+_r:= (r^.x + r^.w) / SourceTexture^.w * SourceTexture^.rx;
+_t:= r^.y / SourceTexture^.h * SourceTexture^.ry;
+_b:= (r^.y + r^.h) / SourceTexture^.h * SourceTexture^.ry;
+
+glBindTexture(GL_TEXTURE_2D, SourceTexture^.id);
+
+VertexBuffer[0].X:= X;
+VertexBuffer[0].Y:= Y;
+VertexBuffer[1].X:= rr.w + X;
+VertexBuffer[1].Y:= Y;
+VertexBuffer[2].X:= rr.w + X;
+VertexBuffer[2].Y:= rr.h + Y;
+VertexBuffer[3].X:= X;
+VertexBuffer[3].Y:= rr.h + Y;
+
+TextureBuffer[0].X:= _l;
+TextureBuffer[0].Y:= _t;
+TextureBuffer[1].X:= _r;
+TextureBuffer[1].Y:= _t;
+TextureBuffer[2].X:= _r;
+TextureBuffer[2].Y:= _b;
+TextureBuffer[3].X:= _l;
+TextureBuffer[3].Y:= _b;
+
+SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
+SetTexCoordPointer(@TextureBuffer[0], Length(VertexBuffer));
+
+{$IFDEF GL2}
+UpdateModelviewProjection;
+{$ENDIF}
+
 glDrawArrays(GL_TRIANGLE_FAN, 0, Length(VertexBuffer));
 end;
 
@@ -126,17 +183,30 @@
 procedure DrawTexture(X, Y: LongInt; Texture: PTexture; Scale: GLfloat);
 begin
 
+{$IFDEF GL2}
+hglPushMatrix;
+hglTranslatef(X, Y, 0);
+hglScalef(Scale, Scale, 1);
+{$ELSE}
 glPushMatrix;
 glTranslatef(X, Y, 0);
 glScalef(Scale, Scale, 1);
+{$ENDIF}
 
 glBindTexture(GL_TEXTURE_2D, Texture^.id);
 
-glVertexPointer(2, GL_FLOAT, 0, @Texture^.vb);
-glTexCoordPointer(2, GL_FLOAT, 0, @Texture^.tb);
+SetVertexPointer(@Texture^.vb, Length(Texture^.vb));
+SetTexCoordPointer(@Texture^.tb, Length(Texture^.vb));
+
+{$IFDEF GL2}
+UpdateModelviewProjection;
 glDrawArrays(GL_TRIANGLE_FAN, 0, Length(Texture^.vb));
+hglPopMatrix;
+{$ELSE}
+glDrawArrays(GL_TRIANGLE_FAN, 0, Length(Texture^.vb));
+glPopMatrix;
+{$ENDIF}
 
-glPopMatrix
 end;
 
 procedure DrawTextureF(Texture: PTexture; Scale: GLfloat; X, Y, Frame, Dir, w, h: LongInt);
@@ -155,14 +225,25 @@
 if (abs(Y) > H) and ((abs(Y + OffsetY - (0.5 * cScreenHeight)) - W / 2) * cScaleFactor > cScreenHeight) then
     exit;
 
+{$IFDEF GL2}
+hglPushMatrix;
+hglTranslatef(X, Y, 0);
+{$ELSE}
 glPushMatrix;
 glTranslatef(X, Y, 0);
+{$ENDIF}
+
 if Dir = 0 then Dir:= 1;
 
+{$IFDEF GL2}
+hglRotatef(Angle, 0, 0, Dir);
+hglTranslatef(Dir*OffsetX, OffsetY, 0);
+hglScalef(Scale, Scale, 1);
+{$ELSE}
 glRotatef(Angle, 0, 0, Dir);
-
 glTranslatef(Dir*OffsetX, OffsetY, 0);
 glScalef(Scale, Scale, 1);
+{$ENDIF}
 
 // Any reason for this call? And why only in t direction, not s?
 //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
@@ -197,11 +278,21 @@
 TextureBuffer[3].X:= fl;
 TextureBuffer[3].Y:= fb;
 
-glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
-glTexCoordPointer(2, GL_FLOAT, 0, @TextureBuffer[0]);
+SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
+SetTexCoordPointer(@TextureBuffer[0], Length(VertexBuffer));
+
+{$IFDEF GL2}
+UpdateModelviewProjection;
+{$ENDIF}
+
 glDrawArrays(GL_TRIANGLE_FAN, 0, Length(VertexBuffer));
 
-glPopMatrix
+{$IFDEF GL2}
+hglPopMatrix;
+{$ELSE}
+glPopMatrix;
+{$ENDIF}
+
 end;
 
 procedure DrawSpriteRotated(Sprite: TSprite; X, Y, Dir: LongInt; Angle: real);
@@ -214,19 +305,42 @@
 
 procedure DrawSpriteRotatedF(Sprite: TSprite; X, Y, Frame, Dir: LongInt; Angle: real);
 begin
+
+{$IFDEF GL2}
+hglPushMatrix;
+hglTranslatef(X, Y, 0);
+{$ELSE}
 glPushMatrix;
 glTranslatef(X, Y, 0);
+{$ENDIF}
 
 if Dir < 0 then
+{$IFDEF GL2}
+    hglRotatef(Angle, 0, 0, -1)
+{$ELSE}
     glRotatef(Angle, 0, 0, -1)
+{$ENDIF}
 else
+{$IFDEF GL2}
+    hglRotatef(Angle, 0, 0,  1);
+{$ELSE}
     glRotatef(Angle, 0, 0,  1);
+{$ENDIF}
 if Dir < 0 then
+{$IFDEF GL2}
+    hglScalef(-1.0, 1.0, 1.0);
+{$ELSE}
     glScalef(-1.0, 1.0, 1.0);
+{$ENDIF}
 
 DrawSprite(Sprite, -SpritesData[Sprite].Width div 2, -SpritesData[Sprite].Height div 2, Frame);
 
-glPopMatrix
+{$IFDEF GL2}
+hglPopMatrix;
+{$ELSE}
+glPopMatrix;
+{$ENDIF}
+
 end;
 
 procedure DrawTextureRotated(Texture: PTexture; hw, hh, X, Y, Dir: LongInt; Angle: real);
@@ -238,17 +352,29 @@
 if (abs(Y) > 2 * hh) and ((abs(Y - 0.5 * cScreenHeight) - hh) > cScreenHeight / cScaleFactor) then
     exit;
 
+{$IFDEF GL2}
+hglPushMatrix;
+hglTranslatef(X, Y, 0);
+{$ELSE}
 glPushMatrix;
 glTranslatef(X, Y, 0);
+{$ENDIF}
 
 if Dir < 0 then
     begin
     hw:= - hw;
+{$IFDEF GL2}
+    hglRotatef(Angle, 0, 0, -1);
+{$ELSE}
     glRotatef(Angle, 0, 0, -1);
+{$ENDIF}
     end
 else
-    glRotatef(Angle, 0, 0,  1);
-
+{$IFDEF GL2}
+    hglRotatef(Angle, 0, 0,  1);
+{$ELSE}
+    glRotatef(Angle, 0, 0, 1);
+{$ENDIF}
 
 glBindTexture(GL_TEXTURE_2D, Texture^.id);
 
@@ -261,11 +387,21 @@
 VertexBuffer[3].X:= -hw;
 VertexBuffer[3].Y:= hh;
 
-glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
-glTexCoordPointer(2, GL_FLOAT, 0, @Texture^.tb);
+SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
+SetTexCoordPointer(@Texture^.tb, Length(VertexBuffer));
+
+{$IFDEF GL2}
+UpdateModelviewProjection;
+{$ENDIF}
+
 glDrawArrays(GL_TRIANGLE_FAN, 0, Length(VertexBuffer));
 
-glPopMatrix
+{$IFDEF GL2}
+hglPopMatrix;
+{$ELSE}
+glPopMatrix;
+{$ENDIF}
+
 end;
 
 procedure DrawSprite(Sprite: TSprite; X, Y, Frame: LongInt);
@@ -324,10 +460,11 @@
 end;
 
 procedure DrawLine(X0, Y0, X1, Y1, Width: Single; r, g, b, a: Byte);
-var VertexBuffer: array [0..3] of TVertex2f;
+var VertexBuffer: array [0..1] of TVertex2f;
 begin
+    glEnable(GL_LINE_SMOOTH);
+{$IFNDEF GL2}
     glDisable(GL_TEXTURE_2D);
-    glEnable(GL_LINE_SMOOTH);
 
     glPushMatrix;
     glTranslatef(WorldDx, WorldDy, 0);
@@ -339,13 +476,37 @@
     VertexBuffer[1].X:= X1;
     VertexBuffer[1].Y:= Y1;
 
-    glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
+    SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
     glDrawArrays(GL_LINES, 0, Length(VertexBuffer));
     Tint($FF, $FF, $FF, $FF);
     
     glPopMatrix;
     
     glEnable(GL_TEXTURE_2D);
+
+{$ELSE}
+    EnableTexture(False);
+
+    hglPushMatrix;
+    hglTranslatef(WorldDx, WorldDy, 0);
+    glLineWidth(Width);
+
+    UpdateModelviewProjection;
+
+    Tint(r, g, b, a);
+    VertexBuffer[0].X:= X0;
+    VertexBuffer[0].Y:= Y0;
+    VertexBuffer[1].X:= X1;
+    VertexBuffer[1].Y:= Y1;
+
+    SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
+    glDrawArrays(GL_LINES, 0, Length(VertexBuffer));
+    Tint($FF, $FF, $FF, $FF);
+
+    hglPopMatrix;
+    EnableTexture(True);
+
+{$ENDIF}
     glDisable(GL_LINE_SMOOTH);
 end;
 
@@ -353,12 +514,17 @@
 var VertexBuffer: array [0..3] of TVertex2f;
 begin
 // do not draw anything outside the visible screen space (first check fixes some sprite drawing, e.g. hedgehogs)
+
 if (abs(r.x) > r.w) and ((abs(r.x + r.w / 2) - r.w / 2) * cScaleFactor > cScreenWidth) then
     exit;
 if (abs(r.y) > r.h) and ((abs(r.y + r.h / 2 - (0.5 * cScreenHeight)) - r.h / 2) * cScaleFactor > cScreenHeight) then
     exit;
 
+{$IFDEF GL2}
+EnableTexture(False);
+{$ELSE}
 glDisable(GL_TEXTURE_2D);
+{$ENDIF}
 
 Tint($00, $00, $00, $80);
 
@@ -371,11 +537,17 @@
 VertexBuffer[3].X:= r.x;
 VertexBuffer[3].Y:= r.y + r.h;
 
-glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
+SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
 glDrawArrays(GL_TRIANGLE_FAN, 0, Length(VertexBuffer));
 
 Tint($FF, $FF, $FF, $FF);
+
+{$IFDEF GL2}
+EnableTexture(True);
+{$ELSE}
 glEnable(GL_TEXTURE_2D)
+{$ENDIF}
+
 end;
 
 procedure DrawCircle(X, Y, Radius, Width: LongInt; r, g, b, a: Byte); 
@@ -394,6 +566,9 @@
         CircleVertex[i].X := X + Radius*cos(i*pi/30);
         CircleVertex[i].Y := Y + Radius*sin(i*pi/30);
     end;
+
+{$IFNDEF GL2}
+
     glDisable(GL_TEXTURE_2D);
     glEnable(GL_LINE_SMOOTH);
     glPushMatrix;
@@ -403,6 +578,18 @@
     glPopMatrix;
     glEnable(GL_TEXTURE_2D);
     glDisable(GL_LINE_SMOOTH);
+
+{$ELSE}
+    EnableTexture(False);
+    glEnable(GL_LINE_SMOOTH);
+    hglPushMatrix;
+    glLineWidth(Width);
+    SetVertexPointer(@CircleVertex[0], 60);
+    glDrawArrays(GL_LINE_LOOP, 0, 60);
+    hglPopMatrix;
+    EnableTexture(True);
+    glDisable(GL_LINE_SMOOTH);
+{$ENDIF}
 end;
 
 
@@ -435,10 +622,15 @@
         r:= (Step + 1) * 32 / HHTexture^.w
     end;
 
-
+{$IFDEF GL2}
+    hglPushMatrix();
+    hglTranslatef(X, Y, 0);
+    hglRotatef(Angle, 0, 0, 1);
+{$ELSE}
     glPushMatrix();
     glTranslatef(X, Y, 0);
     glRotatef(Angle, 0, 0, 1);
+{$ENDIF}
 
     glBindTexture(GL_TEXTURE_2D, HHTexture^.id);
 
@@ -451,11 +643,20 @@
     TextureBuffer[3].X:= l;
     TextureBuffer[3].Y:= b;
 
-    glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
-    glTexCoordPointer(2, GL_FLOAT, 0, @TextureBuffer[0]);
+    SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
+    SetTexCoordPointer(@TextureBuffer[0], Length(VertexBuffer));
+
+{$IFDEF GL2}
+    UpdateModelviewProjection;
+{$ENDIF}
+
     glDrawArrays(GL_TRIANGLE_FAN, 0, Length(VertexBuffer));
 
-    glPopMatrix
+{$IFDEF GL2}
+    hglPopMatrix;
+{$ELSE}
+    glPopMatrix;
+{$ENDIF}
 end;
 
 procedure DrawScreenWidget(widget: POnScreenWidget);
@@ -501,12 +702,14 @@
     end;
 {$ELSE}
 begin
-widget:= widget; // avoid hint
+{widget:= widget; // avoid hint}
 {$ENDIF}
 end;
 
 procedure Tint(r, g, b, a: Byte); inline;
-var nc, tw: Longword;
+var
+    nc, tw: Longword;
+    scale:Real = 1.0/255.0;
 begin
     nc:= (a shl 24) or (b shl 16) or (g shl 8) or r;
 
@@ -523,7 +726,12 @@
         b:= tw
         end;
 
+    {$IFDEF GL2}
+    glUniform4f(uMainTintLocation, r*scale, g*scale, b*scale, a*scale);
+    //glColor4ub(r, g, b, a);
+    {$ELSE}
     glColor4ub(r, g, b, a);
+    {$ENDIF}
     lastTint:= nc;
 end;
 
@@ -532,4 +740,5 @@
     Tint(((c shr 24) and $FF), ((c shr 16) and $FF), (c shr 8) and $FF, (c and $FF))
 end;
 
+
 end.
--- a/hedgewars/uRenderUtils.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uRenderUtils.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -68,7 +68,7 @@
     r.y:= rect^.y + 2;
     r.w:= rect^.w - 2;
     r.h:= rect^.h - 4;
-    SDL_FillRect(Surface, @r, FillColor)
+    SDL_FillRect(Surface, @r, FillColor);
 end;
 (*
 function WriteInRoundRect(Surface: PSDL_Surface; X, Y: LongInt; Color: LongWord; Font: THWFont; s: ansistring): TSDL_Rect;
@@ -115,6 +115,7 @@
     pixels: PLongWordArray;
 begin
     TryDo(Surface^.format^.BytesPerPixel = 4, 'flipSurface failed, expecting 32 bit surface', true);
+    SDL_LockSurface(Surface);
     pixels:= Surface^.pixels;
     if Vertical then
     for y := 0 to (Surface^.h div 2) - 1 do
@@ -136,6 +137,7 @@
             pixels^[i]:= pixels^[j];
             pixels^[j]:= tmpPixel;
             end;
+    SDL_UnlockSurface(Surface);
 end;
 
 procedure copyToXY(src, dest: PSDL_Surface; destX, destY: LongInt); inline;
@@ -150,6 +152,10 @@
 begin
     maxDest:= (dest^.pitch div 4) * dest^.h;
     maxSrc:= (src^.pitch div 4) * src^.h;
+
+    SDL_LockSurface(src);
+    SDL_LockSurface(dest);
+
     srcPixels:= src^.pixels;
     destPixels:= dest^.pixels;
 
@@ -169,6 +175,9 @@
             destPixels^[i]:= SDL_MapRGBA(dest^.format, r0, g0, b0, a0);
             end;
         end;
+
+    SDL_UnlockSurface(src);
+    SDL_UnlockSurface(dest);
 end;
 
 procedure DrawSprite2Surf(sprite: TSprite; dest: PSDL_Surface; x,y: LongInt); inline;
@@ -199,6 +208,9 @@
 begin
     //max:= (dest^.pitch div 4) * dest^.h;
     yMax:= dest^.pitch div 4;
+
+    SDL_LockSurface(dest);
+
     destPixels:= dest^.pixels;
 
     dx:= abs(x1-x0);
@@ -225,7 +237,8 @@
             err:= err + dx;
             y0:=y0+sy
             end;
-        end; 
+        end;
+    SDL_UnlockSurface(dest);
 end;
 
 procedure copyRotatedSurface(src, dest: PSDL_Surface); // this is necessary since width/height are read only in SDL, apparently
@@ -235,6 +248,9 @@
     TryDo(src^.format^.BytesPerPixel = 4, 'rotateSurface failed, expecting 32 bit surface', true);
     TryDo(dest^.format^.BytesPerPixel = 4, 'rotateSurface failed, expecting 32 bit surface', true);
 
+    SDL_LockSurface(src);
+    SDL_LockSurface(dest);
+
     srcPixels:= src^.pixels;
     destPixels:= dest^.pixels;
 
@@ -246,6 +262,10 @@
             destPixels^[j]:= srcPixels^[i];
             inc(j)
             end;
+
+    SDL_UnlockSurface(src);
+    SDL_UnlockSurface(dest);
+
 end;
 
 function RenderStringTex(s: ansistring; Color: Longword; font: THWFont): PTexture;
@@ -282,11 +302,11 @@
 var textWidth, textHeight, x, y, w, h, i, j, pos, prevpos, line, numLines, edgeWidth, edgeHeight, cornerWidth, cornerHeight: LongInt;
     finalSurface, tmpsurf, rotatedEdge: PSDL_Surface;
     rect: TSDL_Rect;
-    chars: set of char = [#9,' ',';',':','?','!',','];
+    //chars: set of char = [#9,' ',';',':','?','!',','];
     substr: shortstring;
     edge, corner, tail: TSPrite;
 begin
-    case SpeechType of
+      case SpeechType of
         1: begin;
         edge:= sprSpeechEdge;
         corner:= sprSpeechCorner;
@@ -326,7 +346,7 @@
         begin
         w:= 0;
         i:= round(Sqrt(length(s)) * 2);
-        s:= WrapText(s, #1, chars, i);
+       // s:= WrapText(s, #1, chars, i);
         pos:= 1; prevpos:= 0; line:= 0;
     // Find the longest line for the purposes of centring the text.  Font dependant.
         while pos <= length(s) do
@@ -463,6 +483,7 @@
 
     SDL_FreeSurface(rotatedEdge);
     SDL_FreeSurface(finalSurface);
+
 end;
 
 end.
--- a/hedgewars/uScript.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uScript.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -139,7 +139,7 @@
         lua_pushnil(L);
         end
     else
-        lua_pushinteger(L, not lua_tointeger(L, 1));
+        lua_pushinteger(L, (not lua_tointeger(L, 1)));
     lc_bnot := 1;
 end;
 
@@ -1248,7 +1248,9 @@
 
 function lc_endgame(L : Plua_State) : LongInt; Cdecl;
 begin
+   {$IFNDEF PAS2C}
     L:= L; // avoid compiler hint
+   {$ENDIF}
     GameState:= gsExit;
     lc_endgame:= 0
 end;
@@ -2018,7 +2020,7 @@
 
 procedure ScriptCall(fname : shortstring);
 begin
-if not ScriptLoaded or (not ScriptExists(fname)) then
+if (not ScriptLoaded) or (not ScriptExists(fname)) then
     exit;
 SetGlobals;
 lua_getglobal(luaState, Str2PChar(fname));
@@ -2069,7 +2071,7 @@
 
 function ScriptCall(fname : shortstring; par1, par2, par3, par4 : LongInt) : LongInt;
 begin
-if not ScriptLoaded or (not ScriptExists(fname)) then
+if (not ScriptLoaded) or (not ScriptExists(fname)) then
     exit;
 SetGlobals;
 lua_getglobal(luaState, Str2PChar(fname));
--- a/hedgewars/uSound.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uSound.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -170,7 +170,7 @@
 procedure InitSound;
 const channels: LongInt = {$IFDEF MOBILE}1{$ELSE}2{$ENDIF};
 begin
-    if (not isSoundEnabled) then
+    if not isSoundEnabled then
         exit;
     WriteToConsole('Init sound...');
     isSoundEnabled:= SDL_InitSubSystem(SDL_INIT_AUDIO) >= 0;
@@ -268,7 +268,7 @@
         if (voicepack^.chunks[snd] = nil) and (Soundz[snd].Path = ptVoices) and (Soundz[snd].FileName <> '') then
             begin
             s:= UserPathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
-            if (not FileExists(s)) then
+            if not FileExists(s) then
                 s:= Pathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
             if (not FileExists(s)) and (snd in [sndFirePunch2, sndFirePunch3, sndFirePunch4, sndFirePunch5, sndFirePunch6]) then
                 s:= Pathz[Soundz[sndFirePunch1].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
@@ -286,7 +286,7 @@
         if (defVoicepack^.chunks[snd] = nil) and (Soundz[snd].Path <> ptVoices) and (Soundz[snd].FileName <> '') then
             begin
             s:= UserPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
-            if (not FileExists(s)) then
+            if not FileExists(s) then
                 s:= Pathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
             defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(SDL_RWFromFile(Str2PChar(s), _P'rb'), 1);
@@ -370,7 +370,7 @@
         if (voicepack^.chunks[snd] = nil) and (Soundz[snd].Path = ptVoices) and (Soundz[snd].FileName <> '') then
            begin
             s:= UserPathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
-            if (not FileExists(s)) then
+            if not FileExists(s) then
                 s:= Pathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
             voicepack^.chunks[snd]:= Mix_LoadWAV_RW(SDL_RWFromFile(Str2PChar(s), _P'rb'), 1);
@@ -386,7 +386,7 @@
         if (defVoicepack^.chunks[snd] = nil) and (Soundz[snd].Path <> ptVoices) and (Soundz[snd].FileName <> '') then
             begin
             s:= UserPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
-            if (not FileExists(s)) then
+            if not FileExists(s) then
                 s:= Pathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
             defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(SDL_RWFromFile(Str2PChar(s), _P'rb'), 1);
@@ -402,7 +402,7 @@
 
 procedure StopSound(snd: TSound);
 begin
-    if (not isSoundEnabled) then
+    if not isSoundEnabled then
         exit;
 
     if (lastChan[snd] <> -1) and (Mix_Playing(lastChan[snd]) <> 0) then
@@ -414,7 +414,7 @@
 
 procedure StopSoundChan(chn: LongInt);
 begin
-    if (not isSoundEnabled) then
+    if not isSoundEnabled then
         exit;
 
     if (chn <> -1) and (Mix_Playing(chn) <> 0) then
@@ -423,7 +423,7 @@
 
 procedure StopSoundChan(chn, fadems: LongInt);
 begin
-    if (not isSoundEnabled) then
+    if not isSoundEnabled then
         exit;
 
     if (chn <> -1) and (Mix_Playing(chn) <> 0) then
@@ -437,7 +437,7 @@
         exit;
 
     s:= UserPathPrefix + '/Data/Music/' + MusicFN;
-    if (not FileExists(s)) then
+    if not FileExists(s) then
         s:= PathPrefix + '/Music/' + MusicFN;
     WriteToConsole(msgLoading + s + ' ');
 
--- a/hedgewars/uStats.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uStats.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -138,7 +138,7 @@
         AddVoice(sndBoring, PreviousTeam^.voicepack);
         AddCaption(Format(GetEventString(eidTurnSkipped), CurrentHedgehog^.Name), cWhiteColor, capgrpMessage);
         end
-    else if (not PlacingHogs) then
+    else if not PlacingHogs then
         AddVoice(sndCoward, PreviousTeam^.voicepack);
     end;
 
@@ -215,7 +215,7 @@
 for t:= 0 to Pred(TeamsCount) do
     with TeamsArray[t]^ do
     begin
-        if (not ExtDriven) then
+        if not ExtDriven then
             SendStat(siTeamStats, GetTeamStatString(TeamsArray[t]));
         for i:= 0 to cMaxHHIndex do
             begin
--- a/hedgewars/uStore.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uStore.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -21,7 +21,10 @@
 
 unit uStore;
 interface
-uses {$IFNDEF PAS2C} StrUtils, {$ENDIF}SysUtils, uConsts, SDLh, GLunit, uTypes, uLandTexture, uCaptions, uChat;
+uses SysUtils, uConsts, SDLh, GLunit, uTypes, uLandTexture, uCaptions, uChat
+     {$IFDEF GL2}, uMatrix{$ENDIF}
+     {$IFNDEF PAS2C}, StrUtils{$ENDIF}
+     ;
 
 procedure initModule;
 procedure freeModule;
@@ -55,6 +58,17 @@
 procedure WarpMouse(x, y: Word); inline;
 procedure SwapBuffers; {$IFDEF USE_VIDEO_RECORDING}cdecl{$ELSE}inline{$ENDIF};
 
+{$IFDEF GL2}
+procedure UpdateModelviewProjection;
+procedure EnableTexture(enable:Boolean);
+{$ENDIF}
+
+procedure SetTexCoordPointer(p: Pointer;n: Integer);
+procedure SetVertexPointer(p: Pointer;n: Integer);
+procedure SetColorPointer(p: Pointer;n: Integer);
+procedure BeginWater;
+procedure EndWater;
+
 implementation
 uses uMisc, uConsole, uMobile, uVariables, uUtils, uTextures, uRender, uRenderUtils, uCommands,
      uDebug{$IFDEF USE_CONTEXT_RESTORE}, uWorld{$ENDIF}
@@ -70,6 +84,17 @@
     SDLPrimSurface: PSDL_Surface;
 {$ENDIF}
 
+{$IFDEF GL2}
+    shaderMain: GLuint;
+    shaderWater: GLuint;
+
+    // attributes
+{$ENDIF}
+
+{$IFDEF WEBGL}
+    OpenGLSetupedBefore : boolean;
+{$ENDIF}
+
 function WriteInRect(Surface: PSDL_Surface; X, Y: LongInt; Color: LongWord; Font: THWFont; s: ansistring): TSDL_Rect;
 var w, h: LongInt;
     tmpsurf: PSDL_Surface;
@@ -303,7 +328,7 @@
     i, imflags: LongInt;
 begin
 AddFileLog('StoreLoad()');
-
+WriteLnToConsole('Entering StoreLoad');
 if not reload then
     for fi:= Low(THWFont) to High(THWFont) do
         with Fontz[fi] do
@@ -434,6 +459,8 @@
 if not reload then
     AddProgress;
 IMG_Quit();
+
+WriteLnToConsole('Leaving StoreLoad');
 end;
 
 {$IF NOT DEFINED(S3D_DISABLED) OR DEFINED(USE_VIDEO_RECORDING)}
@@ -662,7 +689,7 @@
 
 function glLoadExtension(extension : shortstring) : boolean;
 begin
-{$IF GLunit = gles11}
+{$IF (GLunit = gles11) OR DEFINED(PAS2C)}
     // FreePascal doesnt come with OpenGL ES 1.1 Extension headers
     extension:= extension; // avoid hint
     glLoadExtension:= false;
@@ -696,12 +723,117 @@
     SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); // try to prefer hardware rendering
 end;
 
+{$IFDEF GL2}
+function CompileShader(shaderFile: string; shaderType: GLenum): GLuint;
+var
+    shader: GLuint;
+    f: Textfile;
+    source, line: AnsiString;
+    sourceA: Pchar;
+    lengthA: GLint;
+    compileResult: GLint;
+    logLength: GLint;
+    log: PChar;
+begin
+    Assign(f, Pathz[ptShaders] + '/' + shaderFile);
+    filemode:= 0; // readonly
+    Reset(f);
+    if IOResult <> 0 then
+    begin
+        AddFileLog('Unable to load ' + shaderFile);
+        halt(-1);
+    end;
+
+    source:='';
+    while not eof(f) do
+    begin
+        ReadLn(f, line);
+        source:= source + line + #10;
+    end;
+    
+    Close(f);
+
+    WriteLnToConsole('Compiling shader: ' + Pathz[ptShaders] + '/' + shaderFile);
+
+    sourceA:=PChar(source);
+    lengthA:=Length(source);
+
+    shader:=glCreateShader(shaderType);
+    glShaderSource(shader, 1, @sourceA, @lengthA);
+    glCompileShader(shader);
+    glGetShaderiv(shader, GL_COMPILE_STATUS, @compileResult);
+    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, @logLength);
+
+    if logLength > 1 then
+    begin
+        log := GetMem(logLength);
+        glGetShaderInfoLog(shader, logLength, nil, log);
+        WriteLnToConsole('========== Compiler log  ==========');
+        WriteLnToConsole(shortstring(log));
+        WriteLnToConsole('===================================');
+        FreeMem(log, logLength);
+    end;
+
+    if compileResult <> GL_TRUE then
+    begin
+        WriteLnToConsole('Shader compilation failed, halting');
+        halt(-1);
+    end;
+
+    CompileShader:= shader;
+end;
+
+function CompileProgram(shaderName: string): GLuint;
+var
+    program_: GLuint;
+    vs, fs: GLuint;
+    linkResult: GLint;
+    logLength: GLint;
+    log: PChar;
+begin
+    program_:= glCreateProgram();
+    vs:= CompileShader(shaderName + '.vs', GL_VERTEX_SHADER);
+    fs:= CompileShader(shaderName + '.fs', GL_FRAGMENT_SHADER);
+    glAttachShader(program_, vs);
+    glAttachShader(program_, fs);
+
+    glBindAttribLocation(program_, aVertex, PChar('vertex'));
+    glBindAttribLocation(program_, aTexCoord, PChar('texcoord'));
+    glBindAttribLocation(program_, aColor, PChar('color'));
+
+    glLinkProgram(program_);
+    glDeleteShader(vs);
+    glDeleteShader(fs);
+
+    glGetProgramiv(program_, GL_LINK_STATUS, @linkResult);
+    glGetProgramiv(program_, GL_INFO_LOG_LENGTH, @logLength);
+
+    if logLength > 1 then
+    begin
+        log := GetMem(logLength);
+        glGetProgramInfoLog(program_, logLength, nil, log);
+        WriteLnToConsole('========== Compiler log  ==========');
+        WriteLnToConsole(shortstring(log));
+        WriteLnToConsole('===================================');
+        FreeMem(log, logLength);
+    end;
+
+    if linkResult <> GL_TRUE then
+    begin
+        WriteLnToConsole('Linking program failed, halting');
+        halt(-1);
+    end;
+
+    CompileProgram:= program_;
+end;
+
+{$ENDIF}
+
 procedure SetupOpenGL;
 //var vendor: shortstring = '';
 var buf: array[byte] of char;
-{$IFDEF USE_VIDEO_RECORDING}
-    AuxBufNum: LongInt;
-{$ENDIF}
+{$IFDEF PAS2C}err: GLenum;{$ENDIF}
+{$IFDEF USE_VIDEO_RECORDING}AuxBufNum: LongInt;{$ENDIF}
     tmpstr: AnsiString;
     tmpint: LongInt;
     tmpn: LongInt;
@@ -709,6 +841,19 @@
     buf[0]:= char(0); // avoid compiler hint
     AddFileLog('Setting up OpenGL (using driver: ' + shortstring(SDL_VideoDriverName(buf, sizeof(buf))) + ')');
 
+{$IFDEF WEBGL}
+    if OpenGLSetupedBefore then
+        begin
+        glViewport(0, 0, cScreenWidth, cScreenHeight);
+        hglMatrixMode(MATRIX_MODELVIEW);
+        hglLoadIdentity();
+        hglScalef(2.0 / cScreenWidth, -2.0 / cScreenHeight, 1.0);
+        hglTranslatef(0, -cScreenHeight / 2, 0);
+        exit;
+        end
+    OpenGLSetupedBefore := true;
+{$ENDIF}
+
 {$IFDEF SDL13}
     // this function creates an opengles1.1 context by default on mobile devices
     // unless you un-comment this two attributes
@@ -733,7 +878,8 @@
         AddFileLog('Texture size too small for backgrounds, disabling.');
         end;
 
-(*  // find out which gpu we are using (for extension compatibility maybe?)
+(*
+    // find out which gpu we are using (for extension compatibility maybe?)
 {$IFDEF IPHONEOS}
     vendor:= vendor; // avoid hint
     cGPUVendor:= gvApple;
@@ -760,8 +906,12 @@
     glGetIntegerv(GL_AUX_BUFFERS, @AuxBufNum);
     AddFileLog('  |----- Number of auxiliary buffers: ' + inttostr(AuxBufNum));
 {$ENDIF}
+{$IFDEF PAS2C}
+
+    // doesn't seem to print >256 chars
+    AddFileLogRaw(PChar(glGetString(GL_EXTENSIONS)));
+{$ELSE}
     AddFileLog('  \----- Extensions: ');
-{$IFNDEF PAS2C}
     // fetch extentions and store them in string
     tmpstr := StrPas(PChar(glGetString(GL_EXTENSIONS)));
     tmpn := WordCount(tmpstr, [' ']);
@@ -779,9 +929,6 @@
         tmpint := tmpint + 3;
     end;
     until (tmpint > tmpn);
-{$ELSE}
-    // doesn't seem to print >256 chars
-    AddFileLogRaw(PChar(glGetString(GL_EXTENSIONS)));
 {$ENDIF}
     AddFileLog('');
 
@@ -810,6 +957,39 @@
     end;
 {$ENDIF}
 
+{$IFDEF GL2}
+
+{$IFDEF PAS2C}
+    err := glewInit();
+    if err <> GLEW_OK then
+    begin
+        WriteLnToConsole('Failed to initialize GLEW.');
+        halt;
+    end;
+{$ENDIF}
+
+{$IFNDEF PAS2C}
+    if not Load_GL_VERSION_2_0 then
+        halt;
+{$ENDIF}
+
+    shaderWater:= CompileProgram('water');
+    glUseProgram(shaderWater);
+    glUniform1i(glGetUniformLocation(shaderWater, pchar('tex0')), 0);
+    uWaterMVPLocation:= glGetUniformLocation(shaderWater, pchar('mvp'));
+
+    shaderMain:= CompileProgram('default');
+    glUseProgram(shaderMain);
+    glUniform1i(glGetUniformLocation(shaderMain, pchar('tex0')), 0);
+    uMainMVPLocation:= glGetUniformLocation(shaderMain, pchar('mvp'));
+    uMainTintLocation:= glGetUniformLocation(shaderMain, pchar('tint'));
+
+    uCurrentMVPLocation:= uMainMVPLocation;
+
+    Tint(255, 255, 255, 255);
+    UpdateModelviewProjection;
+{$ENDIF}
+
 {$IFNDEF S3D_DISABLED}
     if (cStereoMode = smHorizontal) or (cStereoMode = smVertical) or (cStereoMode = smAFR) then
     begin
@@ -827,18 +1007,31 @@
     end;
 {$ENDIF}
 
-    // set view port to whole window
-    glViewport(0, 0, cScreenWidth, cScreenHeight);
+// set view port to whole window
+glViewport(0, 0, cScreenWidth, cScreenHeight);
 
+{$IFDEF GL2}
+    uMatrix.initModule;
+    hglMatrixMode(MATRIX_MODELVIEW);
+    // prepare default translation/scaling
+    hglLoadIdentity();
+    hglScalef(2.0 / cScreenWidth, -2.0 / cScreenHeight, 1.0);
+    hglTranslatef(0, -cScreenHeight / 2, 0);
+
+    EnableTexture(True);
+    
+    glEnableVertexAttribArray(aVertex);
+    glEnableVertexAttribArray(aTexCoord);
+    glGenBuffers(1, @vBuffer);
+    glGenBuffers(1, @tBuffer);
+    glGenBuffers(1, @cBuffer);
+{$ELSE}
     glMatrixMode(GL_MODELVIEW);
     // prepare default translation/scaling
     glLoadIdentity();
     glScalef(2.0 / cScreenWidth, -2.0 / cScreenHeight, 1.0);
     glTranslatef(0, -cScreenHeight / 2, 0);
 
-    // enable alpha blending
-    glEnable(GL_BLEND);
-    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
     // disable/lower perspective correction (will not need it anyway)
     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
     // disable dithering
@@ -847,8 +1040,92 @@
     glEnable(GL_TEXTURE_2D);
     glEnableClientState(GL_VERTEX_ARRAY);
     glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+{$ENDIF}
+
+    // enable alpha blending
+    glEnable(GL_BLEND);
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+    // disable/lower perspective correction (will not need it anyway)
 end;
 
+{$IFDEF GL2}
+procedure EnableTexture(enable:Boolean);
+begin
+    if enable then
+        glUniform1i(glGetUniformLocation(shaderMain, pchar('enableTexture')), 1)
+    else
+        glUniform1i(glGetUniformLocation(shaderMain, pchar('enableTexture')), 0);
+end;
+{$ENDIF}
+
+procedure SetTexCoordPointer(p: Pointer; n: Integer);
+begin
+    {$IFDEF GL2}
+    glBindBuffer(GL_ARRAY_BUFFER, tBuffer);
+    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * n * 2, p, GL_STATIC_DRAW);
+    glEnableVertexAttribArray(aTexCoord);
+    glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 0, pointer(0));
+    {$ELSE}
+    glTexCoordPointer(2, GL_FLOAT, 0, p);
+    {$ENDIF}
+end;
+
+procedure SetVertexPointer(p: Pointer; n: Integer);
+begin
+    {$IFDEF GL2}
+    glBindBuffer(GL_ARRAY_BUFFER, vBuffer);
+    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * n * 2, p, GL_STATIC_DRAW);
+    glEnableVertexAttribArray(aVertex);
+    glVertexAttribPointer(aVertex, 2, GL_FLOAT, GL_FALSE, 0, pointer(0));
+    {$ELSE}
+    glVertexPointer(2, GL_FLOAT, 0, p);
+    {$ENDIF}
+end;
+
+procedure SetColorPointer(p: Pointer; n: Integer);
+begin
+    {$IFDEF GL2}
+    glBindBuffer(GL_ARRAY_BUFFER, cBuffer);
+    glBufferData(GL_ARRAY_BUFFER, n * 4, p, GL_STATIC_DRAW);
+    glEnableVertexAttribArray(aColor);
+    glVertexAttribPointer(aColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, pointer(0));
+    {$ELSE}
+    glColorPointer(4, GL_UNSIGNED_BYTE, 0, p);
+    {$ENDIF}
+end;
+
+{$IFDEF GL2}
+procedure UpdateModelviewProjection;
+var
+    mvp: TMatrix4x4f;
+begin
+    //MatrixMultiply(mvp, mProjection, mModelview);
+    hglMVP(mvp);
+    glUniformMatrix4fv(uCurrentMVPLocation, 1, GL_FALSE, @mvp[0, 0]);
+end;
+{$ENDIF}
+
+(*
+procedure UpdateProjection;
+var
+    s: GLfloat;
+begin
+    s:=cScaleFactor;
+    mProjection[0,0]:= s/cScreenWidth; mProjection[0,1]:=  0.0;             mProjection[0,2]:=0.0; mProjection[0,3]:=  0.0;
+    mProjection[1,0]:= 0.0;            mProjection[1,1]:= -s/cScreenHeight; mProjection[1,2]:=0.0; mProjection[1,3]:=  0.0;
+    mProjection[2,0]:= 0.0;            mProjection[2,1]:=  0.0;             mProjection[2,2]:=1.0; mProjection[2,3]:=  0.0;
+    mProjection[3,0]:= cStereoDepth;   mProjection[3,1]:=  s/2;             mProjection[3,2]:=0.0; mProjection[3,3]:=  1.0;
+
+    {$IFDEF GL2}
+    UpdateModelviewProjection;
+    {$ELSE}
+    glMatrixMode(GL_PROJECTION);
+    glLoadMatrixf(@mProjection[0, 0]);
+    glMatrixMode(GL_MODELVIEW);
+    {$ENDIF}    
+end;
+*)
+
 procedure SetScale(f: GLfloat);
 begin
 // leave immediately if scale factor did not change
@@ -856,18 +1133,62 @@
         exit;
 
     if f = cDefaultZoomLevel then
-        glPopMatrix         // "return" to default scaling
+{$IFDEF GL2}
+        hglPopMatrix         // "return" to default scaling
+{$ELSE}
+        glPopMatrix
+{$ENDIF}
     else                    // other scaling
         begin
+{$IFDEF GL2}
+        hglPushMatrix;       // save default scaling
+        hglLoadIdentity;
+        hglScalef(f / cScreenWidth, -f / cScreenHeight, 1.0);
+        hglTranslatef(0, -cScreenHeight / 2, 0);
+{$ELSE}
         glPushMatrix;       // save default scaling
         glLoadIdentity;
         glScalef(f / cScreenWidth, -f / cScreenHeight, 1.0);
         glTranslatef(0, -cScreenHeight / 2, 0);
+{$ENDIF}
         end;
 
     cScaleFactor:= f;
+
+{$IFDEF GL2}
+    UpdateModelviewProjection;
+{$ENDIF}
 end;
 
+procedure BeginWater;
+begin
+    {$IFDEF GL2}
+    glUseProgram(shaderWater);
+    uCurrentMVPLocation:=uWaterMVPLocation;
+    UpdateModelviewProjection;
+    glDisableVertexAttribArray(aTexCoord);
+    glEnableVertexAttribArray(aColor);
+    {$ELSE}
+    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+    glEnableClientState(GL_COLOR_ARRAY);
+    {$ENDIF}
+end;
+
+procedure EndWater;
+begin
+    {$IFDEF GL2}
+    glUseProgram(shaderMain);
+    uCurrentMVPLocation:=uMainMVPLocation;
+    UpdateModelviewProjection;
+    glDisableVertexAttribArray(aColor);
+    glEnableVertexAttribArray(aTexCoord);
+    {$ELSE}
+    glDisableClientState(GL_COLOR_ARRAY);
+    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+    {$ENDIF}
+end;
+
+
 ////////////////////////////////////////////////////////////////////////////////
 procedure AddProgress;
 var r: TSDL_Rect;
@@ -902,6 +1223,7 @@
     DrawTextureFromRect( -squaresize div 2, (cScreenHeight - squaresize) shr 1, @r, ProgrTex);
 
     SwapBuffers;
+
     inc(Step);
 end;
 
@@ -1178,9 +1500,11 @@
     {$ENDIF}
         AddFileLog('Freeing old primary surface...');
     {$IFNDEF SDL13}        
+    {$IFNDEF WEBGL}
         SDL_FreeSurface(SDLPrimSurface);
         SDLPrimSurface:= nil;
     {$ENDIF}
+    {$ENDIF}
 {$ENDIF}
         end;
 
@@ -1230,6 +1554,7 @@
 {$ENDIF}
 
     SetupOpenGL();
+
     if reinit then
         begin
         // clean the window from any previous content
@@ -1261,6 +1586,10 @@
     ProgrTex:= nil;
     SupportNPOTT:= false;
 
+{$IFDEF WEBGL}
+    OpenGLSetupedBefore := false;
+{$ENDIF}
+
     // init all ammo name texture pointers
     for ai:= Low(TAmmoType) to High(TAmmoType) do
     begin
@@ -1279,6 +1608,13 @@
 
 procedure freeModule;
 begin
+{$IFDEF GL2}
+    glDeleteProgram(shaderMain);
+    glDeleteProgram(shaderWater);
+    glDeleteBuffers(1, @vBuffer);
+    glDeleteBuffers(1, @tBuffer);
+    glDeleteBuffers(1, @cBuffer);
+{$ENDIF}
     StoreRelease(false);
     TTF_Quit();
 {$IFDEF SDL13}
--- a/hedgewars/uTeams.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uTeams.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -573,8 +573,9 @@
 end;
 
 procedure chBind(var id: shortstring);
-var KeyName, Modifier, tmp: shortstring;
-    b: LongInt;
+var KeyName, Modifier, tmp : shortstring;
+    b			   : LongInt;
+    i			   : Integer;
 begin
 KeyName:= '';
 Modifier:= '';
@@ -582,7 +583,9 @@
 if CurrentTeam = nil then
     exit;
 
-if(Pos('mod:', id) <> 0)then
+i := Pos('mod:', id);
+
+if(i <> 0)then
     begin
     tmp:= '';
     SplitBySpace(id, tmp);
--- a/hedgewars/uTypes.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uTypes.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -44,7 +44,8 @@
     // Different files are stored in different folders, this enumeration is used to tell which folder to use
     TPathType = (ptNone, ptData, ptGraphics, ptThemes, ptCurrTheme, ptTeams, ptMaps,
             ptMapCurrent, ptDemos, ptSounds, ptGraves, ptFonts, ptForts,
-            ptLocale, ptAmmoMenu, ptHedgehog, ptVoices, ptHats, ptFlags, ptMissionMaps, ptSuddenDeath, ptButtons);
+            ptLocale, ptAmmoMenu, ptHedgehog, ptVoices, ptHats, ptFlags, ptMissionMaps, ptSuddenDeath, ptButtons,
+            ptShaders);
 
     // Available sprites for displaying stuff
     TSprite = (sprWater, sprCloud, sprBomb, sprBigDigit, sprFrame,
@@ -200,6 +201,8 @@
             X, Y: GLint;
             end;
 
+    TMatrix4x4f = array[0..3, 0..3] of GLfloat;
+
     PTexture = ^TTexture;
     TTexture = record
             id: GLuint;
@@ -390,12 +393,12 @@
     TClan = record
             Color: Longword;
             Teams: array[0..Pred(cMaxTeams)] of PTeam;
-            TeamsNumber: Longword;
+	    TeamsNumber: LongInt;{xymeng, org:LongWord}
             TagTeamIndex: Longword;
             CurrTeam: LongWord;
             ClanHealth: LongInt;
             ClanIndex: LongInt;
-            TurnNumber: LongWord;
+	    TurnNumber: LongInt;{xymeng, org:LongWord}
             Flawless: boolean;
             end;
 
@@ -430,11 +433,13 @@
             gidRandomMineTimer, gidDamageModifier, gidResetHealth, gidAISurvival, 
             gidInfAttack, gidResetWeps, gidPerHogAmmo, gidTagTeam);
 
+
     TLandArray = packed array of array of LongWord;
     TCollisionArray = packed array of array of Word;
+    TDirtyTag = packed array of array of byte;
+				 
     TPreview  = packed array[0..127, 0..31] of byte;
-    TDirtyTag = packed array of array of byte;
-
+  
     PWidgetMovement = ^TWidgetMovement;
     TWidgetMovement = record
         animate   : Boolean;
--- a/hedgewars/uUtils.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uUtils.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -25,16 +25,19 @@
 
 procedure SplitBySpace(var a, b: shortstring);
 procedure SplitByChar(var a, b: shortstring; c: char);
-procedure SplitByChar(var a, b: ansistring; c: char);
 
 {$IFNDEF PAS2C}
+procedure SplitByChar(var a, b: ansistring; c: char);
+{$ENDIF}
+
+//{$IFNDEF PAS2C}
 function  EnumToStr(const en : TGearType) : shortstring; overload;
 function  EnumToStr(const en : TVisualGearType) : shortstring; overload;
 function  EnumToStr(const en : TSound) : shortstring; overload;
 function  EnumToStr(const en : TAmmoType) : shortstring; overload;
 function  EnumToStr(const en : THogEffect) : shortstring; overload;
 function  EnumToStr(const en : TCapGroup) : shortstring; overload;
-{$ENDIF}
+//{$ENDIF}
 
 function  Min(a, b: LongInt): LongInt; inline;
 function  Max(a, b: LongInt): LongInt; inline;
@@ -86,7 +89,7 @@
     logMutex: TRTLCriticalSection; // mutex for debug file
 {$ENDIF}
 {$ENDIF}
-var CharArray: array[byte] of Char;
+var CharArray: array[0..255] of Char;
 
 procedure SplitBySpace(var a,b: shortstring);
 begin
@@ -105,11 +108,15 @@
             Inc(a[t], 32);
     b:= copy(a, i + 1, Length(a) - i);
     a[0]:= char(Pred(i))
+    {$IFDEF PAS2C}
+       a[i] := 0;
+    {$ENDIF}
     end
 else
     b:= '';
 end;
 
+{$IFNDEF PAS2C}
 procedure SplitByChar(var a, b: ansistring; c: char);
 var i: LongInt;
 begin
@@ -119,9 +126,10 @@
     b:= copy(a, i + 1, Length(a) - i);
     setlength(a, Pred(i));
     end else b:= '';
-end;
+end; { SplitByChar }
+{$ENDIF}
 
-{$IFNDEF PAS2C}
+//{$IFNDEF PAS2C}
 function EnumToStr(const en : TGearType) : shortstring; overload;
 begin
 EnumToStr:= GetEnumName(TypeInfo(TGearType), ord(en))
@@ -150,7 +158,7 @@
 begin
 EnumToStr := GetEnumName(TypeInfo(TCapGroup), ord(en))
 end;
-{$ENDIF}
+//{$ENDIF}
 
 function Min(a, b: LongInt): LongInt;
 begin
@@ -271,10 +279,14 @@
 
 
 function Str2PChar(const s: shortstring): PChar;
+var i :Integer ;
 begin
-CharArray:= s;
+   for i:= 1 to Length(s) do
+      begin
+      CharArray[i - 1] := s[i];
+      end;
 CharArray[Length(s)]:= #0;
-Str2PChar:= @CharArray
+   Str2PChar:= @(CharArray[0]);
 end;
 
 
@@ -293,16 +305,21 @@
 
 procedure AddFileLog(s: shortstring);
 begin
-s:= s;
+// s:= s;
+{$IFNDEF WEBGL}
 {$IFDEF DEBUGFILE}
+
 {$IFDEF USE_VIDEO_RECORDING}
 EnterCriticalSection(logMutex);
 {$ENDIF}
 writeln(f, inttostr(GameTicks)  + ': ' + s);
 flush(f);
+
 {$IFDEF USE_VIDEO_RECORDING}
 LeaveCriticalSection(logMutex);
 {$ENDIF}
+
+{$ENDIF}
 {$ENDIF}
 end;
 
--- a/hedgewars/uVariables.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uVariables.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -21,7 +21,7 @@
 unit uVariables;
 interface
 
-uses SDLh, uTypes, uFloat, GLunit, uConsts, Math, uMobile, uUtils;
+uses SDLh, uTypes, uFloat, GLunit, uConsts, Math, uMobile, uUtils, uMatrix;
 
 var
 /////// init flags ///////
@@ -76,7 +76,7 @@
 
     CheckSum        : LongWord;
     CampaignVariable: shortstring;
-    GameTicks       : LongWord;
+    GameTicks       : LongInt; {xymeng:originally LongWord}
     GameState       : TGameState;
     GameType        : TGameType;
     InputMask       : LongWord;
@@ -197,7 +197,7 @@
 
     LuaGoals        : shortstring;
 
-    LuaTemplateNumber : LongWord;
+    LuaTemplateNumber : LongInt; {org: LongWord}
 
     VoiceList : array[0..7] of TVoice =  (
                     ( snd: sndNone; voicepack: nil),
@@ -245,9 +245,11 @@
         'Graphics/Flags',                // ptFlags
         'Missions/Maps',                 // ptMissionMaps
         'Graphics/SuddenDeath',           // ptSuddenDeath
-        'Graphics/Buttons'                // ptButton
+        'Graphics/Buttons',               // ptButton
+        'Shaders'                        // ptShaders
     );
 
+var
     Fontz: array[THWFont] of THHFont = (
             (Handle: nil;
             Height: 12;
@@ -823,7 +825,7 @@
             TimeAfterTurn: Longword;
             minAngle, maxAngle: Longword;
             isDamaging: boolean;
-            SkipTurns: Longword;
+	    SkipTurns: LongInt; {xymeng, org:LongWord}
             PosCount: Longword;
             PosSprite: TSprite;
             ejectX, ejectY: Longint;
@@ -2489,6 +2491,7 @@
     SyncTexture,
     ConfirmTexture: PTexture;
     cScaleFactor: GLfloat;
+    cStereoDepth: GLfloat;
     SupportNPOTT: Boolean;
     Step: LongInt;
     squaresize : LongInt;
@@ -2527,6 +2530,23 @@
 
     lastTurnChecksum : Longword;
 
+    mModelview: TMatrix4x4f;
+    mProjection: TMatrix4x4f;
+    vBuffer: GLuint; // vertex buffer
+    tBuffer: GLuint; // texture coords buffer
+    cBuffer: GLuint; // color buffer
+
+    uCurrentMVPLocation: GLint;
+
+    uMainMVPLocation: GLint;
+    uMainTintLocation: GLint;
+
+    uWaterMVPLocation: GLint;
+
+    aVertex: GLint;
+    aTexCoord: GLint;
+    aColor: GLint;
+
 var trammo:  array[TAmmoStrId] of ansistring;   // name of the weapon
     trammoc: array[TAmmoStrId] of ansistring;   // caption of the weapon
     trammod: array[TAmmoStrId] of ansistring;   // description of the weapon
@@ -2728,13 +2748,10 @@
     vobSDVelocity:= 15;
     vobSDFallSpeed:= 250;
 
-{$IFNDEF PAS2C}
-    //TODO: FIXME!!
     cMinScreenWidth:= min(cScreenWidth, 640);
     cMinScreenHeight:= min(cScreenHeight, 480);
     cOrigScreenWidth:= cScreenWidth;
     cOrigScreenHeight:= cScreenHeight;
-{$ENDIF}
 
     cNewScreenWidth    := cScreenWidth;
     cNewScreenHeight   := cScreenHeight;
@@ -2744,6 +2761,13 @@
     cMapName:= '';
 
     LuaTemplateNumber:= 0;
+    cStereoDepth := 0;
+
+    MatrixLoadIdentity(mModelview);
+    MatrixLoadIdentity(mProjection);
+    aVertex:= 0;
+    aTexCoord:= 1;
+    aColor:= 2;
 end;
 
 procedure freeModule;
--- a/hedgewars/uVisualGears.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uVisualGears.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -82,7 +82,7 @@
 // ==================================================================
 
 // ==================================================================
-const doStepHandlers: array[TVisualGearType] of TVGearStepProcedure =
+const vdoStepHandlers: array[TVisualGearType] of TVGearStepProcedure =
         (
             @doStepFlake,
             @doStepCloud,
@@ -160,7 +160,7 @@
 gear^.X:= real(X);
 gear^.Y:= real(Y);
 gear^.Kind := Kind;
-gear^.doStep:= doStepHandlers[Kind];
+gear^.doStep:= vdoStepHandlers[Kind];
 gear^.State:= 0;
 gear^.Tint:= $FFFFFFFF;
 gear^.uid:= VGCounter;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hedgewars/uWeb.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -0,0 +1,174 @@
+
+// defines functions used for web port
+
+unit uWeb;
+interface
+
+type
+    TResourceList = record
+        count : Integer;
+        files : array[0..500] of shortstring;
+    end;
+
+function generateResourceList:TResourceList;
+
+implementation
+
+uses uConsts, uVariables, uTypes;
+
+function readThemeCfg:TResourceList; forward;
+
+function generateResourceList:TResourceList;
+var
+    cfgRes : TResourceList;
+    i,j : Integer;
+    t, t2 : shortstring;
+    si : TSprite;
+    res : TResourceList;
+
+begin
+
+    res.count := 0;
+
+    for i:= 0 to Pred(TeamsCount) do
+        with TeamsArray[i]^ do
+            begin
+                Str(i, t);
+                
+                res.files[res.count] := UserPathz[ptGraves] + '/' + GraveName;
+                res.files[res.count + 1] := UserPathz[ptForts] + '/' + FortName;
+                res.files[res.count + 2] := UserPathz[ptGraphics] + '/' + FortName;
+                res.files[res.count + 3] := UserPathz[ptFlags] + '/' + flag;
+
+                inc(res.count, 4);
+                
+            end;
+            
+    for si:= Low(TSprite) to High(TSprite) do
+    with SpritesData[si] do
+        begin
+            Str(si, t);
+            res.files[res.count] := UserPathz[Path] + '/' + FileName;
+            res.files[res.count + 1] := UserPathz[AltPath] + '/' + FileName;
+            inc(res.count, 2);
+
+        end;
+        
+    for i:= 0 to Pred(ClansCount) do
+    with CLansArray[i]^ do
+    begin
+        for j:= 0 to Pred(TeamsNumber) do
+        begin
+            with Teams[j]^ do
+            begin
+                Str(i, t);
+                Str(j, t2);
+                res.files[res.count] := UserPathz[ptForts] + '/' + FortName;
+                inc(res.count);
+
+            end;
+        end;
+    end;
+    
+    cfgRes := readThemeCfg();
+    
+    for i:= 0 to Pred(cfgRes.count) do
+    begin
+        res.files[res.count] := cfgRes.files[i];
+        inc(res.count);
+    end;
+    
+    res.files[res.count] := UserPathz[ptFlags] + '/cpu';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptFlags] + '/hedgewars';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptGraphics] + '/' + cHHFileName;
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptGraphics] + '/Girder';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptCurrTheme] + '/LandTex';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptCurrTheme] + '/LandBackTex';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptCurrTheme] + '/Girder';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptCurrTheme] + '/Border';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptMapCurrent] + '/mask';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptMapCurrent] + '/map';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptGraphics] + '/missions';
+    inc(res.count);
+    
+    res.files[res.count] := UserPathz[ptGraphics] + '/Progress';
+    inc(res.count);
+        
+    res.files[res.count] := UserPathz[ptGraves] + '/Statue';
+    inc(res.count);
+
+    res.files[res.count] := UserPathz[ptGraphics] + '/' + cCHFileName;
+    inc(res.count);
+
+    generateResourceList:=res;
+end;
+
+function readThemeCfg : TResourceList;
+var
+s,key : shortstring;
+f : TextFile;
+i: Integer;
+res : TResourceList;
+begin
+    s:=Pathz[ptCurrTheme] + '/' + cThemeCFGFilename;
+
+    Assign(f, s);
+    {$I-}
+
+    filemode := 0;
+    Reset(f);
+
+    res.count := 0;
+    
+    while not eof(f) do
+    begin
+    Readln(f, s);
+    
+    if Length(s) = 0 then
+        continue;
+    if s[1] = ';' then
+        continue;
+        
+    i:= Pos('=', s);
+    key:= Trim(Copy(s, 1, Pred(i)));
+    Delete(s, 1, i);
+    
+    if (key = 'object') or (key = 'spray') then
+    begin
+        i:=Pos(',', s);
+        
+        res.files[res.count] := Pathz[ptCurrTheme] + '/' + Trim(Copy(s, 1, Pred(i)));
+        res.files[res.count + 1] := Pathz[ptGraphics] + '/' + Trim(Copy(s, 1, Pred(i)));
+        inc(res.count, 2);
+        
+    end;
+    
+    end;
+
+    close(f);
+    {$I+}
+    
+    readThemeCfg := res;
+end;
+
+end.
--- a/hedgewars/uWorld.pas	Sun Nov 11 16:53:16 2012 +0100
+++ b/hedgewars/uWorld.pas	Sun Nov 11 17:15:19 2012 +0100
@@ -64,6 +64,9 @@
 {$IFDEF USE_VIDEO_RECORDING}    
     , uVideoRec
 {$ENDIF}    
+{$IFDEF GL2}
+    , uMatrix
+{$ENDIF}
     ;
 
 var cWaveWidth, cWaveHeight: LongInt;
@@ -755,9 +758,9 @@
 end;
 
 procedure DrawWater(Alpha: byte; OffsetY: LongInt);
-var VertexBuffer: array [0..3] of TVertex2f;
-    r: TSDL_Rect;
-    lw, lh: GLfloat;
+var VertexBuffer : array [0..3] of TVertex2f;
+    r		 : TSDL_Rect;
+    lw, lh	 : GLfloat;
 begin
 if SuddenDeathDmg then
     begin
@@ -783,7 +786,7 @@
     begin
         if r.y < 0 then
             r.y:= 0;
-
+ 
         glDisable(GL_TEXTURE_2D);
         VertexBuffer[0].X:= -lw;
         VertexBuffer[0].Y:= r.y;
@@ -794,6 +797,7 @@
         VertexBuffer[3].X:= -lw;
         VertexBuffer[3].Y:= lh;
 
+{$IFNDEF GL2}
         glDisableClientState(GL_TEXTURE_COORD_ARRAY);
         glEnableClientState(GL_COLOR_ARRAY);
         if SuddenDeathDmg then
@@ -807,8 +811,29 @@
 
         glDisableClientState(GL_COLOR_ARRAY);
         glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+
+{$ELSE}
+        UpdateModelviewProjection;
+
+        BeginWater;
+        if SuddenDeathDmg then
+            SetColorPointer(@SDWaterColorArray[0], 4)
+        else
+            SetColorPointer(@WaterColorArray[0], 4);
+
+        SetVertexPointer(@VertexBuffer[0], 4);
+
+        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
+
+        EndWater;
+{$ENDIF}
+
+        {$IFNDEF GL2}
         glColor4ub($FF, $FF, $FF, $FF); // must not be Tint() as color array seems to stay active and color reset is required
+        {$ENDIF}
+        {$IFNDEF WEBGL}
         glEnable(GL_TEXTURE_2D);
+        {$ENDIF}
     end;
 end;
 
@@ -862,8 +887,13 @@
 TextureBuffer[3].Y:= TextureBuffer[2].Y;
 
 
-glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
-glTexCoordPointer(2, GL_FLOAT, 0, @TextureBuffer[0]);
+SetVertexPointer(@VertexBuffer[0], Length(VertexBuffer));
+SetTexCoordPointer(@TextureBuffer[0], Length(VertexBuffer));
+
+{$IFDEF GL2}
+UpdateModelviewProjection;
+{$ENDIF}
+
 glDrawArrays(GL_TRIANGLE_FAN, 0, Length(VertexBuffer));
 
 Tint($FF, $FF, $FF, $FF);
@@ -1084,24 +1114,34 @@
     else if rm = rmLeftEye then
         d:= -d;
     stereoDepth:= stereoDepth + d;
+
+    {$IFDEF GL2}
+    hglMatrixMode(MATRIX_PROJECTION);
+    hglTranslatef(d, 0, 0);
+    hglMatrixMode(MATRIX_MODELVIEW);
+    {$ELSE}
     glMatrixMode(GL_PROJECTION);
     glTranslatef(d, 0, 0);
     glMatrixMode(GL_MODELVIEW);
+    {$ENDIF}
 {$ENDIF}
 end;
  
 procedure ResetDepth(rm: TRenderMode);
 begin
-{$IFDEF S3D_DISABLED}
-    rm:= rm; // avoid hint
-    exit;
-{$ELSE}
+{$IFNDEF S3D_DISABLED}
     if rm = rmDefault then
         exit;
+    {$IFDEF GL2}
+    hglMatrixMode(MATRIX_PROJECTION);
+    hglTranslatef(-stereoDepth, 0, 0);
+    hglMatrixMode(MATRIX_MODELVIEW);    
+    {$ELSE}
     glMatrixMode(GL_PROJECTION);
     glTranslatef(-stereoDepth, 0, 0);
     glMatrixMode(GL_MODELVIEW);
-    stereoDepth:= 0;
+    {$ENDIF}
+    cStereoDepth:= 0;
 {$ENDIF}
 end;
  
@@ -1161,6 +1201,30 @@
 
     DrawWater(255, 0);
 
+(*
+// Attack bar
+    if CurrentTeam <> nil then
+        case AttackBar of
+        //1: begin
+        //r:= StuffPoz[sPowerBar];
+        //{$WARNINGS OFF}
+        //r.w:= (CurrentHedgehog^.Gear^.Power * 256) div cPowerDivisor;
+        //{$WARNINGS ON}
+        //DrawSpriteFromRect(r, cScreenWidth - 272, cScreenHeight - 48, 16, 0, Surface);
+        //end;
+        2: with CurrentHedgehog^ do
+                begin
+                tdx:= hwSign(Gear^.dX) * Sin(Gear^.Angle * Pi / cMaxAngle);
+                tdy:= - Cos(Gear^.Angle * Pi / cMaxAngle);
+                for i:= (Gear^.Power * 24) div cPowerDivisor downto 0 do
+                    DrawSprite(sprPower,
+                            hwRound(Gear^.X) + GetLaunchX(CurAmmoType, hwSign(Gear^.dX), Gear^.Angle) + LongInt(round(WorldDx + tdx * (24 + i * 2))) - 16,
+                            hwRound(Gear^.Y) + GetLaunchY(CurAmmoType, Gear^.Angle) + LongInt(round(WorldDy + tdy * (24 + i * 2))) - 16,
+                            i)
+                end
+        end;
+*)
+
 DrawVisualGears(1);
 DrawGears;
 DrawVisualGears(6);
@@ -1427,12 +1491,13 @@
 // Chat
 DrawChat;
 
+
 // various captions
 if fastUntilLag then
     DrawTextureCentered(0, (cScreenHeight shr 1), SyncTexture);
 if isPaused then
     DrawTextureCentered(0, (cScreenHeight shr 1), PauseTexture);
-if not isFirstFrame and (missionTimer <> 0) or isPaused or fastUntilLag or (GameState = gsConfirm) then
+if (not isFirstFrame) and (missionTimer <> 0) or isPaused or fastUntilLag or (GameState = gsConfirm) then
     begin
     if (ReadyTimeLeft = 0) and (missionTimer > 0) then
         dec(missionTimer, Lag);
@@ -1549,11 +1614,11 @@
         glDisable(GL_TEXTURE_2D);
 
         glVertexPointer(2, GL_FLOAT, 0, @VertexBuffer[0]);
-        glDrawArrays(GL_TRIANGLE_FAN, 0, Length(VertexBuffer));
+        glDrawArrays(GL_TRIANGLE_FAN, 0, High(VertexBuffer) - Low(VertexBuffer) + 1);
 
         glEnable(GL_TEXTURE_2D);
         Tint($FF, $FF, $FF, $FF);
-        if not isFirstFrame and ((ScreenFadeValue = 0) or (ScreenFadeValue = sfMax)) then
+        if (not isFirstFrame) and ((ScreenFadeValue = 0) or (ScreenFadeValue = sfMax)) then
             ScreenFade:= sfNone
         end
     end;
@@ -1628,6 +1693,7 @@
         DrawSprite(sprArrow, CursorPoint.X, cScreenHeight - CursorPoint.Y, (RealTicks shr 6) mod 8)
         end
     end;
+
 isFirstFrame:= false
 end;