[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

[graphite2] 13/69: Imported Upstream version 1.0.3



This is an automated email from the git hooks/post-receive script.

rene pushed a commit to branch master
in repository graphite2.

commit 79959634b0327e41b3ef9f6b65258e5da9305739
Author: Rene Engelhard <rene@debian.org>
Date:   Thu Apr 21 14:48:42 2016 +0200

    Imported Upstream version 1.0.3
---
 .hg_archival.txt                      |   6 +-
 .hgtags                               |   1 +
 CMakeLists.txt                        |   5 -
 ChangeLog                             |  12 ++
 buildtest.bat                         |   8 +
 contrib/android/jni/loadgr_jni.cpp    |   5 +-
 doc/hacking.txt                       |   4 -
 gr2fonttest/CMakeLists.txt            |   2 +-
 gr2fonttest/gr2FontTest.cpp           |  85 +++------
 include/graphite2/Font.h              |   4 +-
 include/graphite2/Segment.h           |   3 +-
 src/Bidi.cpp                          |   2 +-
 src/CMakeLists.txt                    |   4 -
 src/CmapCache.cpp                     |   5 +-
 src/Code.cpp                          |  77 +++++----
 src/Code.h                            |   5 +-
 src/Endian.h                          | 103 +++++++++++
 src/Face.cpp                          |  23 ++-
 src/FeatureMap.cpp                    |  61 +++----
 src/FeatureMap.h                      |  13 +-
 src/Font.cpp                          |   3 +-
 src/GlyphFace.cpp                     |  27 +--
 src/GlyphFace.h                       |  31 ----
 src/GlyphFaceCache.cpp                |  21 ++-
 src/GlyphFaceCache.h                  |   4 +-
 src/List.h                            |   6 +-
 src/Main.h                            |  35 +---
 src/NameTable.cpp                     |  41 ++---
 src/NameTable.h                       |   2 +-
 src/Pass.cpp                          |  63 +++----
 src/Rule.h                            |   4 +-
 src/SegCache.h                        |   2 +-
 src/SegCacheEntry.cpp                 |   4 +-
 src/SegCacheEntry.h                   |   2 +-
 src/SegCacheStore.h                   |   2 +-
 src/Segment.cpp                       |   1 -
 src/Silf.cpp                          | 232 ++++++++-----------------
 src/Silf.h                            |   2 +-
 src/Sparse.h                          |   6 +-
 src/TtfUtil.cpp                       | 312 +++++++++++++++-------------------
 src/gr_face.cpp                       |   4 +
 src/gr_features.cpp                   |  20 +--
 src/gr_segment.cpp                    |   4 +
 src/opcodes.h                         |  16 +-
 src/processUTF.h                      |   7 +-
 tests/CMakeLists.txt                  |   4 +-
 tests/comparerenderer/Gr2Renderer.h   |   5 +-
 tests/comparerenderer/HbNgRenderer.h  |  17 +-
 tests/comparerenderer/RenderedLine.h  |   2 -
 tests/endian/CMakeLists.txt           |   7 +
 tests/endian/endiantest.cpp           | 149 ++++++++++++++++
 tests/examples/cluster.c              |   3 +-
 tests/examples/linebreak.c            |  10 +-
 tests/featuremap/featuremaptest.cpp   |  21 +--
 tests/fuzztest                        |  19 ++-
 tests/nametabletest/nametabletest.cpp |  37 ++--
 56 files changed, 818 insertions(+), 735 deletions(-)

diff --git a/.hg_archival.txt b/.hg_archival.txt
index c350104..2db55cc 100644
--- a/.hg_archival.txt
+++ b/.hg_archival.txt
@@ -1,5 +1,5 @@
 repo: 999e2033695c3bcf2f65d611737ac9008805bd58
-node: aaa88521e9abb8542b45498dd840fd4653ccbd71
+node: cb735be7d86d894f0667cb63dffc4273fd53d9fe
 branch: default
-latesttag: 1.0.2
-latesttagdistance: 1
+latesttag: 1.0.3
+latesttagdistance: 2
diff --git a/.hgtags b/.hgtags
index a1cb6d6..094d794 100644
--- a/.hgtags
+++ b/.hgtags
@@ -13,3 +13,4 @@ bedb05f72d56f24ca0fc333fd14eabb1ec553902 1.0.1
 0fa690ff089ce0bc382a553cc01c0b721fbdee5c 1.0.2
 0fa690ff089ce0bc382a553cc01c0b721fbdee5c 1.0.2
 b10bcaf1302411513a5961d1854ff8c02e5ad5e6 1.0.2
+8795e344f7964bdf8ef4607004f01b94c41e5775 1.0.3
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 265ec7d..76b5046 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -53,11 +53,6 @@ if (VM_MACHINE_TYPE STREQUAL "direct" AND NOT CMAKE_COMPILER_IS_GNUCXX)
 endif (VM_MACHINE_TYPE STREQUAL "direct" AND NOT CMAKE_COMPILER_IS_GNUCXX)
 message(STATUS "Using vm machine type: ${VM_MACHINE_TYPE}")
 
-TEST_BIG_ENDIAN(WORDS_BIGENDIAN)
-if (WORDS_BIGENDIAN)
-    add_definitions(-DWORDS_BIGENDIAN)
-endif (WORDS_BIGENDIAN)
-
 
 add_subdirectory(src)
 add_subdirectory(gr2fonttest)
diff --git a/ChangeLog b/ChangeLog
index c9850b2..5822f1b 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,14 @@
+1.0.3
+    . Fix UTF16 surrogate support
+    . script and lang tags may be space padded or null padded
+    . Remove need for WORDS_BIGENDIAN, do it all automatically
+    . Remove all #include <new>. Use CLASS_NEW_DELETE instead.
+    . Fix comparerenderer to work with current hbng
+    . Add valgrind to fuzztest to ensure good memory use at all times
+    . Fix new fuzztest exposed bugs.
+    . Fix bugs exposed by Mozilla security review
+    . Add continuous integration build on Windows support
+
 1.0.2
     . Fix Windows build
     . Comparerenderer uses hbng enforcing ot rendering
@@ -7,6 +18,7 @@
     . Chase the FSF around its latest office moves
     . WORDS_BIGENDIAN is set at the top so tests now pass on ppc, etc.
     . More words in the manual
+
 1.0.1
     . Release is the default build in cmake now.
     . Refactor cmake build to not rebuild things so much.
diff --git a/buildtest.bat b/buildtest.bat
new file mode 100644
index 0000000..c8c87d7
--- /dev/null
+++ b/buildtest.bat
@@ -0,0 +1,8 @@
+call vcvars32
+rmdir /s /q build
+mkdir build
+cd build
+cmake -G "NMake Makefiles" -D CMAKE_BUILD_TYPE:STRING=Release -D ENABLE_COMPARE_RENDERER:BOOL=OFF -D VM_MACHINE_TYPE:STRING=Call ..
+nmake
+if errorlevel 0 (nmake test)
+
diff --git a/contrib/android/jni/loadgr_jni.cpp b/contrib/android/jni/loadgr_jni.cpp
index 5aabbef..5b6e3b0 100644
--- a/contrib/android/jni/loadgr_jni.cpp
+++ b/contrib/android/jni/loadgr_jni.cpp
@@ -45,7 +45,7 @@ typedef struct rec_ft_table {
     void *buffer;
     struct rec_ft_table *next;
 
-    ~rec_ft_table() { if (buffer) free(buffer); if (next) delete next; }
+    ~rec_ft_table() { free(buffer); delete next; }
 } rec_ft_table;
 
 typedef struct fontmap {
@@ -151,7 +151,8 @@ void *gettable(const void *recp, unsigned int tag, size_t *len)
     unsigned long length = 0;
     FT_Load_Sfnt_Table(rec->ftface, tag, 0, NULL, &length);
     r->buffer = malloc(length);
-    FT_Load_Sfnt_Table(rec->ftface, tag, 0, (FT_Byte *)(r->buffer), &length);
+    if (r->buffer)
+    	FT_Load_Sfnt_Table(rec->ftface, tag, 0, (FT_Byte *)(r->buffer), &length);
     if (len) *len = length;
     r->len = length;
     return r->buffer;
diff --git a/doc/hacking.txt b/doc/hacking.txt
index 6689fd1..173816d 100644
--- a/doc/hacking.txt
+++ b/doc/hacking.txt
@@ -16,10 +16,6 @@ goto should use the call style virtual machine. See src/direct_machine.cpp and s
 
 Various C preprocessor definitions are also used as part of compiling graphite2:
 
-WORDS_BIG_ENDIAN::
-    This is defined if the target compilation platform is big endian, otherwise it is left undefined
-    for little endian architectures.
-
 DISABLE_SEGCACHE::
     If set, the segment caching code is not compiled into the library. This can be used to save space
     if the engine is under space constraints both for code and memory. The default is that this is not
diff --git a/gr2fonttest/CMakeLists.txt b/gr2fonttest/CMakeLists.txt
index a13eac5..6769b13 100644
--- a/gr2fonttest/CMakeLists.txt
+++ b/gr2fonttest/CMakeLists.txt
@@ -4,7 +4,7 @@ project(gr2fonttest)
 
 enable_testing()
 
-include_directories(${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/../common ${PROJECT_SOURCE_DIR}/../src)
+include_directories(${PROJECT_SOURCE_DIR})
 
 if  (${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
 	# Checkout from http://win-iconv.googlecode.com/svn/trunk
diff --git a/gr2fonttest/gr2FontTest.cpp b/gr2fonttest/gr2FontTest.cpp
index 0155f11..b152ba4 100644
--- a/gr2fonttest/gr2FontTest.cpp
+++ b/gr2fonttest/gr2FontTest.cpp
@@ -44,14 +44,6 @@ diagnostic log of the segment creation in grSegmentLog.txt
 #include "graphite2/Segment.h"
 #include "graphite2/XmlLog.h"
 
-#if !defined WORDS_BIGENDIAN || defined PC_OS
-#define swap16(x) (((x & 0xff) << 8) | ((x & 0xff00) >> 8))
-#define swap32(x) (((x & 0xff) << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000) >> 24))
-#else
-#define swap16(x) (x)
-#define swap32(x) (x)
-#endif
-
 class Gr2TextSrc
 {
 
@@ -476,11 +468,7 @@ bool Parameters::loadFromArgs(int argc, char *argv[])
     return (argError) ? false : true;
 }
 
-union FeatID
-{
-    gr_uint8 uChar[4];
-    gr_uint32 uId;
-};
+typedef gr_uint32 tag_t;
 
 void Parameters::printFeatures(const gr_face * face) const
 {
@@ -492,28 +480,21 @@ void Parameters::printFeatures(const gr_face * face) const
         const gr_feature_ref * f = gr_face_fref(face, i);
         gr_uint32 length = 0;
         char * label = reinterpret_cast<char *>(gr_fref_label(f, &langId, gr_utf8, &length));
-        FeatID featId;
-        featId.uId = gr_fref_id(f);
+        const tag_t featId = gr_fref_id(f);
         if (label)
-            if ((featId.uChar[0] >= 0x20 && featId.uChar[0] < 0x7F) &&
-                (featId.uChar[1] >= 0x20 && featId.uChar[1] < 0x7F) &&
-                (featId.uChar[2] >= 0x20 && featId.uChar[2] < 0x7F) &&
-                (featId.uChar[3] >= 0x20 && featId.uChar[3] < 0x7F))
+            if ((char(featId >> 24) >= 0x20 && char(featId >> 24) < 0x7F) &&
+                (char(featId >> 16) >= 0x20 && char(featId >> 16) < 0x7F) &&
+                (char(featId >> 8)  >= 0x20 && char(featId >> 8)  < 0x7F) &&
+                (char(featId)       >= 0x20 && char(featId)       < 0x7F))
             {
-#ifdef WORDS_BIGENDIAN
-                fprintf(log, "%d %c%c%c%c %s\n", featId.uId, featId.uChar[0], featId.uChar[1],
-                       featId.uChar[2], featId.uChar[3], label);
-#else
-                fprintf(log, "%d %c%c%c%c %s\n", featId.uId, featId.uChar[3], featId.uChar[2],
-                       featId.uChar[1], featId.uChar[0], label);
-#endif
+                fprintf(log, "%d %c%c%c%c %s\n", featId, featId >> 24, featId >> 16, featId >> 8, featId, label);
             }
             else
             {
-                fprintf(log, "%d %s\n", featId.uId, label);
+                fprintf(log, "%d %s\n", featId, label);
             }
         else
-            fprintf(log, "%d\n", featId.uId);
+            fprintf(log, "%d\n", featId);
         gr_label_destroy(reinterpret_cast<void*>(label));
         gr_uint16 numSettings = gr_fref_n_values(f);
         for (gr_uint16 j = 0; j < numSettings; j++)
@@ -529,14 +510,13 @@ void Parameters::printFeatures(const gr_face * face) const
     fprintf(log, "Feature Languages:");
     for (gr_uint16 i = 0; i < numLangs; i++)
     {
-        FeatID langID;
-        langID.uId = gr_face_lang_by_index(face, i);
-        langID.uId = swap32(langID.uId);
+    	const tag_t lang_id = gr_face_lang_by_index(face, i);
         fprintf(log, "\t");
-        for (size_t j = 0; j < 4; j++)
+        for (size_t j = 4; j; --j)
         {
-            if ((langID.uChar[j]) >= 0x20 && (langID.uChar[j] < 0x80))
-                fprintf(log, "%c", langID.uChar[j]);
+        	const char c = lang_id >> (j*8-8);
+            if ((c >= 0x20) && (c < 0x80))
+                fprintf(log, "%c", c);
         }
     }
     fprintf(log, "\n");
@@ -546,21 +526,18 @@ gr_feature_val * Parameters::parseFeatures(const gr_face * face) const
 {
     gr_feature_val * featureList = NULL;
     const char * pLang = NULL;
-    FeatID lang;
-    lang.uId = 0;
+    tag_t lang_id = 0;
     if (features && (pLang = strstr(features, "lang=")))
     {
         pLang += 5;
         size_t i = 0;
-        while ((i < 4) && (*pLang != '0') && (*pLang != '&'))
+        for (int i = 4; i; --i, lang_id <<= 8)
         {
-            lang.uChar[i] = *pLang;
-            ++pLang;
-            ++i;
+        	if (*pLang == '0' || *pLang == '&') continue;
+        	lang_id |= *pLang++;
         }
-        lang.uId = swap32(lang.uId);
     }
-    featureList = gr_face_featureval_for_lang(face, lang.uId);
+    featureList = gr_face_featureval_for_lang(face, lang_id);
     if (!features || strlen(features) == 0)
         return featureList;
     size_t featureLength = strlen(features);
@@ -568,9 +545,8 @@ gr_feature_val * Parameters::parseFeatures(const gr_face * face) const
     const char * valueText = NULL;
     size_t nameLength = 0;
     gr_int32 value = 0;
-    FeatID featId;
     const gr_feature_ref* ref = NULL;
-    featId.uId = 0;
+    tag_t feat_id = 0;
     for (size_t i = 0; i < featureLength; i++)
     {
         switch (features[i])
@@ -586,18 +562,17 @@ gr_feature_val * Parameters::parseFeatures(const gr_face * face) const
                 valueText = NULL;
                 name = features + i + 1;
                 nameLength = 0;
-                featId.uId = 0;
+                feat_id = 0;
                 break;
             case '=':
                 if (nameLength <= 4)
                 {
-                    featId.uId = swap32(featId.uId);
-                    ref = gr_face_find_fref(face, featId.uId);
+                    ref = gr_face_find_fref(face, feat_id);
                 }
                 if (!ref)
                 {
-                    featId.uId = atoi(name);
-                    ref = gr_face_find_fref(face, featId.uId);
+                    feat_id = atoi(name);
+                    ref = gr_face_find_fref(face, feat_id);
                 }
                 valueText = features + i + 1;
                 name = NULL;
@@ -606,9 +581,7 @@ gr_feature_val * Parameters::parseFeatures(const gr_face * face) const
                 if (valueText == NULL)
                 {
                     if (nameLength < 4)
-                    {
-                        featId.uChar[nameLength++] = features[i];
-                    }
+                    	feat_id = feat_id << 8 | features[i];
                 }
                 break;
         }
@@ -616,14 +589,12 @@ gr_feature_val * Parameters::parseFeatures(const gr_face * face) const
         {
             value = atoi(valueText);
             gr_fref_set_feature_value(ref, value, featureList);
-            if (featId.uId > 0x20000000)
+            if (feat_id > 0x20000000)
             {
-                featId.uId = swap32(featId.uId);
-                fprintf(log, "%c%c%c%c=%d\n", featId.uChar[0], featId.uChar[1],
-                         featId.uChar[2], featId.uChar[3], value);
+                fprintf(log, "%c%c%c%c=%d\n", feat_id >> 24, feat_id >> 16, feat_id >> 8, feat_id, value);
             }
             else
-                fprintf(log, "%u=%d\n", featId.uId, value);
+                fprintf(log, "%u=%d\n", feat_id, value);
             ref = NULL;
         }
     }
diff --git a/include/graphite2/Font.h b/include/graphite2/Font.h
index abca683..2e238e0 100644
--- a/include/graphite2/Font.h
+++ b/include/graphite2/Font.h
@@ -121,7 +121,9 @@ GR2_API void gr_tag_to_str(gr_uint32 tag, char *str);
   *          gr_featureval_destroy() to free this object when done.
   * @param pFace The font face to get feature values from
   * @param langname The language tag to get feature values for. If there is no such language or
-  *                  langname is 0, the default feature values for the font are returned
+  *                  langname is 0, the default feature values for the font are returned.
+  *                  langname is right 0 padded and assumes lowercase. Thus the en langauge
+  *                  would be 0x656E0000. Langname may also be space padded, thus 0x656E2020.
   */
 GR2_API gr_feature_val* gr_face_featureval_for_lang(const gr_face* pFace, gr_uint32 langname);
 
diff --git a/include/graphite2/Segment.h b/include/graphite2/Segment.h
index 01966b8..0cad766 100644
--- a/include/graphite2/Segment.h
+++ b/include/graphite2/Segment.h
@@ -198,7 +198,8 @@ GR2_API size_t gr_count_unicode_characters(enum gr_encform enc, const void* buff
   *             of the face.
   * @param face The face containing all the non-size dependent information.
   * @param script This is a tag containing a script identifier that is used to choose
-  *               which graphite table within the font to use. Maybe 0.
+  *               which graphite table within the font to use. Maybe 0. Tag may be 4 chars
+  *               NULL padded in LSBs or space padded in LSBs.
   * @param pFeats Pointer to a feature values to be used for the segment. Only one
   *               feature values may be used for a segment. If NULL the default features
   *               for the font will be used.
diff --git a/src/Bidi.cpp b/src/Bidi.cpp
index 3c3ed5f..3acbbe9 100644
--- a/src/Bidi.cpp
+++ b/src/Bidi.cpp
@@ -438,7 +438,7 @@ void resolveNeutrals(int baseLevel, Slot *s)
     int state = baseLevel ? r : l;
     int cls;
     Slot *sRun = NULL;
-    Slot *sLast;
+    Slot *sLast = s;
     int level = baseLevel;
 
     for ( ; s; s = s->next())
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 6e6f7db..0d50933 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -30,10 +30,6 @@ set(GRAPHITE_API_AGE 0)
 set(GRAPHITE_SO_VERSION ${GRAPHITE_API_MAJOR}.${GRAPHITE_API_MINOR}.${GRAPHITE_API_AGE})
 
 include(TestBigEndian)
-TEST_BIG_ENDIAN(WORDS_BIGENDIAN)
-if (WORDS_BIGENDIAN)
-    add_definitions(-DWORDS_BIGENDIAN)
-endif (WORDS_BIGENDIAN)
 
 include_directories(${PROJECT_SOURCE_DIR})
 
diff --git a/src/CmapCache.cpp b/src/CmapCache.cpp
index 398df8e..0fc85ee 100644
--- a/src/CmapCache.cpp
+++ b/src/CmapCache.cpp
@@ -96,10 +96,7 @@ CmapCache::~CmapCache()
 {
     unsigned int numBlocks = (m_isBmpOnly)? 0x100 : 0x1100;
     for (unsigned int i = 0; i < numBlocks; i++)
-    {
-        if (m_blocks[i])
-            free(m_blocks[i]);
-    }
+    	free(m_blocks[i]);
     free(m_blocks);
     m_blocks = NULL;
 }
diff --git a/src/Code.cpp b/src/Code.cpp
index e6cfd52..af333ae 100644
--- a/src/Code.cpp
+++ b/src/Code.cpp
@@ -106,7 +106,8 @@ private:
     opcode      fetch_opcode(const byte * bc);
     void        analyse_opcode(const opcode, const int8 * const dp) throw();
     bool        emit_opcode(opcode opc, const byte * & bc);
-    void        valid_upto(const uint16 limit, const uint16 x) const throw();
+    bool 		validate_opcode(const opcode opc, const byte * const bc);
+    bool        valid_upto(const uint16 limit, const uint16 x) const throw();
     void        failure(const status_t s) const throw() { _code.failure(s); }
     
     Code              & _code;
@@ -173,7 +174,7 @@ Code::Code(bool is_constraint, const byte * bytecode_begin, const byte * const b
         face.getGlyphFaceCache()->numAttrs(),
         face.numFeatures(), 
         {1,1,1,1,1,1,1,1, 
-         1,1,1,1,1,1,1,(uint8)-1, 
+         1,1,1,1,1,1,1,255,
          1,1,1,1,1,1,1,1, 
          1,1,1,1,1,1,0,0, 
          0,0,0,0,0,0,0,0, 
@@ -239,10 +240,7 @@ bool Code::decoder::load(const byte * bc, const byte * bc_end)
             return false;
     }
     
-    if (bc > bc_end)
-        failure(arguments_exhausted);
-
-    return _code.status() == loaded;
+    return bool(_code);
 }
 
 // Validation check and fixups.
@@ -250,10 +248,12 @@ bool Code::decoder::load(const byte * bc, const byte * bc_end)
 
 opcode Code::decoder::fetch_opcode(const byte * bc)
 {
-    opcode opc = opcode(*bc++);
+    const opcode opc = opcode(*bc++);
 
     // Do some basic sanity checks based on what we know about the opcode
-    // and it's arguments.
+    if (!validate_opcode(opc, bc))	return MAX_OPCODE;
+
+    // And check it's arguments as far as possible
     switch (opc)
     {
         case NOP :
@@ -304,17 +304,9 @@ opcode Code::decoder::fetch_opcode(const byte * bc)
         case DELETE :
             break;
         case ASSOC :
-        {
-            uint8 num = bc[0];
-            if (bc + 1 + num >= _max.bytecode)
-            {
-                failure(arguments_exhausted);
-                break;
-            }
-            while (num) 
-                valid_upto(_rule_length, _pre_context + int8(bc[num--]));
+            for (uint8 num = bc[0]; num; --num)
+                valid_upto(_rule_length, _pre_context + int8(bc[num]));
             break;
-        }
         case CNTXT_ITEM :
             valid_upto(_max.rule_length, _max.pre_context + int8(bc[0]));
             if (bc + 2 + bc[1] >= _max.bytecode)  failure(jump_past_end);
@@ -323,11 +315,11 @@ opcode Code::decoder::fetch_opcode(const byte * bc)
         case ATTR_ADD :
         case ATTR_SUB :
         case ATTR_SET_SLOT :
-            valid_upto(gr_slatMax, bc[0]);
+        	valid_upto(gr_slatMax, bc[0]);
             break;
         case IATTR_SET_SLOT :
-            valid_upto(gr_slatMax, bc[0]);
-            valid_upto(_max.attrid[bc[0]], bc[1]);
+            if (valid_upto(gr_slatMax, bc[0]))
+            	valid_upto(_max.attrid[bc[0]], bc[1]);
             break;
         case PUSH_SLOT_ATTR :
             valid_upto(gr_slatMax, bc[0]);
@@ -356,9 +348,11 @@ opcode Code::decoder::fetch_opcode(const byte * bc)
             // level: dp[2] no check necessary
             break;
         case PUSH_ISLOT_ATTR :
-            valid_upto(gr_slatMax, bc[0]);
-            valid_upto(_rule_length, _pre_context + int8(bc[1]));
-            valid_upto(_max.attrid[bc[0]], bc[2]);
+            if (valid_upto(gr_slatMax, bc[0]))
+            {
+            	valid_upto(_rule_length, _pre_context + int8(bc[1]));
+            	valid_upto(_max.attrid[bc[0]], bc[2]);
+            }
             break;
         case PUSH_IGLYPH_ATTR :// not implemented
         case POP_RET :
@@ -368,8 +362,8 @@ opcode Code::decoder::fetch_opcode(const byte * bc)
         case IATTR_SET :
         case IATTR_ADD :
         case IATTR_SUB :
-            valid_upto(gr_slatMax, bc[0]);
-            valid_upto(_max.attrid[bc[0]], bc[1]);
+            if (valid_upto(gr_slatMax, bc[0]))
+            	valid_upto(_max.attrid[bc[0]], bc[1]);
             break;
         case PUSH_PROC_STATE :  // dummy: dp[0] no check necessary
         case PUSH_VERSION :
@@ -395,7 +389,7 @@ opcode Code::decoder::fetch_opcode(const byte * bc)
             break;
     }
 
-    return _code._status == loaded ? opc : MAX_OPCODE;
+    return bool(_code) ? opc : MAX_OPCODE;
 }
 
 
@@ -513,7 +507,7 @@ bool Code::decoder::emit_opcode(opcode opc, const byte * & bc)
         }
     }
     
-    return _code._status == loaded;
+    return bool(_code);
 }
 
 
@@ -565,11 +559,30 @@ void Code::decoder::apply_analysis(instr * const code, instr * code_end)
 }
 
 
-inline 
-void Code::decoder::valid_upto(const uint16 limit, const uint16 x) const throw()
+inline
+bool Code::decoder::validate_opcode(const opcode opc, const byte * const bc)
+{
+	if (opc >= MAX_OPCODE)
+	{
+		failure(invalid_opcode);
+		return false;
+	}
+	const opcode_t & op = Machine::getOpcodeTable()[opc];
+	const size_t param_sz = op.param_sz == VARARGS ? bc[0] + 1 : op.param_sz;
+	if (bc + param_sz > _max.bytecode)
+	{
+		failure(arguments_exhausted);
+		return false;
+	}
+	return true;
+}
+
+
+bool Code::decoder::valid_upto(const uint16 limit, const uint16 x) const throw()
 {
-    if (x >= limit)
-        failure(out_of_range_data);
+	const bool t = x < limit;
+    if (!t)	failure(out_of_range_data);
+    return t;
 }
 
 inline 
diff --git a/src/Code.h b/src/Code.h
index 7f82d8c..c42fa3b 100644
--- a/src/Code.h
+++ b/src/Code.h
@@ -93,7 +93,8 @@ public:
     bool          deletes() const throw();
 
     int32 run(Machine &m, slotref * & map, Machine::status_t & status) const;
-    CLASS_NEW_DELETE
+    
+    CLASS_NEW_DELETE;
 };
 
 inline Code::Code() throw()
@@ -124,7 +125,7 @@ inline Code & Code::operator=(const Code &rhs) throw() {
     _data_size   = rhs._data_size; 
     _instr_count = rhs._instr_count;
     _status      = rhs._status; 
-    _constraint = rhs._constraint;
+    _constraint  = rhs._constraint;
     _modify      = rhs._modify;
     _delete      = rhs._delete;
     _own         = rhs._own; 
diff --git a/src/Endian.h b/src/Endian.h
new file mode 100644
index 0000000..b441452
--- /dev/null
+++ b/src/Endian.h
@@ -0,0 +1,103 @@
+/*-----------------------------------------------------------------------------
+Copyright (C) 2011 SIL International
+Responsibility: Tim Eves
+
+    This library is free software; you can redistribute it and/or modify
+    it under the terms of the GNU Lesser General Public License as published
+    by the Free Software Foundation; either version 2.1 of License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should also have received a copy of the GNU Lesser General Public
+    License along with this library in the file named "LICENSE".
+    If not, write to the Free Software Foundation, 51 Franklin Street,
+    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
+    internet at http://www.fsf.org/licenses/lgpl.html.
+
+Alternatively, the contents of this file may be used under the terms of the
+Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
+License, as published by the Free Software Foundation, either version 2
+of the License or (at your option) any later version.
+
+Description:
+A set of fast template based decoders for decoding values of any C integer
+type up to long int size laid out with most significant byte first or least
+significant byte first (aka big endian or little endian).  These are CPU
+byte order agnostic and will function the same regardless of the CPUs native
+byte order.
+Being template based means if the either le or be class is not used then
+template code of unused functions will not be instantiated by the compiler
+and thus shouldn't cause any overhead.
+-----------------------------------------------------------------------------*/
+
+class be
+{
+	template<int S>
+	inline static unsigned long int _peek(const unsigned char * p) {
+		return _peek<S/2>(p) << (S/2)*8 | _peek<S/2>(p+S/2);
+	}
+public:
+	template<typename T>
+	inline static T peek(const unsigned char * p) { 
+		return T(_peek<sizeof(T)>(p));
+	}
+
+	template<typename T>
+	inline static T read(const unsigned char * &p) {
+		const T r = T(_peek<sizeof(T)>(p)); 
+		p += sizeof r;
+		return r;
+	}
+	
+	template<typename T>
+	inline static T swap(const T x) {
+		return T(_peek<sizeof(T)>(reinterpret_cast<const unsigned char *>(&x)));
+	}
+
+	template<typename T>
+	inline static void skip(const unsigned char * &p, size_t n=1) {
+		p += sizeof(T)*n;
+	}
+};
+
+template<>
+inline unsigned long int be::_peek<1>(const unsigned char * p) { return *p; }
+
+
+class le 
+{
+	template<int S>
+	inline static unsigned long int _peek(const unsigned char * p) {
+		return _peek<S/2>(p) | _peek<S/2>(p+S/2)  << (S/2)*8;
+	}
+public:
+	template<typename T>
+	inline static T peek(const unsigned char * p) { 
+		return T(_peek<sizeof(T)>(p));
+	}
+
+	template<typename T>
+	inline static T read(const unsigned char * &p) {
+		const T r = T(_peek<sizeof(T)>(p)); 
+		p += sizeof r;
+		return r;
+	}
+	
+	template<typename T>
+	inline static T swap(const T x) {
+		return T(_peek<sizeof(T)>(reinterpret_cast<const unsigned char *>(&x)));
+	}
+
+	template<typename T>
+	inline static void skip(const unsigned char * &p, size_t n=1) {
+		p += sizeof(T)*n;
+	}
+};
+
+template<>
+inline unsigned long int le::_peek<1>(const unsigned char * p) { return *p; }
+
diff --git a/src/Face.cpp b/src/Face.cpp
index 311d325..0c0af0c 100644
--- a/src/Face.cpp
+++ b/src/Face.cpp
@@ -24,14 +24,15 @@ Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
 License, as published by the Free Software Foundation, either version 2
 of the License or (at your option) any later version.
 */
+#include <cstring>
+#include "graphite2/Segment.h"
 #include "Face.h"
-#include <string.h>
+#include "Endian.h"
 #include "Segment.h"
 #include "CmapCache.h"
 #include "NameTable.h"
 #include "SegCacheStore.h"
 #include "XmlTraceLog.h"
-#include <graphite2/Segment.h>
 
 
 using namespace graphite2;
@@ -86,18 +87,18 @@ bool Face::readGraphite()
     uint32 compilerVersion = 0; // wasn't set before GTF version 3
 #endif
     uint32 offset32Pos = 2;
-    version = swap32(*(uint32 *)pSilf);
+    version = be::peek<uint32>(pSilf);
     if (version < 0x00020000) return false;
     if (version >= 0x00030000)
     {
 #ifndef DISABLE_TRACING
-        compilerVersion = swap32(((uint32 *)pSilf)[1]);
+        compilerVersion = be::swap<uint32>(((uint32 *)pSilf)[1]);
 #endif
-        m_numSilf = swap16(((uint16 *)pSilf)[4]);
+        m_numSilf = be::swap<uint16>(((uint16 *)pSilf)[4]);
         offset32Pos = 3;
     }
     else
-        m_numSilf = swap16(((uint16 *)pSilf)[2]);
+        m_numSilf = be::swap<uint16>(((uint16 *)pSilf)[2]);
 
 #ifndef DISABLE_TRACING
         if (XmlTraceLog::get().active())
@@ -116,12 +117,12 @@ bool Face::readGraphite()
     m_silfs = new Silf[m_numSilf];
     for (int i = 0; i < m_numSilf; i++)
     {
-        const uint32 offset = swap32(((uint32 *)pSilf)[offset32Pos + i]);
+        const uint32 offset = be::swap<uint32>(((uint32 *)pSilf)[offset32Pos + i]);
         uint32 next;
         if (i == m_numSilf - 1)
             next = lSilf;
         else
-            next = swap32(((uint32 *)pSilf)[offset32Pos + 1 + i]);
+            next = be::swap<uint32>(((uint32 *)pSilf)[offset32Pos + 1 + i]);
         if (offset > lSilf || next > lSilf)
         {
 #ifndef DISABLE_TRACING
@@ -229,10 +230,8 @@ FileFace::FileFace(const char *filename) :
 
 FileFace::~FileFace()
 {
-    if (m_pTableDir)
-        free(m_pTableDir);
-    if (m_pHeader)
-        free(m_pHeader);
+    free(m_pTableDir);
+    free(m_pHeader);
     if (m_pfile)
         fclose(m_pfile);
     m_pTableDir = NULL;
diff --git a/src/FeatureMap.cpp b/src/FeatureMap.cpp
index 10f70fb..74612e9 100644
--- a/src/FeatureMap.cpp
+++ b/src/FeatureMap.cpp
@@ -27,12 +27,12 @@ of the License or (at your option) any later version.
 #include <string.h>
 
 #include "Main.h"
+#include "Endian.h"
 #include "FeatureMap.h"
 #include "FeatureVal.h"
 #include "graphite2/Font.h"
 #include "XmlTraceLog.h"
 #include "TtfUtil.h"
-//#include <algorithm>
 #include <stdlib.h>
 #include "Face.h"
 
@@ -53,18 +53,15 @@ bool FeatureMap::readFeats(const Face & face)
     if (!pFeat) return true;
     if (lFeat < 12) return false;
 
-    version = read32(pFeat);
+    version = be::read<uint32>(pFeat);
     if (version < 0x00010000) return false;
-    m_numFeats = read16(pFeat);
-    read16(pFeat);
-    read32(pFeat);
+    m_numFeats = be::read<uint16>(pFeat);
+    be::skip<uint16>(pFeat);
+    be::skip<uint32>(pFeat);
     if (m_numFeats * 16U + 12 > lFeat) { m_numFeats = 0; return false; }		//defensive
-    if (m_numFeats)
-    {
-        m_feats = new FeatureRef[m_numFeats];
-        m_pNamedFeats = new NameAndFeatureRef[m_numFeats];
-        defVals = gralloc<uint16>(m_numFeats);
-    }
+    if (!m_numFeats) return true;
+    m_feats = new FeatureRef[m_numFeats];
+    defVals = gralloc<uint16>(m_numFeats);
     byte currIndex = 0;
     byte currBits = 0;     //to cause overflow on first Feature
 
@@ -81,21 +78,26 @@ bool FeatureMap::readFeats(const Face & face)
     {
         uint32 name;
         if (version < 0x00020000)
-            name = read16(pFeat);
+            name = be::read<uint16>(pFeat);
         else
-            name = read32(pFeat);
-        uint16 numSet = read16(pFeat);
+            name = be::read<uint32>(pFeat);
+        uint16 numSet = be::read<uint16>(pFeat);
 
         uint32 offset;
         if (version < 0x00020000)
-            offset = read32(pFeat);
+            offset = be::read<uint32>(pFeat);
         else
         {
-            read16(pFeat);
-            offset = read32(pFeat);
+            be::skip<uint16>(pFeat);
+            offset = be::read<uint32>(pFeat);
+        }
+        if (offset > lFeat)
+        {
+            free(defVals);
+            return false;
         }
-        uint16 flags = read16(pFeat);
-        uint16 uiName = read16(pFeat);
+        uint16 flags = be::read<uint16>(pFeat);
+        uint16 uiName = be::read<uint16>(pFeat);
         const byte *pSet = pOrig + offset;
         uint16 maxVal = 0;
 
@@ -123,11 +125,11 @@ bool FeatureMap::readFeats(const Face & face)
         FeatureSetting *uiSet = gralloc<FeatureSetting>(numSet);
         for (int j = 0; j < numSet; j++)
         {
-            int16 val = read16(pSet);
+            int16 val = be::read<int16>(pSet);
             if (val > maxVal) maxVal = val;
             if (j == 0) defVals[i] = val;
-            uint16 label = read16(pSet);
-            ::new(uiSet + j) FeatureSetting(label, val);
+            uint16 label = be::read<uint16>(pSet);
+            new (uiSet + j) FeatureSetting(label, val);
 #ifndef DISABLE_TRACING
             if (XmlTraceLog::get().active())
             {
@@ -164,6 +166,7 @@ bool FeatureMap::readFeats(const Face & face)
 #endif
     }
     m_defaultFeatures = new Features(currIndex + 1, *this);
+    m_pNamedFeats = new NameAndFeatureRef[m_numFeats];
     for (int i = 0; i < m_numFeats; i++)
     {
     	m_feats[i].applyValToFeature(defVals[i], *m_defaultFeatures);
@@ -197,8 +200,8 @@ bool SillMap::readSill(const Face & face)
 
     if (!pSill) return true;
     if (lSill < 12) return false;
-    if (read32(pSill) != 0x00010000UL) return false;
-    m_numLanguages = read16(pSill);
+    if (be::read<uint32>(pSill) != 0x00010000UL) return false;
+    m_numLanguages = be::read<uint16>(pSill);
     m_langFeats = new LangFeaturePair[m_numLanguages];
     if (!m_langFeats || !m_FeatureMap.m_numFeats) { m_numLanguages = 0; return true; }        //defensive
 
@@ -207,17 +210,17 @@ bool SillMap::readSill(const Face & face)
 
     for (int i = 0; i < m_numLanguages; i++)
     {
-        uint32 langid = read32(pSill);
-        uint16 numSettings = read16(pSill);
-        uint16 offset = read16(pSill);
+        uint32 langid = be::read<uint32>(pSill);
+        uint16 numSettings = be::read<uint16>(pSill);
+        uint16 offset = be::read<uint16>(pSill);
         if (offset + 8U * numSettings > lSill && numSettings > 0) return false;
         Features* feats = new Features(*m_FeatureMap.m_defaultFeatures);
         const byte *pLSet = pBase + offset;
 
         for (int j = 0; j < numSettings; j++)
         {
-            uint32 name = read32(pLSet);
-            uint16 val = read16(pLSet);
+            uint32 name = be::read<uint32>(pLSet);
+            uint16 val = be::read<uint16>(pLSet);
             pLSet += 2;
             const FeatureRef* pRef = m_FeatureMap.findFeatureRef(name);
             if (pRef)
diff --git a/src/FeatureMap.h b/src/FeatureMap.h
index 41d4583..d8c3034 100644
--- a/src/FeatureMap.h
+++ b/src/FeatureMap.h
@@ -45,6 +45,8 @@ public:
     FeatureSetting(const FeatureSetting & fs) : m_label(fs.m_label), m_value(fs.m_value) {};
     uint16 label() const { return m_label; }
     int16 value() const { return m_value; }
+    
+    CLASS_NEW_DELETE;
 private:
     uint16 m_label;
     int16 m_value;
@@ -78,7 +80,7 @@ public:
         }
     }
     ~FeatureRef() {
-        if (m_nameValues) free(m_nameValues);
+        free(m_nameValues);
         m_nameValues = NULL;
     }
     bool applyValToFeature(uint16 val, Features& pDest) const; //defined in GrFaceImp.h
@@ -98,12 +100,7 @@ public:
     const Face* getFace() const { return m_pFace;}
     const FeatureMap* getFeatureMap() const;// { return m_pFace;}
 
-//     void * operator new (size_t s, GrFeatureRef * p)
-//     {
-//         return p;
-//     }
-
-    CLASS_NEW_DELETE
+    CLASS_NEW_DELETE;
 private:
     uint32 m_mask;              // bit mask to get the value from the vector
     uint32 m_id;                // feature identifier/name
@@ -124,7 +121,7 @@ private:        //unimplemented
 class NameAndFeatureRef
 {
   public:
-    NameAndFeatureRef() {}
+    NameAndFeatureRef() : m_pFRef(NULL) {}
     NameAndFeatureRef(uint32 name) : m_name(name) {}
     NameAndFeatureRef(const FeatureRef* p/*not NULL*/) : m_name(p->getId()), m_pFRef(p) {}
 
diff --git a/src/Font.cpp b/src/Font.cpp
index aa83540..9eedf0f 100644
--- a/src/Font.cpp
+++ b/src/Font.cpp
@@ -45,8 +45,7 @@ Font::Font(float ppm, const Face *face/*needed for scaling*/) :
 
 /*virtual*/ Font::~Font()
 {
-    if (m_advances)
-        free(m_advances);
+	free(m_advances);
 }
 
 
diff --git a/src/GlyphFace.cpp b/src/GlyphFace.cpp
index c238ade..66fa9ed 100644
--- a/src/GlyphFace.cpp
+++ b/src/GlyphFace.cpp
@@ -29,6 +29,7 @@ of the License or (at your option) any later version.
 #include "XmlTraceLog.h"
 #include "GlyphFaceCache.h"
 #include "TtfUtil.h"
+#include "Endian.h"
 
 
 using namespace graphite2;
@@ -50,7 +51,7 @@ namespace
 
 		value_type 			operator * () const {
 			if (_n==0) { _v.id = *_p++; _n = *_p++; }
-			_v.value = swap16(*reinterpret_cast<const uint16 *>(_p));
+			_v.value = be::peek<uint16>(_p);
 			return _v;
 		}
 		const value_type *	operator ->() const { operator * (); return &_v; }
@@ -66,12 +67,12 @@ namespace
 	public:
 		glat2_iterator(const void * glat) : glat_iterator(glat) {}
 
-		glat_iterator & operator ++ () 		{ ++_v.id; --_n; _p += sizeof(uint16); if (_n == -1) { _p -= sizeof(uint16)*2; _v.id = read16(_p); _n = read16(_p); } return *this; }
+		glat_iterator & operator ++ () 		{ ++_v.id; --_n; _p += sizeof(uint16); if (_n == -1) { _p -= sizeof(uint16)*2; _v.id = be::read<uint16>(_p); _n = be::read<uint16>(_p); } return *this; }
 		glat_iterator   operator ++ (int) 	{ glat_iterator tmp(*this); operator++(); return tmp; }
 
 		value_type 			operator * () const {
-			if (_n==0) { _v.id = read16(_p); _n = read16(_p); }
-			_v.value = swap16(*reinterpret_cast<const uint16 *>(_p));
+			if (_n==0) { _v.id = be::read<uint16>(_p); _n = be::read<uint16>(_p); }
+			_v.value = be::peek<uint16>(_p);
 			return _v;
 		}
 		const value_type *	operator ->() const { operator * (); return &_v; }
@@ -116,13 +117,13 @@ GlyphFace::GlyphFace(const GlyphFaceCacheHeader& hdr, unsigned short glyphid)
         size_t glocs, gloce;
         if (hdr.m_locFlagsUse32Bit)
         {
-            glocs = swap32(((uint32 *)hdr.m_pGloc)[2+glyphid]);
-            gloce = swap32(((uint32 *)hdr.m_pGloc)[3+glyphid]);
+            glocs = be::swap<uint32>(((uint32 *)hdr.m_pGloc)[2+glyphid]);
+            gloce = be::swap<uint32>(((uint32 *)hdr.m_pGloc)[3+glyphid]);
         }
         else
         {
-            glocs = swap16(((uint16 *)hdr.m_pGloc)[4+glyphid]);
-            gloce = swap16(((uint16 *)hdr.m_pGloc)[5+glyphid]);
+            glocs = be::swap<uint16>(((uint16 *)hdr.m_pGloc)[4+glyphid]);
+            gloce = be::swap<uint16>(((uint16 *)hdr.m_pGloc)[5+glyphid]);
         }
         if (glocs < hdr.m_lGlat && gloce <= hdr.m_lGlat)
         {
@@ -130,14 +131,16 @@ GlyphFace::GlyphFace(const GlyphFaceCacheHeader& hdr, unsigned short glyphid)
 //            readAttrs(hdr.m_pGlat + glocs, hdr.m_pGlat + gloce, m_attrs, hdr.m_numAttrs, hdr.m_fGlat);
         	if (hdr.m_fGlat < 0x00020000)
         	{
-        		if (gloce - glocs > hdr.m_numAttrs*2*sizeof(byte)*sizeof(uint16))
+        		if (gloce - glocs < 2*sizeof(byte)+sizeof(uint16)
+        		 || gloce - glocs > hdr.m_numAttrs*(2*sizeof(byte)+sizeof(uint16)))
         			return;
 
         		new (&m_attrs) sparse(glat_iterator(hdr.m_pGlat + glocs), glat_iterator(hdr.m_pGlat + gloce));
         	}
         	else
         	{
-        		if (gloce - glocs > hdr.m_numAttrs*3*sizeof(uint16))
+        		if (gloce - glocs < 3*sizeof(uint16)
+        		 || gloce - glocs > hdr.m_numAttrs*3*sizeof(uint16))
         			return;
 
         		new (&m_attrs) sparse(glat2_iterator(hdr.m_pGlat + glocs), glat2_iterator(hdr.m_pGlat + gloce));
@@ -199,7 +202,7 @@ GlyphFace::GlyphFace(const GlyphFaceCacheHeader& hdr, unsigned short glyphid)
 //		}
 //		else
 //		{
-//			attr = attrs + read16(glat); attr_end = attr + read16(glat);
+//			attr = attrs + be::read<uint16>(glat); attr_end = attr + be::read<uint16>(glat);
 //		}
 //
 //		if (attr_end > attrs + num)
@@ -211,7 +214,7 @@ GlyphFace::GlyphFace(const GlyphFaceCacheHeader& hdr, unsigned short glyphid)
 //		}
 //		while (attr != attr_end)
 //		{
-//			*attr++ = read16(glat);
+//			*attr++ = be::read<uint16>(glat);
 //			logAttr(attrs, attr-1);
 //		}
 //	}
diff --git a/src/GlyphFace.h b/src/GlyphFace.h
index 2268f6f..78a19d1 100644
--- a/src/GlyphFace.h
+++ b/src/GlyphFace.h
@@ -64,19 +64,10 @@ private:
 friend class GlyphFaceCache;
     GlyphFace(const GlyphFaceCacheHeader& hdr, unsigned short glyphid);
     ~GlyphFace() throw();
-    void * operator new (size_t /*s*/, GlyphFace * p)
-    {
-        return p;
-    }
-    // delete in case an exception is thrown in constructor
-    void operator delete(void*, GlyphFace*) {}
-    void operator delete (void *) {}
 
 public:
 
     const Position    & theAdvance() const;
-//    void                setAdvance(const Position& a);
-//    void    setBBox(const Rect& a);
     const Rect &theBBox() const { return m_bbox; }
     uint16  getAttr(uint8 index) const { 
         if (m_attrs)
@@ -95,22 +86,10 @@ private:
 private:
     Rect     m_bbox;        // bounding box metrics in design units
     Position m_advance;     // Advance width and height in design units
-//    short  * m_attribs;     // array of glyph attributes, fontface knows how many
-//    short  * m_columns;     // array of fsm column values
-//    int      m_gloc;        // glat offset
     sparse   m_attrs;
-//    uint16 * m_attrs;
 };
 
 
-#if 0
-inline GlyphFace::GlyphFace(Position pos, Rect box) throw()
-  : m_bbox(box), m_advance(pos), m_gloc(0),
-//    m_attribs(0), m_columns(0), 
-    m_attrs(0) {
-}
-#endif
-
 inline GlyphFace::~GlyphFace() throw() {
 }
 
@@ -118,14 +97,4 @@ inline const Position & GlyphFace::theAdvance() const {
     return m_advance;
 }
 
-#if 0
-inline void GlyphFace::setAdvance(const Position& a) { 
-    m_advance = a;
-}
-
-inline void GlyphFace::setBBox(const Rect& a) {
-    m_bbox = a;
-}
-#endif
-
 } // namespace graphite2
diff --git a/src/GlyphFaceCache.cpp b/src/GlyphFaceCache.cpp
index 5b807de..e0d2587 100644
--- a/src/GlyphFaceCache.cpp
+++ b/src/GlyphFaceCache.cpp
@@ -27,7 +27,7 @@ of the License or (at your option) any later version.
 #include "GlyphFaceCache.h"
 #include "graphite2/Font.h"
 #include "Face.h"     //for the tags
-
+#include "Endian.h"
 
 using namespace graphite2;
 
@@ -39,7 +39,7 @@ using namespace graphite2;
     if ((m_pHmtx = face.getTable(Tag::hmtx, &m_lHmtx)) == NULL) return false;
     if ((m_pHHea = face.getTable(Tag::hhea)) == NULL) return false;
     if ((m_pGlat = face.getTable(Tag::Glat, &m_lGlat)) == NULL) return false;
-    m_fGlat = swap32(*reinterpret_cast<const uint32 *>(m_pGlat));
+    m_fGlat = be::peek<uint32>(m_pGlat);
 
     const void* pMaxp = face.getTable(Tag::maxp);
     if (pMaxp == NULL) return false;
@@ -48,13 +48,13 @@ using namespace graphite2;
     size_t lGloc;
     if ((m_pGloc = face.getTable(Tag::Gloc, &lGloc)) == NULL) return false;
     if (lGloc < 6) return false;
-    int version = swap32(*((uint32 *)m_pGloc));
+    int version = be::peek<uint32>(m_pGloc);
     if (version != 0x00010000) return false;
 
-    m_numAttrs = swap16(((uint16 *)m_pGloc)[3]);
+    m_numAttrs = be::swap<uint16>(((uint16 *)m_pGloc)[3]);
     if (m_numAttrs > 0x1000) return false;                  // is this hard limit appropriate?
 
-    unsigned short locFlags = swap16(((uint16 *)m_pGloc)[2]);
+    unsigned short locFlags = be::swap<uint16>(((uint16 *)m_pGloc)[2]);
     if (locFlags & 1)
     {
         m_locFlagsUse32Bit = true;
@@ -74,9 +74,9 @@ using namespace graphite2;
     return true;
 }
 
-/*static*/ GlyphFaceCache* GlyphFaceCache::makeCache(const GlyphFaceCacheHeader& hdr)
+GlyphFaceCache* GlyphFaceCache::makeCache(const GlyphFaceCacheHeader& hdr)
 {
-    return new(hdr) GlyphFaceCache(hdr);
+    return new (hdr) GlyphFaceCache(hdr);
 }
 
 GlyphFaceCache::GlyphFaceCache(const GlyphFaceCacheHeader& hdr)
@@ -90,9 +90,8 @@ GlyphFaceCache::GlyphFaceCache(const GlyphFaceCacheHeader& hdr)
     }
 }
 
-/*virtual*/ GlyphFaceCache::~GlyphFaceCache()
+GlyphFaceCache::~GlyphFaceCache()
 {
-//    delete[] m_glyphs;        //can't do this since not allocated by new[] and so does not know array size.
     unsigned int nGlyphs = numGlyphs();
     int deltaPointers = (*glyphPtrDirect(nGlyphs-1u) - *glyphPtrDirect(0u));
     if ((nGlyphs > 0u) && (deltaPointers == static_cast<int>(nGlyphs - 1)))
@@ -101,7 +100,7 @@ GlyphFaceCache::GlyphFaceCache(const GlyphFaceCacheHeader& hdr)
         {
             GlyphFace *p = *glyphPtrDirect(i);
             assert (p);
-            delete p;      //invokes d'tor. Does not release the memory.
+            p->~GlyphFace();
         }
         free (*glyphPtrDirect(0));
     }
@@ -112,7 +111,7 @@ GlyphFaceCache::GlyphFaceCache(const GlyphFaceCacheHeader& hdr)
             GlyphFace *p = *glyphPtrDirect(i);
             if (p)
             {
-                delete p;      //invokes d'tor. Does not release the memory.
+                p->~GlyphFace();
                 free(p);
             }
         }
diff --git a/src/GlyphFaceCache.h b/src/GlyphFaceCache.h
index 389828e..148ee1a 100644
--- a/src/GlyphFaceCache.h
+++ b/src/GlyphFaceCache.h
@@ -77,9 +77,9 @@ public:
         return malloc(s + sizeof(GlyphFace*)*hdr.numGlyphs());
     }
     // delete in case an exception is thrown in constructor
-    void operator delete(void* p, const GlyphFaceCacheHeader& )
+    void operator delete(void* p, const GlyphFaceCacheHeader& ) throw()
     {
-        if (p) free(p);
+        free(p);
     }
 
     const GlyphFace *glyph(unsigned short glyphid) const;      //result may be changed by subsequent call with a different glyphid
diff --git a/src/List.h b/src/List.h
index b7dfc0c..3288f81 100644
--- a/src/List.h
+++ b/src/List.h
@@ -84,7 +84,7 @@ public:
     void                insert(iterator p, size_t n, const T & x);
     void                insert(iterator p, const_iterator first, const_iterator last);
     void                pop_back()              { assert(size() > 0); --m_last; }
-    void                push_back(const T &v)   { if (m_last == m_end) reserve(size()+1); ::new (m_last++) T(v); }
+    void                push_back(const T &v)   { if (m_last == m_end) reserve(size()+1); new (m_last++) T(v); }
 
     void                clear()                 { erase(begin(), end()); }
     iterator            erase(iterator p)       { return erase(p, p+1); }
@@ -128,7 +128,7 @@ void Vector<T>::insert(iterator p, size_t n, const T & x)
 {
     p = _insert_default(p, n);
     // Copy in elements
-    for (; n; --n, ++p) { ::new (p) T(x); }
+    for (; n; --n, ++p) { new (p) T(x); }
 }
 
 template<typename T>
@@ -137,7 +137,7 @@ void Vector<T>::insert(iterator p, const_iterator first, const_iterator last)
 {
     p = _insert_default(p, distance(first, last));
     // Copy in elements
-    for (;first != last; ++first, ++p) { ::new (p) T(*first); }
+    for (;first != last; ++first, ++p) { new (p) T(*first); }
 }
 
 template<typename T>
diff --git a/src/Main.h b/src/Main.h
index 85f9add..1cfd809 100644
--- a/src/Main.h
+++ b/src/Main.h
@@ -41,29 +41,6 @@ typedef gr_int16        int16;
 typedef gr_int32        int32;
 typedef size_t          uintptr;
 
-#if !defined WORDS_BIGENDIAN || defined PC_OS
-inline uint16 swap16(uint16 x) { return (x << 8) | (x >> 8); }
-inline  int16 swap16(int16 x)  { return int16(swap16(uint16(x))); }
-inline uint32 swap32(uint32 x) { return (uint32(swap16(uint16(x))) << 16) | swap16(uint16(x >> 16)); }
-inline  int32 swap32(int32 x)  { return int32(swap32(uint32(x))); }
-#else
-#define swap16(x) (x)
-#define swap32(x) (x)
-#endif
-
-inline uint16 read16(const byte *&x) { 
-  const uint16 r = swap16(*reinterpret_cast<const uint16 *&>(x));
-  x += sizeof(uint16);
-  return r;
-}
-inline uint16 read16(byte *&x) { return read16(const_cast<const byte * &>(x)); }
-inline uint32 read32(const byte *&x) { 
-  const uint32 r = swap32(*reinterpret_cast<const uint32 *&>(x));
-  x += sizeof(uint32);
-  return r;
-}
-inline uint32 read32(byte *&x) { return read32(const_cast<const byte * &>(x)); }
-
 // typesafe wrapper around malloc for simple types
 // use free(pointer) to deallocate
 template <typename T> T * gralloc(size_t n)
@@ -79,10 +56,14 @@ template <typename T> T * grzeroalloc(size_t n)
 } // namespace graphite2
 
 #define CLASS_NEW_DELETE \
-    void * operator new[](size_t size) {return malloc(size);} \
-    void operator delete[] (void * p)throw() { if (p) free(p); } \
-    void * operator new(size_t size){ return malloc(size);} \
-    void operator delete (void * p) throw() {if (p) free(p);}
+    void * operator new   (size_t size){ return malloc(size);} \
+    void * operator new   (size_t, void * p) throw() { return p; } \
+    void * operator new[] (size_t size) {return malloc(size);} \
+    void * operator new[] (size_t, void * p) throw() { return p; } \
+    void operator delete   (void * p) throw() { free(p);} \
+    void operator delete   (void *, void *) throw() {} \
+    void operator delete[] (void * p)throw() { free(p); } \
+    void operator delete[] (void *, void *) throw() {} \
 
 #ifdef __GNUC__
 #define GR_MAYBE_UNUSED __attribute__((unused))
diff --git a/src/NameTable.cpp b/src/NameTable.cpp
index 5a9b3b4..c471767 100644
--- a/src/NameTable.cpp
+++ b/src/NameTable.cpp
@@ -25,6 +25,7 @@ License, as published by the Free Software Foundation, either version 2
 of the License or (at your option) any later version.
 */
 #include "Main.h"
+#include "Endian.h"
 
 #include "NameTable.h"
 #include "processUTF.h"
@@ -36,7 +37,7 @@ NameTable::NameTable(const void* data, size_t length, uint16 platformId, uint16
     :
     m_platformId(0), m_encodingId(0), m_languageCount(0),
     m_platformOffset(0), m_platformLastRecord(0), m_nameDataLength(0),
-    m_nameData(NULL)
+    m_table(0), m_nameData(NULL)
 {
     void *pdata = malloc(length);
     if (!pdata) return;
@@ -45,9 +46,9 @@ NameTable::NameTable(const void* data, size_t length, uint16 platformId, uint16
 
     if ((length > sizeof(TtfUtil::Sfnt::FontNames)) &&
         (length > sizeof(TtfUtil::Sfnt::FontNames) +
-         sizeof(TtfUtil::Sfnt::NameRecord) * ( swap16(m_table->count) - 1)))
+         sizeof(TtfUtil::Sfnt::NameRecord) * ( be::swap<uint16>(m_table->count) - 1)))
     {
-        uint16 offset = swap16(m_table->string_offset);
+        uint16 offset = be::swap<uint16>(m_table->string_offset);
         m_nameData = reinterpret_cast<const uint8*>(pdata) + offset;
         setPlatformEncoding(platformId, encodingID);
         m_nameDataLength = length - offset;
@@ -63,19 +64,19 @@ uint16 NameTable::setPlatformEncoding(uint16 platformId, uint16 encodingID)
 {
     if (!m_nameData) return 0;
     uint16 i = 0;
-    uint16 count = swap16(m_table->count);
+    uint16 count = be::swap<uint16>(m_table->count);
     for (; i < count; i++)
     {
-        if (swap16(m_table->name_record[i].platform_id) == platformId &&
-            swap16(m_table->name_record[i].platform_specific_id) == encodingID)
+        if (be::swap<uint16>(m_table->name_record[i].platform_id) == platformId &&
+            be::swap<uint16>(m_table->name_record[i].platform_specific_id) == encodingID)
         {
             m_platformOffset = i;
             break;
         }
     }
     while ((++i < count) &&
-           (swap16(m_table->name_record[i].platform_id) == platformId) &&
-           (swap16(m_table->name_record[i].platform_specific_id) == encodingID))
+           (be::swap<uint16>(m_table->name_record[i].platform_id) == platformId) &&
+           (be::swap<uint16>(m_table->name_record[i].platform_specific_id) == encodingID))
     {
         m_platformLastRecord = i;
     }
@@ -97,9 +98,9 @@ void* NameTable::getName(uint16& languageId, uint16 nameId, gr_encform enc, uint
     }
     for (uint16 i = m_platformOffset; i <= m_platformLastRecord; i++)
     {
-        if (swap16(m_table->name_record[i].name_id) == nameId)
+        if (be::swap<uint16>(m_table->name_record[i].name_id) == nameId)
         {
-            uint16 langId = swap16(m_table->name_record[i].language_id);
+            uint16 langId = be::swap<uint16>(m_table->name_record[i].language_id);
             if (langId == languageId)
             {
                 bestLang = i;
@@ -135,9 +136,9 @@ void* NameTable::getName(uint16& languageId, uint16 nameId, gr_encform enc, uint
         }
     }
     const TtfUtil::Sfnt::NameRecord & nameRecord = m_table->name_record[bestLang];
-    languageId = swap16(nameRecord.language_id);
-    uint16 utf16Length = swap16(nameRecord.length);
-    uint16 offset = swap16(nameRecord.offset);
+    languageId = be::swap<uint16>(nameRecord.language_id);
+    uint16 utf16Length = be::swap<uint16>(nameRecord.length);
+    uint16 offset = be::swap<uint16>(nameRecord.offset);
     if(offset + utf16Length > m_nameDataLength)
     {
         languageId = 0;
@@ -149,7 +150,7 @@ void* NameTable::getName(uint16& languageId, uint16 nameId, gr_encform enc, uint
     const uint8* pName = m_nameData + offset;
     for (size_t i = 0; i < utf16Length; i++)
     {
-        utf16Name[i] = read16(pName);
+        utf16Name[i] = be::read<uint16>(pName);
     }
     utf16Name[utf16Length] = 0;
     if (enc == gr_utf16)
@@ -190,27 +191,27 @@ uint16 NameTable::getLanguageId(const char * bcp47Locale)
 {
     size_t localeLength = strlen(bcp47Locale);
     uint16 localeId = m_locale2Lang.getMsId(bcp47Locale);
-    if (m_table && (swap16(m_table->format) == 1))
+    if (m_table && (be::swap<uint16>(m_table->format) == 1))
     {
         const uint8 * pLangEntries = reinterpret_cast<const uint8*>(m_table) +
             sizeof(TtfUtil::Sfnt::FontNames)
-            + sizeof(TtfUtil::Sfnt::NameRecord) * ( swap16(m_table->count) - 1);
-        uint16 numLangEntries = read16(pLangEntries);
+            + sizeof(TtfUtil::Sfnt::NameRecord) * ( be::swap<uint16>(m_table->count) - 1);
+        uint16 numLangEntries = be::read<uint16>(pLangEntries);
         const TtfUtil::Sfnt::LangTagRecord * langTag =
             reinterpret_cast<const TtfUtil::Sfnt::LangTagRecord*>(pLangEntries);
         if (pLangEntries + numLangEntries * sizeof(TtfUtil::Sfnt::LangTagRecord) <= m_nameData)
         {
             for (uint16 i = 0; i < numLangEntries; i++)
             {
-                uint16 offset = swap16(langTag[i].offset);
-                uint16 length = swap16(langTag[i].length);
+                uint16 offset = be::swap<uint16>(langTag[i].offset);
+                uint16 length = be::swap<uint16>(langTag[i].length);
                 if ((offset + length <= m_nameDataLength) && (length == 2 * localeLength))
                 {
                     const uint8* pName = m_nameData + offset;
                     bool match = true;
                     for (size_t j = 0; j < localeLength; j++)
                     {
-                        uint16 code = read16(pName);
+                        uint16 code = be::read<uint16>(pName);
                         if ((code > 0x7F) || (code != bcp47Locale[j]))
                         {
                             match = false;
diff --git a/src/NameTable.h b/src/NameTable.h
index ede5f74..25a6de7 100644
--- a/src/NameTable.h
+++ b/src/NameTable.h
@@ -36,7 +36,7 @@ class NameTable
 {
 public:
     NameTable(const void * data, size_t length, uint16 platfromId=3, uint16 encodingID = 1);
-    ~NameTable() { if (m_table) free(const_cast<TtfUtil::Sfnt::FontNames *>(m_table)); }
+    ~NameTable() { free(const_cast<TtfUtil::Sfnt::FontNames *>(m_table)); }
     enum eNameFallback {
         eNoFallback = 0,
         eEnUSFallbackOnly = 1,
diff --git a/src/Pass.cpp b/src/Pass.cpp
index 79a002b..51b3608 100644
--- a/src/Pass.cpp
+++ b/src/Pass.cpp
@@ -25,6 +25,7 @@ License, as published by the Free Software Foundation, either version 2
 of the License or (at your option) any later version.
 */
 #include "Main.h"
+#include "Endian.h"
 #include "Pass.h"
 #include <string.h>
 #include <stdlib.h>
@@ -76,17 +77,17 @@ bool Pass::readPass(void *pass, size_t pass_length, size_t subtable_base, const
     m_iMaxLoop = *p++;
     p++; // skip maxContext
     p += sizeof(byte);     // skip maxBackup
-    m_numRules = read16(p);
+    m_numRules = be::read<uint16>(p);
     p += sizeof(uint16);   // not sure why we would want this
-    const byte * const pcCode = pass_start + read32(p) - subtable_base,
-               * const rcCode = pass_start + read32(p) - subtable_base,
-               * const aCode  = pass_start + read32(p) - subtable_base;
+    const byte * const pcCode = pass_start + be::read<uint32>(p) - subtable_base,
+               * const rcCode = pass_start + be::read<uint32>(p) - subtable_base,
+               * const aCode  = pass_start + be::read<uint32>(p) - subtable_base;
     p += sizeof(uint32);
-    m_sRows = read16(p);
-    m_sTransition = read16(p);
-    m_sSuccess = read16(p);
-    m_sColumns = read16(p);
-    numRanges = read16(p);
+    m_sRows = be::read<uint16>(p);
+    m_sTransition = be::read<uint16>(p);
+    m_sSuccess = be::read<uint16>(p);
+    m_sColumns = be::read<uint16>(p);
+    numRanges = be::read<uint16>(p);
     p += sizeof(uint16)   // skip searchRange
          +  sizeof(uint16)   // skip entrySelector
          +  sizeof(uint16);  // skip rangeShift
@@ -108,7 +109,7 @@ bool Pass::readPass(void *pass, size_t pass_length, size_t subtable_base, const
         return false;
 
     if (p + numRanges * 6 - 4 > pass_end) return false;
-    m_numGlyphs = swap16(*(uint16 *)(p + numRanges * 6 - 4)) + 1;
+    m_numGlyphs = be::swap<uint16>(*(uint16 *)(p + numRanges * 6 - 4)) + 1;
     // Caculate the start of vairous arrays.
     const uint16 * const ranges = reinterpret_cast<const uint16 *>(p);
     p += numRanges*sizeof(uint16)*3;
@@ -119,7 +120,7 @@ bool Pass::readPass(void *pass, size_t pass_length, size_t subtable_base, const
     if (   reinterpret_cast<const byte *>(o_rule_map) > pass_end
             || p > pass_end)
         return false;
-    const size_t numEntries = swap16(o_rule_map[m_sSuccess]);
+    const size_t numEntries = be::swap<uint16>(o_rule_map[m_sSuccess]);
     const uint16 * const   rule_map = reinterpret_cast<const uint16 *>(p);
     p += numEntries*sizeof(uint16);
 
@@ -135,7 +136,7 @@ bool Pass::readPass(void *pass, size_t pass_length, size_t subtable_base, const
     p += sizeof(byte);     // skip reserved byte
 
     if (p > pass_end) return false;
-    const size_t pass_constraint_len = read16(p);
+    const size_t pass_constraint_len = be::read<uint16>(p);
     const uint16 * const o_constraint = reinterpret_cast<const uint16 *>(p);
     p += (m_numRules + 1)*sizeof(uint16);
     const uint16 * const o_actions = reinterpret_cast<const uint16 *>(p);
@@ -146,7 +147,7 @@ bool Pass::readPass(void *pass, size_t pass_length, size_t subtable_base, const
     if (p != pcCode || p >= pass_end) return false;
     p += pass_constraint_len;
     if (p != rcCode || p >= pass_end) return false;
-    p += swap16(o_constraint[m_numRules]);
+    p += be::swap<uint16>(o_constraint[m_numRules]);
     if (p != aCode || p >= pass_end) return false;
     if (size_t(rcCode - pcCode) != pass_constraint_len) return false;
 
@@ -154,7 +155,7 @@ bool Pass::readPass(void *pass, size_t pass_length, size_t subtable_base, const
     if (pass_constraint_len)
     {
         m_cPConstraint = vm::Code(true, pcCode, pcCode + pass_constraint_len, 
-                                  precontext[0], swap16(sort_keys[0]), *m_silf, face);
+                                  precontext[0], be::swap<uint16>(sort_keys[0]), *m_silf, face);
         if (!m_cPConstraint) return false;
     }
     if (!readRanges(ranges, numRanges)) return false;
@@ -170,8 +171,8 @@ bool Pass::readRules(const uint16 * rule_map, const size_t num_entries,
                      const uint16 * o_action,     const byte * ac_data,
                      const Face & face)
 {
-    const byte * const ac_data_end = ac_data + swap16(o_action[m_numRules]);
-    const byte * const rc_data_end = rc_data + swap16(o_constraint[m_numRules]);
+    const byte * const ac_data_end = ac_data + be::swap<uint16>(o_action[m_numRules]);
+    const byte * const rc_data_end = rc_data + be::swap<uint16>(o_constraint[m_numRules]);
 
     if (!(m_rules = new Rule [m_numRules])) return false;
     precontext += m_numRules;
@@ -181,20 +182,20 @@ bool Pass::readRules(const uint16 * rule_map, const size_t num_entries,
 
     // Load rules.
     const byte * ac_begin = 0, * rc_begin = 0,
-               * ac_end = ac_data + swap16(*o_action),
-               * rc_end = rc_data + swap16(*o_constraint);
+               * ac_end = ac_data + be::swap<uint16>(*o_action),
+               * rc_end = rc_data + be::swap<uint16>(*o_constraint);
     Rule * r = m_rules + m_numRules - 1;
     for (size_t n = m_numRules; n; --n, --r, ac_end = ac_begin, rc_end = rc_begin)
     {
         r->preContext = *--precontext;
-        r->sort       = swap16(*--sort_key);
+        r->sort       = be::swap<uint16>(*--sort_key);
 #ifndef NDEBUG
         r->rule_idx   = n - 1;
 #endif
         if (r->sort > 63 || r->preContext >= r->sort || r->preContext > m_maxPreCtxt || r->preContext < m_minPreCtxt)
             return false;
-        ac_begin      = ac_data + swap16(*--o_action);
-        rc_begin      = *--o_constraint ? rc_data + swap16(*o_constraint) : rc_end;
+        ac_begin      = ac_data + be::swap<uint16>(*--o_action);
+        rc_begin      = *--o_constraint ? rc_data + be::swap<uint16>(*o_constraint) : rc_end;
 
         if (ac_begin > ac_end || ac_begin > ac_data_end || ac_end > ac_data_end
                 || rc_begin > rc_end || rc_begin > rc_data_end || rc_end > rc_data_end)
@@ -215,7 +216,7 @@ bool Pass::readRules(const uint16 * rule_map, const size_t num_entries,
     RuleEntry * re = m_ruleMap = gralloc<RuleEntry>(num_entries);
     for (size_t n = num_entries; n; --n, ++re)
     {
-        const ptrdiff_t rn = swap16(*rule_map++);
+        const ptrdiff_t rn = be::swap<uint16>(*rule_map++);
         if (rn >= m_numRules)  return false;
         re->rule = m_rules + rn;
     }
@@ -237,7 +238,7 @@ bool Pass::readStates(const int16 * starts, const int16 *states, const uint16 *
     for (State * * s = m_startStates,
             * * const s_end = s + m_maxPreCtxt - m_minPreCtxt + 1; s != s_end; ++s)
     {
-        *s = m_states + swap16(*starts++);
+        *s = m_states + be::swap<uint16>(*starts++);
         if (*s < m_states || *s >= m_states + m_sRows) return false; // true;
     }
 
@@ -245,19 +246,19 @@ bool Pass::readStates(const int16 * starts, const int16 *states, const uint16 *
     for (State * * t = m_sTable,
                * * const t_end = t + m_sTransition*m_sColumns; t != t_end; ++t)
     {
-        *t = m_states + swap16(*states++);
+        *t = m_states + be::swap<uint16>(*states++);
         if (*t < m_states || *t >= m_states + m_sRows) return false;
     }
 
     State * s = m_states,
           * const transitions_end = m_states + m_sTransition,
           * const success_begin = m_states + m_sRows - m_sSuccess;
-    const RuleEntry * rule_map_end = m_ruleMap + swap16(o_rule_map[m_sSuccess]);
+    const RuleEntry * rule_map_end = m_ruleMap + be::swap<uint16>(o_rule_map[m_sSuccess]);
     for (size_t n = m_sRows; n; --n, ++s)
     {
         s->transitions = s < transitions_end ? m_sTable + (s-m_states)*m_sColumns : 0;
-        RuleEntry * const begin = s < success_begin ? 0 : m_ruleMap + swap16(*o_rule_map++),
-                  * const end   = s < success_begin ? 0 : m_ruleMap + swap16(*o_rule_map);
+        RuleEntry * const begin = s < success_begin ? 0 : m_ruleMap + be::swap<uint16>(*o_rule_map++),
+                  * const end   = s < success_begin ? 0 : m_ruleMap + be::swap<uint16>(*o_rule_map);
 
         if (begin >= rule_map_end || end > rule_map_end || begin > end)
             return false;
@@ -291,7 +292,7 @@ void Pass::logRule(GR_MAYBE_UNUSED const Rule * r, GR_MAYBE_UNUSED const uint16
     {
         XmlTraceLog::get().openElement(ElementRule);
         XmlTraceLog::get().addAttribute(AttrIndex, lid);
-        XmlTraceLog::get().addAttribute(AttrSortKey, swap16(sort_key[lid]));
+        XmlTraceLog::get().addAttribute(AttrSortKey, be::swap<uint16>(sort_key[lid]));
         XmlTraceLog::get().addAttribute(AttrPrecontext, r->preContext);
         XmlTraceLog::get().closeElement(ElementRule);
     }
@@ -350,9 +351,9 @@ bool Pass::readRanges(const uint16 *ranges, size_t num_ranges)
     memset(m_cols, 0xFF, m_numGlyphs * sizeof(uint16));
     for (size_t n = num_ranges; n; --n)
     {
-        const uint16 first = swap16(*ranges++),
-                     last  = swap16(*ranges++),
-                     col   = swap16(*ranges++);
+        const uint16 first = be::swap<uint16>(*ranges++),
+                     last  = be::swap<uint16>(*ranges++),
+                     col   = be::swap<uint16>(*ranges++);
         uint16 *p;
 
         if (first > last || last >= m_numGlyphs || col >= m_sColumns)
diff --git a/src/Rule.h b/src/Rule.h
index 872ce56..bf8dc3f 100644
--- a/src/Rule.h
+++ b/src/Rule.h
@@ -32,7 +32,6 @@ of the License or (at your option) any later version.
 namespace graphite2 {
 
 struct Rule {
-  ~Rule();
   const vm::Code * constraint, 
                  * action;
   unsigned short   sort;
@@ -41,6 +40,9 @@ struct Rule {
   uint16           rule_idx;
 #endif
 
+  Rule() : constraint(0), action(0) {}
+  ~Rule();
+
   CLASS_NEW_DELETE;
 };
 
diff --git a/src/SegCache.h b/src/SegCache.h
index ff4bfc1..f6ead48 100644
--- a/src/SegCache.h
+++ b/src/SegCache.h
@@ -131,7 +131,7 @@ public:
             m_entries[length-1] = newEntries;
         }
         m_entryCounts[length-1] += 1;
-        ::new (m_entries[length-1] + insertPos)
+        new (m_entries[length-1] + insertPos)
             SegCacheEntry(cmapGlyphs, length, seg, charOffset, totalAccessCount);
         return m_entries[length-1]  + insertPos;
     }
diff --git a/src/SegCacheEntry.cpp b/src/SegCacheEntry.cpp
index 6c7718b..b942e32 100644
--- a/src/SegCacheEntry.cpp
+++ b/src/SegCacheEntry.cpp
@@ -158,8 +158,8 @@ void SegCacheEntry::log(GR_MAYBE_UNUSED size_t unicodeLength) const
 
 void SegCacheEntry::clear()
 {
-    if (m_unicode) free(m_unicode);
-    if (m_attr) free(m_attr);
+    free(m_unicode);
+    free(m_attr);
     delete [] m_glyph;
     m_unicode = NULL;
     m_glyph = NULL;
diff --git a/src/SegCacheEntry.h b/src/SegCacheEntry.h
index e42ebdc..78fbb3b 100644
--- a/src/SegCacheEntry.h
+++ b/src/SegCacheEntry.h
@@ -97,7 +97,7 @@ public:
     }
     unsigned long long lastAccess() const { return m_lastAccess; };
 
-    CLASS_NEW_DELETE
+    CLASS_NEW_DELETE;
 private:
 
     size_t m_glyphLength;
diff --git a/src/SegCacheStore.h b/src/SegCacheStore.h
index a098d01..2a3342b 100644
--- a/src/SegCacheStore.h
+++ b/src/SegCacheStore.h
@@ -52,7 +52,7 @@ public:
             m_caches[i]->clear(cacheStore);
             delete m_caches[i];
         }
-        if (m_caches) free(m_caches);
+        free(m_caches);
         m_caches = NULL;
         m_cacheCount = 0;
     }
diff --git a/src/Segment.cpp b/src/Segment.cpp
index 0bb7332..1fb97e0 100644
--- a/src/Segment.cpp
+++ b/src/Segment.cpp
@@ -27,7 +27,6 @@ of the License or (at your option) any later version.
 #include "processUTF.h"
 #include <string.h>
 #include <stdlib.h>
-#include <new>
 
 #include "Segment.h"
 #include "graphite2/Font.h"
diff --git a/src/Silf.cpp b/src/Silf.cpp
index 48691ca..907bef2 100644
--- a/src/Silf.cpp
+++ b/src/Silf.cpp
@@ -26,6 +26,7 @@ of the License or (at your option) any later version.
 */
 #include <cstdlib>
 #include "graphite2/Segment.h"
+#include "Endian.h"
 #include "Silf.h"
 #include "XmlTraceLog.h"
 #include "Segment.h"
@@ -64,8 +65,8 @@ void Silf::releaseBuffers() throw()
 
 bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 version)
 {
-    byte *p = (byte *)pSilf;
-    byte *eSilf = p + lSilf;
+    const byte *p = (byte *)pSilf;
+    const byte * const eSilf = p + lSilf;
     uint32 *pPasses;
 #ifndef DISABLE_TRACING
     XmlTraceLog::get().openElement(ElementSilfSub);
@@ -75,8 +76,8 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
 #ifndef DISABLE_TRACING
         if (XmlTraceLog::get().active())
         {
-            XmlTraceLog::get().addAttribute(AttrMajor, swap16(((uint16*) p)[0]));
-            XmlTraceLog::get().addAttribute(AttrMinor, swap16(((uint16*) p)[1]));
+            XmlTraceLog::get().addAttribute(AttrMajor, be::peek<uint16>(p));
+            XmlTraceLog::get().addAttribute(AttrMinor, be::peek<uint16>(p+sizeof(uint16)));
         }
 #endif
         if (lSilf < 27) { releaseBuffers(); return false; }
@@ -143,7 +144,7 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
     }
 //    p += uint8(*p) * 8 + 1;     // ignore justification for now
     if (p + 9 >= eSilf) { releaseBuffers(); return false; }
-    m_aLig = read16(p);
+    m_aLig = be::read<uint16>(p);
 #ifndef DISABLE_TRACING
     XmlTraceLog::get().addAttribute(AttrLigComp, *p);
 #endif
@@ -183,7 +184,7 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
     }
     pPasses = (uint32 *)p;
     p += 4 * (m_numPasses + 1);
-    m_numPseudo = read16(p);
+    m_numPseudo = be::read<uint16>(p);
 #ifndef DISABLE_TRACING
     XmlTraceLog::get().addAttribute(AttrNumPseudo, m_numPseudo);
 #endif
@@ -196,8 +197,8 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
     m_pseudos = new Pseudo[m_numPseudo];
     for (int i = 0; i < m_numPseudo; i++)
     {
-        m_pseudos[i].uid = read32(p);
-        m_pseudos[i].gid = read16(p);
+        m_pseudos[i].uid = be::read<uint32>(p);
+        m_pseudos[i].gid = be::read<uint16>(p);
 #ifndef DISABLE_TRACING
         XmlTraceLog::get().openElement(ElementPseudo);
         XmlTraceLog::get().addAttribute(AttrIndex, i);
@@ -212,7 +213,7 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
         return false;
     }
 
-    int clen = readClassMap((void *)p, swap32(*pPasses) - (p - (byte *)pSilf), face.getGlyphFaceCache()->numGlyphs() + m_numPseudo);
+    int clen = readClassMap(p, be::swap<uint32>(*pPasses) - (p - (byte *)pSilf));
     if (clen < 0) {
         releaseBuffers();
         return false;
@@ -221,8 +222,8 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
 
     for (size_t i = 0; i < m_numPasses; ++i)
     {
-        uint32 pOffset = swap32(pPasses[i]);
-        if ((uint8 *)pSilf + pOffset > eSilf || swap32(pPasses[i + 1]) < pOffset)
+        uint32 pOffset = be::swap<uint32>(pPasses[i]);
+        if ((uint8 *)pSilf + pOffset > eSilf || be::swap<uint32>(pPasses[i + 1]) < pOffset)
         {
             releaseBuffers();
             return false;
@@ -235,7 +236,7 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
             XmlTraceLog::get().addAttribute(AttrPassId, i);
         }
 #endif
-        if (!m_passes[i].readPass((char *)pSilf + pOffset, swap32(pPasses[i + 1]) - pOffset, pOffset, face))
+        if (!m_passes[i].readPass((char *)pSilf + pOffset, be::swap<uint32>(pPasses[i + 1]) - pOffset, pOffset, face))
         {
 #ifndef DISABLE_TRACING
             XmlTraceLog::get().closeElement(ElementPass);
@@ -255,112 +256,55 @@ bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 vers
     return true;
 }
 
-size_t Silf::readClassMap(void *pClass, size_t lClass, GR_MAYBE_UNUSED int numGlyphs)
+size_t Silf::readClassMap(const byte *p, size_t data_len)
 {
-    const byte *p = reinterpret_cast<const byte *>(pClass);
-    m_nClass = read16(p);
-    m_nLinear = read16(p);
-    m_classOffsets = gralloc<uint16>(m_nClass + 1);
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementClassMap);
-        XmlTraceLog::get().addAttribute(AttrNumClasses, m_nClass);
-        XmlTraceLog::get().addAttribute(AttrNumLinear, m_nLinear);
-    }
-#endif
+	if (data_len < sizeof(uint16)*2)	return -1;
 
-    for (int i = 0; i <= m_nClass; i++)
-    {
-        m_classOffsets[i] = read16(p) / 2 - (2 + m_nClass + 1);     // uint16[] index
-    }
+	m_nClass  = be::read<uint16>(p);
+	m_nLinear = be::read<uint16>(p);
 
-    if (m_classOffsets[0] != 0)
-    {
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-            XmlTraceLog::get().error("Invalid first Class Offset %d expected %d",
-                m_classOffsets[0], m_nLinear);
-            XmlTraceLog::get().closeElement(ElementClassMap);
-        }
-#endif
-        return -1;
-    }
-    if (m_classOffsets[m_nClass] + (2u + m_nClass + 1u) * 2 > lClass)
-    {
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-            XmlTraceLog::get().error("Invalid Class Offset %d max size %d",
-                m_classOffsets[m_nClass], lClass);
-            XmlTraceLog::get().closeElement(ElementClassMap);
-        }
-#endif
-        return -1;
-    }
-    m_classData = gralloc<uint16>(m_classOffsets[m_nClass]);
-    for (int i = 0; i < m_classOffsets[m_nClass]; i++)
-        m_classData[i] = read16(p);
-#ifndef DISABLE_TRACING
-    // TODO this includes extra checking which shouldn't be
-    // disabled when tracing is inactive unless it is duplicated elsewhere
-    if (XmlTraceLog::get().active())
-    {
-        bool glyphsOk = true;
-        for (int i = 0; i < m_nClass; i++)
-        {
-            XmlTraceLog::get().openElement(ElementLookupClass);
-            XmlTraceLog::get().addAttribute(AttrIndex, i);
-            if (i < m_nLinear)
-            {
-                for (int j = m_classOffsets[i]; j < m_classOffsets[i+1]; j++)
-                {
-                    XmlTraceLog::get().openElement(ElementLookup);
-                    XmlTraceLog::get().addAttribute(AttrGlyphId, m_classData[j]);
-		    // out of range glyphids are allowed as place holders
-                    // if (m_classData[j] >= numGlyphs)
-                    // {
-                    //     XmlTraceLog::get().warning("GlyphId out of range %d",
-                    //         m_classData[j]);
-                    //         glyphsOk = false;
-                    // }
-                    XmlTraceLog::get().closeElement(ElementLookup);
-                }
-            }
-            else
-            {
-                int offset = m_classOffsets[i];
-                uint16 numIds = m_classData[offset];
-                XmlTraceLog::get().addAttribute(AttrNum, numIds);
-                for (int j = offset + 4; j < m_classOffsets[i+1]; j += 2)
-                {
-                    XmlTraceLog::get().openElement(ElementLookup);
-                    XmlTraceLog::get().addAttribute(AttrGlyphId, m_classData[j]);
-                    XmlTraceLog::get().addAttribute(AttrIndex, m_classData[j+1]);
-                    if (m_classData[j] >= numGlyphs)
-                    {
-                        XmlTraceLog::get().warning("GlyphId out of range %d",
-                            m_classData[j]);
-                    //         glyphsOk = false;
-                    }
-                    if (m_classData[j+1] >= numIds)
-                    {
-                       XmlTraceLog::get().warning("Index out of range %d",
-                           m_classData[j+1]);
-                           glyphsOk = false;
-                    }
-                    XmlTraceLog::get().closeElement(ElementLookup);
-                }
-            }
-            XmlTraceLog::get().closeElement(ElementLookupClass);
-        }
-        XmlTraceLog::get().closeElement(ElementClassMap);
-        if (!glyphsOk)
-            return -1;
-    }
-#endif
-    return (p - reinterpret_cast<const byte*>(pClass));
+	// Check that numLinear < numClass,
+	// that there is at least enough data for numClasses offsets.
+	if (m_nLinear > m_nClass
+	 || (m_nClass + 1) > (data_len/sizeof(uint16)-2))
+		return -1;
+
+	const uint16 cls_off = sizeof(uint16)*(2 + m_nClass+1);
+	const uint16 max_off = (be::peek<uint16>(p + sizeof(uint16)*m_nClass) - cls_off)/sizeof(uint16);
+	// Check that the last+1 offset is less than or equal to the class map length.
+	if (be::peek<uint16>(p) != cls_off || max_off > (data_len - cls_off)/sizeof(uint16))
+		return -1;
+
+	// Read in all the offsets.
+	m_classOffsets = gralloc<uint16>(m_nClass+1);
+	for (uint16 * o = m_classOffsets, * const o_end = o + m_nClass + 1; o != o_end; ++o)
+	{
+		*o = (be::read<uint16>(p) - cls_off)/sizeof(uint16);
+		if (*o > max_off)
+			return -1;
+	}
+
+	// Check the linear offsets are sane, these must be monotonically increasing.
+	for (const uint16 *o = m_classOffsets, * const o_end = o + m_nLinear; o != o_end; ++o)
+		if (o[0] > o[1])
+			return -1;
+
+	// Fortunately the class data is all uint16s so we can decode these now
+    m_classData = gralloc<uint16>(max_off);
+    for (uint16 *d = m_classData, * const d_end = d + max_off; d != d_end; ++d)
+        *d = be::read<uint16>(p);
+
+	// Check the lookup class invariants for each non-linear class
+	for (const uint16 *o = m_classOffsets + m_nLinear, * const o_end = m_classOffsets + m_nClass; o != o_end; ++o)
+	{
+		const uint16 * lookup = m_classData + *o;
+		if (lookup[0] == 0							// A LookupClass with no looks is a suspicious thing ...
+		 || lookup[0] > (max_off - *o - 4)/2  	    // numIDs lookup pairs fits within (start of LookupClass' lookups array, max_off]
+		 || lookup[3] != lookup[0] - lookup[1])		// rangeShift:	 numIDs  - searchRange
+			return -1;
+	}
+
+	return cls_off;
 }
 
 uint16 Silf::findPseudo(uint32 uid) const
@@ -374,60 +318,26 @@ uint16 Silf::findClassIndex(uint16 cid, uint16 gid) const
 {
     if (cid > m_nClass) return -1;
 
-#ifdef ENABLE_DEEP_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementLookupClass);
-        XmlTraceLog::get().addAttribute(AttrNum, cid);
-        XmlTraceLog::get().addAttribute(AttrGlyphId, gid);
-    }
-#endif
-
-    uint16 loc = m_classOffsets[cid];
+    const uint16 * cls = m_classData + m_classOffsets[cid];
     if (cid < m_nLinear)        // output class being used for input, shouldn't happen
     {
-        for (int i = loc; i < m_classOffsets[cid + 1]; i++)
-            if (m_classData[i] == gid) return i - loc;
+        for (int i = 0, n = m_classOffsets[cid + 1]; i < n; ++i, ++cls)
+            if (*cls == gid) return i;
+        return -1;
     }
     else
     {
-//        uint16 num = m_classData[loc];
-        uint16 search = m_classData[loc + 1] << 1;
-//        uint16 selector = m_classData[loc + 2];
-        uint16 range = m_classData[loc + 3];
-
-        uint16 curr = loc + 4 + range * 2;
-
-        while (search > 1)
+    	const uint16 *	min = cls + 4,		// lookups array
+    				 * 	max = min + cls[0]*2; // lookups aray is numIDs (cls[0]) uint16 pairs long
+    	do
         {
-            int test;
-            if (curr < loc + 4)
-                test = -1;
-            else
-                test = m_classData[curr] - gid;
-
-            if (test == 0)
-            {
-                uint16 res = m_classData[curr + 1];
-#ifdef ENABLE_DEEP_TRACING
-                XmlTraceLog::get().addAttribute(AttrIndex, res);
-                XmlTraceLog::get().closeElement(ElementLookupClass);
-#endif
-                return res;
-            }
-            
-            search >>= 1;
-            if (test < 0)
-                curr += search;
-            else
-                curr -= search;
+        	const uint16 * p = min + (-2U & ((max-min)/2));
+        	if 	(p[0] > gid)	max = p;
+        	else 				min = p;
         }
+        while (max - min > 2);
+        return min[0] == gid ? min[1] : -1;
     }
-#ifdef ENABLE_DEEP_TRACING
-    XmlTraceLog::get().addAttribute(AttrIndex, -1);
-    XmlTraceLog::get().closeElement(ElementLookupClass);
-#endif
-    return -1;
 }
 
 uint16 Silf::getClassGlyph(uint16 cid, int index) const
diff --git a/src/Silf.h b/src/Silf.h
index 27bdca0..f59647d 100644
--- a/src/Silf.h
+++ b/src/Silf.h
@@ -84,7 +84,7 @@ public:
     CLASS_NEW_DELETE
 
 private:
-    size_t readClassMap(void *pClass, size_t lClass, int numGlyphs);
+    size_t readClassMap(const byte *p, size_t data_len);
 
     Pass          * m_passes;
     Pseudo        * m_pseudos;
diff --git a/src/Sparse.h b/src/Sparse.h
index 841d0af..fcf3fd2 100644
--- a/src/Sparse.h
+++ b/src/Sparse.h
@@ -60,6 +60,8 @@ public:
 	size_t size()     const throw();
 
 	size_t _sizeof() const throw();
+	
+	CLASS_NEW_DELETE;
 private:
 	union {
 		chunk * map;
@@ -90,7 +92,7 @@ sparse::sparse(I attr, const I last)
 
 	m_array.values = grzeroalloc<value>((m_nchunks*sizeof(chunk) + sizeof(value)/2)/sizeof(value) + n_values*sizeof(value));
 
-	if (!*this)
+	if (m_array.values == 0 || m_nchunks == 0)
 	{
 		free(m_array.values); m_array.map=0;
 		return;
@@ -119,7 +121,7 @@ sparse::sparse(I attr, const I last)
 inline
 sparse::operator bool () const throw()
 {
-	return m_array.map;
+	return m_array.map != 0;
 }
 
 
diff --git a/src/TtfUtil.cpp b/src/TtfUtil.cpp
index 8d8c35a..6b72452 100644
--- a/src/TtfUtil.cpp
+++ b/src/TtfUtil.cpp
@@ -51,6 +51,7 @@ Description
 // Module headers
 #include "TtfUtil.h"
 #include "TtfTypes.h"
+#include "Endian.h"
 
 /***********************************************************************************************
 	Forward declarations
@@ -64,41 +65,6 @@ namespace
 	// max number of components allowed in composite glyphs
 	const int kMaxGlyphComponents = 8;
 
-	// These are basic byte order swapping functions
-	template<typename T> inline T rev16(const T d) {
-		T r =  (d & 0xff) << 8; r |= (d & 0xff00) >> 8;
-		return r;
-	}
-
-	template<typename T> inline T rev32(const T d) {
-		T r  = (d & 0xff) << 24; r |= (d & 0xff00) << 8;
-		  r |= (d & 0xff0000) >> 8; r |= (d & 0xff000000) >> 24;
-		return r;
-	}
-
-	// This is the generic read function which does the swapping
-	template<typename T> inline T read(const T d) {
-		return d;
-	}
-	
-#if !defined WORDS_BIGENDIAN || defined PC_OS
-    template<> inline graphite2::TtfUtil::uint16 read(const graphite2::TtfUtil::uint16 d) {
-		return rev16(d);
-	}
-	
-	template<> inline graphite2::TtfUtil::int16 read(const graphite2::TtfUtil::int16 d) {
-		return rev16(d);
-	}
-
-	template<> inline graphite2::TtfUtil::uint32 read(const graphite2::TtfUtil::uint32 d) {
-		return rev32(d);
-	}
-	
-	template<> inline graphite2::TtfUtil::int32 read(const graphite2::TtfUtil::int32 d) {
-		return rev32(d);
-	}
-#endif
-
 	template <int R, typename T>
 	inline float fixed_to_float(const T f) {
 		return float(f)/float(2^R);
@@ -202,7 +168,7 @@ bool CheckHeader(const void * pHdr)
 	const Sfnt::OffsetSubTable * pOffsetTable  
 		= reinterpret_cast<const Sfnt::OffsetSubTable *>(pHdr);
 
-	return read(pOffsetTable->scaler_type) == Sfnt::OffsetSubTable::TrueTypeWin;
+	return be::swap(pOffsetTable->scaler_type) == Sfnt::OffsetSubTable::TrueTypeWin;
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -215,7 +181,7 @@ bool GetTableDirInfo(const void * pHdr, size_t & lOffset, size_t & lSize)
 		= reinterpret_cast<const Sfnt::OffsetSubTable *>(pHdr);
 
 	lOffset = offsetof(Sfnt::OffsetSubTable, table_directory);
-	lSize   = read(pOffsetTable->num_tables) 
+	lSize   = be::swap(pOffsetTable->num_tables)
 		* sizeof(Sfnt::OffsetSubTable::Entry);
 	
 	return true;
@@ -234,17 +200,17 @@ bool GetTableInfo(const Tag TableTag, const void * pHdr, const void * pTableDir,
 	const Sfnt::OffsetSubTable::Entry 
 		* entry_itr = reinterpret_cast<const Sfnt::OffsetSubTable::Entry *>(
 			pTableDir),
-		* const  dir_end = entry_itr + read(pOffsetTable->num_tables);
+		* const  dir_end = entry_itr + be::swap(pOffsetTable->num_tables);
 
-	if (read(pOffsetTable->num_tables) > 40)
+	if (be::swap(pOffsetTable->num_tables) > 40)
 		return false;
 
 	for (;entry_itr != dir_end; ++entry_itr) // 40 - safe guard
 	{
-		if (read(entry_itr->tag) == TableTag)
+		if (be::swap(entry_itr->tag) == TableTag)
 		{
-			lOffset = read(entry_itr->offset);
-			lSize   = read(entry_itr->length);
+			lOffset = be::swap(entry_itr->offset);
+			lSize   = be::swap(entry_itr->length);
 			return true;
 		}
 	}
@@ -268,20 +234,20 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 	{
 		const Sfnt::CharacterCodeMap * const pCmap 
 			= reinterpret_cast<const Sfnt::CharacterCodeMap *>(pTable);
-		return read(pCmap->version) == 0;
+		return be::swap(pCmap->version) == 0;
 	}
 
 	case Tag::head: // head
 	{
 		const Sfnt::FontHeader * const pHead 
 			= reinterpret_cast<const Sfnt::FontHeader *>(pTable);
-		bool r = read(pHead->version) == OneFix 
-			&& read(pHead->magic_number) == FontHeader::MagicNumber 
-			&& read(pHead->glyph_data_format) 
+		bool r = be::swap(pHead->version) == OneFix
+			&& be::swap(pHead->magic_number) == FontHeader::MagicNumber
+			&& be::swap(pHead->glyph_data_format)
 					== FontHeader::GlypDataFormat 
-			&& (read(pHead->index_to_loc_format) 
+			&& (be::swap(pHead->index_to_loc_format)
 					== FontHeader::ShortIndexLocFormat 
-				|| read(pHead->index_to_loc_format) 
+				|| be::swap(pHead->index_to_loc_format)
 					== FontHeader::LongIndexLocFormat) 
 			&& sizeof(FontHeader) <= lTableSize;
 		return r;
@@ -291,7 +257,7 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 	{
 		const Sfnt::PostScriptGlyphName * const pPost 
 			= reinterpret_cast<const Sfnt::PostScriptGlyphName *>(pTable);
-		const fixed format = read(pPost->format);
+		const fixed format = be::swap(pPost->format);
 		bool r = format == PostScriptGlyphName::Format1 
 			|| format == PostScriptGlyphName::Format2 
 			|| format == PostScriptGlyphName::Format3 
@@ -303,8 +269,8 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 	{
 		const Sfnt::HorizontalHeader * pHhea = 
 			reinterpret_cast<const Sfnt::HorizontalHeader *>(pTable);
-		bool r = read(pHhea->version) == OneFix 
-			&& read(pHhea->metric_data_format) == 0
+		bool r = be::swap(pHhea->version) == OneFix
+			&& be::swap(pHhea->metric_data_format) == 0
 			&& sizeof (Sfnt::HorizontalHeader) <= lTableSize;
 		return r;
 	}
@@ -313,7 +279,7 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 	{
 		const Sfnt::MaximumProfile * pMaxp = 
 			reinterpret_cast<const Sfnt::MaximumProfile *>(pTable);
-		bool r = read(pMaxp->version) == OneFix 
+		bool r = be::swap(pMaxp->version) == OneFix
 			&& sizeof(Sfnt::MaximumProfile) <= lTableSize;
 		return r;
 	}
@@ -322,7 +288,7 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 	{
 		const Sfnt::Compatibility * pOs2 
 			= reinterpret_cast<const Sfnt::Compatibility *>(pTable);
-		if (read(pOs2->version) == 0)
+		if (be::swap(pOs2->version) == 0)
 		{ // OS/2 table version 1 size
 //			if (sizeof(Sfnt::Compatibility) 
 //					- sizeof(uint32)*2 - sizeof(int16)*2 
@@ -330,7 +296,7 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 			if (sizeof(Sfnt::Compatibility0) <= lTableSize)
 				return true;
 		}
-		else if (read(pOs2->version) == 1)
+		else if (be::swap(pOs2->version) == 1)
 		{ // OS/2 table version 2 size
 //			if (sizeof(Sfnt::Compatibility) 
 //					- sizeof(int16) *2 
@@ -338,12 +304,12 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 			if (sizeof(Sfnt::Compatibility1) <= lTableSize)
 				return true;
 		}
-		else if (read(pOs2->version) == 2)
+		else if (be::swap(pOs2->version) == 2)
 		{ // OS/2 table version 3 size
 			if (sizeof(Sfnt::Compatibility2) <= lTableSize)
 				return true;
 		}
-		else if (read(pOs2->version) == 3 || read(pOs2->version) == 4)
+		else if (be::swap(pOs2->version) == 3 || be::swap(pOs2->version) == 4)
 		{ // OS/2 table version 4 size - version 4 changed the meaning of some fields which we don't use
 			if (sizeof(Sfnt::Compatibility3) <= lTableSize)
 				return true;
@@ -357,7 +323,7 @@ bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 	{
 		const Sfnt::FontNames * pName 
 			= reinterpret_cast<const Sfnt::FontNames *>(pTable);
-		return read(pName->format) == 0;
+		return be::swap(pName->format) == 0;
 	}
 
 	default:
@@ -376,7 +342,7 @@ size_t GlyphCount(const void * pMaxp)
 {
 	const Sfnt::MaximumProfile * pTable = 
 			reinterpret_cast<const Sfnt::MaximumProfile *>(pMaxp);
-	return read(pTable->num_glyphs);
+	return be::swap(pTable->num_glyphs);
 }
 
 #ifdef ALL_TTFUTILS
@@ -389,7 +355,7 @@ size_t  MaxCompositeComponentCount(const void * pMaxp)
 {
 	const Sfnt::MaximumProfile * pTable = 
 			reinterpret_cast<const Sfnt::MaximumProfile *>(pMaxp);
-	return read(pTable->max_component_elements);
+	return be::swap(pTable->max_component_elements);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -403,7 +369,7 @@ size_t  MaxCompositeLevelCount(const void * pMaxp)
 {
 	const Sfnt::MaximumProfile * pTable = 
 			reinterpret_cast<const Sfnt::MaximumProfile *>(pMaxp);
-	return read(pTable->max_component_depth);
+	return be::swap(pTable->max_component_depth);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -418,12 +384,12 @@ size_t LocaGlyphCount(size_t lLocaSize, const void * pHead) //throw(std::domain_
 	const Sfnt::FontHeader * pTable 
 		= reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 
-	if (read(pTable->index_to_loc_format) 
+	if (be::swap(pTable->index_to_loc_format)
 		== Sfnt::FontHeader::ShortIndexLocFormat)
 	// loca entries are two bytes and have been divided by two
 		return (lLocaSize >> 1) - 1;
 	
-	if (read(pTable->index_to_loc_format) 
+	if (be::swap(pTable->index_to_loc_format)
 		== Sfnt::FontHeader::LongIndexLocFormat)
 	 // loca entries are four bytes
 		return (lLocaSize >> 2) - 1;
@@ -441,7 +407,7 @@ int DesignUnits(const void * pHead)
 	const Sfnt::FontHeader * pTable = 
 			reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 	
-	return read(pTable->units_per_em);
+	return be::swap(pTable->units_per_em);
 }
 
 #ifdef ALL_TTFUTILS
@@ -453,7 +419,7 @@ int HeadTableCheckSum(const void * pHead)
 	const Sfnt::FontHeader * pTable = 
 			reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 	
-	return read(pTable->check_sum_adjustment);
+	return be::swap(pTable->check_sum_adjustment);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -468,8 +434,8 @@ void HeadTableCreateTime(const void * pHead,
 	const Sfnt::FontHeader * pTable = 
 			reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 	
-	*pnDateBC = read(pTable->created[0]);
-	*pnDateAD = read(pTable->created[1]);
+	*pnDateBC = be::swap(pTable->created[0]);
+	*pnDateAD = be::swap(pTable->created[1]);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -484,8 +450,8 @@ void HeadTableModifyTime(const void * pHead,
 	const Sfnt::FontHeader * pTable = 
 			reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 	
-	*pnDateBC = read(pTable->modified[0]);
-	*pnDateAD = read(pTable->modified[1]);
+	*pnDateBC = be::swap(pTable->modified[0]);
+	*pnDateAD = be::swap(pTable->modified[1]);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -496,7 +462,7 @@ bool IsItalic(const void * pHead)
 	const Sfnt::FontHeader * pTable = 
 			reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 
-	return ((read(pTable->mac_style) & 0x00000002) != 0);
+	return ((be::swap(pTable->mac_style) & 0x00000002) != 0);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -506,7 +472,7 @@ int FontAscent(const void * pOs2)
 {
 	const Sfnt::Compatibility * pTable = reinterpret_cast<const Sfnt::Compatibility *>(pOs2);
 
-	return read(pTable->win_ascent);
+	return be::swap(pTable->win_ascent);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -516,7 +482,7 @@ int FontDescent(const void * pOs2)
 {
 	const Sfnt::Compatibility * pTable = reinterpret_cast<const Sfnt::Compatibility *>(pOs2);
 
-	return read(pTable->win_descent);
+	return be::swap(pTable->win_descent);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -530,8 +496,8 @@ bool FontOs2Style(const void *pOs2, bool & fBold, bool & fItalic)
 {
 	const Sfnt::Compatibility * pTable = reinterpret_cast<const Sfnt::Compatibility *>(pOs2);
 
-	fBold = (read(pTable->fs_selection) & Sfnt::Compatibility::Bold) != 0;
-	fItalic = (read(pTable->fs_selection) & Sfnt::Compatibility::Italic) != 0;
+	fBold = (be::swap(pTable->fs_selection) & Sfnt::Compatibility::Bold) != 0;
+	fItalic = (be::swap(pTable->fs_selection) & Sfnt::Compatibility::Italic) != 0;
 	
 	return true;
 }
@@ -547,19 +513,19 @@ bool GetNameInfo(const void * pName, int nPlatformId, int nEncodingId,
 	lSize = 0;
 
 	const Sfnt::FontNames * pTable = reinterpret_cast<const Sfnt::FontNames *>(pName);
-	uint16 cRecord = read(pTable->count);
-	uint16 nRecordOffset = read(pTable->string_offset);
+	uint16 cRecord = be::swap(pTable->count);
+	uint16 nRecordOffset = be::swap(pTable->string_offset);
 	const Sfnt::NameRecord * pRecord = reinterpret_cast<const Sfnt::NameRecord *>(pTable + 1);
 
 	for (int i = 0; i < cRecord; ++i)
 	{
-		if (read(pRecord->platform_id) == nPlatformId && 
-			read(pRecord->platform_specific_id) == nEncodingId &&
-			read(pRecord->language_id) == nLangId && 
-			read(pRecord->name_id) == nNameId)
+		if (be::swap(pRecord->platform_id) == nPlatformId &&
+			be::swap(pRecord->platform_specific_id) == nEncodingId &&
+			be::swap(pRecord->language_id) == nLangId &&
+			be::swap(pRecord->name_id) == nNameId)
 		{
-			lOffset = read(pRecord->offset) + nRecordOffset;
-			lSize = read(pRecord->length);
+			lOffset = be::swap(pRecord->offset) + nRecordOffset;
+			lSize = be::swap(pRecord->length);
 			return true;
 		}
 		pRecord++;
@@ -579,19 +545,19 @@ int GetLangsForNames(const void * pName, int nPlatformId, int nEncodingId,
 {
 	const Sfnt::FontNames * pTable = reinterpret_cast<const Sfnt::FontNames *>(pName);
         int cLangIds = 0;
-	uint16 cRecord = read(pTable->count);
+	uint16 cRecord = be::swap(pTable->count);
         if (cRecord > 127) return cLangIds;
 	//uint16 nRecordOffset = swapw(pTable->stringOffset);
 	const Sfnt::NameRecord * pRecord = reinterpret_cast<const Sfnt::NameRecord *>(pTable + 1);
 
 	for (int i = 0; i < cRecord; ++i)
 	{
-		if (read(pRecord->platform_id) == nPlatformId && 
-			read(pRecord->platform_specific_id) == nEncodingId)
+		if (be::swap(pRecord->platform_id) == nPlatformId &&
+			be::swap(pRecord->platform_specific_id) == nEncodingId)
 		{
 			bool fNameFound = false;
-			int nLangId = read(pRecord->language_id);
-			int nNameId = read(pRecord->name_id);
+			int nLangId = be::swap(pRecord->language_id);
+			int nNameId = be::swap(pRecord->name_id);
 			for (int j = 0; j < cNameIds; j++)
 			{
 				if (nNameId == nameIdList[j])
@@ -688,7 +654,7 @@ int PostLookup(const void * pPost, size_t lPostSize, const void * pMaxp,
 	
 	const Sfnt::PostScriptGlyphName * pTable 
 		= reinterpret_cast<const Sfnt::PostScriptGlyphName *>(pPost);
-	fixed format = read(pTable->format);
+	fixed format = be::swap(pTable->format);
 
 	if (format == PostScriptGlyphName::Format3)
 	{ // format 3 - no Postscript glyph info in font
@@ -733,13 +699,13 @@ int PostLookup(const void * pPost, size_t lPostSize, const void * pMaxp,
 		const PostScriptGlyphName2 * pTable2 
 			= static_cast<const PostScriptGlyphName2 *>(pTable);
 		
-		int cnGlyphs = read(pTable2->number_of_glyphs);
+		int cnGlyphs = be::swap(pTable2->number_of_glyphs);
 
 		if (iPostName != -1)
 		{ // did match a standard name, look for first glyph id mapped to that name
 			for (gid16 nGlyphId = 0; nGlyphId < cnGlyphs; nGlyphId++)
 			{
-				if (read(pTable2->glyph_name_index[nGlyphId]) == iPostName)
+				if (be::swap(pTable2->glyph_name_index[nGlyphId]) == iPostName)
 					return nGlyphId;
 			}
 			return -1; // no glyph with this standard name
@@ -775,7 +741,7 @@ int PostLookup(const void * pPost, size_t lPostSize, const void * pMaxp,
 			iInNames += kcPostNames;
 			for (gid16 nGlyphId = 0; nGlyphId < cnGlyphs; nGlyphId++)
 			{ // search for first glyph id that maps to the found string index
-				if (read(pTable2->glyph_name_index[nGlyphId]) == iInNames)
+				if (be::swap(pTable2->glyph_name_index[nGlyphId]) == iInNames)
 					return nGlyphId;
 			}
 			return -1; // no glyph mapped to this index (very strange)
@@ -805,12 +771,12 @@ void SwapWString(void * pWStr, size_t nSize /* = 0 */) //throw (std::invalid_arg
 	uint16 * const pStrEnd = pStr + (nSize == 0 ? wcslen((const wchar_t*)pStr) : nSize);
 
         for (; pStr != pStrEnd; ++pStr)
-          *pStr = read(*pStr);
+          *pStr = be::swap(*pStr);
 //	std::transform(pStr, pStrEnd, pStr, read<uint16>);
 
 //		for (int i = 0; i < nSize; i++)
 //		{ // swap the wide characters in the string
-//			pStr[i] = utf16(read(uint16(pStr[i])));
+//			pStr[i] = utf16(be::swap(uint16(pStr[i])));
 //		}
 }
 #endif
@@ -828,12 +794,12 @@ bool HorMetrics(gid16 nGlyphId, const void * pHmtx, size_t lHmtxSize, const void
 	const Sfnt::HorizontalHeader * phhea = 
 		reinterpret_cast<const Sfnt::HorizontalHeader *>(pHhea);
 
-	size_t cLongHorMetrics = read(phhea->num_long_hor_metrics);
+	size_t cLongHorMetrics = be::swap(phhea->num_long_hor_metrics);
 	if (nGlyphId < cLongHorMetrics) 
 	{	// glyph id is acceptable
                 if (nGlyphId * sizeof(Sfnt::HorizontalMetric) > lHmtxSize) return false;
-		nAdvWid = read(phmtx[nGlyphId].advance_width);
-		nLsb = read(phmtx[nGlyphId].left_side_bearing);
+		nAdvWid = be::swap(phmtx[nGlyphId].advance_width);
+		nLsb = be::swap(phmtx[nGlyphId].left_side_bearing);
 	}
 	else
 	{
@@ -845,10 +811,10 @@ bool HorMetrics(gid16 nGlyphId, const void * pHmtx, size_t lHmtxSize, const void
 			nLsb = 0;
 			return false;
 		}
-                nAdvWid = read(phmtx[cLongHorMetrics - 1].advance_width);
+                nAdvWid = be::swap(phmtx[cLongHorMetrics - 1].advance_width);
 		const int16 * pLsb = reinterpret_cast<const int16 *>(phmtx) + 
 			lLsbOffset / sizeof(int16);
-		nLsb = read(*pLsb);
+		nLsb = be::swap(*pLsb);
 	}
 
 	return true;
@@ -862,40 +828,40 @@ bool HorMetrics(gid16 nGlyphId, const void * pHmtx, size_t lHmtxSize, const void
 const void * FindCmapSubtable(const void * pCmap, int nPlatformId, /* =3 */ int nEncodingId, /* = 1 */ size_t length)
 {
     const Sfnt::CharacterCodeMap * pTable = reinterpret_cast<const Sfnt::CharacterCodeMap *>(pCmap);
-    uint16 csuPlatforms = read(pTable->num_subtables);
+    uint16 csuPlatforms = be::swap(pTable->num_subtables);
     if (length && (sizeof(Sfnt::CharacterCodeMap) + 8 * (csuPlatforms - 1) > length))
         return NULL;
     for (int i = 0; i < csuPlatforms; i++)
     {
-        if (read(pTable->encoding[i].platform_id) == nPlatformId &&
-                (nEncodingId == -1 || read(pTable->encoding[i].platform_specific_id) == nEncodingId))
+        if (be::swap(pTable->encoding[i].platform_id) == nPlatformId &&
+                (nEncodingId == -1 || be::swap(pTable->encoding[i].platform_specific_id) == nEncodingId))
         {
-            uint32 offset = read(pTable->encoding[i].offset);
+            uint32 offset = be::swap(pTable->encoding[i].offset);
             const uint8 * pRtn = reinterpret_cast<const uint8 *>(pCmap) + offset;
             if (length)
             {
                 if (offset > length) return NULL;
-                uint16 format = read(*reinterpret_cast<const uint16*>(pRtn));
+                uint16 format = be::swap(*reinterpret_cast<const uint16*>(pRtn));
                 if (format == 4)
                 {
-                    uint16 subTableLength = read(*reinterpret_cast<const uint16*>(pRtn + 2));
+                    uint16 subTableLength = be::swap(*reinterpret_cast<const uint16*>(pRtn + 2));
                     if (i + 1 == csuPlatforms)
                     {
                         if (subTableLength > length - offset)
                             return NULL;
                     }
-                    else if (subTableLength > read(pTable->encoding[i+1].offset))
+                    else if (subTableLength > be::swap(pTable->encoding[i+1].offset))
                         return NULL;
                 }
                 if (format == 12)
                 {
-                    uint32 subTableLength = read(*reinterpret_cast<const uint32*>(pRtn + 2));
+                    uint32 subTableLength = be::swap(*reinterpret_cast<const uint32*>(pRtn + 2));
                     if (i + 1 == csuPlatforms)
                     {
                         if (subTableLength > length - offset)
                             return NULL;
                     }
-                    else if (subTableLength > read(pTable->encoding[i+1].offset))
+                    else if (subTableLength > be::swap(pTable->encoding[i+1].offset))
                         return NULL;
                 }
             }
@@ -914,16 +880,16 @@ bool CheckCmap31Subtable(const void * pCmap31)
 	const Sfnt::CmapSubTable * pTable = reinterpret_cast<const Sfnt::CmapSubTable *>(pCmap31);
 	// Bob H says ome freeware TT fonts have version 1 (eg, CALIGULA.TTF) 
 	// so don't check subtable version. 21 Mar 2002 spec changes version to language.
-    if (read(pTable->format) != 4) return false;
+    if (be::swap(pTable->format) != 4) return false;
     const Sfnt::CmapSubTableFormat4 * pTable4 = reinterpret_cast<const Sfnt::CmapSubTableFormat4 *>(pCmap31);
-    uint16 length = read(pTable4->length);
+    uint16 length = be::swap(pTable4->length);
     if (length < sizeof(Sfnt::CmapSubTableFormat4))
         return false;
-    uint16 nRanges = read(pTable4->seg_count_x2) >> 1;
+    uint16 nRanges = be::swap(pTable4->seg_count_x2) >> 1;
     if (length < sizeof(Sfnt::CmapSubTableFormat4) + 4 * nRanges * sizeof(uint16))
         return false;
     // check last range is properly terminated
-    uint16 chEnd = read(pTable4->end_code[nRanges-1]);
+    uint16 chEnd = be::swap(pTable4->end_code[nRanges-1]);
     return (chEnd == 0xFFFF);
 }
 
@@ -936,7 +902,7 @@ gid16 Cmap31Lookup(const void * pCmap31, int nUnicodeId, int rangeKey)
 {
 	const Sfnt::CmapSubTableFormat4 * pTable = reinterpret_cast<const Sfnt::CmapSubTableFormat4 *>(pCmap31);
 
-	uint16 nSeg = read(pTable->seg_count_x2) >> 1;
+	uint16 nSeg = be::swap(pTable->seg_count_x2) >> 1;
   
 	uint16 n;
     	const uint16 * pLeft, * pMid;
@@ -945,7 +911,7 @@ gid16 Cmap31Lookup(const void * pCmap31, int nUnicodeId, int rangeKey)
     if (rangeKey)
     {
         pMid = &(pTable->end_code[rangeKey]);
-        chEnd = read(*pMid);
+        chEnd = be::swap(*pMid);
         n = rangeKey;
     }
     else
@@ -957,10 +923,10 @@ gid16 Cmap31Lookup(const void * pCmap31, int nUnicodeId, int rangeKey)
         {
             cMid = n >> 1;           // Pick an element in the middle
             pMid = pLeft + cMid;
-            chEnd = read(*pMid);
+            chEnd = be::swap(*pMid);
             if (nUnicodeId <= chEnd)
             {
-                if (cMid == 0 || nUnicodeId > read(pMid[-1]))
+                if (cMid == 0 || nUnicodeId > be::swap(pMid[-1]))
                         break;          // Must be this seg or none!
                 n = cMid;            // Continue on left side, omitting mid point
             }
@@ -978,12 +944,12 @@ gid16 Cmap31Lookup(const void * pCmap31, int nUnicodeId, int rangeKey)
     // Ok, we're down to one segment and pMid points to the endCode element
     // Either this is it or none is.
 
-    chStart = read(*(pMid += nSeg + 1));
+    chStart = be::swap(*(pMid += nSeg + 1));
     if (chEnd >= nUnicodeId && nUnicodeId >= chStart)
     {
         // Found correct segment. Find Glyph Id
-        int16 idDelta = read(*(pMid += nSeg));
-        uint16 idRangeOffset = read(*(pMid += nSeg));
+        int16 idDelta = be::swap(*(pMid += nSeg));
+        uint16 idRangeOffset = be::swap(*(pMid += nSeg));
 
         if (idRangeOffset == 0)
             return (uint16)(idDelta + nUnicodeId); // must use modulus 2^16
@@ -993,7 +959,7 @@ gid16 Cmap31Lookup(const void * pCmap31, int nUnicodeId, int rangeKey)
                 (reinterpret_cast<const uint16 *>(pMid) - reinterpret_cast<const uint16 *>(pTable));
         if (offset * 2 >= pTable->length)
             return 0;
-        gid16 nGlyphId = read(*(pMid + (nUnicodeId - chStart) + (idRangeOffset >> 1)));
+        gid16 nGlyphId = be::swap(*(pMid + (nUnicodeId - chStart) + (idRangeOffset >> 1)));
         // If this value is 0, return 0. Else add the idDelta
         return nGlyphId ? nGlyphId + idDelta : 0;
     }
@@ -1011,7 +977,7 @@ unsigned int Cmap31NextCodepoint(const void *pCmap31, unsigned int nUnicodeId, i
 {
 	const Sfnt::CmapSubTableFormat4 * pTable = reinterpret_cast<const Sfnt::CmapSubTableFormat4 *>(pCmap31);
 
-	uint16 nRange = read(pTable->seg_count_x2) >> 1;
+	uint16 nRange = be::swap(pTable->seg_count_x2) >> 1;
 
 	uint32 nUnicodePrev = (uint32)nUnicodeId;
 
@@ -1024,7 +990,7 @@ unsigned int Cmap31NextCodepoint(const void *pCmap31, unsigned int nUnicodeId, i
 		// return the first codepoint.
 		if (pRangeKey)
 			*pRangeKey = 0;
-		return read(pStartCode[0]);
+		return be::swap(pStartCode[0]);
 	}
 	else if (nUnicodePrev >= 0xFFFF)
 	{
@@ -1035,14 +1001,14 @@ unsigned int Cmap31NextCodepoint(const void *pCmap31, unsigned int nUnicodeId, i
 
 	int iRange = (pRangeKey) ? *pRangeKey : 0;
 	// Just in case we have a bad key:
-	while (iRange > 0 && read(pStartCode[iRange]) > nUnicodePrev)
+	while (iRange > 0 && be::swap(pStartCode[iRange]) > nUnicodePrev)
 		iRange--;
-	while (read(pTable->end_code[iRange]) < nUnicodePrev)
+	while (be::swap(pTable->end_code[iRange]) < nUnicodePrev)
 		iRange++;
 
 	// Now iRange is the range containing nUnicodePrev.
-	unsigned int nStartCode = read(pStartCode[iRange]);
-	unsigned int nEndCode = read(pTable->end_code[iRange]);
+	unsigned int nStartCode = be::swap(pStartCode[iRange]);
+	unsigned int nEndCode = be::swap(pTable->end_code[iRange]);
 
 	if (nStartCode > nUnicodePrev)
 		// Oops, nUnicodePrev is not in the cmap! Adjust so we get a reasonable
@@ -1062,7 +1028,7 @@ unsigned int Cmap31NextCodepoint(const void *pCmap31, unsigned int nUnicodeId, i
 	// ends with 0xFFFF.
 	if (pRangeKey)
 		*pRangeKey = iRange + 1;
-	return read(pStartCode[iRange + 1]);
+	return be::swap(pStartCode[iRange + 1]);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -1071,14 +1037,14 @@ unsigned int Cmap31NextCodepoint(const void *pCmap31, unsigned int nUnicodeId, i
 bool CheckCmap310Subtable(const void *pCmap310)
 {
 	const Sfnt::CmapSubTable * pTable = reinterpret_cast<const Sfnt::CmapSubTable *>(pCmap310);
-    if (read(pTable->format) != 12)
+    if (be::swap(pTable->format) != 12)
         return false;
     const Sfnt::CmapSubTableFormat12 * pTable12 = reinterpret_cast<const Sfnt::CmapSubTableFormat12 *>(pCmap310);
-    uint32 length = read(pTable12->length);
+    uint32 length = be::swap(pTable12->length);
     if (length < sizeof(Sfnt::CmapSubTableFormat12))
         return false;
     
-	return (length == (sizeof(Sfnt::CmapSubTableFormat12) + (read(pTable12->num_groups) - 1)
+	return (length == (sizeof(Sfnt::CmapSubTableFormat12) + (be::swap(pTable12->num_groups) - 1)
         * sizeof(uint32) * 3));
 }
 
@@ -1091,17 +1057,17 @@ gid16 Cmap310Lookup(const void * pCmap310, unsigned int uUnicodeId, int rangeKey
 {
 	const Sfnt::CmapSubTableFormat12 * pTable = reinterpret_cast<const Sfnt::CmapSubTableFormat12 *>(pCmap310);
 
-	//uint32 uLength = read(pTable->length); //could use to test for premature end of table
-	uint32 ucGroups = read(pTable->num_groups);
+	//uint32 uLength = be::swap(pTable->length); //could use to test for premature end of table
+	uint32 ucGroups = be::swap(pTable->num_groups);
 
 	for (unsigned int i = rangeKey; i < ucGroups; i++)
 	{
-		uint32 uStartCode = read(pTable->group[i].start_char_code);
-		uint32 uEndCode = read(pTable->group[i].end_char_code);
+		uint32 uStartCode = be::swap(pTable->group[i].start_char_code);
+		uint32 uEndCode = be::swap(pTable->group[i].end_char_code);
 		if (uUnicodeId >= uStartCode && uUnicodeId <= uEndCode)
 		{
 			uint32 uDiff = uUnicodeId - uStartCode;
-			uint32 uStartGid = read(pTable->group[i].start_glyph_id);
+			uint32 uStartGid = be::swap(pTable->group[i].start_glyph_id);
 			return static_cast<gid16>(uStartGid + uDiff);
 		}
 	}
@@ -1119,7 +1085,7 @@ unsigned int Cmap310NextCodepoint(const void *pCmap310, unsigned int nUnicodeId,
 {
 	const Sfnt::CmapSubTableFormat12 * pTable = reinterpret_cast<const Sfnt::CmapSubTableFormat12 *>(pCmap310);
 
-	int nRange = read(pTable->num_groups);
+	int nRange = be::swap(pTable->num_groups);
 
 	uint32 nUnicodePrev = (uint32)nUnicodeId;
 
@@ -1128,7 +1094,7 @@ unsigned int Cmap310NextCodepoint(const void *pCmap310, unsigned int nUnicodeId,
 		// return the first codepoint.
 		if (pRangeKey)
 			*pRangeKey = 0;
-		return read(pTable->group[0].start_char_code);
+		return be::swap(pTable->group[0].start_char_code);
 	}
 	else if (nUnicodePrev >= 0x10FFFF)
 	{
@@ -1139,15 +1105,15 @@ unsigned int Cmap310NextCodepoint(const void *pCmap310, unsigned int nUnicodeId,
 
 	int iRange = (pRangeKey) ? *pRangeKey : 0;
 	// Just in case we have a bad key:
-	while (iRange > 0 && read(pTable->group[iRange].start_char_code) > nUnicodePrev)
+	while (iRange > 0 && be::swap(pTable->group[iRange].start_char_code) > nUnicodePrev)
 		iRange--;
-	while (read(pTable->group[iRange].end_char_code) < nUnicodePrev)
+	while (be::swap(pTable->group[iRange].end_char_code) < nUnicodePrev)
 		iRange++;
 
 	// Now iRange is the range containing nUnicodePrev.
 
-	unsigned int nStartCode = read(pTable->group[iRange].start_char_code);
-	unsigned int nEndCode = read(pTable->group[iRange].end_char_code);
+	unsigned int nStartCode = be::swap(pTable->group[iRange].start_char_code);
+	unsigned int nEndCode = be::swap(pTable->group[iRange].end_char_code);
 
 	if (nStartCode > nUnicodePrev)
 		// Oops, nUnicodePrev is not in the cmap! Adjust so we get a reasonable
@@ -1165,7 +1131,7 @@ unsigned int Cmap310NextCodepoint(const void *pCmap310, unsigned int nUnicodeId,
 	// Otherwise the next codepoint is the first one in the next range, or 10FFFF if we're done.
 	if (pRangeKey)
 		*pRangeKey = iRange + 1;
-	return (iRange + 1 >= nRange) ? 0x10FFFF : read(pTable->group[iRange + 1].start_char_code);
+	return (iRange + 1 >= nRange) ? 0x10FFFF : be::swap(pTable->group[iRange + 1].start_char_code);
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -1182,21 +1148,21 @@ size_t LocaLookup(gid16 nGlyphId,
 	const Sfnt::FontHeader * pTable = reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 
 	// CheckTable verifies the index_to_loc_format is valid
-	if (read(pTable->index_to_loc_format) == Sfnt::FontHeader::ShortIndexLocFormat)
+	if (be::swap(pTable->index_to_loc_format) == Sfnt::FontHeader::ShortIndexLocFormat)
 	{ // loca entries are two bytes and have been divided by two
 		if (nGlyphId <= (lLocaSize >> 1) - 1) // allow sentinel value to be accessed
 		{
 			const uint16 * pShortTable = reinterpret_cast<const uint16 *>(pLoca);
-			return (read(pShortTable[nGlyphId]) << 1);
+			return (be::swap(pShortTable[nGlyphId]) << 1);
 		}
 	}
 	
-	if (read(pTable->index_to_loc_format) == Sfnt::FontHeader::LongIndexLocFormat)
+	if (be::swap(pTable->index_to_loc_format) == Sfnt::FontHeader::LongIndexLocFormat)
 	{ // loca entries are four bytes
 		if (nGlyphId <= (lLocaSize >> 2) - 1)
 		{
 			const uint32 * pLongTable = reinterpret_cast<const uint32 *>(pLoca);
-			return read(pLongTable[nGlyphId]);
+			return be::swap(pLongTable[nGlyphId]);
 		}
 	}
 
@@ -1226,10 +1192,10 @@ bool GlyfBox(const void * pSimpleGlyf, int & xMin, int & yMin,
 {
 	const Sfnt::Glyph * pGlyph = reinterpret_cast<const Sfnt::Glyph *>(pSimpleGlyf);
 
-	xMin = read(pGlyph->x_min);
-	yMin = read(pGlyph->y_min);
-	xMax = read(pGlyph->x_max);
-	yMax = read(pGlyph->y_max);
+	xMin = be::swap(pGlyph->x_min);
+	yMin = be::swap(pGlyph->y_min);
+	xMax = be::swap(pGlyph->x_max);
+	yMax = be::swap(pGlyph->y_max);
 
 	return true;
 }
@@ -1242,7 +1208,7 @@ bool GlyfBox(const void * pSimpleGlyf, int & xMin, int & yMin,
 int GlyfContourCount(const void * pSimpleGlyf)
 {
 	const Sfnt::Glyph * pGlyph = reinterpret_cast<const Sfnt::Glyph *>(pSimpleGlyf);
-	return read(pGlyph->number_of_contours); // -1 means composite glyph
+	return be::swap(pGlyph->number_of_contours); // -1 means composite glyph
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -1259,13 +1225,13 @@ bool GlyfContourEndPoints(const void * pSimpleGlyf, int * prgnContourEndPoint,
 {
 	const Sfnt::SimpleGlyph * pGlyph = reinterpret_cast<const Sfnt::SimpleGlyph *>(pSimpleGlyf);
 
-	int cContours = read(pGlyph->number_of_contours);
+	int cContours = be::swap(pGlyph->number_of_contours);
 	if (cContours < 0)
 		return false; // this method isn't supposed handle composite glyphs
 
 	for (int i = 0; i < cContours && i < cnPointsTotal; i++)
 	{
-		prgnContourEndPoint[i] = read(pGlyph->end_pts_of_contours[i]);
+		prgnContourEndPoint[i] = be::swap(pGlyph->end_pts_of_contours[i]);
 	}
 
 	cnPoints = cContours;
@@ -1290,11 +1256,11 @@ bool GlyfPoints(const void * pSimpleGlyf, int * prgnX, int * prgnY,
 	using namespace Sfnt;
 	
 	const Sfnt::SimpleGlyph * pGlyph = reinterpret_cast<const Sfnt::SimpleGlyph *>(pSimpleGlyf);
-	int cContours = read(pGlyph->number_of_contours);
+	int cContours = be::swap(pGlyph->number_of_contours);
 	// return false for composite glyph
 	if (cContours <= 0)
 		return false;
-	int cPts = read(pGlyph->end_pts_of_contours[cContours - 1]) + 1;
+	int cPts = be::swap(pGlyph->end_pts_of_contours[cContours - 1]) + 1;
 	if (cPts > cnPointsTotal)
 		return false;
 
@@ -1303,7 +1269,7 @@ bool GlyfPoints(const void * pSimpleGlyf, int * prgnX, int * prgnY,
 		(&pGlyph->end_pts_of_contours[cContours]);
 	
 	// skip over hints & point to first flag
-	int cbHints = read(*(uint16 *)pbGlyph);
+	int cbHints = be::swap(*(uint16 *)pbGlyph);
 	pbGlyph += sizeof(uint16);
 	pbGlyph += cbHints;
 
@@ -1357,7 +1323,7 @@ bool GlyfPoints(const void * pSimpleGlyf, int * prgnX, int * prgnY,
 			}
 			else
 			{
-				prgnX[iFlag] = read(*(int16 *)pbGlyph);
+				prgnX[iFlag] = be::swap(*(int16 *)pbGlyph);
 				pbGlyph += sizeof(int16);
 			}
 		}
@@ -1386,7 +1352,7 @@ bool GlyfPoints(const void * pSimpleGlyf, int * prgnX, int * prgnY,
 			}
 			else
 			{
-				prgnY[iFlag] = read(*(int16 *)pbGlyph);
+				prgnY[iFlag] = be::swap(*(int16 *)pbGlyph);
 				pbGlyph += sizeof(int16);
 			}
 		}
@@ -1422,9 +1388,9 @@ bool GetComponentGlyphIds(const void * pSimpleGlyf, int * prgnCompId,
 	size_t iCurrentComp = 0;
 	do 
 	{
-		GlyphFlags = read(*((uint16 *)pbGlyph));
+		GlyphFlags = be::swap(*((uint16 *)pbGlyph));
 		pbGlyph += sizeof(uint16);
-		prgnCompId[iCurrentComp++] = read(*((uint16 *)pbGlyph));
+		prgnCompId[iCurrentComp++] = be::swap(*((uint16 *)pbGlyph));
 		pbGlyph += sizeof(uint16);
 		if (iCurrentComp >= cnCompIdTotal) 
 			return false;
@@ -1466,18 +1432,18 @@ bool GetComponentPlacement(const void * pSimpleGlyf, int nCompId,
 	uint16 GlyphFlags;
 	do 
 	{
-		GlyphFlags = read(*((uint16 *)pbGlyph));
+		GlyphFlags = be::swap(*((uint16 *)pbGlyph));
 		pbGlyph += sizeof(uint16);
-		if (read(*((uint16 *)pbGlyph)) == nCompId)
+		if (be::swap(*((uint16 *)pbGlyph)) == nCompId)
 		{
 			pbGlyph += sizeof(uint16); // skip over glyph id of component
 			fOffset = (GlyphFlags & CompoundGlyph::ArgsAreXYValues) == CompoundGlyph::ArgsAreXYValues;
 
 			if (GlyphFlags & CompoundGlyph::Arg1Arg2Words )
 			{
-				a = read(*(int16 *)pbGlyph);
+				a = be::swap(*(int16 *)pbGlyph);
 				pbGlyph += sizeof(int16);
-				b = read(*(int16 *)pbGlyph);
+				b = be::swap(*(int16 *)pbGlyph);
 				pbGlyph += sizeof(int16);
 			}
 			else
@@ -1531,9 +1497,9 @@ bool GetComponentTransform(const void * pSimpleGlyf, int nCompId,
 	uint16 GlyphFlags;
 	do 
 	{
-		GlyphFlags = read(*((uint16 *)pbGlyph));
+		GlyphFlags = be::swap(*((uint16 *)pbGlyph));
 		pbGlyph += sizeof(uint16);
-		if (read(*((uint16 *)pbGlyph)) == nCompId)
+		if (be::swap(*((uint16 *)pbGlyph)) == nCompId)
 		{
 			pbGlyph += sizeof(uint16); // skip over glyph id of component
 			pbGlyph += GlyphFlags & CompoundGlyph::Arg1Arg2Words  ? 4 : 2; // skip over placement data
@@ -1545,7 +1511,7 @@ bool GetComponentTransform(const void * pSimpleGlyf, int nCompId,
 
 			if (GlyphFlags & CompoundGlyph::HaveScale)
 			{
-				flt11 = fixed_to_float<14>(read(*(uint16 *)pbGlyph));
+				flt11 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
 				pbGlyph += sizeof(uint16);
 				flt12 = 0;
 				flt21 = 0;
@@ -1553,22 +1519,22 @@ bool GetComponentTransform(const void * pSimpleGlyf, int nCompId,
 			}
 			else if (GlyphFlags & CompoundGlyph::HaveXAndYScale)
 			{
-				flt11 = fixed_to_float<14>(read(*(uint16 *)pbGlyph));
+				flt11 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
 				pbGlyph += sizeof(uint16);
 				flt12 = 0;
 				flt21 = 0;
-				flt22 = fixed_to_float<14>(read(*(uint16 *)pbGlyph));
+				flt22 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
 				pbGlyph += sizeof(uint16);
 			}
 			else if (GlyphFlags & CompoundGlyph::HaveTwoByTwo)
 			{
-				flt11 = fixed_to_float<14>(read(*(uint16 *)pbGlyph));
+				flt11 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
 				pbGlyph += sizeof(uint16);
-				flt12 = fixed_to_float<14>(read(*(uint16 *)pbGlyph));
+				flt12 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
 				pbGlyph += sizeof(uint16);
-				flt21 = fixed_to_float<14>(read(*(uint16 *)pbGlyph));
+				flt21 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
 				pbGlyph += sizeof(uint16);
-				flt22 = fixed_to_float<14>(read(*(uint16 *)pbGlyph));
+				flt22 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
 				pbGlyph += sizeof(uint16);
 			}
 			else
@@ -1613,7 +1579,7 @@ void * GlyfLookup(gid16 nGlyphId, const void * pGlyf, const void * pLoca,
 	const Sfnt::FontHeader * pTable 
 		= reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 
-	if (read(pTable->index_to_loc_format) == Sfnt::FontHeader::ShortIndexLocFormat)
+	if (be::swap(pTable->index_to_loc_format) == Sfnt::FontHeader::ShortIndexLocFormat)
 	{ // loca entries are two bytes (and have been divided by two)
 		if (nGlyphId >= (lLocaSize >> 1) - 1) // don't allow nGlyphId to access sentinel
 		{
@@ -1621,7 +1587,7 @@ void * GlyfLookup(gid16 nGlyphId, const void * pGlyf, const void * pLoca,
             return NULL;
 		}
 	}
-	if (read(pTable->index_to_loc_format) == Sfnt::FontHeader::LongIndexLocFormat)
+	if (be::swap(pTable->index_to_loc_format) == Sfnt::FontHeader::LongIndexLocFormat)
 	{ // loca entries are four bytes
 		if (nGlyphId >= (lLocaSize >> 2) - 1)
 		{
diff --git a/src/gr_face.cpp b/src/gr_face.cpp
index bf52cb0..bcb692c 100644
--- a/src/gr_face.cpp
+++ b/src/gr_face.cpp
@@ -123,6 +123,10 @@ void gr_tag_to_str(gr_uint32 tag, char *str)
 gr_feature_val* gr_face_featureval_for_lang(const gr_face* pFace, gr_uint32 langname/*0 means clone default*/) //clones the features. if none for language, clones the default
 {
     assert(pFace);
+    if (langname == 0x20202020) langname = 0;
+    else if ((langname & 0x00FFFFFF) == 0x00202020) langname = langname & 0xFF000000;
+    else if ((langname & 0x0000FFFF) == 0x00002020) langname = langname & 0xFFFF0000;
+    else if ((langname & 0x000000FF) == 0x00000020) langname = langname & 0xFFFFFF00;
     return static_cast<gr_feature_val *>(pFace->theSill().cloneFeatures(langname));
 }
 
diff --git a/src/gr_features.cpp b/src/gr_features.cpp
index 6c38280..692abc5 100644
--- a/src/gr_features.cpp
+++ b/src/gr_features.cpp
@@ -127,31 +127,13 @@ void* gr_fref_value_label(const gr_feature_ref*pfeatureref, gr_uint16 setting,
 
 void gr_label_destroy(void * label)
 {
-    if (label)
-        free(label);
+	free(label);
 }
 
 gr_feature_val* gr_featureval_clone(const gr_feature_val* pfeatures/*may be NULL*/)
 {                      //When finished with the Features, call features_destroy    
     return static_cast<gr_feature_val*>(pfeatures ? new Features(*pfeatures) : new Features);
 }
-
-
-#if 0
-//not public since there is no public way of making the mask
-int gr_featureval_masked_or(gr_feature_val* pSrc, const gr_feature_val* pOther, const gr_feature_val* pMask)    //returns false iff any of the Features* are NULL
-{
-    if (!pSrc)
-    return false;
-    if (!pOther)
-    return false;
-    if (!pMask)
-    return false;
-    
-    pSrc->maskedOr(*pOther, *pMask);
-    return true;
-}
-#endif 
   
 void gr_featureval_destroy(gr_feature_val *p)
 {
diff --git a/src/gr_segment.cpp b/src/gr_segment.cpp
index a7f24ad..f6cf52d 100644
--- a/src/gr_segment.cpp
+++ b/src/gr_segment.cpp
@@ -68,6 +68,10 @@ namespace
 
   gr_segment* makeAndInitialize(const Font *font, const Face *face, uint32 script, const Features* pFeats/*must not be NULL*/, gr_encform enc, const void* pStart, size_t nChars, int dir)
   {
+      if (script == 0x20202020) script = 0;
+      else if ((script & 0x00FFFFFF) == 0x00202020) script = script & 0xFF000000;
+      else if ((script & 0x0000FFFF) == 0x00002020) script = script & 0xFFFF0000;
+      else if ((script & 0x000000FF) == 0x00000020) script = script & 0xFFFFFF00;
       // if (!font) return NULL;
       Segment* pRes=new Segment(nChars, face, script, dir);
 
diff --git a/src/opcodes.h b/src/opcodes.h
index cdf1c01..121be9c 100644
--- a/src/opcodes.h
+++ b/src/opcodes.h
@@ -276,7 +276,7 @@ STARTOP(insert)
         {
             seg.last()->next(newSlot);
             newSlot->prev(seg.last());
-	    newSlot->before(seg.last()->before());
+            newSlot->before(seg.last()->before());
             seg.last(newSlot);
         }
         else
@@ -294,7 +294,7 @@ STARTOP(insert)
     else
     {
         newSlot->prev(NULL);
-	newSlot->before(iss->before());
+        newSlot->before(iss->before());
         seg.first(newSlot);
     }
     newSlot->next(iss);
@@ -333,9 +333,7 @@ STARTOP(delete_)
         seg.last(is->prev());
     
     if (is->prev())
-    {
         is = is->prev();
-    }
     seg.extendLength(-1);
 ENDOP
 
@@ -354,8 +352,11 @@ STARTOP(assoc)
         if (ts && (min == -1 || ts->before() < min)) min = ts->before();
         if (ts && ts->after() > max) max = ts->after();
     }
-    is->before(min);
-    is->after(max);
+    if (min > -1)   // implies max > -1
+    {
+        is->before(min);
+        is->after(max);
+    }
 ENDOP
 
 STARTOP(cntxt_item)
@@ -365,7 +366,8 @@ STARTOP(cntxt_item)
     const size_t    iskip  = uint8(param[1]),
                     dskip  = uint8(param[2]);
 
-    if (mapb + is_arg != map) {
+    if (mapb + is_arg != map)
+    {
         ip += iskip;
         dp += dskip;
         push(true);
diff --git a/src/processUTF.h b/src/processUTF.h
index de8d307..18c5e6a 100644
--- a/src/processUTF.h
+++ b/src/processUTF.h
@@ -199,9 +199,6 @@ private:
 
 class Utf16Consumer
 {
-private:
-    static const unsigned int SURROGATE_OFFSET = 0x10000 - 0xDC00;
-
 public:
       Utf16Consumer(const uint16* pCharStart2) : m_pCharStart(pCharStart2) {}
       
@@ -223,7 +220,7 @@ public:
       inline bool consumeChar(const LIMIT& limit, uint32* pRes, ERRORHANDLER* pErrHandler)			//At start, limit.inBuffer(m_pCharStart) is true. return value is iff character contents does not go past limit
       {
 	  *pRes = *m_pCharStart;
-      if (0xD800 > *pRes || pErrHandler->ignoreUnicodeOutOfRangeErrors(*pRes >= 0xE000)) {
+      if (0xD800 > *pRes || !pErrHandler->ignoreUnicodeOutOfRangeErrors(*pRes >= 0xE000)) {
           ++m_pCharStart;
           return true;
       }
@@ -242,7 +239,7 @@ public:
           return respondToError(pRes, pErrHandler);
 	  }
 	  ++m_pCharStart;
-	  *pRes =  (*pRes<<10) + ul + SURROGATE_OFFSET;
+	  *pRes =  ((*pRes - 0xD800)<<10) + ul - 0xDC00;
 	  return true;
       }
 
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 35ce9d6..541fb2e 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -12,10 +12,8 @@ add_subdirectory(segcache)
 add_subdirectory(featuremap)
 add_subdirectory(nametabletest)
 add_subdirectory(examples)
-
-if (EXISTS ${PROJECT_SOURCE_DIR}/grlist)
 add_subdirectory(grlist)
-endif(EXISTS ${PROJECT_SOURCE_DIR}/grlist)
+add_subdirectory(endian)
 
 enable_testing()
 
diff --git a/tests/comparerenderer/Gr2Renderer.h b/tests/comparerenderer/Gr2Renderer.h
index 8f1b5ce..c658b18 100644
--- a/tests/comparerenderer/Gr2Renderer.h
+++ b/tests/comparerenderer/Gr2Renderer.h
@@ -32,11 +32,12 @@ class Gr2Renderer : public Renderer
 public:
     Gr2Renderer(const char * fontFile, int fontSize, int textDir, int cache, FeatureParser * features)
         : m_rtl(textDir),
-        m_grFace((cache == 0)?
+          m_grFace((cache == 0)?
             gr_make_file_face(fontFile, gr_face_preloadGlyphs):
             gr_make_file_face_with_seg_cache(fontFile, cache,
                 gr_face_cacheCmap | gr_face_preloadGlyphs)),
-        m_grFont(0)
+        m_grFont(0),
+        m_grFeatures(0)
     {
         if (m_grFace)
         {
diff --git a/tests/comparerenderer/HbNgRenderer.h b/tests/comparerenderer/HbNgRenderer.h
index b54b6ed..8c79980 100644
--- a/tests/comparerenderer/HbNgRenderer.h
+++ b/tests/comparerenderer/HbNgRenderer.h
@@ -49,7 +49,7 @@ class HbNgRenderer : public Renderer
 public:
     HbNgRenderer(const char * fileName, int fontSize, int textDir, FeatureParser * features)
         : m_ftLibrary(NULL), m_ftFace(NULL),
-        m_face(NULL), m_font(NULL), m_feats(NULL), m_bufferLength(1024), m_featCount(0)
+        m_face(NULL), m_font(NULL), m_feats(NULL), m_featCount(0)
     {
         if ((FT_Init_FreeType(&m_ftLibrary) == 0) &&
             (FT_New_Face(m_ftLibrary, fileName, 0, &m_ftFace) == 0))
@@ -73,7 +73,7 @@ public:
                 fprintf(stderr, "FT_Request_Size %d failed\n", fontSize);
             }
         }
-        m_buffer = hb_buffer_create(m_bufferLength);
+        m_buffer = hb_buffer_create();
         if (features)
         {
             m_featCount = features->featureCount() + 1;
@@ -110,12 +110,12 @@ public:
     }
     virtual void renderText(const char * utf8, size_t length, RenderedLine * result)
     {
-        if (length > m_bufferLength)
-        {
-            hb_buffer_destroy(m_buffer);
-            m_bufferLength = length;
-            hb_buffer_create(m_bufferLength);
-        }
+//        if (length > m_bufferLength)
+//        {
+//            hb_buffer_destroy(m_buffer);
+//            m_bufferLength = length;
+//            hb_buffer_create(m_bufferLength);
+//        }
         hb_buffer_reset(m_buffer);
         hb_buffer_add_utf8(m_buffer, utf8, length, 0, length);
         hb_unicode_funcs_t * unicodeFuncs = hb_glib_get_unicode_funcs();
@@ -149,6 +149,5 @@ private:
     hb_font_t * m_font;
     hb_buffer_t * m_buffer;
     hb_feature_t* m_feats;
-    size_t m_bufferLength;
     size_t m_featCount;
 };
diff --git a/tests/comparerenderer/RenderedLine.h b/tests/comparerenderer/RenderedLine.h
index e5f2351..a8b24d7 100644
--- a/tests/comparerenderer/RenderedLine.h
+++ b/tests/comparerenderer/RenderedLine.h
@@ -139,8 +139,6 @@ class RenderedLine
         unsigned long numGlyphs() const { return m_numGlyphs; }
         float advance() const { return m_advance; }
         // define placement new for windows
-        void * operator new (size_t size, RenderedLine * p) { return p; }
-        void operator delete (void *, RenderedLine * p) { }
         bool resize(size_t newGlyphCount)
         {
             if (newGlyphCount <= m_numGlyphs)
diff --git a/tests/endian/CMakeLists.txt b/tests/endian/CMakeLists.txt
new file mode 100644
index 0000000..affcd61
--- /dev/null
+++ b/tests/endian/CMakeLists.txt
@@ -0,0 +1,7 @@
+project(endian)
+
+include_directories(../../src)
+
+add_executable(endiantest endiantest.cpp)
+
+add_test(NAME endian COMMAND $<TARGET_FILE:endiantest> 10)
diff --git a/tests/endian/endiantest.cpp b/tests/endian/endiantest.cpp
new file mode 100644
index 0000000..6a679ef
--- /dev/null
+++ b/tests/endian/endiantest.cpp
@@ -0,0 +1,149 @@
+/*-----------------------------------------------------------------------------
+Copyright (C) 2011 SIL International
+Responsibility: Tim Eves
+
+    This library is free software; you can redistribute it and/or modify
+    it under the terms of the GNU Lesser General Public License as published
+    by the Free Software Foundation; either version 2.1 of License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should also have received a copy of the GNU Lesser General Public
+    License along with this library in the file named "LICENSE".
+    If not, write to the Free Software Foundation, 51 Franklin Street,
+    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
+    internet at http://www.fsf.org/licenses/lgpl.html.
+
+Alternatively, the contents of this file may be used under the terms of the
+Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
+License, as published by the Free Software Foundation, either version 2
+of the License or (at your option) any later version.
+
+Description:
+The test harness for the Endian.h template library.  This validates the
+Endian.h classes are working correctly and with all fundamental C/C++ integer
+types. This may also be used for benchmarking by suppling the base two
+magnitude for the number of rounds to run.
+Adding -DHAVE_64_LONG to your compilers command line will test 64bit wide
+integers in addition to 32, 16 and 8 bit.
+-----------------------------------------------------------------------------*/
+#include <cstdlib>
+#include <string>
+#include "Endian.h"
+
+typedef unsigned char 		uint8;
+typedef signed char		     int8;
+typedef short unsigned int 	uint16;
+typedef short signed int 	 int16;
+typedef unsigned int 		uint32;
+typedef signed int 		     int32;
+#if defined(HAVE_64_LONG)
+typedef long unsigned int 	uint64;
+typedef long signed int 	 int64;
+#else
+typedef void                uint64;
+typedef void                 int64;
+#endif
+
+template <typename T8, typename T4, typename T2, typename T1> 
+bool test_swaps()
+{
+	bool t = true;
+	
+	t &= be::swap<T1>(T1(0xFEU)) == T1(0xFEU);
+	t &= le::swap<T1>(T1(0xFEU)) == T1(0xFEU);
+
+	t &= be::swap<T2>(be::swap<T2>(T2(0xFFEEU))) == T2(0xFFEEU);
+	t &= le::swap<T2>(le::swap<T2>(T2(0xFFEEU))) == T2(0xFFEEU);
+	t &= be::swap<T2>(T2(0xFFEEU)) == le::swap<T2>(T2(0xEEFFU));
+#if defined(HAVE_64_LONG)
+	t &= be::swap<T4>(be::swap<T4>(T4(0xDEADBEEFU))) == T4(0xDEADBEEFU);
+	t &= le::swap<T4>(le::swap<T4>(T4(0xDEADBEEFU))) == T4(0xDEADBEEFU);
+	t &= be::swap<T4>(T4(0xDEADBEEFU)) == le::swap<T4>(T4(0xEFBEADDEU));
+#endif
+    return t;
+}
+
+
+template <typename T8, typename T4, typename T2, typename T1> 
+int test_reads(const size_t rounds)
+{
+	static const unsigned char data[] = {0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF,
+	                                     0xEF,0xCD,0xAB,0x89,0x67,0x45,0x23,0x01};
+	bool t = true;
+	
+#if defined(HAVE_64_LONG)
+	for (size_t r = rounds; r; --r)
+	{
+	    const unsigned char *p = data;
+		if (be::read<T8>(p) != T8(0x0123456789ABCDEF))  return  8;
+		if (le::read<T8>(p) != T8(0x0123456789ABCDEF))  return 80;
+	}
+#endif
+	for (size_t r = rounds; r; --r)
+	{
+	    const unsigned char *p = data;
+		t  = be::read<T4>(p) == T4(0x01234567);
+		t &= be::read<T4>(p) == T4(0x89ABCDEF);
+		if (!t) return  4;
+		t  = le::read<T4>(p) == T4(0x89ABCDEF);
+		t &= le::read<T4>(p) == T4(0x01234567);
+		if (!t) return 40;		
+	}
+	for (size_t r = rounds; r; --r)
+    {
+	    const unsigned char *p = data;
+		t  = be::read<T2>(p) == T2(0x0123);
+		t &= be::read<T2>(p) == T2(0x4567); 
+		t &= be::read<T2>(p) == T2(0x89AB); 
+		t &= be::read<T2>(p) == T2(0xCDEF); 
+		if (!t) return  2;
+		t  = le::read<T2>(p) == T2(0xCDEF); 
+		t &= le::read<T2>(p) == T2(0x89AB); 
+		t &= le::read<T2>(p) == T2(0x4567); 
+		t &= le::read<T2>(p) == T2(0x0123);
+		if (!t) return 20;
+	}
+	for (size_t r = rounds; r; --r)
+	{
+	    const unsigned char *p = data;
+		t  = be::read<T1>(p) == T1(0x01); 
+		t &= be::read<T1>(p) == T1(0x23);
+		t &= be::read<T1>(p) == T1(0x45);
+		t &= be::read<T1>(p) == T1(0x67); 
+		t &= be::read<T1>(p) == T1(0x89);
+		t &= be::read<T1>(p) == T1(0xAB);
+		t &= be::read<T1>(p) == T1(0xCD);
+		t &= be::read<T1>(p) == T1(0xEF);
+		if (!t) return  1;
+		t  = le::read<T1>(p) == T1(0xEF);
+		t &= le::read<T1>(p) == T1(0xCD);
+		t &= le::read<T1>(p) == T1(0xAB);
+		t &= le::read<T1>(p) == T1(0x89);
+		t &= le::read<T1>(p) == T1(0x67); 
+		t &= le::read<T1>(p) == T1(0x45);
+		t &= le::read<T1>(p) == T1(0x23);
+		t &= le::read<T1>(p) == T1(0x01); 
+		if (!t) return 10;
+	}
+	return 0;
+}
+
+int main(int argc , char *argv[])
+{
+	const size_t rounds = 1UL << atoi(argv[1]);
+	int r = 0;
+
+    if   (!test_swaps<uint64, uint32, uint16, uint8>()
+       || !test_swaps<int64, int32, int16, int8>())
+        return 5;
+    
+	if (r == 0) r = test_reads<uint64, uint32, uint16, uint8>(rounds);
+	if (r == 0) r = test_reads<int64, int32, int16, int8>(rounds);
+	return r;
+}
+
diff --git a/tests/examples/cluster.c b/tests/examples/cluster.c
index c529c33..3859e6f 100644
--- a/tests/examples/cluster.c
+++ b/tests/examples/cluster.c
@@ -25,6 +25,7 @@ int main(int argc, char **argv)
     cluster_t *clusters;
     int ic, ci = 0;
     const gr_slot *s, *is;
+    FILE *log;
     gr_face *face = gr_make_file_face(argv[1], 0);
     if (!face) return 1;
     font = gr_make_font(pointsize * dpi / 72.0f, face);
@@ -65,7 +66,7 @@ int main(int argc, char **argv)
     }
 
     ci = 0;
-    FILE *log = fopen("cluster.log", "w");
+    log = fopen("cluster.log", "w");
     for (s = gr_seg_first_slot(seg); s; s = gr_slot_next_in_segment(s))
     {
         fprintf(log, "%d(%f,%f) ", gr_slot_gid(s), gr_slot_origin_X(s),
diff --git a/tests/examples/linebreak.c b/tests/examples/linebreak.c
index 823782f..ef29a4e 100644
--- a/tests/examples/linebreak.c
+++ b/tests/examples/linebreak.c
@@ -16,6 +16,10 @@ int main(int argc, char **argv)
     size_t numCodePoints = 0;
     gr_segment * seg = NULL;
     const gr_slot *s, *sprev;
+    int i;
+    int lineend = width;
+    int numlines = 0;
+    const gr_slot **lineslots;
     gr_face *face = gr_make_file_face(argv[1], 0);
     if (!face) return 1;
     font = gr_make_font(pointsize * dpi / 72.0f, face);
@@ -26,10 +30,7 @@ int main(int argc, char **argv)
     seg = gr_make_seg(font, face, 0, 0, gr_utf8, argv[3], numCodePoints, rtl);  /*<1>*/
     if (!seg) return 3;
 
-    int lineend = width;
-    int numlines = 0;
-    const gr_slot **lineslots = (const gr_slot **)malloc(numCodePoints 
-                                                        * sizeof(gr_slot *));
+    lineslots = (const gr_slot **)malloc(numCodePoints * sizeof(gr_slot *));
     lineslots[numlines++] = gr_seg_first_slot(seg);                             /*<2>*/
     for (s = lineslots[0]; s; s = gr_slot_next_in_segment(s))
     {
@@ -53,7 +54,6 @@ int main(int argc, char **argv)
         }
     }
 
-    int i;
     printf("%d:", width);
     for (i = 0; i < numlines; i++)
     {                                                                           
diff --git a/tests/featuremap/featuremaptest.cpp b/tests/featuremap/featuremaptest.cpp
index 456ab03..4e3365f 100644
--- a/tests/featuremap/featuremaptest.cpp
+++ b/tests/featuremap/featuremaptest.cpp
@@ -24,6 +24,7 @@
 #include <cstdlib>
 #include <cstring>
 #include "Main.h"
+#include "Endian.h"
 #include "Face.h"
 #include "FeatureMap.h"
 #include "TtfTypes.h"
@@ -170,22 +171,22 @@ public:
         memcpy(m_table, &data, sizeof(T));
         // convert to big endian if needed
         T * bigEndian = reinterpret_cast<T*>(m_table);
-        bigEndian->m_header.m_major = swap16(data.m_header.m_major);
-        bigEndian->m_header.m_minor = swap16(data.m_header.m_minor);
-        bigEndian->m_header.m_numFeat = swap16(data.m_header.m_numFeat);
+        bigEndian->m_header.m_major = be::swap<uint16>(data.m_header.m_major);
+        bigEndian->m_header.m_minor = be::swap<uint16>(data.m_header.m_minor);
+        bigEndian->m_header.m_numFeat = be::swap<uint16>(data.m_header.m_numFeat);
         m_tableLen = sizeof(T);
         for (size_t i = 0; i < sizeof(data.m_defs)/sizeof(FeatDefn); i++)
         {
-            bigEndian->m_defs[i].m_featId = swap32(data.m_defs[i].m_featId);
-            bigEndian->m_defs[i].m_numFeatSettings = swap16(data.m_defs[i].m_numFeatSettings);
-            bigEndian->m_defs[i].m_settingsOffset = swap32(data.m_defs[i].m_settingsOffset);
-            bigEndian->m_defs[i].m_flags = swap16(data.m_defs[i].m_flags);
-            bigEndian->m_defs[i].m_label = swap16(data.m_defs[i].m_label);
+            bigEndian->m_defs[i].m_featId = be::swap<uint32>(data.m_defs[i].m_featId);
+            bigEndian->m_defs[i].m_numFeatSettings = be::swap<uint16>(data.m_defs[i].m_numFeatSettings);
+            bigEndian->m_defs[i].m_settingsOffset = be::swap<uint32>(data.m_defs[i].m_settingsOffset);
+            bigEndian->m_defs[i].m_flags = be::swap<uint16>(data.m_defs[i].m_flags);
+            bigEndian->m_defs[i].m_label = be::swap<uint16>(data.m_defs[i].m_label);
         }
         for (size_t i = 0; i < sizeof(data.m_settings)/sizeof(FeatSetting); i++)
         {
-            bigEndian->m_settings[i].m_value = swap16(data.m_settings[i].m_value);
-            bigEndian->m_settings[i].m_label = swap16(data.m_settings[i].m_label);
+            bigEndian->m_settings[i].m_value = be::swap<uint16>(data.m_settings[i].m_value);
+            bigEndian->m_settings[i].m_label = be::swap<uint16>(data.m_settings[i].m_label);
         }
     }
     void * m_table;
diff --git a/tests/fuzztest b/tests/fuzztest
index d4ef016..86156c4 100755
--- a/tests/fuzztest
+++ b/tests/fuzztest
@@ -72,7 +72,7 @@ def table_from_offset(o,tables):
 parser = OptionParser(usage="usage: %prog -f font [options] -- command")
 parser.add_option("-l", "--logfile", help="Log results to this file")
 parser.add_option("-f", "--font", help="Required font file to corrupt")
-parser.add_option("-p", "--position", default=0, help="Specifies position to corrupt (hex)")
+parser.add_option("-p", "--position", default="0", help="Specifies position to corrupt (hex)")
 parser.add_option("-v", "--value", help="Specifies value to use (dec)")
 parser.add_option("-i", "--input", help=".log file to read test values from")
 parser.add_option("-V", "--verbose", action="store_true", help="Be noisy")
@@ -81,10 +81,14 @@ parser.add_option("--memory", type="int", help="limit subprocess address space i
 parser.add_option("-c","--count",type='int',help='Flag every count iterations')
 parser.add_option("-r","--random",help="Seed the random number generator with the given string")
 parser.add_option("-L","--linear",action="store_true",help="Linearly process every location in the source font")
+parser.add_option("--valgrind",action="store_true",help="Run tests with valgrind and report errors")
 
 (opts, args) = parser.parse_args()
 
 if opts.random : seed(opts.random)
+if opts.valgrind : 
+    args.insert(0, "-q")
+    args.insert(0, "valgrind")
 
 fontlen = os.path.getsize(opts.font)
 if opts.logfile :
@@ -130,14 +134,21 @@ for loc, val in valpos(fontlen, opts)() :
         print count / opts.count,
         sys.stdout.flush()
     subfile = open("templog.txt", "w")
-    retval = call(args, stdout=subfile, stderr=subfile, preexec_fn=rlimit, close_fds = True)
+    errfile = open("errlog.txt", "w")
+    retval = call(args, stdout=subfile, stderr=errfile, preexec_fn=rlimit, close_fds = True)
+    subfile.close()
+    errfile.close()
+    lenerr = os.stat("errlog.txt").st_size
     if retval < 0 :
     	(t,s,_) = table_from_offset(loc, tables) or (0,0,fontlen)
         print >>log, "%d,0x%x,%d,%s0x%x" % (retval, loc, val, tag(t) + '+' if t else '', loc-s)
-    elif opts.verbose :
+    elif opts.verbose or lenerr :
         print >>log, ",0x%x,%d" % (loc, val)
+        if lenerr :
+            errfile = open("errlog.txt", "r")
+            for l in errfile.readlines() : print >>log, l.rstrip()
+            errfile.close()
     log.flush()
-    subfile.close()
     font = open(opts.font, "r+b")
     font.seek(loc, 0)
     font.write(oldval)
diff --git a/tests/nametabletest/nametabletest.cpp b/tests/nametabletest/nametabletest.cpp
index 8b783d5..86e5ef9 100644
--- a/tests/nametabletest/nametabletest.cpp
+++ b/tests/nametabletest/nametabletest.cpp
@@ -25,6 +25,7 @@
 #include <cstring>
 #include <graphite2/Types.h>
 #include "Main.h"
+#include "Endian.h"
 #include "TtfTypes.h"
 #include "NameTable.h"
 
@@ -131,26 +132,26 @@ void testLangId(void * data, size_t length, const char * id, uint16 expected)
 template <class T> T * toBigEndian(T & table)
 {
     T * bigEndian = gralloc<T>(1);
-    bigEndian->m_nameHeader.format = swap16(table.m_nameHeader.format);
-    bigEndian->m_nameHeader.count = swap16(table.m_nameHeader.count);
-    bigEndian->m_nameHeader.string_offset = swap16(table.m_nameHeader.string_offset);
+    bigEndian->m_nameHeader.format = be::swap<uint16>(table.m_nameHeader.format);
+    bigEndian->m_nameHeader.count = be::swap<uint16>(table.m_nameHeader.count);
+    bigEndian->m_nameHeader.string_offset = be::swap<uint16>(table.m_nameHeader.string_offset);
 
     for (uint16 i = 0; i < table.m_nameHeader.count; i++)
     {
-        bigEndian->m_records[i].platform_id = swap16(table.m_records[i].platform_id);
-        bigEndian->m_records[i].platform_specific_id = swap16(table.m_records[i].platform_specific_id);
-        bigEndian->m_records[i].language_id = swap16(table.m_records[i].language_id);
-        bigEndian->m_records[i].name_id = swap16(table.m_records[i].name_id);
-        bigEndian->m_records[i].length = swap16(table.m_records[i].length);
-        bigEndian->m_records[i].offset = swap16(table.m_records[i].offset);
+        bigEndian->m_records[i].platform_id = be::swap<uint16>(table.m_records[i].platform_id);
+        bigEndian->m_records[i].platform_specific_id = be::swap<uint16>(table.m_records[i].platform_specific_id);
+        bigEndian->m_records[i].language_id = be::swap<uint16>(table.m_records[i].language_id);
+        bigEndian->m_records[i].name_id = be::swap<uint16>(table.m_records[i].name_id);
+        bigEndian->m_records[i].length = be::swap<uint16>(table.m_records[i].length);
+        bigEndian->m_records[i].offset = be::swap<uint16>(table.m_records[i].offset);
     }
 
-    bigEndian->m_nameHeader.name_record[0].platform_id = swap16(table.m_nameHeader.name_record[0].platform_id);
-    bigEndian->m_nameHeader.name_record[0].platform_specific_id = swap16(table.m_nameHeader.name_record[0].platform_specific_id);
-    bigEndian->m_nameHeader.name_record[0].language_id = swap16(table.m_nameHeader.name_record[0].language_id);
-    bigEndian->m_nameHeader.name_record[0].name_id = swap16(table.m_nameHeader.name_record[0].name_id);
-    bigEndian->m_nameHeader.name_record[0].length = swap16(table.m_nameHeader.name_record[0].length);
-    bigEndian->m_nameHeader.name_record[0].offset = swap16(table.m_nameHeader.name_record[0].offset);
+    bigEndian->m_nameHeader.name_record[0].platform_id = be::swap<uint16>(table.m_nameHeader.name_record[0].platform_id);
+    bigEndian->m_nameHeader.name_record[0].platform_specific_id = be::swap<uint16>(table.m_nameHeader.name_record[0].platform_specific_id);
+    bigEndian->m_nameHeader.name_record[0].language_id = be::swap<uint16>(table.m_nameHeader.name_record[0].language_id);
+    bigEndian->m_nameHeader.name_record[0].name_id = be::swap<uint16>(table.m_nameHeader.name_record[0].name_id);
+    bigEndian->m_nameHeader.name_record[0].length = be::swap<uint16>(table.m_nameHeader.name_record[0].length);
+    bigEndian->m_nameHeader.name_record[0].offset = be::swap<uint16>(table.m_nameHeader.name_record[0].offset);
     
     memcpy(bigEndian->m_textData, table.m_textData, sizeof(table.m_textData) );
     return bigEndian;
@@ -159,11 +160,11 @@ template <class T> T * toBigEndian(T & table)
 template <class T> T * toBigEndian1(T & table)
 {
     T * bigEndian = toBigEndian<T>(table);
-    bigEndian->m_langTagCount = swap16(table.m_langTagCount);
+    bigEndian->m_langTagCount = be::swap<uint16>(table.m_langTagCount);
     for (size_t i = 0; i < table.m_langTagCount; i++)
     {
-        bigEndian->m_languages[i] = swap16(table.m_languages[i]);
-        bigEndian->m_languages[i] = swap16(table.m_languages[i]);
+        bigEndian->m_languages[i] = be::swap<uint16>(table.m_languages[i]);
+        bigEndian->m_languages[i] = be::swap<uint16>(table.m_languages[i]);
     }
 }
 

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-openoffice/graphite2.git


Reply to: