ecere: Further tweaks for Emscripten
[sdk] / ecere / src / com / instance.ec
index c486597..db2b5d2 100644 (file)
@@ -1,10 +1,18 @@
+#define _Noreturn
+
 namespace com;
 
+// #define DISABLE_MEMMGR
+
 import "BinaryTree"
 import "OldList"
 import "String"
 import "dataTypes"
 
+//#define JUST_CHECK_LEAKS
+//#define JUST_CHECK_BOUNDARIES
+
+
 #if defined(ECERE_BOOTSTRAP) || defined(ECERE_STATIC)
 #define dllexport
 #if !defined(ECERE_BOOTSTRAP)
@@ -14,9 +22,15 @@ import "dataTypes"
 
 #undef __BLOCKS__
 
+#if !defined(__EMSCRIPTEN__)
 #if !defined(ECERE_BOOTSTRAP)
 import "Mutex"
 #endif
+#endif
+
+#if defined(__EMSCRIPTEN__)
+#define GetCurrentThreadID()  0
+#endif
 
 // #define MEMINFO
 /*
@@ -25,12 +39,21 @@ import "Mutex"
  #define REDZONE   256
 #endif
 */
-#ifndef REDZONE
+
+#if defined(JUST_CHECK_LEAKS) || !defined(REDZONE)
+#undef REDZONE
 #define REDZONE 0
 #endif
 
+
+#ifdef _DEBUG
+// #define MEMTRACKING
+#endif
+
 #ifdef MEMINFO
+#if !defined(__EMSCRIPTEN__)
 import "Thread"
+#endif
 static define MAX_MEMORY_LOC = 40;
 static define MAX_STACK_FRAMES = 1000;
 
@@ -49,6 +72,28 @@ static uint memoryErrorsCount = 0;
 default:
 #define property _property
 
+#if defined(DISABLE_MEMMGR)
+
+#ifndef ECERE_BOOTSTRAP
+# include <malloc.h>
+#endif
+
+#if defined(__WIN32__)
+#ifdef ECERE_BOOTSTRAP
+uintsize _msize(void * p);
+#endif
+
+#  define msize _msize
+#else
+#ifdef ECERE_BOOTSTRAP
+uintsize malloc_usable_size(void * p);
+#endif
+
+#  define msize malloc_usable_size
+#endif
+
+#endif
+
 #include <stdlib.h>
 #include <stdio.h>
 
@@ -82,8 +127,12 @@ default:
 extern int __ecereVMethodID_class_OnGetDataFromString;
 
 // IMPLEMENTATION FOR THESE IN _instance.c:
+#if defined(__MINGW32__) && !defined(_W64) && __GNUC__ < 4
+dllexport int isblank(int c);
+#endif
 bool Instance_LocateModule(const char * name, const char * fileName);
 void Instance_COM_Initialize(int argc, char ** argv, char ** parsedCommand, int * argcPtr, const char *** argvPtr);
+void System_SetArgs(int argc, char ** argv, int * argcPtr, const char *** argvPtr);
 void * Instance_Module_Load(const char * libLocation, const char * name, void ** Load, void ** Unload);
 void Instance_Module_Free(void * library);
 #if defined(_DEBUG)
@@ -151,7 +200,9 @@ public dllexport void MemoryGuard_PushLoc(const char * loc)
 {
 #ifdef MEMINFO
    MemStack stack;
+#if !defined(__EMSCRIPTEN__)
    memMutex.Wait();
+#endif
    stack = (MemStack)memStacks.Find(GetCurrentThreadID());
    if(!stack)
    {
@@ -161,22 +212,28 @@ public dllexport void MemoryGuard_PushLoc(const char * loc)
    }
    if(stack.pos < MAX_STACK_FRAMES)
       stack.frames[stack.pos++] = loc;
+#if !defined(__EMSCRIPTEN__)
    memMutex.Release();
 #endif
+#endif
 }
 
 public dllexport void MemoryGuard_PopLoc()
 {
 #ifdef MEMINFO
    MemStack stack;
+#if !defined(__EMSCRIPTEN__)
    memMutex.Wait();
+#endif
    stack = (MemStack)memStacks.Find(GetCurrentThreadID());
    if(stack && stack.pos > 0)
    {
       stack.pos--;
    }
+#if !defined(__EMSCRIPTEN__)
    memMutex.Release();
 #endif
+#endif
 }
 
 #ifdef ECERE_STATIC
@@ -317,7 +374,7 @@ public:
    ClassTemplateArgument * templateArgs;
    Class templateClass;
    OldList templatized;
-   int numParams;
+   int numParams;       // TOTAL number of params including all base classes; use templateParams.count for this level
    bool isInstanceClass;
    bool byValueSystemClass;
 
@@ -671,19 +728,24 @@ bool allocateInternal;
 #endif
 
 static uint TOTAL_MEM = 0;
-#ifndef MEMINFO
+#if !defined(MEMINFO) && !defined(DISABLE_MEMMGR)
 static uint OUTSIDE_MEM = 0;
 #endif
 
+#if !defined(__EMSCRIPTEN__)
 #if !defined(ECERE_BOOTSTRAP)
 static Mutex memMutex { };
 #endif
+#endif
 
 private class MemBlock : struct
 {
    MemBlock prev, next;
    MemPart part;
    uint size;
+#if !defined(MEMINFO) && defined(MEMTRACKING)
+   Class _class;
+#endif
 };
 
 private class MemPart : struct
@@ -990,6 +1052,7 @@ private struct BlockPool
 
    void Remove(MemBlock block)
    {
+      MemPart part = block.part;
       /*if(blockSize == 28)
          printf("BlockPool::Remove (%d)\n", blockSize);*/
       if(block.prev)
@@ -1011,14 +1074,13 @@ private struct BlockPool
          printf("Setting new free block: part = %x\n", block.part);
       }*/
 
-      block.part.blocksUsed--;
+      part.blocksUsed--;
       numBlocks--;
-      block.part.pool->usedSpace -= block.size;
+      part.pool->usedSpace -= block.size;
 
-      if(!block.part.blocksUsed && numBlocks && totalSize > numBlocks + numBlocks / 2)
+      if(!part.blocksUsed && numBlocks && totalSize > numBlocks + numBlocks / 2)
       {
          MemBlock next = free, prev = null;
-         MemPart part = block.part;
          free = null;
          totalSize -= part.size;
          /*if(blockSize == 28)
@@ -1050,7 +1112,7 @@ private struct BlockPool
    }
 };
 
-#ifndef MEMINFO
+#if !defined(MEMINFO) && !defined(DISABLE_MEMMGR)
 static BlockPool * pools; //[NUM_POOLS];
 
 /*static uint PosFibonacci(uint number)
@@ -1113,6 +1175,7 @@ static uint log1_5i(uint number)
          break;
       current = current * 3 / 2;
       if(current == 1) current = 2;
+      if(current & 7) current += 8 - (current & 7);
    }
    return pos;
 }
@@ -1125,6 +1188,7 @@ static uint pow1_5(uint number)
    {
       current = current * 3 / 2;
       if(current == 1) current = 2;
+      if(current & 7) current += 8 - (current & 7);
    }
    return (uint)current;
 }
@@ -1140,6 +1204,7 @@ static uint pow1_5i(uint number)
          return (uint)current;
       current = current * 3 / 2;
       if(current == 1) current = 2;
+      if(current & 7) current += 8 - (current & 7);
    }
    return (uint)current;
 }
@@ -1161,7 +1226,7 @@ public uint pow2i(uint number)
    return 1<<log2i(number);
 }
 
-#ifndef MEMINFO
+#if !defined(MEMINFO) && !defined(DISABLE_MEMMGR)
 static bool memoryInitialized = false;
 static void InitMemory()
 {
@@ -1187,7 +1252,7 @@ static void InitMemory()
 }
 #endif
 
-#ifndef MEMINFO
+#if !defined(MEMINFO) && !defined(DISABLE_MEMMGR)
 static void * _mymalloc(unsigned int size)
 {
    MemBlock block = null;
@@ -1200,6 +1265,9 @@ static void * _mymalloc(unsigned int size)
          block = pools[p].Add();
          if(block)
          {
+#if defined(MEMTRACKING)
+            block._class = null;
+#endif
             block.size = size;
             pools[p].usedSpace += size;
          }
@@ -1212,6 +1280,9 @@ static void * _mymalloc(unsigned int size)
             TOTAL_MEM += sizeof(class MemBlock) + size;
             OUTSIDE_MEM += sizeof(class MemBlock) + size;
             block.part = null;
+#if defined(MEMTRACKING)
+            block._class = null;
+#endif
             block.size = size;
          }
       }
@@ -1239,11 +1310,20 @@ static void _myfree(void * pointer)
          printf("WARNING! pool is -1\n");
       else   */
       if(pool)
+      {
+#ifdef _DEBUG
+         memset(pointer, 0xec, block.size);
+#endif
          pool->Remove(block);
+      }
       else
       {
          TOTAL_MEM -= sizeof(class MemBlock) + block.size;
          OUTSIDE_MEM -= sizeof(class MemBlock) + block.size;
+
+#ifdef _DEBUG
+         memset(block, 0xec, sizeof(class MemBlock) + block.size);
+#endif
          free(block);
       }
    }
@@ -1281,6 +1361,7 @@ static void * _myrealloc(void * pointer, unsigned int size)
             TOTAL_MEM += size - newBlock.size;
             OUTSIDE_MEM += size - newBlock.size;
             newPointer = ((struct MemBlock *)newBlock + 1);
+            newBlock.size = size;
          }
       }
    }
@@ -1357,9 +1438,7 @@ static void * _mycrealloc(void * pointer, unsigned int size)
    }
    return newPointer;
 }
-#endif
 
-#ifndef MEMINFO
 #undef realloc
 #undef crealloc
 #undef malloc
@@ -1375,9 +1454,13 @@ static void * _mycrealloc(void * pointer, unsigned int size)
 
 static void * _malloc(unsigned int size)
 {
+#if defined(DISABLE_MEMMGR) && !defined(MEMINFO)
+   return size ? malloc(size) : null;
+#else
    void * pointer;
 
-#if !defined(ECERE_BOOTSTRAP)
+
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Wait();
 #endif
 
@@ -1404,7 +1487,9 @@ static void * _malloc(unsigned int size)
                printf("      %s\n", stack.frames[c]);
 
          memoryErrorsCount++;
+#if !defined(__EMSCRIPTEN__)
          memMutex.Release();
+#endif
          return null;
       }
 
@@ -1419,7 +1504,7 @@ static void * _malloc(unsigned int size)
    }
 #endif
 
-#if !defined(ECERE_BOOTSTRAP)
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Release();
 #endif
 
@@ -1432,12 +1517,17 @@ static void * _malloc(unsigned int size)
    }
 #endif
    return pointer ? ((byte*)pointer + REDZONE) : null;
+#endif
 }
 
 static void * _calloc(int n, unsigned int size)
 {
+#if defined(DISABLE_MEMMGR) && !defined(MEMINFO)
+   return size ? calloc(n, size) : null;
+#else
    void * pointer;
-#if !defined(ECERE_BOOTSTRAP)
+
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Wait();
 #endif
 
@@ -1462,7 +1552,9 @@ static void * _calloc(int n, unsigned int size)
             if(stack.frames[c])
                printf("      %s\n", stack.frames[c]);
          memoryErrorsCount++;
+#if !defined(__EMSCRIPTEN__)
          memMutex.Release();
+#endif
          return null;
       }
 
@@ -1479,7 +1571,7 @@ static void * _calloc(int n, unsigned int size)
    }
 #endif
 
-#if !defined(ECERE_BOOTSTRAP)
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Release();
 #endif
 
@@ -1491,12 +1583,19 @@ static void * _calloc(int n, unsigned int size)
    }
 #endif
    return pointer ? ((byte*)pointer + REDZONE) : null;
+#endif
 }
 
 static void * _realloc(void * pointer, unsigned int size)
 {
+#if defined(DISABLE_MEMMGR) && !defined(MEMINFO)
+   if(!size) { free(pointer); return null; }
+   return realloc(pointer, size);
+
+#else
    if(!size) { _free(pointer); return null; }
-#if !defined(ECERE_BOOTSTRAP)
+
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Wait();
 #endif
 
@@ -1538,7 +1637,9 @@ static void * _realloc(void * pointer, unsigned int size)
          if(stack.frames[c])
             printf("      %s\n", stack.frames[c]);
       memoryErrorsCount++;
+#if !defined(__EMSCRIPTEN__)
       memMutex.Release();
+#endif
       return null;
    }
    memset(pointer, 0xAB, REDZONE);
@@ -1546,6 +1647,12 @@ static void * _realloc(void * pointer, unsigned int size)
 
    if(block)
    {
+#if defined(JUST_CHECK_LEAKS) || defined(JUST_CHECK_BOUNDARIES)
+      memcpy((byte *)pointer + REDZONE, (byte *)block.key, Min(block.size, size));
+      free((byte *)block.key - REDZONE);
+      memBlocks.Remove(block);
+      free(block);
+#else
       if(block.freed)
       {
          memcpy((byte *)pointer + REDZONE, block.oldmem, Min(block.size, size));
@@ -1563,6 +1670,7 @@ static void * _realloc(void * pointer, unsigned int size)
          memset((byte *)block.key - REDZONE, 0xEC, block.size + REDZONE * 2);
          block.freed = true;
       }
+#endif
    }
 
    if(!recurse && !stack.recurse)
@@ -1579,16 +1687,28 @@ static void * _realloc(void * pointer, unsigned int size)
    pointer = realloc(pointer, size);
 #endif
 
-#if !defined(ECERE_BOOTSTRAP)
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Release();
 #endif
    return pointer ? ((byte *)pointer + REDZONE) : null;
+#endif
 }
 
 static void * _crealloc(void * pointer, unsigned int size)
 {
-   if(!size) return null;
-#if !defined(ECERE_BOOTSTRAP)
+#if defined(DISABLE_MEMMGR) && !defined(MEMINFO)
+   uintsize s = pointer ? msize(pointer) : 0;
+   void * p;
+   if(!size) { free(pointer); return null; }
+
+   p = realloc(pointer, size);
+   if(size > s)
+      memset((byte *)p + s, 0, size - s);
+   return p;
+#else
+   if(!size) { _free(pointer); return null; }
+
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Wait();
 #endif
 
@@ -1630,7 +1750,9 @@ static void * _crealloc(void * pointer, unsigned int size)
          if(stack.frames[c])
             printf("      %s\n", stack.frames[c]);
       memoryErrorsCount++;
+#if !defined(__EMSCRIPTEN__)
       memMutex.Release();
+#endif
       return null;
    }
    memset(pointer, 0xAB, REDZONE);
@@ -1638,6 +1760,12 @@ static void * _crealloc(void * pointer, unsigned int size)
 
    if(block)
    {
+#if defined(JUST_CHECK_LEAKS) || defined(JUST_CHECK_BOUNDARIES)
+      memcpy((byte *)pointer + REDZONE, (byte *)block.key, Min(block.size, size));
+      free((byte *)block.key - REDZONE);
+      memBlocks.Remove(block);
+      free(block);
+#else
       if(block.freed)
       {
          memcpy((byte *)pointer + REDZONE, block.oldmem, Min(block.size, size));
@@ -1655,6 +1783,7 @@ static void * _crealloc(void * pointer, unsigned int size)
          memset((byte *)block.key - REDZONE, 0xEC, block.size + REDZONE * 2);
          block.freed = true;
       }
+#endif
    }
 
    if(!recurse && !stack.recurse)
@@ -1671,17 +1800,21 @@ static void * _crealloc(void * pointer, unsigned int size)
    pointer = crealloc(pointer, size);
 #endif
 
-#if !defined(ECERE_BOOTSTRAP)
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
    memMutex.Release();
 #endif
    return pointer ? ((byte *)pointer + REDZONE) : null;
+#endif
 }
 
 static void _free(void * pointer)
 {
    if(pointer)
    {
-#if !defined(ECERE_BOOTSTRAP)
+#if defined(DISABLE_MEMMGR) && !defined(MEMINFO)
+      free(pointer);
+#else
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
       if(memMutex != pointer) memMutex.Wait();
 #endif
 
@@ -1754,13 +1887,13 @@ static void _free(void * pointer)
                {
                   if(address[-c-1] != 0xAB)
                   {
-                     printf("Buffer Underrun\n");
+                     printf("Buffer Underrun (%d bytes before)\n", c+1);
                      memoryErrorsCount++;
                      block.OutputStacks(block.freed);
                   }
                   if(address[c + size] != 0xAB)
                   {
-                     printf("Buffer Overrun\n");
+                     printf("Buffer Overrun (%d bytes past block)\n", c);
                      memoryErrorsCount++;
                      block.OutputStacks(block.freed);
                   }
@@ -1768,6 +1901,11 @@ static void _free(void * pointer)
             }
 
             block.freed = true;
+#if defined(JUST_CHECK_LEAKS) || defined(JUST_CHECK_BOUNDARIES)
+            free((byte *)block.key - REDZONE);
+            memBlocks.Remove(block);
+            free(block);
+#else
             block.oldmem = (byte *)malloc(block.size + REDZONE * 2);
             if(block.oldmem)
             {
@@ -1777,6 +1915,7 @@ static void _free(void * pointer)
             memset((byte *)block.key - REDZONE, 0xEC, block.size + REDZONE * 2);
 
             memcpy(block.freeLoc, stack.frames + stack.pos - Min(stack.pos, MAX_MEMORY_LOC), Min(stack.pos, MAX_MEMORY_LOC) * sizeof(char *));
+#endif
          }
          stack.recurse = false;
       }
@@ -1785,9 +1924,11 @@ static void _free(void * pointer)
       free(pointer);
 #endif
 
-#if !defined(ECERE_BOOTSTRAP)
+#if !defined(ECERE_BOOTSTRAP) && !defined(__EMSCRIPTEN__)
       if(memMutex != pointer) memMutex.Release();
 #endif
+
+#endif
    }
 }
 
@@ -1806,6 +1947,14 @@ public void memswap(byte * a, byte * b, uint size)
    }
 }
 
+public void CheckConsistency()
+{
+#ifdef MEMINFO
+   if(!memBlocks.Check())
+      printf("Memory Blocks Tree Integrity Failed\n");
+#endif
+}
+
 public void CheckMemory()
 {
 #ifdef MEMINFO
@@ -1896,13 +2045,13 @@ public void CheckMemory()
       {
          if(address[-c-1] != 0xAB)
          {
-            printf("Buffer Underrun\n");
+            printf("Buffer Underrun (%d bytes before)\n", c + 1);
             memoryErrorsCount++;
             block.OutputStacks(block.freed);
          }
          if(address[c + size] != 0xAB)
          {
-            printf("Buffer Overrun\n");
+            printf("Buffer Overrun (%d bytes past)\n", c);
             memoryErrorsCount++;
             block.OutputStacks(block.freed);
          }
@@ -1982,7 +2131,12 @@ static void FixDerivativesBase(Class base, Class mod)
       // _class.memberID = _class.startMemberID = (base && (type == normalClass || type == noHeadClass || type == structClass)) ? base.memberID : 0;
 
       if(type == normalClass || type == noHeadClass)
-         _class.offset = (base && (base.templateClass ? base.templateClass.structSize : base.structSize) && base.type != systemClass) ? (base.templateClass ? base.templateClass.structSize : base.structSize) : ((type == noHeadClass) ? 0 : sizeof(class Instance));
+      {
+         // Use 'memberOffset' for nohead class as the members get added without padding
+         _class.offset = (base && (base.templateClass ? (type == normalClass ? base.templateClass.structSize : base.templateClass.memberOffset) : (type == normalClass ? base.structSize : base.memberOffset)) && base.type != systemClass) ? (base.templateClass ? base.templateClass.structSize : base.structSize) : ((type == noHeadClass) ? 0 : sizeof(class Instance));
+         if(_class.structAlignment && (_class.offset % _class.structAlignment))
+            _class.offset += _class.structAlignment - _class.offset % _class.structAlignment;
+      }
       else
          _class.offset = 0; // Force set to 0
 
@@ -2044,6 +2198,7 @@ static void FixDerivativesBase(Class base, Class mod)
             _class._vTbl = renew _class._vTbl void *[_class.vTblSize];
             // memmove(_class._vTbl + mod.base.vTblSize, _class._vTbl + baseClass.vTblSize, (mod.base.vTblSize - baseClass.vTblSize) * sizeof(void *));
             memmove(_class._vTbl + mod.base.vTblSize, _class._vTbl + baseClass.vTblSize, (_class.vTblSize - mod.vTblSize) * sizeof(void *));
+            memcpy(_class._vTbl + baseClass.vTblSize, mod._vTbl + baseClass.vTblSize, (mod.base.vTblSize - baseClass.vTblSize) * sizeof(void *));
 
             updateStart = baseClass.vTblSize;
             updateEnd = updateStart + mod.base.vTblSize - baseClass.vTblSize;
@@ -2444,7 +2599,8 @@ public dllexport Class eSystem_RegisterClass(ClassType type, const char * name,
          }
          {
             NameSpace * ns = _class.nameSpace;
-            while(ns->parent &&
+            while(ns != nameSpace &&
+               ns->parent &&
                !ns->classes.first &&
                !ns->functions.first &&
                !ns->defines.first &&
@@ -2642,7 +2798,9 @@ public dllexport Class eSystem_RegisterClass(ClassType type, const char * name,
          }
          _class.memberID = _class.startMemberID = (base && (type == normalClass || type == noHeadClass || type == structClass)) ? base.memberID : 0;
          if(type == normalClass || type == noHeadClass)
-            _class.offset = (base && base.structSize && base.type != systemClass) ? base.structSize : ((type == noHeadClass) ? 0 : ((force64Bits && inCompiler && fixed) ? 24 : (force32Bits && inCompiler && fixed) ? 12 : sizeof(class Instance)));
+            _class.offset = (base && base.structSize && base.type != systemClass) ?
+               // Use 'memberOffset' for nohead class as the members get added without padding
+               (base.type == normalClass ? base.structSize : base.memberOffset) : ((type == noHeadClass) ? 0 : ((force64Bits && inCompiler && fixed) ? 24 : (force32Bits && inCompiler && fixed) ? 12 : sizeof(class Instance)));
          else
             _class.offset = 0;   // Force set to 0 for redefinitions
 
@@ -2656,7 +2814,8 @@ public dllexport Class eSystem_RegisterClass(ClassType type, const char * name,
                !strcmp(name, "LineStyle") ||
                !strcmp(name, "FillStyle") ||
                !strcmp(name, "FontObject") ||
-               !strcmp(name, "SymbolStyle"))
+               !strcmp(name, "FontObject") ||
+               !strcmp(name, "ecere::sys::Thread"))
             {
                _class.offset = force32Bits ? 24 : 12;
             }
@@ -2816,6 +2975,7 @@ static void FreeTemplateArg(Class template, ClassTemplateParameter param, int id
    {
       case type:
          delete (void *)template.templateArgs[id].dataTypeString;
+         template.templateArgs[id].dataTypeClass = null;
          break;
       case identifier:
          delete (void *)template.templateArgs[id].memberString;
@@ -2850,6 +3010,7 @@ static void FreeTemplateArgs(Class template)
                {
                   case type:
                      delete (void *)template.templateArgs[id].dataTypeString;
+                     template.templateArgs[id].dataTypeClass = null;
                      break;
                   case identifier:
                      delete (void *)template.templateArgs[id].memberString;
@@ -2872,14 +3033,12 @@ static void FreeTemplate(Class template)
    if(template.nameSpace)
    {
       BTNamedLink link = (BTNamedLink)template.nameSpace->classes.FindString(template.name);
-      template.nameSpace->classes.Delete((BTNode)link);
+      if(link)
+         template.nameSpace->classes.Delete((BTNode)link);
    }
-   FreeTemplateArgs(template);
 
-   delete (void *)template.fullName;
-   delete (void *)template.name;
-   delete (void *)template.templateArgs;
-   delete (void *)template.dataTypeString;
+   FreeTemplatesDerivatives(template);
+   FreeTemplateArgs(template);
 
    while((deriv = template.derivatives.first))
    {
@@ -2887,7 +3046,15 @@ static void FreeTemplate(Class template)
       template.derivatives.Delete(deriv);
    }
 
-   _free(template);
+   delete (void *)template.fullName;
+   delete (void *)template.name;
+   delete template.templateArgs;
+   delete (void *)template.dataTypeString;
+
+   if(template.module)
+      template.module.classes.Delete(template);
+   else
+      _free(template);
 }
 
 static void FreeTemplates(Class _class)
@@ -2900,8 +3067,6 @@ static void FreeTemplates(Class _class)
    }
 
    FreeTemplateArgs(_class);
-   //if(_class.templateArgs)
-      //printf("Deleting  Template args for %s\n", _class.name);
    delete _class.templateArgs;
    delete (void *)_class.dataTypeString;
 
@@ -2922,13 +3087,26 @@ public dllexport void eClass_Unregister(Class _class)
    ClassProperty classProp;
    ClassTemplateParameter param;
 
+   if(_class.templateClass)
+   {
+      // Unregistering templates... Used in IDE to address crash on Ecere classes templatized with imported modules
+      OldLink templateLink;
+      for(templateLink = _class.templateClass.templatized.first; templateLink; templateLink = templateLink.next)
+      {
+         if(templateLink.data == _class)
+         {
+            _class.templateClass.templatized.Delete(templateLink);
+            break;
+         }
+      }
+      FreeTemplate(_class);
+      return;
+   }
+
    delete _class._vTbl;
 
    FreeTemplates(_class);
 
-   FreeTemplateArgs(_class);
-   delete _class.templateArgs;
-
    while((template = _class.templatized.first))
    {
       FreeTemplate(template.data);
@@ -3150,25 +3328,20 @@ public int64 _strtoi64(const char * string, const char ** endString, int base)
       else if(ch >= 'A' && ch <= 'Z')
          ch -= ('A'- 10);
       else
-      {
-         if(endString)
-            *endString = string + c;
          // Invalid character
          break;
-      }
       if(ch < base)
       {
          value *= base;
          value += ch;
       }
       else
-      {
-         if(endString)
-            *endString = string + c;
          // Invalid character
          break;
-      }
    }
+   if(endString)
+      *endString = string + c;
+
    return sign*value;
 }
 
@@ -3205,25 +3378,19 @@ public uint64 _strtoui64(const char * string, const char ** endString, int base)
       else if(ch >= 'A' && ch <= 'Z')
          ch -= ('A' - 10);
       else
-      {
-         if(endString)
-            *endString = string + c;
          // Invalid character
          break;
-      }
       if(ch < base)
       {
          value *= base;
          value += ch;
       }
       else
-      {
-         if(endString)
-            *endString = string + c;
          // Invalid character
          break;
-      }
    }
+   if(endString)
+      *endString = string + c;
    return sign*value;
 }
 
@@ -3286,6 +3453,12 @@ public dllexport Class eSystem_FindClass(Module module, const char * name)
                templatedClass.numParams = 0;
                templatedClass.derivatives = { };
                templatedClass.templatized = { };
+               templatedClass.module = module;
+               templatedClass.count = 0; // TOCHECK: Keeping track of individual templatized classes?
+               templatedClass.prev = null;
+               templatedClass.next = null;
+
+               module.classes.Add(templatedClass);
 
                ComputeClassParameters(templatedClass, templateParams, module);
 
@@ -3303,7 +3476,7 @@ static void CopyTemplateArg(ClassTemplateParameter param, ClassTemplateArgument
    switch(param.type)
    {
       case type:
-         arg.dataTypeString = CopyString(arg.dataTypeString);
+            arg.dataTypeString = CopyString(arg.dataTypeString);
          break;
       case expression:
 
@@ -3520,9 +3693,11 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
             {
                case type:
                   argument.dataTypeString = CopyString(value);
-                  argument.dataTypeClass = eSystem_FindClass(_class.module, value);
-                  if(!argument.dataTypeClass) argument.dataTypeClass = eSystem_FindClass(_class.module.application, value);
-                  if(!argument.dataTypeClass) argument.dataTypeClass = eSystem_FindClass(findModule, value);
+                  argument.dataTypeClass = eSystem_FindClass(findModule, value);
+                  if(!argument.dataTypeClass)
+                     argument.dataTypeClass = eSystem_FindClass(_class.module, value);
+                  if(!argument.dataTypeClass)
+                     argument.dataTypeClass = eSystem_FindClass(_class.module.application, value);
                   break;
                case expression:
                {
@@ -3620,11 +3795,11 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
             CopyTemplateArg(param, templatedClass.templateArgs[curParamID]);
             if(param.type == type && param.defaultArg.dataTypeString)
             {
-               templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module, param.defaultArg.dataTypeString);
+               templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(findModule, param.defaultArg.dataTypeString);
                if(!templatedClass.templateArgs[curParamID].dataTypeClass)
-                  templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module.application, param.defaultArg.dataTypeString);
+                  templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module, param.defaultArg.dataTypeString);
                if(!templatedClass.templateArgs[curParamID].dataTypeClass)
-                  templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(findModule, param.defaultArg.dataTypeString);
+                  templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module.application, param.defaultArg.dataTypeString);
             }
          }
          curParamID++;
@@ -3666,6 +3841,7 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
                         {
                            int id = p;
                            Class sClass;
+                           // NOTE: This struct 'arg' here is only to build up templateString
                            ClassTemplateArgument arg;
                            for(sClass = expClass.base; sClass; sClass = sClass.base) id += sClass.templateParams.count;
                            arg = expClass.templateArgs[id];
@@ -3677,8 +3853,7 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
                               {
                                  if(cParam.type == type && arg.dataTypeString && !strcmp(cParam.name, arg.dataTypeString))
                                  {
-                                    arg.dataTypeString = templatedClass.templateArgs[p].dataTypeString;
-                                    arg.dataTypeClass = templatedClass.templateArgs[p].dataTypeClass;
+                                    arg = templatedClass.templateArgs[p];
                                     break;
                                  }
                               }
@@ -3748,7 +3923,9 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
                      FreeTemplateArg(templatedClass, param, c);
 
                      arg->dataTypeString = CopyString(templateString);
-                     arg->dataTypeClass = eSystem_FindClass(templatedClass.module, templateString);
+                     arg->dataTypeClass = eSystem_FindClass(findModule, templateString);
+                     if(!arg->dataTypeClass)
+                        arg->dataTypeClass = eSystem_FindClass(templatedClass.module, templateString);
                      if(!arg->dataTypeClass)
                         arg->dataTypeClass = eSystem_FindClass(templatedClass.module.application, templateString);
                   }
@@ -3763,6 +3940,7 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
                         {
                            FreeTemplateArg(templatedClass, param, c);
 
+                           // TRICKY: This copies from equivalent parameters
                            arg->dataTypeString = templatedClass.templateArgs[p].dataTypeString;
                            arg->dataTypeClass = templatedClass.templateArgs[p].dataTypeClass;
                            CopyTemplateArg(cParam, arg);
@@ -3800,11 +3978,11 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
                CopyTemplateArg(param, templatedClass.templateArgs[curParamID]);
                if(param.type == type && param.defaultArg.dataTypeString)
                {
-                  templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module, param.defaultArg.dataTypeString);
+                  templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(findModule, param.defaultArg.dataTypeString);
                   if(!templatedClass.templateArgs[curParamID].dataTypeClass)
-                     templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module.application, param.defaultArg.dataTypeString);
+                     templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module, param.defaultArg.dataTypeString);
                   if(!templatedClass.templateArgs[curParamID].dataTypeClass)
-                     templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(findModule, param.defaultArg.dataTypeString);
+                     templatedClass.templateArgs[curParamID].dataTypeClass = eSystem_FindClass(templatedClass.module.application, param.defaultArg.dataTypeString);
                }
             }
             curParamID++;
@@ -3902,10 +4080,10 @@ static void ComputeClassParameters(Class templatedClass, const char * templatePa
                         id++;
                      }
                   }
-                  memberClass = eSystem_FindClass(templatedClass.module, className);
                   // TESTING: Added this here...
+                  memberClass = eSystem_FindClass(findModule, className);
                   if(!memberClass)
-                     memberClass = eSystem_FindClass(findModule, className);
+                     memberClass = eSystem_FindClass(templatedClass.module, className);
                   if(!memberClass)
                      memberClass = eSystem_FindClass(templatedClass.module.application, className);
                }
@@ -4083,7 +4261,7 @@ public dllexport Method eClass_AddMethod(Class _class, const char * name, const
                if(method.vid >= _class.vTblSize)
                   printf("error: virtual methods overriding failure\n");
                else
-                  _class._vTbl[method.vid] = function ? function : DefaultFunction;
+                  _class._vTbl[method.vid] = function ? function : null; //(void *)DefaultFunction;
                for(deriv = _class.derivatives.first; deriv; deriv = deriv.next)
                {
                   Class derivClass = deriv.data;
@@ -4124,7 +4302,7 @@ public dllexport Method eClass_AddMethod(Class _class, const char * name, const
          Method method
          {
             name = CopyString(name),
-            function = function ? function : DefaultFunction;
+            function = function ? function : null; //DefaultFunction;
             _class = _class;
             dataTypeString = CopyString(type);
             memberAccess = declMode;
@@ -4152,7 +4330,7 @@ public dllexport Method eClass_AddVirtualMethod(Class _class, const char * name,
                if(method.vid >= _class.vTblSize)
                   printf("error: virtual methods overriding failure\n");
                else
-                  _class._vTbl[method.vid] = function ? function : DefaultFunction;
+                  _class._vTbl[method.vid] = function ? function : null; //(void *)DefaultFunction;
             }
             else
                base = null;
@@ -4165,7 +4343,7 @@ public dllexport Method eClass_AddVirtualMethod(Class _class, const char * name,
          Method method
          {
             name = CopyString(name);
-            function = function ? function : DefaultFunction;
+            function = function ? function : null; //DefaultFunction;
             type = virtualMethod;
             _class = _class;
             vid = _class.vTblSize++;
@@ -4174,11 +4352,11 @@ public dllexport Method eClass_AddVirtualMethod(Class _class, const char * name,
          };
          _class.methods.Add((BTNode)method);
          _class._vTbl = renew _class._vTbl void *[_class.vTblSize];
-         _class._vTbl[method.vid] = function ? function : DefaultFunction;
+         _class._vTbl[method.vid] = function ? function : null; //(void *)DefaultFunction;
 
          // TODO: Fix derived classes
          if(_class.derivatives.first || _class.templatized.first)
-            FixDerivativeVirtualMethod(_class, name, method.vid, function ? function : (void *)DefaultFunction, type);
+            FixDerivativeVirtualMethod(_class, name, method.vid, function ? function : null /*(void *)DefaultFunction*/, type);
          return method;
       }
    }
@@ -4450,7 +4628,9 @@ public dllexport void * eInstance_New(Class _class)
 #ifdef MEMINFO
 
 #undef malloc
+#if !defined(__EMSCRIPTEN__)
    memMutex.Wait();
+#endif
       //allocateClass = _class;
       allocateClass = malloc(strlen(_class.name)+1);
       allocateInternal = _class.module == __thisModule;
@@ -4476,18 +4656,32 @@ public dllexport void * eInstance_New(Class _class)
                size *= 3;
          }
          instance = _calloc(1, size);
+         if(!instance && size)
+            printf("Failed to allocate memory instantiating %s object!\n", _class.name);
+         else if(!size)
+            printf("Warning: 0 size instantiating %s object!\n", _class.name);
       }
 #ifdef MEMINFO
       allocateClass = null;
+#if !defined(__EMSCRIPTEN__)
    memMutex.Release();
 #endif
-      if(_class.type == normalClass)
+#endif
+
+#if !defined(MEMINFO) && defined(MEMTRACKING)
+      {
+         MemBlock block = (MemBlock)((byte *)instance - sizeof(class MemBlock));
+         block._class = _class;
+      }
+#endif
+
+      if(instance && _class.type == normalClass)
       {
          instance._class = _class;
          // Copy the virtual table initially
          instance._vTbl = _class._vTbl;
       }
-      if(!ConstructInstance(instance, _class, null))
+      if(instance && !ConstructInstance(instance, _class, null))
       {
          _free(instance);
          instance = null;
@@ -4503,6 +4697,7 @@ public dllexport void eInstance_Evolve(Instance * instancePtr, Class _class)
    if(_class && instancePtr && *instancePtr)
    {
       bool wasApp = false, wasGuiApp = false;
+      Instance oldInstance = *instancePtr;
       Instance instance = (Instance)renew *instancePtr byte[_class.structSize];
       Class fromClass = instance._class;
       *instancePtr = instance;
@@ -4571,7 +4766,8 @@ public dllexport void eInstance_Evolve(Instance * instancePtr, Class _class)
             for(templateLink = _class.templatized.first; templateLink; templateLink = templateLink.next)
             {
                Class template = templateLink.data;
-               template.module = _class.module;
+               if(template.module == oldInstance)
+                  template.module = _class.module;
             }
          }
 
@@ -4580,11 +4776,13 @@ public dllexport void eInstance_Evolve(Instance * instancePtr, Class _class)
             for(_class = module.classes.first; _class; _class = _class.next)
             {
                OldLink templateLink;
+               Module oldModule = _class.module;
                _class.module = module;
                for(templateLink = _class.templatized.first; templateLink; templateLink = templateLink.next)
                {
                   Class template = templateLink.data;
-                  template.module = _class.module;
+                  if(template.module == oldModule)
+                     template.module = _class.module;
                }
             }
          }
@@ -5032,7 +5230,7 @@ public dllexport void eInstance_SetMethod(Instance instance, const char * name,
                memcpy(instance._vTbl, instance._class._vTbl,
                   sizeof(int(*)()) * instance._class.vTblSize);
             }
-            instance._vTbl[method.vid] = function ? function : DefaultFunction;
+            instance._vTbl[method.vid] = function ? function : null; //(void *)DefaultFunction;
          }
       }
    }
@@ -5101,8 +5299,23 @@ public dllexport DataMember eClass_AddDataMember(Class _class, const char * name
          if(alignment)
          {
             bool pointerAlignment = alignment == 0xF000F000;
+            bool force64Bits = (_class.module.application.isGUIApp & 2) ? true : false;
+            bool force32Bits = (_class.module.application.isGUIApp & 4) ? true : false;
+            if((force32Bits || force64Bits) && !strcmp(_class.name, "AVLNode") && !strcmp(name, "__ecerePrivateData0"))
+            {
+               if(force64Bits)
+               {
+                  type = "byte[32]";
+                  size = 32;
+               }
+               if(force32Bits)
+               {
+                  type = "byte[16]";
+                  size = 16;
+               }
+            }
 
-            if(pointerAlignment) alignment = sizeof(void *);
+            if(pointerAlignment) alignment = force64Bits ? 8 : force32Bits ? 4 : sizeof(void *);
 
             if(pointerAlignment && _class.structAlignment <= 4)
                _class.pointerAlignment = 1;
@@ -5111,6 +5324,11 @@ public dllexport DataMember eClass_AddDataMember(Class _class, const char * name
 
             _class.structAlignment = Max(_class.structAlignment, alignment);
 
+            if(_class.offset % alignment)
+            {
+               _class.structSize += alignment - (_class.offset % alignment);
+               _class.offset += alignment - (_class.offset % alignment);
+            }
             if(_class.memberOffset % alignment)
                _class.memberOffset += alignment - (_class.memberOffset % alignment);
          }
@@ -5144,7 +5362,9 @@ public dllexport DataMember eMember_AddDataMember(DataMember member, const char
       if(alignment)
       {
          bool pointerAlignment = alignment == 0xF000F000;
-         if(pointerAlignment) alignment = sizeof(void *);
+         bool force64Bits = false; //(member._class.module.application.isGUIApp & 2) ? true : false;
+         bool force32Bits = false; //(member._class.module.application.isGUIApp & 4) ? true : false;
+         if(pointerAlignment) alignment = force64Bits ? 8 : force32Bits ? 4 : sizeof(void *);
 
          if(pointerAlignment && member.structAlignment <= 4)
             member.pointerAlignment = 1;
@@ -5346,7 +5566,7 @@ static Module Module_Load(Module fromModule, const char * name, AccessMode impor
       }
       else
       {
-         char * libLocation = null;
+         const char * libLocation = null;
 #if defined(__ANDROID__)
          libLocation = AndroidInterface_GetLibLocation();
 #endif
@@ -5543,6 +5763,19 @@ static void NameSpace_Free(NameSpace parentNameSpace)
    NameSpace * nameSpace;
    delete (void *)parentNameSpace.name;
 
+         /*   {
+      BTNamedLink n, next;
+      for(n = (BTNamedLink)parentNameSpace.classes.first; n; n = next)
+      {
+         Class c = n.data;
+
+         next = (BTNamedLink)((BTNode)n).next;
+
+         if(c.templateClass)
+            eClass_Unregister(c);
+      }
+   }         */
+
    while((nameSpace = (NameSpace *)parentNameSpace.nameSpaces.first))
    {
       NameSpace_Free(nameSpace);
@@ -5640,17 +5873,26 @@ static void Module_Destructor(Module module)
       if(_class.nameSpace)
       {
          BTNamedLink classLink = (BTNamedLink)_class.nameSpace->classes.FindString(_class.name);
-         OldLink t;
-         for(t = _class.templatized.first; t; t = t.next)
+         if(classLink)
          {
-            Class template = t.data;
-            BTNamedLink link;
-            link = (BTNamedLink)template.nameSpace->classes.FindString(template.name);
+            OldLink t;
+            for(t = _class.templatized.first; t; t = t.next)
+            {
+               Class template = t.data;
+               BTNamedLink link;
+               link = (BTNamedLink)template.nameSpace->classes.FindString(template.name);
 
-            template.nameSpace->classes.Delete((BTNode)link);
-            template.nameSpace = null;
+               template.nameSpace->classes.Delete((BTNode)link);
+               template.nameSpace = null;
+            }
+            _class.nameSpace->classes.Delete((BTNode)classLink);
          }
-         _class.nameSpace->classes.Delete((BTNode)classLink);
+#ifdef _DEBUG
+         else
+         {
+            printf("Warning: Could not find %s in namespace classes while destructing module %s\n", _class.name, module.name);
+         }
+#endif
          _class.nameSpace = null;
       }
       _class.module = null;
@@ -5727,7 +5969,7 @@ static int64 GetEnumSize(Class _class)
 #define strnicmp strncasecmp
 #endif
 
-#if defined(ECERE_BOOTSTRAP) || (defined(__GNUC__) && !defined(__DJGPP__) && !defined(__WIN32__))
+#if defined(ECERE_BOOTSTRAP) || (defined(__GNUC__) && !defined(__DJGPP__) && !defined(__WIN32__) && !defined(__EMSCRIPTEN__))
 #undef strlwr
 #undef strupr
 default dllexport char * strlwr(char *string)
@@ -6277,9 +6519,6 @@ static void LoadCOM(Module module)
    eSystem_RegisterFunction("system", "int system(const char*)", system, module, baseSystemAccess);
    eSystem_RegisterFunction("atoi", "int atoi(const char*)", atoi, module, baseSystemAccess);
    eSystem_RegisterFunction("atof", "double atof(const char*)", atof, module, baseSystemAccess);
-   eSystem_RegisterFunction("tolower", "int tolower(int)", tolower, module, baseSystemAccess);
-   eSystem_RegisterFunction("toupper", "int toupper(int)", toupper, module, baseSystemAccess);
-   eSystem_RegisterFunction("isdigit", "bool isdigit(int)", isdigit, module, baseSystemAccess);
    eSystem_RegisterFunction("memset", "void * memset(void * area, int value, uintsize count)", memset, module, baseSystemAccess);
    eSystem_RegisterFunction("getenv", "char * getenv(const char * name)", getenv, module, baseSystemAccess);
    eSystem_RegisterFunction("rename", "int rename(const char *oldpath, const char *newpath)", rename, module, baseSystemAccess);
@@ -6322,7 +6561,7 @@ static void LoadCOM(Module module)
 
    // --- Stdio ---
    eSystem_RegisterFunction("sprintf", "int sprintf(char *, const char *, ...)", sprintf, module, baseSystemAccess);
-   eSystem_RegisterFunction("snprintf", "int sprintf(char *, uintsize, const char *, ...)", snprintf, module, baseSystemAccess);
+   eSystem_RegisterFunction("snprintf", "int snprintf(char *, uintsize, const char *, ...)", snprintf, module, baseSystemAccess);
    eSystem_RegisterFunction("printf", "int printf(const char *, ...)", printf, module, baseSystemAccess);
    eSystem_RegisterFunction("vsprintf", "int vsprintf(char*, const char*, __builtin_va_list)", vsprintf, module, baseSystemAccess);
    eSystem_RegisterFunction("vsnprintf", "int vsnprintf(char*, uintsize, const char*, __builtin_va_list)", vsnprintf, module, baseSystemAccess);
@@ -6330,12 +6569,17 @@ static void LoadCOM(Module module)
    eSystem_RegisterFunction("fputs", "int fputs(const char *, void * stream)", fputs, module, baseSystemAccess);
 
    // --- Ctype ---
+   eSystem_RegisterFunction("tolower", "int tolower(int)", tolower, module, baseSystemAccess);
+   eSystem_RegisterFunction("toupper", "int toupper(int)", toupper, module, baseSystemAccess);
+   eSystem_RegisterFunction("isdigit", "bool isdigit(int)", isdigit, module, baseSystemAccess);
+   eSystem_RegisterFunction("isxdigit","bool isxdigit(int)", isxdigit, module, baseSystemAccess);
    eSystem_RegisterFunction("isalnum", "int isalnum(int c)", isalnum, module, baseSystemAccess);
    eSystem_RegisterFunction("isspace", "int isspace(int c)", isspace, module, baseSystemAccess);
    eSystem_RegisterFunction("isalpha", "int isalpha(int c)", isalpha, module, baseSystemAccess);
    eSystem_RegisterFunction("islower", "int islower(int c)", islower, module, baseSystemAccess);
    eSystem_RegisterFunction("isupper", "int isupper(int c)", isupper, module, baseSystemAccess);
    eSystem_RegisterFunction("isprint", "int isprint(int c)", isprint, module, baseSystemAccess);
+   eSystem_RegisterFunction("isblank", "int isblank(int c)", isblank, module, baseSystemAccess);
 
 }
 
@@ -6384,6 +6628,11 @@ public dllexport Application __ecere_COM_Initialize(bool guiApp, int argc, char
    return app;
 }
 
+public dllexport void eSystem_SetArgs(Application app, int argc, char * argv[])
+{
+   System_SetArgs(argc, argv, &app.argc, &app.argv);
+}
+
 public dllexport ClassTemplateParameter eClass_AddTemplateParameter(Class _class, const char * name, TemplateParameterType type, const void * info, ClassTemplateArgument defaultArg)
 {
    if(_class && name)
@@ -6738,38 +6987,65 @@ public int ISO8859_1toUTF8(const char * source, char * dest, int max)
 {
    int c;
    int d = 0;
+   byte * byteDest = (byte *)dest;
    for(c = 0; source[c]; c++)
    {
       unichar ch = ((byte *)source)[c];
       switch(ch)
       {
-         case 150: ch = (unichar)0x2012; break;
+         case 128: ch = (unichar)0x20AC; break;
+         case 130: ch = (unichar)0x201A; break;
+         case 131: ch = (unichar)0x0192; break;
+         case 132: ch = (unichar)0x201E; break;
+         case 133: ch = (unichar)0x2026; break;
+         case 134: ch = (unichar)0x2020; break;
+         case 135: ch = (unichar)0x2021; break;
+         case 136: ch = (unichar)0x02C6; break;
+         case 137: ch = (unichar)0x2030; break;
+         case 138: ch = (unichar)0x0160; break;
+         case 139: ch = (unichar)0x2039; break;
+         case 140: ch = (unichar)0x0152; break;
+         case 142: ch = (unichar)0x017D; break;
+         case 145: ch = (unichar)0x2018; break;
+         case 146: ch = (unichar)0x2019; break;
+         case 147: ch = (unichar)0x201C; break;
+         case 148: ch = (unichar)0x201D; break;
+         case 149: ch = (unichar)0x2022; break;
+         case 150: ch = (unichar)0x2013; break;
+         case 151: ch = (unichar)0x2014; break;
+         case 152: ch = (unichar)0x02DC; break;
+         case 153: ch = (unichar)0x2122; break;
+         case 154: ch = (unichar)0x0161; break;
+         case 155: ch = (unichar)0x203A; break;
+         case 156: ch = (unichar)0x0153; break;
+         case 158: ch = (unichar)0x017E; break;
+         case 159: ch = (unichar)0x0178; break;
       }
       if(ch < 0x80)
       {
          if(d + 1 >= max) break;
-         dest[d++] = (char)ch;
+         byteDest[d++] = (char)ch;
       }
       else if(ch < 0x800)
       {
          if(d + 2 >= max) break;
-         dest[d++] = 0xC0 | (byte)((ch & 0x7C0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xC0 | (byte)((ch & 0x7C0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
       else if(ch < 0x10000)
       {
          if(d + 3 >= max) break;
-         dest[d++] = 0xE0 | (byte)((ch & 0xF000) >> 12);
-         dest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xE0 | (byte)((ch & 0xF000) >> 12);
+         byteDest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
       else
       {
          if(d + 4 >= max) break;
-         dest[d++] = 0xF0 | (byte)((ch & 0x1C0000) >> 18);
-         dest[d++] = 0x80 | (byte)((ch & 0x3F000) >> 12);
-         dest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xF0 | (byte)((ch & 0x1C0000) >> 18);
+         byteDest[d++] = 0x80 | (byte)((ch & 0x3F000) >> 12);
+         byteDest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
    }
    dest[d] = 0;
@@ -6781,12 +7057,12 @@ public char * UTF16toUTF8(const uint16 * source)
    int c;
    int d = 0;
    int len;
-   char * dest;
+   byte * dest;
    uint16 u16;
    bool invert = false;
 
    for(len = 0; source[len]; len++);
-   dest = new char[len * 3 + 1];
+   dest = new byte[len * 3 + 1];
    for(c = 0; (u16 = source[c]); c++)
    {
       unichar ch;
@@ -6826,8 +7102,8 @@ public char * UTF16toUTF8(const uint16 * source)
       }
    }
    dest[d] = 0;
-   dest = renew dest char[d+1];
-   return dest;
+   dest = renew dest byte[d+1];
+   return (char *)dest;
 }
 
 public int UTF16toUTF8Buffer(const uint16 * source, char * dest, int max)
@@ -6835,6 +7111,7 @@ public int UTF16toUTF8Buffer(const uint16 * source, char * dest, int max)
    int c;
    int d = 0;
    uint16 u16;
+   byte * byteDest = (byte *)dest;
    for(c = 0; (u16 = source[c]); c++)
    {
       unichar ch;
@@ -6846,31 +7123,31 @@ public int UTF16toUTF8Buffer(const uint16 * source, char * dest, int max)
       if(ch < 0x80)
       {
          if(d + 1 >= max) break;
-         dest[d++] = (char)ch;
+         byteDest[d++] = (char)ch;
       }
       else if(ch < 0x800)
       {
          if(d + 2 >= max) break;
-         dest[d++] = 0xC0 | (byte)((ch & 0x7C0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xC0 | (byte)((ch & 0x7C0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
       else if(ch < 0x10000)
       {
          if(d + 3 >= max) break;
-         dest[d++] = 0xE0 | (byte)((ch & 0xF000) >> 12);
-         dest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xE0 | (byte)((ch & 0xF000) >> 12);
+         byteDest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
       else
       {
          if(d + 4 >= max) break;
-         dest[d++] = 0xF0 | (byte)((ch & 0x1C0000) >> 18);
-         dest[d++] = 0x80 | (byte)((ch & 0x3F000) >> 12);
-         dest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xF0 | (byte)((ch & 0x1C0000) >> 18);
+         byteDest[d++] = 0x80 | (byte)((ch & 0x3F000) >> 12);
+         byteDest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
    }
-   dest[d] = 0;
+   byteDest[d] = 0;
    return d;
 }
 
@@ -6967,7 +7244,7 @@ public int UTF8toUTF16Buffer(const char * source, uint16 * dest, int max)
          if(codePoint > 0xFFFF)
          {
             uint16 lead = (uint16)(LEAD_OFFSET + (codePoint >> 10));
-            uint16 trail = 0xDC00 + (uint16)(codePoint & 0x3FF);
+            uint16 trail = (uint16)(0xDC00 | (codePoint & 0x3FF));
             if(d >= max - 1) break;
             dest[d++] = lead;
             dest[d++] = trail;
@@ -6989,36 +7266,37 @@ public int UTF32toUTF8Len(const unichar * source, int count, char * dest, int ma
    int c;
    int d = 0;
    uint32 ch;
+   byte * byteDest = (byte *)dest;
    for(c = 0; c<count && (ch = source[c]); c++)
    {
       if(ch < 0x80)
       {
          if(d + 1 >= max) break;
-         dest[d++] = (char)ch;
+         byteDest[d++] = (char)ch;
       }
       else if(ch < 0x800)
       {
          if(d + 2 >= max) break;
-         dest[d++] = 0xC0 | (byte)((ch & 0x7C0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xC0 | (byte)((ch & 0x7C0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
       else if(ch < 0x10000)
       {
          if(d + 3 >= max) break;
-         dest[d++] = 0xE0 | (byte)((ch & 0xF000) >> 12);
-         dest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xE0 | (byte)((ch & 0xF000) >> 12);
+         byteDest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
       else
       {
          if(d + 4 >= max) break;
-         dest[d++] = 0xF0 | (byte)((ch & 0x1C0000) >> 18);
-         dest[d++] = 0x80 | (byte)((ch & 0x3F000) >> 12);
-         dest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
-         dest[d++] = 0x80 | (byte)(ch & 0x03F);
+         byteDest[d++] = 0xF0 | (byte)((ch & 0x1C0000) >> 18);
+         byteDest[d++] = 0x80 | (byte)((ch & 0x3F000) >> 12);
+         byteDest[d++] = 0x80 | (byte)((ch & 0xFC0) >> 6);
+         byteDest[d++] = 0x80 | (byte)(ch & 0x03F);
       }
    }
-   dest[d] = 0;
+   byteDest[d] = 0;
    return d;
 }
 
@@ -7062,7 +7340,7 @@ public uint16 * UTF8toUTF16(const char * source, int * wordCount)
          if(codePoint > 0xFFFF)
          {
             uint16 lead = (uint16)(LEAD_OFFSET + (codePoint >> 10));
-            uint16 trail = 0xDC00 + (uint16)(codePoint & 0x3FF);
+            uint16 trail = (uint16)(0xDC00 | (codePoint & 0x3FF));
             dest[d++] = lead;
             dest[d++] = trail;
          }
@@ -7079,3 +7357,86 @@ public uint16 * UTF8toUTF16(const char * source, int * wordCount)
 }
 
 namespace com;
+
+#if !defined(MEMINFO) && defined(MEMTRACKING)
+import "Map"
+
+Map<Class, int> blocksByClass { };
+Map<Class, uintsize> sizeByClass { };
+#endif
+
+public void queryMemInfo(char * string)
+{
+#if !defined(MEMINFO) && defined(MEMTRACKING) && !defined(DISABLE_MEMMGR)
+   char s[1024];
+   int p;
+   uint numBlocks = 0;
+   uintsize totalMemUsed = 0;
+   sprintf(s, "Total System Memory Usage: %.02f\n", TOTAL_MEM / 1048576.0f);
+   strcat(string, s);
+
+   for(p = 0; pools && p < NUM_POOLS; p++)
+   {
+      BlockPool * pool = &pools[p];
+      if(pool->totalSize)
+      {
+         numBlocks += pool->totalSize;
+         sprintf(s, "%8d bytes: %d blocks in %d parts (%.02f mb used; taking up %.02f mb space)\n",
+            pool->blockSize, pool->numBlocks, pool->numParts, pool->usedSpace / 1048576.0f, pool->totalSize * pool->blockSpace / 1048576.0f);
+         totalMemUsed += pool->usedSpace;
+         strcat(string, s);
+      }
+   }
+
+
+   blocksByClass.Free();
+   sizeByClass.Free();
+#if !defined(__EMSCRIPTEN__)
+   memMutex.Wait();
+#endif
+   for(p = 0; pools && p < NUM_POOLS; p++)
+   {
+      BlockPool * pool = &pools[p];
+      MemBlock block;
+      for(block = pool->first; block; block = block.next)
+      {
+         Class c = block._class;
+         blocksByClass[c]++;
+         sizeByClass[c] += block.size;
+      }
+   }
+#if !defined(__EMSCRIPTEN__)
+   memMutex.Release();
+#endif
+
+   //for(c : blocksByClass)
+   {
+      MapIterator<Class, int> it { map = blocksByClass };
+      while(it.Next())
+      {
+         int c = it.data;
+         Class _class = it.key; //&c;
+         uintsize size = sizeByClass[_class];
+         float totalSize = (float) size / 1048576.0f;
+         if(totalSize > 1)
+         {
+            sprintf(s, "%s (%d bytes): %d instances (%.02f mb used)\n", _class ? _class.name : "(none)", (int)size, c, totalSize);
+            strcat(string, s);
+         }
+      }
+   }
+
+   sprintf(s, "Non-pooled memory: %.02f\n", OUTSIDE_MEM / 1048576.0f);
+   strcat(string, s);
+   sprintf(s, "Total Memory in use: %.02f\n", (float)(totalMemUsed + OUTSIDE_MEM) / 1048576.0f);
+   strcat(string, s);
+
+   sprintf(s, "Total Blocks Count: %d (%.02f mb overhead)\n", numBlocks, (float)sizeof(struct MemBlock) * numBlocks / 1048576.0f);
+   strcat(string, s);
+#ifdef MEMORYGUARD
+   sprintf(s, "MemoryGuard: %d blocks (%.02f mb RedZone, %.02f mb MemInfo)\n", memBlocks.count,
+      numBlocks * 2 * REDZONE / 1048576.0f, sizeof(struct MemInfo) * memBlocks.count / 1048576.0f);
+   strcat(string, s);
+#endif
+#endif
+}