bug 721068 - update to latest graphite2 code from upstream (hg rev 911:a697cecbaddd). rs=roc
authorJonathan Kew <jfkthame@gmail.com>
Thu, 26 Jan 2012 11:20:57 +0000
changeset 86692 3ea57c1351ccae8b545deef76c044df4d11de60a
parent 86691 d2d6243b6fb445ea6827210e15fb3700d8244f10
child 86693 8ee43a7c94dd5d52465166a1bbad04012dbcb899
push id805
push userakeybl@mozilla.com
push dateWed, 01 Feb 2012 18:17:35 +0000
treeherdermozilla-aurora@6fb3bf232436 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersroc
bugs721068
milestone12.0a1
bug 721068 - update to latest graphite2 code from upstream (hg rev 911:a697cecbaddd). rs=roc
gfx/graphite2/include/graphite2/Font.h
gfx/graphite2/include/graphite2/Log.h
gfx/graphite2/include/graphite2/Types.h
gfx/graphite2/src/Bidi.cpp
gfx/graphite2/src/CMakeLists.txt
gfx/graphite2/src/CachedFace.cpp
gfx/graphite2/src/CachedFace.h
gfx/graphite2/src/CharInfo.h
gfx/graphite2/src/CmapCache.cpp
gfx/graphite2/src/CmapCache.h
gfx/graphite2/src/Code.cpp
gfx/graphite2/src/Code.h
gfx/graphite2/src/Endian.h
gfx/graphite2/src/Face.cpp
gfx/graphite2/src/Face.h
gfx/graphite2/src/FeatureMap.cpp
gfx/graphite2/src/FeatureMap.h
gfx/graphite2/src/FeatureVal.h
gfx/graphite2/src/Font.cpp
gfx/graphite2/src/Font.h
gfx/graphite2/src/GlyphFace.cpp
gfx/graphite2/src/GlyphFace.h
gfx/graphite2/src/GlyphFaceCache.cpp
gfx/graphite2/src/GlyphFaceCache.h
gfx/graphite2/src/List.h
gfx/graphite2/src/Machine.h
gfx/graphite2/src/Main.h
gfx/graphite2/src/Makefile.in
gfx/graphite2/src/NameTable.cpp
gfx/graphite2/src/NameTable.h
gfx/graphite2/src/Pass.cpp
gfx/graphite2/src/Pass.h
gfx/graphite2/src/Position.h
gfx/graphite2/src/Rule.cpp
gfx/graphite2/src/Rule.h
gfx/graphite2/src/SegCache.cpp
gfx/graphite2/src/SegCache.h
gfx/graphite2/src/SegCacheEntry.cpp
gfx/graphite2/src/SegCacheEntry.h
gfx/graphite2/src/SegCacheStore.cpp
gfx/graphite2/src/SegCacheStore.h
gfx/graphite2/src/Segment.cpp
gfx/graphite2/src/Segment.h
gfx/graphite2/src/Silf.cpp
gfx/graphite2/src/Silf.h
gfx/graphite2/src/Slot.cpp
gfx/graphite2/src/Slot.h
gfx/graphite2/src/Sparse.cpp
gfx/graphite2/src/Sparse.h
gfx/graphite2/src/TtfTypes.h
gfx/graphite2/src/TtfUtil.cpp
gfx/graphite2/src/TtfUtil.h
gfx/graphite2/src/UtfCodec.cpp
gfx/graphite2/src/UtfCodec.h
gfx/graphite2/src/XmlTraceLog.h
gfx/graphite2/src/XmlTraceLogTags.h
gfx/graphite2/src/call_machine.cpp
gfx/graphite2/src/direct_machine.cpp
gfx/graphite2/src/files.mk
gfx/graphite2/src/gr_char_info.cpp
gfx/graphite2/src/gr_face.cpp
gfx/graphite2/src/gr_features.cpp
gfx/graphite2/src/gr_font.cpp
gfx/graphite2/src/gr_logging.cpp
gfx/graphite2/src/gr_segment.cpp
gfx/graphite2/src/gr_slot.cpp
gfx/graphite2/src/inc/CachedFace.h
gfx/graphite2/src/inc/CharInfo.h
gfx/graphite2/src/inc/CmapCache.h
gfx/graphite2/src/inc/Code.h
gfx/graphite2/src/inc/Endian.h
gfx/graphite2/src/inc/Face.h
gfx/graphite2/src/inc/FeatureMap.h
gfx/graphite2/src/inc/FeatureVal.h
gfx/graphite2/src/inc/Font.h
gfx/graphite2/src/inc/GlyphFace.h
gfx/graphite2/src/inc/GlyphFaceCache.h
gfx/graphite2/src/inc/List.h
gfx/graphite2/src/inc/Machine.h
gfx/graphite2/src/inc/Main.h
gfx/graphite2/src/inc/NameTable.h
gfx/graphite2/src/inc/Pass.h
gfx/graphite2/src/inc/Position.h
gfx/graphite2/src/inc/Rule.h
gfx/graphite2/src/inc/SegCache.h
gfx/graphite2/src/inc/SegCacheEntry.h
gfx/graphite2/src/inc/SegCacheStore.h
gfx/graphite2/src/inc/Segment.h
gfx/graphite2/src/inc/Silf.h
gfx/graphite2/src/inc/Slot.h
gfx/graphite2/src/inc/Sparse.h
gfx/graphite2/src/inc/TtfTypes.h
gfx/graphite2/src/inc/TtfUtil.h
gfx/graphite2/src/inc/UtfCodec.h
gfx/graphite2/src/inc/debug.h
gfx/graphite2/src/inc/json.h
gfx/graphite2/src/inc/locale2lcid.h
gfx/graphite2/src/inc/opcode_table.h
gfx/graphite2/src/inc/opcodes.h
gfx/graphite2/src/json.cpp
gfx/graphite2/src/locale2lcid.h
gfx/graphite2/src/opcode_table.h
gfx/graphite2/src/opcodes.h
gfx/graphite2/src/processUTF.h
gfx/thebes/Makefile.in
gfx/thebes/gfxGraphiteShaper.h
--- a/gfx/graphite2/include/graphite2/Font.h
+++ b/gfx/graphite2/include/graphite2/Font.h
@@ -23,17 +23,17 @@
     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.
 */
 #pragma once
 
 #include "graphite2/Types.h"
 
-#define GR2_VERSION_MAJOR   1
+#define GR2_VERSION_MAJOR   2
 #define GR2_VERSION_MINOR   0
 #define GR2_VERSION_BUGFIX  1
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
@@ -82,28 +82,28 @@ typedef const void *(*gr_get_table_fn)(c
   * @param appFaceHandle This is application specific information that is passed to the getTable
   *                      function. The appFaceHandle must stay alive as long as the gr_face is alive.
   * @param getTable  This function is called whenever graphite needs access to a table of data
   *                  in the font.
   * @param faceOptions   Bitfield describing various options. See enum gr_face_options for details.
   */
 GR2_API gr_face* gr_make_face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable, unsigned int faceOptions);
 
-#ifndef DISABLE_SEGCACHE
+//#ifndef GRAPHITE2_NSEGCACHE
 /** Create a gr_face object given application information, with subsegmental caching support
   *
   * @return gr_face or NULL if the font fails to load.
   * @param appFaceHandle is a pointer to application specific information that is passed to getTable.
   *                      This may not be NULL and must stay alive as long as the gr_face is alive.
   * @param getTable  The function graphite calls to access font table data
   * @param segCacheMaxSize   How large the segment cache is.
   * @param faceOptions   Bitfield of values from enum gr_face_options
   */
 GR2_API gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle, gr_get_table_fn getTable, unsigned int segCacheMaxSize, unsigned int faceOptions);
-#endif
+//#endif
 
 /** Convert a tag in a string into a gr_uint32
   *
   * @return gr_uint32 tag, zero padded
   * @param str a nul terminated string of which at most the first 4 characters are read
   */
 GR2_API gr_uint32 gr_str_to_tag(const char *str);
 
@@ -149,36 +149,36 @@ GR2_API unsigned short gr_face_n_languag
 GR2_API gr_uint32 gr_face_lang_by_index(const gr_face* pFace, gr_uint16 i);
 
 /** Destroy the given face and free its memory **/
 GR2_API void gr_face_destroy(gr_face *face);
 
 /** Returns the number of glyphs in the face **/
 GR2_API unsigned short gr_face_n_glyphs(const gr_face* pFace);
 
-#ifndef DISABLE_FILE_FACE
+#ifndef GRAPHITE2_NFILEFACE
 /** Create gr_face from a font file
   *
   * @return gr_face that accesses a font file directly. Returns NULL on failure.
   * @param filename Full path and filename to font file
   * @param faceOptions Bitfile from enum gr_face_options to control face options.
   */
 GR2_API gr_face* gr_make_file_face(const char *filename, unsigned int faceOptions);
 
-#ifndef DISABLE_SEGCACHE
+//#ifndef GRAPHITE2_NSEGCACHE
 /** Create gr_face from a font file, with subsegment caching support.
   *
   * @return gr_face that accesses a font file directly. Returns NULL on failure.
   * @param filename Full path and filename to font file
   * @param segCacheMaxSize Specifies how big to make the cache in segments.
   * @param faceOptions   Bitfield from enum gr_face_options to control face options.
   */
 GR2_API gr_face* gr_make_file_face_with_seg_cache(const char *filename, unsigned int segCacheMaxSize, unsigned int faceOptions);
-#endif
-#endif      // !DISABLE_FILE_FACE
+//#endif
+#endif      // !GRAPHITE2_NFILEFACE
 
 /** Create a font from a face
   *
   * @return gr_font Call font_destroy to free this font
   * @param ppm Resolution of the font in pixels per em
   * @param face Face this font corresponds to. This must stay alive as long as the font is alive.
   */
 GR2_API gr_font* gr_make_font(float ppm, const gr_face *face);
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/include/graphite2/Log.h
@@ -0,0 +1,55 @@
+/*  GRAPHITE2 LICENSING
+
+    Copyright 2010, SIL International
+    All rights reserved.
+
+    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.
+*/
+#pragma once
+
+#include <graphite2/Types.h>
+#include <stdio.h>
+
+typedef enum {
+    GRLOG_NONE = 0x0,
+    GRLOG_FACE = 0x01,
+    GRLOG_SEGMENT = 0x02,
+    GRLOG_PASS = 0x04,
+    GRLOG_CACHE = 0x08,
+    
+    GRLOG_OPCODE = 0x80,
+    GRLOG_ALL = 0xFF
+} GrLogMask;
+
+// If startGraphiteLogging returns true, logging is enabled and the FILE handle
+// will be closed by graphite when stopGraphiteLogging is called.
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+GR2_API bool graphite_start_logging(FILE * logFile, GrLogMask mask);		//may not do anthing if disabled in the implementation of the engine.
+GR2_API void graphite_stop_logging();
+
+#ifdef __cplusplus
+}
+#endif
--- a/gfx/graphite2/include/graphite2/Types.h
+++ b/gfx/graphite2/include/graphite2/Types.h
@@ -37,24 +37,26 @@ typedef unsigned int    gr_uint32;
 typedef int             gr_int32;
 
 enum gr_encform {
   gr_utf8 = 1/*sizeof(uint8)*/, gr_utf16 = 2/*sizeof(uint16)*/, gr_utf32 = 4/*sizeof(uint32)*/
 };
 
 // Definitions for library publicly exported symbols
 #if defined _WIN32 || defined __CYGWIN__
-  #ifdef GR2_EXPORTING
-    #ifdef __GNUC__
+  #if defined GRAPHITE2_STATIC
+    #define GR2_API
+  #elif defined GRAPHITE2_EXPORTING
+    #if defined __GNUC__
       #define GR2_API    __attribute__((dllexport))
     #else
       #define GR2_API    __declspec(dllexport)
     #endif
   #else
-    #ifdef __GNUC__
+    #if defined __GNUC__
       #define GR2_API    __attribute__((dllimport))
     #else
       #define GR2_API    __declspec(dllimport)
     #endif
   #endif
   #define GR2_LOCAL
 #else
   #if __GNUC__ >= 4
--- a/gfx/graphite2/src/Bidi.cpp
+++ b/gfx/graphite2/src/Bidi.cpp
@@ -19,19 +19,19 @@
     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.
 */
-#include "Main.h"
-#include "Slot.h"
-#include "Segment.h"
+#include "inc/Main.h"
+#include "inc/Slot.h"
+#include "inc/Segment.h"
 
 using namespace graphite2;
 
 enum DirCode {  // Hungarian: dirc
         Unk        = -1,
         N          =  0,   // other neutrals (default) - ON
         L          =  1,   // left-to-right, strong - L
         R          =  2,   // right-to-left, strong - R
--- a/gfx/graphite2/src/CMakeLists.txt
+++ b/gfx/graphite2/src/CMakeLists.txt
@@ -19,51 +19,52 @@
 #    Suite 500, Boston, MA 02110-1335, USA or visit their web page on the 
 #    internet at http://www.fsf.org/licenses/lgpl.html.
 
 CMAKE_MINIMUM_REQUIRED(VERSION 2.8.0 FATAL_ERROR)
 project(graphite2_core)
 cmake_policy(SET CMP0012 NEW)
 INCLUDE(CheckCXXSourceCompiles)
 
-set(GRAPHITE_API_MAJOR 2)
-set(GRAPHITE_API_MINOR 0)
+set(GRAPHITE_API_CURRENT 2)
+set(GRAPHITE_API_REVISION 0)
 set(GRAPHITE_API_AGE 0)
-set(GRAPHITE_SO_VERSION ${GRAPHITE_API_MAJOR}.${GRAPHITE_API_MINOR}.${GRAPHITE_API_AGE})
+set(GRAPHITE_SO_VERSION ${GRAPHITE_API_CURRENT}.${GRAPHITE_API_REVISION}.${GRAPHITE_API_AGE})
 
 include(TestBigEndian)
 
 include_directories(${PROJECT_SOURCE_DIR})
 
-if (DISABLE_SEGCACHE)
-    add_definitions(-DDISABLE_SEGCACHE)
-endif (DISABLE_SEGCACHE)
+set(SEGCACHE SegCache.cpp SegCacheEntry.cpp SegCacheStore.cpp)
+if (GRAPHITE2_NSEGCACHE)
+    add_definitions(-DGRAPHITE2_NSEGCACHE)
+    set(SEGCACHE)
+endif (GRAPHITE2_NSEGCACHE)
 
-if (DISABLE_FILEFACE)
-    add_definitions(-DDISABLE_FILE_FACE)
-endif (DISABLE_FILEFACE)
+if (GRAPHITE2_NFILEFACE)
+    add_definitions(-DGRAPHITE2_NFILEFACE)
+endif (GRAPHITE2_NFILEFACE)
 
-if (NOT DISABLE_TRACING)
-    set(TRACE_HEADERS ../include/graphite2/XmlLog.h)
-    if (ENABLE_DEEP_TRACING)
-        add_definitions(-DENABLE_DEEP_TRACING)
-    endif (ENABLE_DEEP_TRACING)
-endif (NOT DISABLE_TRACING)
+set(TRACING json.cpp)
+if (GRAPHITE2_NTRACING)
+    add_definitions(-DGRAPHITE2_NTRACING)
+    set(TRACING)
+endif (GRAPHITE2_NTRACING)
+
 
 set(GRAPHITE_HEADERS 
     ../include/graphite2/Font.h
     ../include/graphite2/Segment.h
     ../include/graphite2/Types.h
-    ${TRACE_HEADERS}
     )
 
-file(GLOB PRIVATE_HEADERS *.h) 
+file(GLOB PRIVATE_HEADERS inc/*.h) 
 
 add_library(graphite2 SHARED
-    ${VM_MACHINE_TYPE}_machine.cpp
+    ${GRAPHITE2_VM_TYPE}_machine.cpp
     gr_char_info.cpp
     gr_features.cpp
     gr_face.cpp
     gr_font.cpp
     gr_logging.cpp
     gr_segment.cpp
     gr_slot.cpp
     Bidi.cpp
@@ -72,32 +73,29 @@ add_library(graphite2 SHARED
     Code.cpp
     Face.cpp
     FeatureMap.cpp
     Font.cpp
     GlyphFace.cpp
     GlyphFaceCache.cpp
     NameTable.cpp
     Pass.cpp
-    SegCache.cpp
-    SegCacheEntry.cpp
-    SegCacheStore.cpp
     Segment.cpp
     Silf.cpp
     Slot.cpp
     Sparse.cpp
     TtfUtil.cpp
     UtfCodec.cpp
-    XmlTraceLog.cpp
-    XmlTraceLogTags.cpp)
+    ${SEGCACHE}
+    ${TRACING})
 
 set_target_properties(graphite2 PROPERTIES  PUBLIC_HEADER "${GRAPHITE_HEADERS}"
                                             SOVERSION ${GRAPHITE_SO_VERSION}
-                                            LT_VERSION_CURRENT ${GRAPHITE_API_MAJOR}
-                                            LT_VERSION_REVISION ${GRAPHITE_API_MINOR}
+                                            LT_VERSION_CURRENT ${GRAPHITE_API_CURRENT}
+                                            LT_VERSION_REVISION ${GRAPHITE_API_REVISION}
                                             LT_VERSION_AGE ${GRAPHITE_API_AGE})
 
 if  (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
     add_definitions(-Wall -Wno-unknown-pragmas -Wparentheses -Wextra -Wendif-labels
      -Wshadow -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor -fdiagnostics-show-option
      -fno-rtti -fno-exceptions -nodefaultlibs
      -fvisibility=hidden -fvisibility-inlines-hidden -fno-stack-protector)
     set_target_properties(graphite2 PROPERTIES LINK_FLAGS "-nodefaultlibs" LINKER_LANGUAGE C)
@@ -108,14 +106,14 @@ if  (${CMAKE_SYSTEM_NAME} STREQUAL "Linu
         include(Graphite)
         nolib_test(stdc++ $<TARGET_SONAME_FILE:graphite2>)
     endif (${CMAKE_CXX_COMPILER} MATCHES  ".*mingw.*")
     set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "")
     CREATE_LIBTOOL_FILE(graphite2 "/lib${LIB_SUFFIX}")
 endif (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
 
 if  (${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
-    add_definitions(-D_SCL_SECURE_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS -DUNICODE -DGR2_EXPORTING)
+    add_definitions(-D_SCL_SECURE_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS -DUNICODE -DGRAPHITE2_EXPORTING)
 endif (${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
 
 
 install(TARGETS graphite2 EXPORT graphite2 LIBRARY DESTINATION lib${LIB_SUFFIX} ARCHIVE DESTINATION lib${LIB_SUFFIX} PUBLIC_HEADER DESTINATION include/graphite2 RUNTIME DESTINATION bin)
-install(EXPORT graphite2 DESTINATION share/graphite2 NAMESPACE gr2_)
\ No newline at end of file
+install(EXPORT graphite2 DESTINATION share/graphite2 NAMESPACE gr2_)
--- a/gfx/graphite2/src/CachedFace.cpp
+++ b/gfx/graphite2/src/CachedFace.cpp
@@ -20,21 +20,21 @@
     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.
 */
 
-#ifndef DISABLE_SEGCACHE
+#ifndef GRAPHITE2_NSEGCACHE
 
 #include <graphite2/Segment.h>
-#include "CachedFace.h"
-#include "SegCacheStore.h"
+#include "inc/CachedFace.h"
+#include "inc/SegCacheStore.h"
 
 
 using namespace graphite2;
 
 CachedFace::CachedFace(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable2)
 : Face(appFaceHandle, getTable2), m_cacheStore(0) 
 {
 }
@@ -105,24 +105,16 @@ bool CachedFace::runGraphite(Segment *se
                 // spaces should be left untouched by graphite rules in any sane font
             }
             else
             {
                 // found a break position, check for a cache of the sub sequence
                 const SegCacheEntry * entry = (segCache)?
                     segCache->find(cmapGlyphs, i - subSegStart + 1) : NULL;
                 // TODO disable cache for words at start/end of line with contextuals
-#ifndef DISABLE_TRACING
-                if (XmlTraceLog::get().active())
-                {
-                    XmlTraceLog::get().openElement(ElementSubSeg);
-                    XmlTraceLog::get().addAttribute(AttrFirstId, subSegStart);
-                    XmlTraceLog::get().addAttribute(AttrLastId, i);
-                }
-#endif
                 if (!entry)
                 {
                     unsigned int length = i - subSegStart + 1;
                     SegmentScopeState scopeState = seg->setScope(subSegStartSlot, subSegEndSlot, length);
                     pSilf->runGraphite(seg, pSilf->substitutionPass(), pSilf->numPasses());
                     //entry =runGraphiteOnSubSeg(segCache, seg, cmapGlyphs,
                     //                           subSegStartSlot, subSegEndSlot,
                     //                           subSegStart, i - subSegStart + 1);
@@ -131,22 +123,16 @@ bool CachedFace::runGraphite(Segment *se
                     seg->removeScope(scopeState);
                 }
                 else
                 {
                     //seg->splice(subSegStart, i - subSegStart + 1, subSegStartSlot, subSegEndSlot, entry);
                     seg->splice(subSegStart, i - subSegStart + 1, subSegStartSlot, subSegEndSlot,
                         entry->first(), entry->glyphLength());
                 }
-#ifndef DISABLE_TRACING
-                if (XmlTraceLog::get().active())
-                {
-                    XmlTraceLog::get().closeElement(ElementSubSeg);
-                }
-#endif
             }
             subSegEndSlot = nextSlot;
             subSegStartSlot = nextSlot;
             subSegStart = i + 1;
             spaceOnly = true;
         }
         else
         {
deleted file mode 100644
--- a/gfx/graphite2/src/CachedFace.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#ifndef DISABLE_SEGCACHE
-
-#include "Face.h"
-
-namespace graphite2 {
-
-class SegCacheStore;
-
-class CachedFace : public Face
-{
-public:
-    CachedFace(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable2);
-    bool setupCache(unsigned int cacheSize);
-    virtual ~CachedFace();
-    virtual bool runGraphite(Segment *seg, const Silf *silf) const;
-    SegCacheStore * cacheStore() { return m_cacheStore; }
-private:
-    SegCacheStore * m_cacheStore;
-};
-
-} // namespace graphite2
-
-#endif
-
deleted file mode 100644
--- a/gfx/graphite2/src/CharInfo.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-#include "Main.h"
-
-
-namespace graphite2 {
-
-class CharInfo
-{
-
-public:
-    CharInfo() : m_before(-1), m_after(0) {}
-    void init(int cid) { m_char = cid; }
-    unsigned int unicodeChar() const { return m_char; }
-    void feats(int offset) { m_featureid = offset; }
-    int fid() const { return m_featureid; }
-    int breakWeight() const { return m_break; }
-    void breakWeight(int val) { m_break = val; }
-    int after() const { return m_after; }
-    void after(int val) { m_after = val; }
-    int before() const { return m_before; }
-    void before(int val) { m_before = val; }
-    size_t base() const { return m_base; }
-    void base(size_t offset) { m_base = offset; }
-
-    CLASS_NEW_DELETE
-private:
-    int m_char;     // Unicode character from character stream
-    int m_before;   // slot index before us, comes before
-    int m_after;    // slot index after us, comes after
-    size_t  m_base; // offset into input string corresponding to this charinfo
-    uint8 m_featureid;	// index into features list in the segment
-    int8 m_break;	// breakweight coming from lb table
-};
-
-} // namespace graphite2
-
-struct gr_char_info : public graphite2::CharInfo {};
-
--- a/gfx/graphite2/src/CmapCache.cpp
+++ b/gfx/graphite2/src/CmapCache.cpp
@@ -20,20 +20,20 @@
     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.
 */
 
-#include "Main.h"
-#include "CmapCache.h"
-#include "TtfTypes.h"
-#include "TtfUtil.h"
+#include "inc/Main.h"
+#include "inc/CmapCache.h"
+#include "inc/TtfTypes.h"
+#include "inc/TtfUtil.h"
 
 
 using namespace graphite2;
 
 CmapCache::CmapCache(const void* cmapTable, size_t length)
 {
     const void * table31 = TtfUtil::FindCmapSubtable(cmapTable, 3, 1, length);
     const void * table310 = TtfUtil::FindCmapSubtable(cmapTable, 3, 10, length);
deleted file mode 100644
--- a/gfx/graphite2/src/CmapCache.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include <Main.h>
-
-namespace graphite2 {
-
-class Face;
-
-class Cmap
-{
-public:
-	virtual ~Cmap() throw() {}
-
-	virtual uint16 operator [] (const uint32) const throw() { return 0; }
-
-	virtual operator bool () const throw() { return false; }
-
-	CLASS_NEW_DELETE;
-};
-
-class DirectCmap : public Cmap
-{
-public:
-	DirectCmap(const void* cmap, size_t length);
-	virtual uint16 operator [] (const uint32 usv) const throw();
-	virtual operator bool () const throw();
-
-    CLASS_NEW_DELETE;
-private:
-    const void *_stable,
-    		   *_ctable;
-};
-
-class CmapCache : public Cmap
-{
-public:
-	CmapCache(const void * cmapTable, size_t length);
-	virtual ~CmapCache() throw();
-	virtual uint16 operator [] (const uint32 usv) const throw();
-	virtual operator bool () const throw();
-    CLASS_NEW_DELETE;
-private:
-    bool m_isBmpOnly;
-    uint16 ** m_blocks;
-};
-
-} // namespace graphite2
--- a/gfx/graphite2/src/Code.cpp
+++ b/gfx/graphite2/src/Code.cpp
@@ -25,29 +25,29 @@ License, as published by the Free Softwa
 of the License or (at your option) any later version.
 */
 // This class represents loaded graphite stack machine code.  It performs 
 // basic sanity checks, on the incoming code to prevent more obvious problems
 // from crashing graphite.
 // Author: Tim Eves
 
 #include <cassert>
+#include <cstddef>
 #include <cstdlib>
 #include <cstring>
 #include "graphite2/Segment.h"
-#include "Code.h"
-#include "Machine.h"
-#include "Silf.h"
-#include "Face.h"
-#include "Rule.h"
-#include "XmlTraceLog.h"
+#include "inc/Code.h"
+#include "inc/Machine.h"
+#include "inc/Silf.h"
+#include "inc/Face.h"
+#include "inc/Rule.h"
 
 #include <cstdio>
 
-#ifdef DISABLE_TRACING
+#ifdef NDEBUG
 #ifdef __GNUC__
 #pragma GCC diagnostic ignored "-Wunused-parameter"
 #endif
 #endif
 
 
 using namespace graphite2;
 using namespace vm;
@@ -57,18 +57,16 @@ namespace {
 inline bool is_return(const instr i) {
     const opcode_t * opmap = Machine::getOpcodeTable();
     const instr pop_ret  = *opmap[POP_RET].impl,
                 ret_zero = *opmap[RET_ZERO].impl,
                 ret_true = *opmap[RET_TRUE].impl;
     return i == pop_ret || i == ret_zero || i == ret_true;
 }
 
-void emit_trace_message(opcode, const byte *const, const opcode_t &);
-
 struct context
 {
     context(uint8 ref=0) : codeRef(ref) {flags.changed=false; flags.referenced=false; flags.inserted=false;}
     struct { 
         uint8   changed:1,
                 referenced:1,
                 inserted:1;
     } flags;
@@ -201,18 +199,18 @@ Machine::Code::Code(bool is_constraint, 
 
     assert((_constraint && immutable()) || !_constraint);
     dec.apply_analysis(_code, _code + _instr_count);
     _max_ref = dec.max_ref();
     
     // Now we know exactly how much code and data the program really needs
     // realloc the buffers to exactly the right size so we don't waste any 
     // memory.
-    assert((bytecode_end - bytecode_begin) >= ptrdiff_t(_instr_count));
-    assert((bytecode_end - bytecode_begin) >= ptrdiff_t(_data_size));
+    assert((bytecode_end - bytecode_begin) >= std::ptrdiff_t(_instr_count));
+    assert((bytecode_end - bytecode_begin) >= std::ptrdiff_t(_data_size));
     _code = static_cast<instr *>(realloc(_code, (_instr_count+1)*sizeof(instr)));
     _data = static_cast<byte *>(realloc(_data, _data_size*sizeof(byte)));
     
     // Make this RET_ZERO, we should never reach this but just in case ...
     _code[_instr_count] = op_to_fn[RET_ZERO].impl[_constraint];
 
     if (!_code)
         failure(alloc_failed);
@@ -425,20 +423,20 @@ void Machine::Code::decoder::analyse_opc
     case PUT_COPY :
     {
       if (arg[0] != 0) { _analysis.set_changed(_analysis.slotref); _code._modify = true; }
       if (arg[0] <= 0 && -arg[0] <= _analysis.slotref - _analysis.contexts[_analysis.slotref].flags.inserted)
         _analysis.set_ref(_analysis.slotref + arg[0] - _analysis.contexts[_analysis.slotref].flags.inserted);
       else if (_analysis.slotref + arg[0] > _analysis.max_ref) _analysis.max_ref = _analysis.slotref + arg[0];
       break;
     }
-    case PUSH_ATT_TO_GATTR_OBS :
+    case PUSH_ATT_TO_GATTR_OBS : // slotref on 2nd parameter
         if (_code._constraint) return;
     case PUSH_GLYPH_ATTR_OBS :
-    case PUSH_SLOT_ATTR :       // slotref on 2nd parameter
+    case PUSH_SLOT_ATTR :
     case PUSH_GLYPH_METRIC :
     case PUSH_ATT_TO_GLYPH_METRIC :
     case PUSH_ISLOT_ATTR :
     case PUSH_FEAT :
       if (arg[1] <= 0 && -arg[1] <= _analysis.slotref - _analysis.contexts[_analysis.slotref].flags.inserted)
         _analysis.set_ref(_analysis.slotref + arg[1] - _analysis.contexts[_analysis.slotref].flags.inserted);
       else if (_analysis.slotref + arg[1] > _analysis.max_ref) _analysis.max_ref = _analysis.slotref + arg[1];
       break;
@@ -467,23 +465,22 @@ bool Machine::Code::decoder::emit_opcode
         return false;
     }
 
     const size_t     param_sz = op.param_sz == VARARGS ? bc[0] + 1 : op.param_sz;
 
     // Add this instruction
     *_instr++ = op.impl[_code._constraint]; 
     ++_code._instr_count;
-    emit_trace_message(opc, bc, op);
 
     // Grab the parameters
     if (param_sz) {
-        memmove(_data, bc, param_sz * sizeof(byte));
-        bc         += param_sz;
-        _data         += param_sz;
+        memcpy(_data, bc, param_sz * sizeof(byte));
+        bc               += param_sz;
+        _data            += param_sz;
         _code._data_size += param_sz;
     }
     
     // recursively decode a context item so we can split the skip into 
     // instruction and data portions.
     if (opc == CNTXT_ITEM)
     {
         assert(_pre_context == 0);
@@ -505,42 +502,16 @@ bool Machine::Code::decoder::emit_opcode
             _pre_context = 0;
         }
     }
     
     return bool(_code);
 }
 
 
-
-namespace {
-
-inline void emit_trace_message(opcode opc, const byte *const params, 
-                        const opcode_t &op)
-{
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementAction);
-        XmlTraceLog::get().addAttribute(AttrActionCode, opc);
-        XmlTraceLog::get().addAttribute(AttrAction, op.name);
-        for (size_t p = 0; p < 8 && p < op.param_sz; ++p)
-        {
-            XmlTraceLog::get().addAttribute(
-                                XmlTraceLogAttribute(Attr0 + p),
-                                params[p]);
-        }
-        XmlTraceLog::get().closeElement(ElementAction);
-    }
-#endif
-}
-
-} // end of namespace
-
-
 void Machine::Code::decoder::apply_analysis(instr * const code, instr * code_end)
 {
     // insert TEMP_COPY commands for slots that need them (that change and are referenced later)
     int tempcount = 0;
     if (_code._constraint) return;
 
     const instr temp_copy = Machine::getOpcodeTable()[TEMP_COPY].impl[0];
     for (const context * c = _analysis.contexts, * const ce = c + _analysis.slotref; c != ce; ++c)
@@ -579,43 +550,48 @@ bool Machine::Code::decoder::validate_op
 
 bool Machine::Code::decoder::valid_upto(const uint16 limit, const uint16 x) const throw()
 {
 	const bool t = x < limit;
     if (!t)	failure(out_of_range_data);
     return t;
 }
 
+
 inline 
 void Machine::Code::failure(const status_t s) throw() {
     release_buffers();
     _status = s;
 }
 
+
 inline
 void Machine::Code::decoder::analysis::set_ref(const int index) throw() {
     contexts[index].flags.referenced = true;
     if (index > max_ref) max_ref = index;
 }
 
+
 inline
 void Machine::Code::decoder::analysis::set_changed(const int index) throw() {
     contexts[index].flags.changed = true;
     if (index > max_ref) max_ref = index;
 }
 
+
 void Machine::Code::release_buffers() throw()
 {
     free(_code);
     free(_data);
     _code = 0;
     _data = 0;
     _own  = false;
 }
 
+
 int32 Machine::Code::run(Machine & m, slotref * & map) const
 {
     assert(_own);
     assert(*this);          // Check we are actually runnable
 
     if (m.slotMap().size() <= _max_ref + m.slotMap().context())
     {
         m._status = Machine::slot_offset_out_bounds;
deleted file mode 100644
--- a/gfx/graphite2/src/Code.h
+++ /dev/null
@@ -1,172 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-// This class represents loaded graphite stack machine code.  It performs 
-// basic sanity checks, on the incoming code to prevent more obvious problems
-// from crashing graphite.
-// Author: Tim Eves
-
-#pragma once
-
-#include <cassert>
-#include <graphite2/Types.h>
-#include "Main.h"
-#include "Machine.h"
-
-namespace graphite2 {
-
-class Silf;
-class Face;
-
-namespace vm {
-
-class Machine::Code
-{
-public:
-    enum status_t 
-    {
-        loaded,
-        alloc_failed, 
-        invalid_opcode, 
-        unimplemented_opcode_used,
-        out_of_range_data,
-        jump_past_end,
-        arguments_exhausted,
-        missing_return
-    };
-
-private:
-    class decoder;
-
-    instr *     _code;
-    byte  *     _data;
-    size_t      _data_size,
-                _instr_count;
-    byte        _max_ref;
-    mutable status_t _status;
-    bool        _constraint,
-                _modify,
-                _delete;
-    mutable bool _own;
-
-    void release_buffers() throw ();
-    void failure(const status_t) throw();
-
-public:
-    Code() throw();
-    Code(bool is_constraint, const byte * bytecode_begin, const byte * const bytecode_end,
-         uint8 pre_context, uint16 rule_length, const Silf &, const Face &);
-    Code(const Machine::Code &) throw();
-    ~Code() throw();
-    
-    Code & operator=(const Code &rhs) throw();
-    operator bool () const throw();
-    status_t      status() const throw();
-    bool          constraint() const throw();
-    size_t        dataSize() const throw();
-    size_t        instructionCount() const throw();
-    bool          immutable() const throw();
-    bool          deletes() const throw();
-    size_t        maxRef() const throw();
-
-    int32 run(Machine &m, slotref * & map) const;
-    
-    CLASS_NEW_DELETE;
-};
-
-inline Machine::Code::Code() throw()
-: _code(0), _data(0), _data_size(0), _instr_count(0), _max_ref(0),
-  _status(loaded), _own(false) {
-}
-
-inline Machine::Code::Code(const Machine::Code &obj) throw ()
- :  _code(obj._code), 
-    _data(obj._data), 
-    _data_size(obj._data_size), 
-    _instr_count(obj._instr_count),
-    _max_ref(obj._max_ref),
-    _status(obj._status), 
-    _constraint(obj._constraint),
-    _modify(obj._modify),
-    _delete(obj._delete),
-    _own(obj._own) 
-{
-    obj._own = false;
-}
-
-inline Machine::Code & Machine::Code::operator=(const Machine::Code &rhs) throw() {
-    if (_instr_count > 0)
-        release_buffers();
-    _code        = rhs._code; 
-    _data        = rhs._data;
-    _data_size   = rhs._data_size; 
-    _instr_count = rhs._instr_count;
-    _status      = rhs._status; 
-    _constraint  = rhs._constraint;
-    _modify      = rhs._modify;
-    _delete      = rhs._delete;
-    _own         = rhs._own; 
-    rhs._own = false;
-    return *this;
-}
-
-inline Machine::Code::operator bool () const throw () {
-    return _code && status() == loaded;
-}
-
-inline Machine::Code::status_t Machine::Code::status() const throw() {
-    return _status;
-}
-
-inline bool Machine::Code::constraint() const throw() {
-    return _constraint;
-}
-
-inline size_t Machine::Code::dataSize() const throw() {
-    return _data_size;
-}
-
-inline size_t Machine::Code::instructionCount() const throw() {
-    return _instr_count;
-}
-
-inline bool Machine::Code::immutable() const throw()
-{
-  return !(_delete || _modify);
-}
-
-inline bool Machine::Code::deletes() const throw()
-{
-  return _delete;
-}
-
-inline size_t Machine::Code::maxRef() const throw()
-{
-	return _max_ref;
-}
-
-} // namespace vm
-} // namespace graphite2
deleted file mode 100644
--- a/gfx/graphite2/src/Endian.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*-----------------------------------------------------------------------------
-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; }
-
--- a/gfx/graphite2/src/Face.cpp
+++ b/gfx/graphite2/src/Face.cpp
@@ -21,23 +21,22 @@
 
 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.
 */
 #include <cstring>
 #include "graphite2/Segment.h"
-#include "Face.h"
-#include "Endian.h"
-#include "Segment.h"
-#include "CmapCache.h"
-#include "NameTable.h"
-#include "SegCacheStore.h"
-#include "XmlTraceLog.h"
+#include "inc/Face.h"
+#include "inc/Endian.h"
+#include "inc/Segment.h"
+#include "inc/CmapCache.h"
+#include "inc/NameTable.h"
+#include "inc/SegCacheStore.h"
 
 
 using namespace graphite2;
 
 Face::~Face()
 {
     delete m_pGlyphFaceCache;
     delete m_cmap;
@@ -79,87 +78,44 @@ bool Face::readGlyphs(uint32 faceOptions
     if (!m_upem) return false;
     // m_glyphidx = new unsigned short[m_numGlyphs];        // only need this if doing occasional glyph reads
     
     return true;
 }
 
 bool Face::readGraphite()
 {
-    const byte *pSilf;
     size_t lSilf;
-    if ((pSilf = getTable(Tag::Silf, &lSilf)) == NULL) return false;
-    uint32 version;
-#ifndef DISABLE_TRACING
-    uint32 compilerVersion = 0; // wasn't set before GTF version 3
-#endif
-    uint32 offset32Pos = 2;
-    version = be::peek<uint32>(pSilf);
+    const byte * const pSilf = getTable(Tag::Silf, &lSilf),
+    		   *      p = pSilf;
+    if (!p) return false;
+
+    const uint32 version = be::read<uint32>(p);
     if (version < 0x00020000) return false;
     if (version >= 0x00030000)
-    {
-#ifndef DISABLE_TRACING
-        compilerVersion = be::swap<uint32>(((uint32 *)pSilf)[1]);
-#endif
-        m_numSilf = be::swap<uint16>(((uint16 *)pSilf)[4]);
-        offset32Pos = 3;
-    }
-    else
-        m_numSilf = be::swap<uint16>(((uint16 *)pSilf)[2]);
+    	be::skip<uint32>(p);		// compilerVersion
+    m_numSilf = be::read<uint16>(p);
+    be::skip<uint16>(p);			// reserved
 
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-            XmlTraceLog::get().openElement(ElementSilf);
-            XmlTraceLog::get().addAttribute(AttrMajor, version >> 16);
-            XmlTraceLog::get().addAttribute(AttrMinor, version & 0xFFFF);
-            XmlTraceLog::get().addAttribute(AttrCompilerMajor, compilerVersion >> 16);
-            XmlTraceLog::get().addAttribute(AttrCompilerMinor, compilerVersion & 0xFFFF);
-            XmlTraceLog::get().addAttribute(AttrNum, m_numSilf);
-            if (m_numSilf == 0)
-                XmlTraceLog::get().warning("No Silf subtables!");
-        }
-#endif
     bool havePasses = false;
     m_silfs = new Silf[m_numSilf];
     for (int i = 0; i < m_numSilf; i++)
     {
-        const uint32 offset = be::swap<uint32>(((uint32 *)pSilf)[offset32Pos + i]);
-        uint32 next;
-        if (i == m_numSilf - 1)
-            next = lSilf;
-        else
-            next = be::swap<uint32>(((uint32 *)pSilf)[offset32Pos + 1 + i]);
-        if (offset > lSilf || next > lSilf)
-        {
-#ifndef DISABLE_TRACING
-            XmlTraceLog::get().error("Invalid table %d offset %d length %u", i, offset, lSilf);
-            XmlTraceLog::get().closeElement(ElementSilf);
-#endif
+        const uint32 offset = be::read<uint32>(p),
+        			 next   = i == m_numSilf - 1 ? lSilf : be::peek<uint32>(p);
+        if (next > lSilf || offset >= next)
             return false;
-        }
-        if (!m_silfs[i].readGraphite((void *)((char *)pSilf + offset), next - offset, *this, version))
-        {
-#ifndef DISABLE_TRACING
-            if (XmlTraceLog::get().active())
-            {
-                XmlTraceLog::get().error("Error reading Graphite subtable %d", i);
-                XmlTraceLog::get().closeElement(ElementSilfSub); // for convenience
-                XmlTraceLog::get().closeElement(ElementSilf);
-            }
-#endif
+
+        if (!m_silfs[i].readGraphite(pSilf + offset, next - offset, *this, version))
             return false;
-        }
+
         if (m_silfs[i].numPasses())
             havePasses = true;
     }
 
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().closeElement(ElementSilf);
-#endif
     return havePasses;
 }
 
 bool Face::runGraphite(Segment *seg, const Silf *aSilf) const
 {
     return aSilf->runGraphite(seg, 0, aSilf->numPasses());
 }
 
@@ -206,17 +162,17 @@ uint16 Face::languageForLocale(const cha
 {
     nameTable();
     if (m_pNames)
         return m_pNames->getLanguageId(locale);
     return 0;
 }
 
 
-#ifndef DISABLE_FILE_FACE
+#ifndef GRAPHITE2_NFILEFACE
 
 FileFace::FileFace(const char *filename) :
     m_pHeader(NULL),
     m_pTableDir(NULL)
 {
     if (!(m_pfile = fopen(filename, "rb"))) return;
     if (fseek(m_pfile, 0, SEEK_END)) return;
     m_lfile = ftell(m_pfile);
@@ -288,9 +244,9 @@ const void *FileFace::table_fn(const voi
             free(tptr);
             return NULL;
         }
         tci->set(tptr, tlen);
     }
     if (len) *len = tci->size();
     return tci->data();
 }
-#endif                  //!DISABLE_FILE_FACE
+#endif                  //!GRAPHITE2_NFILEFACE
deleted file mode 100644
--- a/gfx/graphite2/src/Face.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include "Main.h"
-#include "GlyphFace.h"
-#include "Silf.h"
-#include "TtfUtil.h"
-#include "Main.h"
-#include "graphite2/Font.h"
-#include "FeatureMap.h"
-#include "GlyphFaceCache.h"
-
-#ifndef DISABLE_FILE_FACE
-#include <cstdio>
-#include <cassert>
-#include "TtfTypes.h"
-#endif      //!DISABLE_FILE_FACE
-
-namespace graphite2 {
-
-class Segment;
-class FeatureVal;
-class NameTable;
-class Cmap;
-
-using TtfUtil::Tag;
-
-// These are the actual tags, as distinct from the consecutive IDs in TtfUtil.h
-
-#ifndef DISABLE_FILE_FACE
-class TableCacheItem
-{
-public:
-    TableCacheItem(char * theData, size_t theSize) : m_data(theData), m_size(theSize) {}
-    TableCacheItem() : m_data(0), m_size(0) {}
-    ~TableCacheItem()
-    {
-        if (m_size) free(m_data);
-    }
-    void set(char * theData, size_t theSize) { m_data = theData; m_size = theSize; }
-    const void * data() const { return m_data; }
-    size_t size() const { return m_size; }
-private:
-    char * m_data;
-    size_t m_size;
-};
-#endif      //!DISABLE_FILE_FACE
-
-
-
-
-class FileFace
-{
-#ifndef DISABLE_FILE_FACE
-public:
-    static const void *table_fn(const void* appFaceHandle, unsigned int name, size_t *len);
-  
-    FileFace(const char *filename);
-    ~FileFace();
-//    virtual const void *getTable(unsigned int name, size_t *len) const;
-    bool isValid() const { return m_pfile && m_pHeader && m_pTableDir; }
-
-    CLASS_NEW_DELETE
-public:     //for local convenience    
-    FILE* m_pfile;
-    unsigned int m_lfile;
-    mutable TableCacheItem m_tables[18];
-    TtfUtil::Sfnt::OffsetSubTable* m_pHeader;
-    TtfUtil::Sfnt::OffsetSubTable::Entry* m_pTableDir;       //[] number of elements is determined by m_pHeader->num_tables
-#endif      //!DISABLE_FILE_FACE
-   
-private:        //defensive
-    FileFace(const FileFace&);
-    FileFace& operator=(const FileFace&);
-};
-
-class Face
-{
-public:
-    const byte *getTable(const Tag name, size_t  * len = 0) const {
-    	size_t tbl_len=0;
-    	const byte * const tbl = reinterpret_cast<const byte *>((*m_getTable)(m_appFaceHandle, name, &tbl_len));
-    	if (len) *len = tbl_len;
-    	return TtfUtil::CheckTable(name, tbl, tbl_len) ? tbl : 0;
-    }
-    float advance(unsigned short id) const { return m_pGlyphFaceCache->glyph(id)->theAdvance().x; }
-    const Silf *silf(int i) const { return ((i < m_numSilf) ? m_silfs + i : (const Silf *)NULL); }
-    virtual bool runGraphite(Segment *seg, const Silf *silf) const;
-    uint16 findPseudo(uint32 uid) const { return (m_numSilf) ? m_silfs[0].findPseudo(uid) : 0; }
-
-public:
-    Face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable2) : 
-        m_appFaceHandle(appFaceHandle), m_getTable(getTable2), m_pGlyphFaceCache(NULL),
-        m_cmap(NULL), m_numSilf(0), m_silfs(NULL), m_pFileFace(NULL),
-        m_pNames(NULL) {}
-    virtual ~Face();
-public:
-    float getAdvance(unsigned short glyphid, float scale) const { return advance(glyphid) * scale; }
-    const Rect &theBBoxTemporary(uint16 gid) const { return m_pGlyphFaceCache->glyph(gid)->theBBox(); }   //warning value may become invalid when another glyph is accessed
-    unsigned short upem() const { return m_upem; }
-    uint16 glyphAttr(uint16 gid, uint8 gattr) const { return m_pGlyphFaceCache->glyphAttr(gid, gattr); }
-
-private:
-    friend class Font;
-    unsigned short numGlyphs() const { return m_pGlyphFaceCache->m_nGlyphs; }
-
-public:
-    bool readGlyphs(uint32 faceOptions);
-    bool readGraphite();
-    bool readFeatures() { return m_Sill.readFace(*this); }
-    const Silf *chooseSilf(uint32 script) const;
-    const SillMap& theSill() const { return m_Sill; }
-    uint16 numFeatures() const { return m_Sill.m_FeatureMap.numFeats(); }
-    const FeatureRef *featureById(uint32 id) const { return m_Sill.m_FeatureMap.findFeatureRef(id); }
-    const FeatureRef *feature(uint16 index) const { return m_Sill.m_FeatureMap.feature(index); }
-    uint16 getGlyphMetric(uint16 gid, uint8 metric) const;
-
-    const GlyphFaceCache* getGlyphFaceCache() const { return m_pGlyphFaceCache; }      //never NULL
-    void takeFileFace(FileFace* pFileFace/*takes ownership*/);
-    Cmap & cmap() const { return *m_cmap; };
-    NameTable * nameTable() const;
-    uint16 languageForLocale(const char * locale) const;
-
-    CLASS_NEW_DELETE
-private:
-    const void* m_appFaceHandle/*non-NULL*/;
-    gr_get_table_fn m_getTable;
-    uint16 m_ascent;
-    uint16 m_descent;
-    // unsigned short *m_glyphidx;     // index for each glyph id in the font
-    // unsigned short m_readglyphs;    // how many glyphs have we in m_glyphs?
-    // unsigned short m_capacity;      // how big is m_glyphs
-    mutable GlyphFaceCache* m_pGlyphFaceCache;      //owned - never NULL
-    mutable Cmap * m_cmap; // cmap cache if available
-    unsigned short m_upem;          // design units per em
-protected:
-    unsigned short m_numSilf;       // number of silf subtables in the silf table
-    Silf *m_silfs;                   // silf subtables.
-private:
-    SillMap m_Sill;
-    FileFace* m_pFileFace;      //owned
-    mutable NameTable* m_pNames;
-    
-private:        //defensive on m_pGlyphFaceCache, m_pFileFace and m_silfs
-    Face(const Face&);
-    Face& operator=(const Face&);
-};
-
-} // namespace graphite2
-
-struct gr_face : public graphite2::Face {};
--- a/gfx/graphite2/src/FeatureMap.cpp
+++ b/gfx/graphite2/src/FeatureMap.cpp
@@ -21,32 +21,38 @@
 
 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.
 */
 #include <cstring>
 
-#include "Main.h"
-#include "Endian.h"
-#include "FeatureMap.h"
-#include "FeatureVal.h"
+#include "inc/Main.h"
+#include "inc/Endian.h"
+#include "inc/FeatureMap.h"
+#include "inc/FeatureVal.h"
 #include "graphite2/Font.h"
-#include "XmlTraceLog.h"
-#include "TtfUtil.h"
+#include "inc/TtfUtil.h"
 #include <cstdlib>
-#include "Face.h"
+#include "inc/Face.h"
 
 
 using namespace graphite2;
 
-static int cmpNameAndFeatures(const void *a, const void *b) { return (*(NameAndFeatureRef *)a < *(NameAndFeatureRef *)b 
-                                                                        ? -1 : (*(NameAndFeatureRef *)b < *(NameAndFeatureRef *)a 
-                                                                                    ? 1 : 0)); }
+namespace
+{
+	static int cmpNameAndFeatures(const void *ap, const void *bp)
+	{
+		const NameAndFeatureRef & a = *static_cast<const NameAndFeatureRef *>(ap),
+								& b = *static_cast<const NameAndFeatureRef *>(bp);
+		return (a < b ? -1 : (b < a ? 1 : 0));
+	}
+}
+
 
 bool FeatureMap::readFeats(const Face & face)
 {
     size_t lFeat;
     const byte *pFeat = face.getTable(TtfUtil::Tag::Feat, &lFeat);
     const byte *pOrig = pFeat;
     uint16 *defVals=0;
     uint32 version;
@@ -60,25 +66,16 @@ bool FeatureMap::readFeats(const Face & 
     be::skip<uint32>(pFeat);
     if (m_numFeats * 16U + 12 > lFeat) { m_numFeats = 0; return false; }		//defensive
     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
 
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementFeatures);
-        XmlTraceLog::get().addAttribute(AttrMajor, version >> 16);
-        XmlTraceLog::get().addAttribute(AttrMinor, version & 0xFFFF);
-        XmlTraceLog::get().addAttribute(AttrNum, m_numFeats);
-    }
-#endif
     for (int i = 0, ie = m_numFeats; i != ie; i++)
     {
         uint32 name;
         if (version < 0x00020000)
             name = be::read<uint16>(pFeat);
         else
             name = be::read<uint32>(pFeat);
         uint16 numSet = be::read<uint16>(pFeat);
@@ -96,56 +93,31 @@ bool FeatureMap::readFeats(const Face & 
             free(defVals);
             return false;
         }
         uint16 flags = be::read<uint16>(pFeat);
         uint16 uiName = be::read<uint16>(pFeat);
         const byte *pSet = pOrig + offset;
         uint16 maxVal = 0;
 
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-            XmlTraceLog::get().openElement(ElementFeature);
-            XmlTraceLog::get().addAttribute(AttrIndex, i);
-            XmlTraceLog::get().addAttribute(AttrNum, name);
-            XmlTraceLog::get().addAttribute(AttrFlags, flags);
-            XmlTraceLog::get().addAttribute(AttrLabel, uiName);
-        }
-#endif
-
         if (numSet == 0)
         {
             --m_numFeats;
-#ifndef DISABLE_TRACING
-            XmlTraceLog::get().closeElement(ElementFeature);
-#endif
             continue;
         }
 
         if (offset + numSet * 4 > lFeat) return false;
         FeatureSetting *uiSet = gralloc<FeatureSetting>(numSet);
         for (int j = 0; j < numSet; j++)
         {
             int16 val = be::read<int16>(pSet);
             if (val > maxVal) maxVal = val;
             if (j == 0) defVals[i] = val;
             uint16 label = be::read<uint16>(pSet);
             new (uiSet + j) FeatureSetting(label, val);
-#ifndef DISABLE_TRACING
-            if (XmlTraceLog::get().active())
-            {
-                XmlTraceLog::get().openElement(ElementFeatureSetting);
-                XmlTraceLog::get().addAttribute(AttrIndex, j);
-                XmlTraceLog::get().addAttribute(AttrValue, val);
-                XmlTraceLog::get().addAttribute(AttrLabel, label);
-                if (j == 0) XmlTraceLog::get().addAttribute(AttrDefault, defVals[i]);
-                XmlTraceLog::get().closeElement(ElementFeatureSetting);
-            }
-#endif
         }
         uint32 mask = 1;
         byte bits = 0;
         for (bits = 0; bits < 32; bits++, mask <<= 1)
         {
             if (mask > maxVal)
             {
                 if (bits + currBits > 32)
@@ -156,36 +128,29 @@ bool FeatureMap::readFeats(const Face & 
                 }
                 ::new (m_feats + i) FeatureRef (currBits, currIndex,
                                                (mask - 1) << currBits, flags,
                                                name, uiName, numSet, uiSet, &face);
                 currBits += bits;
                 break;
             }
         }
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().closeElement(ElementFeature);
-#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);
         m_pNamedFeats[i] = m_feats+i;
     }
     
     free(defVals);
 
     qsort(m_pNamedFeats, m_numFeats, sizeof(NameAndFeatureRef), &cmpNameAndFeatures);
 
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().closeElement(ElementFeatures);
-#endif
-
     return true;
 }
 
 bool SillMap::readFace(const Face & face)
 {
     if (!m_FeatureMap.readFeats(face)) return false;
     if (!readSill(face)) return false;
     return true;
deleted file mode 100644
--- a/gfx/graphite2/src/FeatureMap.h
+++ /dev/null
@@ -1,202 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-// #include <cstring>
-// #include "graphite2/Types.h"
-#include "graphite2/Font.h"
-#include "Main.h"
-#include "FeatureVal.h"
-
-namespace graphite2 {
-
-// Forward declarations for implmentation types
-class FeatureMap;
-class Face;
-
-
-class FeatureSetting
-{
-public:
-    FeatureSetting(uint16 labelId, int16 theValue) : m_label(labelId), m_value(theValue) {};
-    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;
-};
-
-class FeatureRef
-{
-public:
-    FeatureRef() :
-        m_nameValues(NULL), m_pFace(NULL)
-      {}
-    FeatureRef(byte bits, byte index, uint32 mask, uint16 flags,
-               uint32 name, uint16 uiName, uint16 numSet,
-               FeatureSetting *uiNames, const Face* pFace/*not NULL*/) throw()
-      : m_mask(mask), m_id(name), m_max((uint16)(mask >> bits)), m_bits(bits), m_index(index),
-      m_nameid(uiName), m_nameValues(uiNames), m_pFace(pFace), m_flags(flags),
-      m_numSet(numSet)
-      {}
-    FeatureRef(const FeatureRef & toCopy)
-        : m_mask(toCopy.m_mask), m_id(toCopy.m_id), m_max(toCopy.m_max),
-        m_bits(toCopy.m_bits), m_index(toCopy.m_index),
-        m_nameid(toCopy.m_nameid),
-        m_nameValues((toCopy.m_nameValues)? gralloc<FeatureSetting>(toCopy.m_numSet) : NULL),
-        m_pFace(toCopy.m_pFace), m_flags(toCopy.m_flags),
-        m_numSet(toCopy.m_numSet)
-    {
-        // most of the time these name values aren't used, so NULL might be acceptable
-        if (toCopy.m_nameValues)
-        {
-            memcpy(m_nameValues, toCopy.m_nameValues, sizeof(FeatureSetting) * m_numSet);
-        }
-    }
-    ~FeatureRef() {
-        free(m_nameValues);
-        m_nameValues = NULL;
-    }
-    bool applyValToFeature(uint16 val, Features& pDest) const; //defined in GrFaceImp.h
-    void maskFeature(Features & pDest) const {
-	if (m_index < pDest.size()) 				//defensive
-	    pDest[m_index] |= m_mask; 
-    }
-
-    uint16 getFeatureVal(const Features& feats) const; //defined in GrFaceImp.h
-
-    uint32 getId() const { return m_id; }
-    uint16 getNameId() const { return m_nameid; }
-    uint16 getNumSettings() const { return m_numSet; }
-    uint16 getSettingName(uint16 index) const { return m_nameValues[index].label(); }
-    int16 getSettingValue(uint16 index) const { return m_nameValues[index].value(); }
-    uint16 maxVal() const { return m_max; }
-    const Face* getFace() const { return m_pFace;}
-    const FeatureMap* getFeatureMap() const;// { return m_pFace;}
-
-    CLASS_NEW_DELETE;
-private:
-    uint32 m_mask;              // bit mask to get the value from the vector
-    uint32 m_id;                // feature identifier/name
-    uint16 m_max;               // max value the value can take
-    byte m_bits;                // how many bits to shift the value into place
-    byte m_index;               // index into the array to find the ulong to mask
-    uint16 m_nameid;            // Name table id for feature name
-    FeatureSetting *m_nameValues;       // array of name table ids for feature values
-    const Face* m_pFace;   //not NULL
-    uint16 m_flags;             // feature flags (unused at the moment but read from the font)
-    uint16 m_numSet;            // number of values (number of entries in m_nameValues)
-
-private:        //unimplemented
-    FeatureRef& operator=(const FeatureRef&);
-};
-
-
-class NameAndFeatureRef
-{
-  public:
-    NameAndFeatureRef() : m_pFRef(NULL) {}
-    NameAndFeatureRef(uint32 name) : m_name(name) {}
-    NameAndFeatureRef(const FeatureRef* p/*not NULL*/) : m_name(p->getId()), m_pFRef(p) {}
-
-    bool operator<(const NameAndFeatureRef& rhs) const //orders by m_name
-        {   return m_name<rhs.m_name; }
-
-    CLASS_NEW_DELETE
- 
-    uint32 m_name;
-    const FeatureRef* m_pFRef;
-};
-
-class FeatureMap
-{
-public:
-    FeatureMap() : m_numFeats(0), m_feats(NULL), m_pNamedFeats(NULL),
-        m_defaultFeatures(NULL) {}
-    ~FeatureMap() { delete[] m_feats; delete[] m_pNamedFeats; delete m_defaultFeatures; }
-
-    bool readFeats(const Face & face);
-    const FeatureRef *findFeatureRef(uint32 name) const;
-    FeatureRef *feature(uint16 index) const { return m_feats + index; }
-    //GrFeatureRef *featureRef(byte index) { return index < m_numFeats ? m_feats + index : NULL; }
-    const FeatureRef *featureRef(byte index) const { return index < m_numFeats ? m_feats + index : NULL; }
-    FeatureVal* cloneFeatures(uint32 langname/*0 means default*/) const;      //call destroy_Features when done.
-    uint16 numFeats() const { return m_numFeats; };
-    CLASS_NEW_DELETE
-private:
-friend class SillMap;
-    uint16 m_numFeats;
-
-    FeatureRef *m_feats;
-    NameAndFeatureRef* m_pNamedFeats;   //owned
-    FeatureVal* m_defaultFeatures;        //owned
-    
-private:		//defensive on m_feats, m_pNamedFeats, and m_defaultFeatures
-    FeatureMap(const FeatureMap&);
-    FeatureMap& operator=(const FeatureMap&);
-};
-
-
-class SillMap
-{
-private:
-    class LangFeaturePair
-    {
-    public:
-        LangFeaturePair() : m_pFeatures(NULL) {}
-        ~LangFeaturePair() { delete m_pFeatures; }
-        
-        uint32 m_lang;
-        Features* m_pFeatures;      //owns
-        CLASS_NEW_DELETE
-    };
-public:
-    SillMap() : m_langFeats(NULL), m_numLanguages(0) {}
-    ~SillMap() { delete[] m_langFeats; }
-    bool readFace(const Face & face);
-    bool readSill(const Face & face);
-    FeatureVal* cloneFeatures(uint32 langname/*0 means default*/) const;      //call destroy_Features when done.
-    uint16 numLanguages() const { return m_numLanguages; };
-    uint32 getLangName(uint16 index) const { return (index < m_numLanguages)? m_langFeats[index].m_lang : 0; };
-
-    const FeatureMap & theFeatureMap() const { return m_FeatureMap; };
-private:
-friend class Face;
-    FeatureMap m_FeatureMap;        //of face
-    LangFeaturePair * m_langFeats;
-    uint16 m_numLanguages;
-
-private:        //defensive on m_langFeats
-    SillMap(const SillMap&);
-    SillMap& operator=(const SillMap&);
-};
-
-} // namespace graphite2
-
-struct gr_feature_ref : public graphite2::FeatureRef {};
deleted file mode 100644
--- a/gfx/graphite2/src/FeatureVal.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-#include <cstring>
-#include <cassert>
-#include "Main.h"
-#include "List.h"
-
-namespace graphite2 {
-
-class FeatureRef;
-class FeatureMap;
-
-class FeatureVal : public Vector<uint32>
-{
-public:
-    uint32 maskedOr(const FeatureVal &other, const FeatureVal &mask) {
-        uint32 len = size() ;
-        if (other.size()<len) len = other.size();		//defensive
-        if (mask.size()<len) len = mask.size();		//defensive
-        for (uint32 i = 0; i < len; i++)
-            if (mask[i]) operator[](i) = (operator[](i) & ~mask[i]) | (other[i] & mask[i]);
-        return len;
-    }
-
-    FeatureVal() : m_pMap(0) { }
-    FeatureVal(int num, const FeatureMap & pMap) : Vector<uint32>(num), m_pMap(&pMap) {}
-    FeatureVal(const FeatureVal & rhs) : Vector<uint32>(rhs), m_pMap(rhs.m_pMap) {}
-
-    bool operator ==(const FeatureVal & b) const
-    {
-        size_t n = size();
-        if (n != b.size())      return false;
-        
-        for(const_iterator l = begin(), r = b.begin(); n && *l == *r; --n, ++l, ++r);
-        
-        return n == 0;
-    }
-
-    CLASS_NEW_DELETE
-private:
-    friend class FeatureRef;		//so that FeatureRefs can manipulate m_vec directly
-    const FeatureMap* m_pMap;
-};
-
-typedef FeatureVal Features;
-
-} // namespace graphite2
-
-
-struct gr_feature_val : public graphite2::FeatureVal {};
--- a/gfx/graphite2/src/Font.cpp
+++ b/gfx/graphite2/src/Font.cpp
@@ -19,17 +19,17 @@
     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.
 */
-#include "Font.h"
+#include "inc/Font.h"
 
 
 using namespace graphite2;
 
 Font::Font(float ppm, const Face *face/*needed for scaling*/) :
     m_scale(ppm / face->upem())
 {
     size_t nGlyphs=face->numGlyphs();
deleted file mode 100644
--- a/gfx/graphite2/src/Font.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-#include <cassert>
-#include "graphite2/Font.h"
-#include "Main.h"
-#include "Face.h"
-
-namespace graphite2 {
-
-#define INVALID_ADVANCE -1e38f		// can't be a static const because non-integral
-
-class Font
-{
-public:
-    Font(float ppm, const Face *face/*needed for scaling*/);
-    virtual ~Font();
-
-    float advance(unsigned short glyphid) const {
-        if (m_advances[glyphid] == INVALID_ADVANCE)
-            m_advances[glyphid] = computeAdvance(glyphid);
-        return m_advances[glyphid];
-    }
-//    Position scale(const Position& p) const { return Position(m_scale * p.x, m_scale * p.y); }
-//    float scale(float p) const { return m_scale * p; }
-    float scale() const { return m_scale; }
-    virtual bool isHinted() const { return false; }
-
-    CLASS_NEW_DELETE
-private:
-    virtual float computeAdvance(unsigned short /*glyphid*/) const { assert(false); return .0f; };
-    
-protected:
-    float m_scale;      // scales from design units to ppm
-    float *m_advances;  // One advance per glyph in pixels. Nan if not defined
-    
-private:			//defensive on m_advances
-    Font(const Font&);
-    Font& operator=(const Font&);
-};
-
-
-class SimpleFont : public Font      //has no external hints - gets advance information from the face
-{
-public:
-    SimpleFont(float ppm/*pixels per em*/, const Face *face);
-private:
-    virtual float computeAdvance(unsigned short glyphid) const;
-private:
-    const Face *m_face;   // GrFace to get the rest of the info from
-};
-
-
-class HintedFont : public Font
-{
-public:
-    HintedFont(float ppm/*pixels per em*/, const void* appFontHandle/*non-NULL*/, gr_advance_fn advance, const Face *face/*needed for scaling*/);
-    virtual bool isHinted() const { return true; }
-private:
-    virtual float computeAdvance(unsigned short glyphid) const;
-
-private:
-    const void* m_appFontHandle/*non-NULL*/;
-    gr_advance_fn m_advance;
-};
-
-} // namespace graphite2
-
-struct gr_font : public graphite2::Font {};
--- a/gfx/graphite2/src/GlyphFace.cpp
+++ b/gfx/graphite2/src/GlyphFace.cpp
@@ -20,21 +20,20 @@
     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.
 */
 #include <iterator>
-#include "GlyphFace.h"
-#include "XmlTraceLog.h"
-#include "GlyphFaceCache.h"
-#include "TtfUtil.h"
-#include "Endian.h"
+#include "inc/GlyphFace.h"
+#include "inc/GlyphFaceCache.h"
+#include "inc/TtfUtil.h"
+#include "inc/Endian.h"
 
 
 using namespace graphite2;
 
 namespace
 {
 	struct glyph_attr { uint16 id, value; };
 
@@ -74,66 +73,60 @@ namespace
 			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; }
 	};
 }
 
+
+
 GlyphFace::GlyphFace(const GlyphFaceCacheHeader& hdr, unsigned short glyphid)
 {
     if (glyphid < hdr.m_nGlyphsWithGraphics)
     {
         int nLsb, xMin, yMin, xMax, yMax;
         unsigned int nAdvWid;
         size_t locidx = TtfUtil::LocaLookup(glyphid, hdr.m_pLoca, hdr.m_lLoca, hdr.m_pHead);
         void *pGlyph = TtfUtil::GlyfLookup(hdr.m_pGlyf, locidx, hdr.m_lGlyf);
         if (TtfUtil::HorMetrics(glyphid, hdr.m_pHmtx, hdr.m_lHmtx, hdr.m_pHHea, nLsb, nAdvWid))
             m_advance = Position(static_cast<float>(nAdvWid), 0);
         else
             m_advance = Position();
         if (pGlyph && TtfUtil::GlyfBox(pGlyph, xMin, yMin, xMax, yMax))
             m_bbox = Rect(Position(static_cast<float>(xMin), static_cast<float>(yMin)),
-//                    Position(static_cast<float>(xMax - xMin), static_cast<float>(yMax - yMin)));
                 Position(static_cast<float>(xMax), static_cast<float>(yMax)));
         else
             m_bbox = Rect();
     }
     else
     {
         m_advance = Position();
         m_bbox = Rect();
     }
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementGlyphFace);
-        XmlTraceLog::get().addAttribute(AttrGlyphId, glyphid);
-        XmlTraceLog::get().addAttribute(AttrAdvanceX, m_advance.x);
-        XmlTraceLog::get().addAttribute(AttrAdvanceY, m_advance.y);
-    }
-#endif
     if (glyphid < hdr.m_nGlyphsWithAttributes)
     {
         size_t glocs, gloce;
+        const byte * gloc = hdr.m_pGloc;
+
         if (hdr.m_locFlagsUse32Bit)
         {
-            glocs = be::swap<uint32>(((uint32 *)hdr.m_pGloc)[2+glyphid]);
-            gloce = be::swap<uint32>(((uint32 *)hdr.m_pGloc)[3+glyphid]);
+        	be::skip<uint32>(gloc, glyphid);
+            glocs = be::read<uint32>(gloc);
+            gloce = be::read<uint32>(gloc);
         }
         else
         {
-            glocs = be::swap<uint16>(((uint16 *)hdr.m_pGloc)[4+glyphid]);
-            gloce = be::swap<uint16>(((uint16 *)hdr.m_pGloc)[5+glyphid]);
+        	be::skip<uint16>(gloc, glyphid);
+            glocs = be::read<uint16>(gloc);
+            gloce = be::read<uint16>(gloc);
         }
         if (glocs < hdr.m_lGlat && gloce <= hdr.m_lGlat)
         {
-//            m_attrs = grzeroalloc<uint16>(hdr.m_numAttrs);
-//            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 < 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));
         	}
@@ -148,98 +141,19 @@ GlyphFace::GlyphFace(const GlyphFaceCach
 
         	if (m_attrs.size() > hdr.m_numAttrs)
         	{
         		m_attrs.~sparse();
         		new (&m_attrs) sparse();
         	}
         }
     }
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().closeElement(ElementGlyphFace);
-#endif
 }
 
 
-//void GlyphFace::readAttrs(const byte *glat, const byte * const glat_end, uint16 * attrs, size_t num, uint32 format)
-//{
-//	glat_iterator::value_type v;
-//
-//	if (format < 0x00020000)
-//	{
-//		for (glat_iterator i = glat, end = glat_end; i != end; ++i)
-//		{
-//			v = *i;
-//			if (v.id >= num) break;
-//			attrs[v.id] = v.value;
-//		}
-//	}
-//	else
-//	{
-//		for (glat2_iterator i = glat, end = glat_end; i != end; ++i)
-//		{
-//			v = *i;
-//			if (v.id >= num) break;
-//			attrs[v.id] = v.value;
-//		}
-//	}
-//
-//	if (v.id >= num) {
-//#ifndef DISABLE_TRACING
-//		XmlTraceLog::get().warning("Invalid glat entry: attr id %d max id %d", v.id, num);
-//#endif
-//	}
-//
-//	const byte * 		glat 		= static_cast<const byte *>(pGlat) + start,
-//			   * const 	glat_end 	= glat + end - start;
-
-
-//	while (glat < glat_end)
-//	{
-//		uint16 * attr, * attr_end;
-//
-//		if (format < 0x00020000)
-//		{
-//			attr = attrs + *glat++; attr_end = attr + *glat++;
-//		}
-//		else
-//		{
-//			attr = attrs + be::read<uint16>(glat); attr_end = attr + be::read<uint16>(glat);
-//		}
-//
-//		if (attr_end > attrs + num)
-//		{
-//#ifndef DISABLE_TRACING
-//			XmlTraceLog::get().warning("Invalid glat entry: attr id %d count %d", *attr, attr_end - attr);
-//#endif
-//			return;
-//		}
-//		while (attr != attr_end)
-//		{
-//			*attr++ = be::read<uint16>(glat);
-//			logAttr(attrs, attr-1);
-//		}
-//	}
-//}
-
-
-inline
-void GlyphFace::logAttr(GR_MAYBE_UNUSED const uint16 attrs[], GR_MAYBE_UNUSED const uint16 * attr)
-{
-#ifndef DISABLE_TRACING
-	if (XmlTraceLog::get().active())
-	{
-		XmlTraceLog::get().openElement(ElementAttr);
-		XmlTraceLog::get().addAttribute(AttrAttrId, attr - attrs);
-		XmlTraceLog::get().addAttribute(AttrAttrVal, *attr);
-		XmlTraceLog::get().closeElement(ElementAttr);
-	}
-#endif
-}
-
 
 uint16 GlyphFace::getMetric(uint8 metric) const
 {
     switch (metrics(metric))
     {
         case kgmetLsb : return static_cast<uint16>(m_bbox.bl.x);
         case kgmetRsb : return static_cast<uint16>(m_advance.x - m_bbox.tr.x);
         case kgmetBbTop : return static_cast<uint16>(m_bbox.tr.y);
deleted file mode 100644
--- a/gfx/graphite2/src/GlyphFace.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include "Main.h"
-#include "XmlTraceLog.h"
-#include "Main.h"
-#include "Position.h"
-#include "Sparse.h"
-
-namespace graphite2 {
-
-enum metrics {
-    kgmetLsb = 0, kgmetRsb,
-    kgmetBbTop, kgmetBbBottom, kgmetBbLeft, kgmetBbRight,
-    kgmetBbHeight, kgmetBbWidth,
-    kgmetAdvWidth, kgmetAdvHeight,
-    kgmetAscent, kgmetDescent
-};
-
-class Rect
-{
-public :
-    Rect() {}
-    Rect(const Position& botLeft, const Position& topRight): bl(botLeft), tr(topRight) {}
-    Rect widen(const Rect& other) { return Rect(Position(bl.x > other.bl.x ? other.bl.x : bl.x, bl.y > other.bl.y ? other.bl.y : bl.y), Position(tr.x > other.tr.x ? tr.x : other.tr.x, tr.y > other.tr.y ? tr.y : other.tr.y)); }
-    Rect operator + (const Position &a) const { return Rect(Position(bl.x + a.x, bl.y + a.y), Position(tr.x + a.x, tr.y + a.y)); }
-    Rect operator * (float m) const { return Rect(Position(bl.x, bl.y) * m, Position(tr.x, tr.y) * m); }
-
-    Position bl;
-    Position tr;
-};
-
-class XmlTraceLog;
-class GlyphFaceCacheHeader;
-
-class GlyphFace
-{
-private:
-friend class GlyphFaceCache;
-    GlyphFace(const GlyphFaceCacheHeader& hdr, unsigned short glyphid);
-    ~GlyphFace() throw();
-
-public:
-
-    const Position    & theAdvance() const;
-    const Rect &theBBox() const { return m_bbox; }
-    uint16  getAttr(uint8 index) const { 
-        if (m_attrs)
-            return m_attrs[index];
-#ifdef ENABLE_DEEP_TRACING
-        XmlTraceLog::get().warning("No attributes for glyph attr %d", index);
-#endif
-        return 0;
-    }
-    uint16  getMetric(uint8 metric) const;
-
-private:
-//    static void readAttrs(const byte *glat, const byte * const glat_end, uint16 * attrs, size_t num, uint32 format);       //only called from constructor
-    static void logAttr(const uint16 attrs[], const uint16 * attr);
-
-private:
-    Rect     m_bbox;        // bounding box metrics in design units
-    Position m_advance;     // Advance width and height in design units
-    sparse   m_attrs;
-};
-
-
-inline GlyphFace::~GlyphFace() throw() {
-}
-
-inline const Position & GlyphFace::theAdvance() const { 
-    return m_advance;
-}
-
-} // namespace graphite2
--- a/gfx/graphite2/src/GlyphFaceCache.cpp
+++ b/gfx/graphite2/src/GlyphFaceCache.cpp
@@ -19,20 +19,20 @@
     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.
 */
-#include "GlyphFaceCache.h"
+#include "inc/GlyphFaceCache.h"
 #include "graphite2/Font.h"
-#include "Face.h"     //for the tags
-#include "Endian.h"
+#include "inc/Face.h"     //for the tags
+#include "inc/Endian.h"
 
 using namespace graphite2;
 
 /*virtual*/ bool GlyphFaceCacheHeader::initialize(const Face & face, const bool dumb_font)    //return result indicates success. Do not use if failed.
 {
     if ((m_pLoca = face.getTable(Tag::loca, &m_lLoca)) == NULL) return false;
     if ((m_pHead = face.getTable(Tag::head)) == NULL) return false;
     if ((m_pGlyf = face.getTable(Tag::glyf, &m_lGlyf)) == NULL) return false;
@@ -45,23 +45,23 @@ using namespace graphite2;
     
     if (!dumb_font)
     {
 		if ((m_pGlat = face.getTable(Tag::Glat, &m_lGlat)) == NULL) return false;
 		m_fGlat = be::peek<uint32>(m_pGlat);
 		size_t lGloc;
 		if ((m_pGloc = face.getTable(Tag::Gloc, &lGloc)) == NULL) return false;
 		if (lGloc < 6) return false;
-		int version = be::peek<uint32>(m_pGloc);
+		int version = be::read<uint32>(m_pGloc);
 		if (version != 0x00010000) return false;
 
-		m_numAttrs = be::swap<uint16>(((uint16 *)m_pGloc)[3]);
+		const uint16 locFlags = be::read<uint16>(m_pGloc);
+		m_numAttrs = be::read<uint16>(m_pGloc);
 		if (m_numAttrs > 0x1000) return false;                  // is this hard limit appropriate?
 
-		unsigned short locFlags = be::swap<uint16>(((uint16 *)m_pGloc)[2]);
 		if (locFlags & 1)
 		{
 			m_locFlagsUse32Bit = true;
 			m_nGlyphsWithAttributes = (unsigned short)((lGloc - 12) / 4);
 		}
 		else
 		{
 			m_locFlagsUse32Bit = false;
deleted file mode 100644
--- a/gfx/graphite2/src/GlyphFaceCache.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include "GlyphFace.h"
-#include "graphite2/Font.h"
-
-namespace graphite2 {
-
-class Segment;
-class Face;
-class FeatureVal;
-
-
-class GlyphFaceCacheHeader
-{
-public:
-    bool initialize(const Face & face, const bool dumb_font);    //return result indicates success. Do not use if failed.
-    unsigned short numGlyphs() const { return m_nGlyphs; }
-    unsigned short numAttrs() const { return m_numAttrs; }
-
-private:
-friend class Face;
-friend class GlyphFace;
-    const byte* m_pHead,
-    		  * m_pHHea,
-    		  * m_pHmtx,
-    		  * m_pGlat,
-    		  * m_pGloc,
-    		  * m_pGlyf,
-    		  * m_pLoca;
-    size_t		m_lHmtx,
-    			m_lGlat,
-    			m_lGlyf,
-    			m_lLoca;
-
-    uint32			m_fGlat;
-    unsigned short 	m_numAttrs,					// number of glyph attributes per glyph
-    				m_nGlyphsWithGraphics,		//i.e. boundary box and advance
-    				m_nGlyphsWithAttributes,
-    				m_nGlyphs;					// number of glyphs in the font. Max of the above 2.
-    bool 			m_locFlagsUse32Bit;
-};
-
-class GlyphFaceCache : public GlyphFaceCacheHeader
-{
-public:
-    static GlyphFaceCache* makeCache(const GlyphFaceCacheHeader& hdr /*, EGlyphCacheStrategy requested */);
-
-    GlyphFaceCache(const GlyphFaceCacheHeader& hdr);
-    ~GlyphFaceCache();
-
-    const GlyphFace *glyphSafe(unsigned short glyphid) const { return glyphid<numGlyphs()?glyph(glyphid):NULL; }
-    uint16 glyphAttr(uint16 gid, uint8 gattr) const { if (gattr>=numAttrs()) return 0; const GlyphFace*p=glyphSafe(gid); return p?p->getAttr(gattr):0; }
-
-    void * operator new (size_t s, const GlyphFaceCacheHeader& hdr)
-    {
-        return malloc(s + sizeof(GlyphFace*)*hdr.numGlyphs());
-    }
-    // delete in case an exception is thrown in constructor
-    void operator delete(void* p, const GlyphFaceCacheHeader& ) throw()
-    {
-        free(p);
-    }
-
-    const GlyphFace *glyph(unsigned short glyphid) const;      //result may be changed by subsequent call with a different glyphid
-    void loadAllGlyphs();
-
-    CLASS_NEW_DELETE
-    
-private:
-    GlyphFace **glyphPtrDirect(unsigned short glyphid) const { return (GlyphFace **)((const char*)(this)+sizeof(GlyphFaceCache)+sizeof(GlyphFace*)*glyphid);}
-
-private:      //defensive
-    GlyphFaceCache(const GlyphFaceCache&);
-    GlyphFaceCache& operator=(const GlyphFaceCache&);
-};
-
-} // namespace graphite2
deleted file mode 100644
--- a/gfx/graphite2/src/List.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-
-// designed to have a limited subset of the std::vector api
-#pragma once
-
-#include <cassert>
-#include <cstring>
-#include <cstdlib>
-#include <new>
-
-
-namespace graphite2 {
-
-template <typename T> 
-inline
-ptrdiff_t distance(T* first, T* last) { return last-first; }
-
-
-template <typename T> 
-class Vector
-{
-    T * m_first, *m_last, *m_end;
-public:
-    typedef       T &   reference;
-    typedef const T &   const_reference;
-    typedef       T *   iterator;
-    typedef const T *   const_iterator;
-
-    Vector() : m_first(0), m_last(0), m_end(0) {}
-    Vector(size_t n, const T& value = T())      : m_first(0), m_last(0), m_end(0) { insert(begin(), n, value); }
-    Vector(const Vector<T> &rhs)                : m_first(0), m_last(0), m_end(0) { insert(begin(), rhs.begin(), rhs.end()); }
-    template <typename I> 
-    Vector(I first, const I last)               : m_first(0), m_last(0), m_end(0) { insert(begin(), first, last); }
-    ~Vector() { clear(); free(m_first); }
-    
-    iterator            begin()         { return m_first; }
-    const_iterator      begin() const   { return m_first; }
-
-    iterator            end()           { return m_last; }
-    const_iterator      end() const     { return m_last; }
-    
-    bool                empty() const   { return m_first == m_last; }
-    size_t              size() const    { return m_last - m_first; }
-    size_t              capacity() const{ return m_end - m_first; }
-    
-    void                reserve(size_t n);
-    
-    reference           front()         { assert(size() > 0); return *begin(); }
-    const_reference     front() const   { assert(size() > 0); return *begin(); }
-    reference           back()          { assert(size() > 0); return *(end()-1); }
-    const_reference     back() const    { assert(size() > 0); return *(end()-1); }
-    
-    Vector<T>         & operator = (const Vector<T> & rhs) { assign(rhs.begin(), rhs.end()); return *this; }
-    reference           operator [] (size_t n)          { assert(size() > n); return m_first[n]; }
-    const_reference     operator [] (size_t n) const    { assert(size() > n); return m_first[n]; }
-    
-    void                assign(size_t n, const T& u)    { clear(); insert(begin(), n, u); }
-    void                assign(const_iterator first, const_iterator last)      { clear(); insert(begin(), first, last); }
-    iterator            insert(iterator p, const T & x) { p = _insert_default(p, 1); *p = x; return p; }
-    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                clear()                 { erase(begin(), end()); }
-    iterator            erase(iterator p)       { return erase(p, p+1); }
-    iterator            erase(iterator first, iterator last);
-
-private:
-    iterator            _insert_default(iterator p, size_t n);
-};
-    
-template <typename T>
-inline 
-void Vector<T>::reserve(size_t n)
-{
-    if (n > capacity()) 
-    {
-        const ptrdiff_t sz = size();
-        m_first = static_cast<T*>(realloc(m_first, n*sizeof(T)));
-        m_last  = m_first + sz;
-        m_end   = m_first + n;
-    }
-}
-
-template<typename T> 
-inline 
-typename Vector<T>::iterator Vector<T>::_insert_default(iterator p, size_t n)
-{
-    assert(begin() <= p && p <= end());
-    const ptrdiff_t i = p - begin();
-    reserve((size() + n + 7) >> 3 << 3);
-    p = begin() + i;
-    // Move tail if there is one
-    if (p != end()) memmove(p + n, p, distance(p,end())*sizeof(T));
-    m_last += n;
-    return p;
-}
-
-template<typename T> 
-inline 
-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); }
-}
-
-template<typename T>
-inline 
-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); }
-}
-
-template<typename T>
-inline
-typename Vector<T>::iterator Vector<T>::erase(iterator first, iterator last)
-{
-    for (iterator e = first; e != last; ++e) e->~T();
-    const size_t sz = distance(first, last);
-    if (m_last != last) memmove(first, last, distance(last,end())*sizeof(T));
-    m_last -= sz;
-    return first;
-}
-
-} // namespace graphite2
deleted file mode 100644
--- a/gfx/graphite2/src/Machine.h
+++ /dev/null
@@ -1,197 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-// This general interpreter interface.
-// Author: Tim Eves
-
-// Build one of direct_machine.cpp or call_machine.cpp to implement this 
-// interface.
-
-#pragma once
-#include <cstring>
-#include <graphite2/Types.h>
-#include "Main.h"
-
-#if defined(__GNUC__)
-#define     HOT             __attribute__((hot))
-#if defined(__x86_64)
-#define     REGPARM(n)      __attribute__((hot, regparm(n)))
-#else
-#define     REGPARM(n)
-#endif
-#else
-#define     HOT
-#define     REGPARM(n)
-#endif
-
-namespace graphite2 {
-
-// Forward declarations
-class Segment;
-class Slot;
-class SlotMap;
-
-
-namespace vm 
-{
-
-
-typedef void * instr;
-typedef Slot * slotref;
-
-enum {VARARGS = 0xff, MAX_NAME_LEN=32};
-
-enum opcode {
-    NOP = 0,
-
-    PUSH_BYTE,      PUSH_BYTEU,     PUSH_SHORT,     PUSH_SHORTU,    PUSH_LONG,
-
-    ADD,            SUB,            MUL,            DIV,
-    MIN_,           MAX_,
-    NEG,
-    TRUNC8,         TRUNC16,
-
-    COND,
-
-    AND,            OR,             NOT,
-    EQUAL,          NOT_EQ,
-    LESS,           GTR,            LESS_EQ,        GTR_EQ,
-
-    NEXT,           NEXT_N,         COPY_NEXT,
-    PUT_GLYPH_8BIT_OBS,              PUT_SUBS_8BIT_OBS,   PUT_COPY,
-    INSERT,         DELETE,
-    ASSOC,
-    CNTXT_ITEM,
-
-    ATTR_SET,       ATTR_ADD,       ATTR_SUB,
-    ATTR_SET_SLOT,
-    IATTR_SET_SLOT,
-    PUSH_SLOT_ATTR,                 PUSH_GLYPH_ATTR_OBS,
-    PUSH_GLYPH_METRIC,              PUSH_FEAT,
-    PUSH_ATT_TO_GATTR_OBS,          PUSH_ATT_TO_GLYPH_METRIC,
-    PUSH_ISLOT_ATTR,
-
-    PUSH_IGLYPH_ATTR,    // not implemented
-
-    POP_RET,                        RET_ZERO,           RET_TRUE,
-    IATTR_SET,                      IATTR_ADD,          IATTR_SUB,
-    PUSH_PROC_STATE,                PUSH_VERSION,
-    PUT_SUBS,                       PUT_SUBS2,          PUT_SUBS3,
-    PUT_GLYPH,                      PUSH_GLYPH_ATTR,    PUSH_ATT_TO_GLYPH_ATTR,
-    MAX_OPCODE,
-    // private opcodes for internal use only, comes after all other on disk opcodes
-    TEMP_COPY = MAX_OPCODE
-};
-
-struct opcode_t 
-{
-    instr           impl[2];
-    uint8           param_sz;
-    char            name[MAX_NAME_LEN];
-};
-
-
-class Machine
-{
-public:
-    typedef int32  stack_t;
-    static size_t const STACK_ORDER  = 10,
-                        STACK_MAX    = 1 << STACK_ORDER,
-                        STACK_GUARD  = 2;
-
-    class Code;
-
-    enum status_t {
-        finished = 0,
-        stack_underflow,
-        stack_not_empty,
-        stack_overflow,
-        slot_offset_out_bounds
-    };
-
-    Machine(SlotMap &) throw();
-    static const opcode_t *   getOpcodeTable() throw();
-
-    CLASS_NEW_DELETE;
-
-    SlotMap   & slotMap() const throw();
-    status_t	status() const throw();
-    operator bool () const throw();
-
-private:
-    void    check_final_stack(const stack_t * const sp);
-    stack_t run(const instr * program, const byte * data,
-                slotref * & map) HOT;
-
-    SlotMap       & _map;
-    stack_t         _stack[STACK_MAX + 2*STACK_GUARD];
-    status_t		_status;
-};
-
-inline Machine::Machine(SlotMap & map) throw()
-: _map(map), _status(finished)
-{
-	memset(_stack, 0, STACK_GUARD);
-}
-
-inline SlotMap& Machine::slotMap() const throw()
-{
-    return _map;
-}
-
-inline Machine::status_t Machine::status() const throw()
-{
-    return _status;
-}
-
-inline void Machine::check_final_stack(const int32 * const sp)
-{
-    stack_t const * const base  = _stack + STACK_GUARD,
-                  * const limit = base + STACK_MAX;
-    if      (sp <  base)    _status = stack_underflow;       // This should be impossible now.
-    else if (sp >= limit)   _status = stack_overflow;        // So should this.
-    else if (sp != base)    _status = stack_not_empty;
-    else                    _status = finished;
-}
-
-} // namespace vm
-} // namespace graphite2
-
-#ifdef ENABLE_DEEP_TRACING
-#define STARTTRACE(name,is) if (XmlTraceLog::get().active()) { \
-                                XmlTraceLog::get().openElement(ElementOpCode); \
-                                XmlTraceLog::get().addAttribute(AttrName, # name); \
-                                XmlTraceLog::get().addAttribute(AttrIndex, unsigned(map - smap.begin())); \
-                            }
-
-#define ENDTRACE            XmlTraceLog::get().closeElement(ElementOpCode)
-#else // ENABLE_DEEP_TRACING
-#define STARTTRACE(name,is)
-#define ENDTRACE
-#endif // ENABLE_DEEP_TRACING
-
-
-
deleted file mode 100644
--- a/gfx/graphite2/src/Main.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include <cstdlib>
-#include "graphite2/Types.h"
-
-#ifdef GR2_CUSTOM_HEADER
-#include GR2_CUSTOM_HEADER
-#endif
-
-namespace graphite2 {
-
-typedef gr_uint8        uint8;
-typedef gr_uint8        byte;
-typedef gr_uint16       uint16;
-typedef gr_uint32       uint32;
-typedef gr_int8         int8;
-typedef gr_int16        int16;
-typedef gr_int32        int32;
-typedef size_t          uintptr;
-
-// typesafe wrapper around malloc for simple types
-// use free(pointer) to deallocate
-template <typename T> T * gralloc(size_t n)
-{
-    return reinterpret_cast<T*>(malloc(sizeof(T) * n));
-}
-
-template <typename T> T * grzeroalloc(size_t n)
-{
-    return reinterpret_cast<T*>(calloc(n, sizeof(T)));
-}
-
-} // namespace graphite2
-
-#define CLASS_NEW_DELETE \
-    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))
-#else
-#define GR_MAYBE_UNUSED
-#endif
--- a/gfx/graphite2/src/Makefile.in
+++ b/gfx/graphite2/src/Makefile.in
@@ -69,18 +69,21 @@ FORCE_STATIC_LIB = 1
 FORCE_USE_PIC = 1
 
 include $(topsrcdir)/config/rules.mk
 
 DEFINES += -DPACKAGE_VERSION="\"moz\""
 DEFINES += -DPACKAGE_BUGREPORT="\"http://bugzilla.mozilla.org/\""
 
 # disable features we don't need in the graphite2 code, to reduce code size
-DEFINES += -DDISABLE_FILE_FACE -DDISABLE_TRACING -DDISABLE_SEGCACHE
+DEFINES += -DGRAPHITE2_NFILEFACE -DGRAPHITE2_NTRACING -DGRAPHITE2_NSEGCACHE
+
+# tell graphite2 not to export symbols, we'll be linking it directly with thebes
+DEFINES += -DGRAPHITE2_STATIC
 
 # provide a custom header that overrides malloc() and friends,
 # to ensure safe OOM handling
-DEFINES += -DGR2_CUSTOM_HEADER="\"MozGrMalloc.h\""
+DEFINES += -DGRAPHITE2_CUSTOM_HEADER="\"MozGrMalloc.h\""
 
 # Filter out -pedantic so that direct_machine.cpp can use computed goto
 CXXFLAGS := $(filter-out -pedantic,$(CXXFLAGS))
 CFLAGS := $(filter-out -pedantic,$(CFLAGS))
 
--- a/gfx/graphite2/src/NameTable.cpp
+++ b/gfx/graphite2/src/NameTable.cpp
@@ -19,21 +19,21 @@
     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.
 */
-#include "Main.h"
-#include "Endian.h"
+#include "inc/Main.h"
+#include "inc/Endian.h"
 
-#include "NameTable.h"
-#include "UtfCodec.h"
+#include "inc/NameTable.h"
+#include "inc/UtfCodec.h"
 
 using namespace graphite2;
 
 NameTable::NameTable(const void* data, size_t length, uint16 platformId, uint16 encodingID)
     :
     m_platformId(0), m_encodingId(0), m_languageCount(0),
     m_platformOffset(0), m_platformLastRecord(0), m_nameDataLength(0),
     m_table(0), m_nameData(NULL)
deleted file mode 100644
--- a/gfx/graphite2/src/NameTable.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include <graphite2/Segment.h>
-#include "TtfTypes.h"
-#include "locale2lcid.h"
-
-namespace graphite2 {
-
-class NameTable
-{
-public:
-    NameTable(const void * data, size_t length, uint16 platfromId=3, uint16 encodingID = 1);
-    ~NameTable() { free(const_cast<TtfUtil::Sfnt::FontNames *>(m_table)); }
-    enum eNameFallback {
-        eNoFallback = 0,
-        eEnUSFallbackOnly = 1,
-        eEnOrAnyFallback = 2
-    };
-    uint16 setPlatformEncoding(uint16 platfromId=3, uint16 encodingID = 1);
-    void * getName(uint16 & languageId, uint16 nameId, gr_encform enc, uint32 & length);
-    uint16 getLanguageId(const char * bcp47Locale);
-
-    CLASS_NEW_DELETE
-private:
-    uint16 m_platformId;
-    uint16 m_encodingId;
-    uint16 m_languageCount;
-    uint16 m_platformOffset; // offset of first NameRecord with for platform 3, encoding 1
-    uint16 m_platformLastRecord;
-    uint16 m_nameDataLength;
-    const TtfUtil::Sfnt::FontNames * m_table;
-    const uint8 * m_nameData;
-    Locale2Lang m_locale2Lang;
-};
-
-} // namespace graphite2
--- a/gfx/graphite2/src/Pass.cpp
+++ b/gfx/graphite2/src/Pass.cpp
@@ -19,26 +19,26 @@
     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.
 */
-#include "Main.h"
-#include "Endian.h"
-#include "Pass.h"
+#include "inc/Main.h"
+#include "inc/debug.h"
+#include "inc/Endian.h"
+#include "inc/Pass.h"
 #include <cstring>
 #include <cstdlib>
 #include <cassert>
-#include "Segment.h"
-#include "Code.h"
-#include "Rule.h"
-#include "XmlTraceLog.h"
+#include "inc/Segment.h"
+#include "inc/Code.h"
+#include "inc/Rule.h"
 
 using namespace graphite2;
 using vm::Machine;
 typedef Machine::Code  Code;
 
 
 Pass::Pass()
         :
@@ -85,354 +85,260 @@ bool Pass::readPass(void *pass, size_t 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
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrFlags,          m_immutable);
-    XmlTraceLog::get().addAttribute(AttrMaxRuleLoop,    m_iMaxLoop);
-    XmlTraceLog::get().addAttribute(AttrNumRules,       m_numRules);
-    XmlTraceLog::get().addAttribute(AttrNumRows,        m_sRows);
-    XmlTraceLog::get().addAttribute(AttrNumTransition,  m_sTransition);
-    XmlTraceLog::get().addAttribute(AttrNumSuccess,     m_sSuccess);
-    XmlTraceLog::get().addAttribute(AttrNumColumns,     m_sColumns);
-    XmlTraceLog::get().addAttribute(AttrNumRanges,      numRanges);
-#endif
     assert(p - pass_start == 40);
     // Perform some sanity checks.
     if (   m_sTransition > m_sRows
             || m_sSuccess > m_sRows
             || m_sSuccess + m_sTransition < m_sRows)
         return false;
 
     if (p + numRanges * 6 - 4 > pass_end) return false;
-    m_numGlyphs = be::swap<uint16>(*(uint16 *)(p + numRanges * 6 - 4)) + 1;
+    m_numGlyphs = be::peek<uint16>(p + numRanges * 6 - 4) + 1;
     // Caculate the start of vairous arrays.
-    const uint16 * const ranges = reinterpret_cast<const uint16 *>(p);
+    const byte * const ranges = p;
     p += numRanges*sizeof(uint16)*3;
-    const uint16 * const o_rule_map = reinterpret_cast<const uint16 *>(p);
+    const byte * const o_rule_map = p;
     p += (m_sSuccess + 1)*sizeof(uint16);
 
     // More sanity checks
     if (   reinterpret_cast<const byte *>(o_rule_map) > pass_end
             || p > pass_end)
         return false;
-    const size_t numEntries = be::swap<uint16>(o_rule_map[m_sSuccess]);
-    const uint16 * const   rule_map = reinterpret_cast<const uint16 *>(p);
+    const size_t numEntries = be::peek<uint16>(o_rule_map + m_sSuccess*sizeof(uint16));
+    const byte * const   rule_map = p;
     p += numEntries*sizeof(uint16);
 
     if (p > pass_end) return false;
     m_minPreCtxt = *p++;
     m_maxPreCtxt = *p++;
-    const int16 * const start_states = reinterpret_cast<const int16 *>(p);
+    const byte * const start_states = p;
     p += (m_maxPreCtxt - m_minPreCtxt + 1)*sizeof(int16);
     const uint16 * const sort_keys = reinterpret_cast<const uint16 *>(p);
     p += m_numRules*sizeof(uint16);
     const byte * const precontext = p;
     p += m_numRules;
     p += sizeof(byte);     // skip reserved byte
 
     if (p > pass_end) return false;
     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);
     p += (m_numRules + 1)*sizeof(uint16);
-    const int16 * const states = reinterpret_cast<const int16 *>(p);
+    const byte * const states = p;
     p += m_sTransition*m_sColumns*sizeof(int16);
     p += sizeof(byte);          // skip reserved byte
     if (p != pcCode || p >= pass_end) return false;
     p += pass_constraint_len;
     if (p != rcCode || p >= pass_end) return false;
-    p += be::swap<uint16>(o_constraint[m_numRules]);
+    p += be::peek<uint16>(o_constraint + m_numRules);
     if (p != aCode || p >= pass_end) return false;
     if (size_t(rcCode - pcCode) != pass_constraint_len) return false;
 
     // Load the pass constraint if there is one.
     if (pass_constraint_len)
     {
         m_cPConstraint = vm::Machine::Code(true, pcCode, pcCode + pass_constraint_len, 
-                                  precontext[0], be::swap<uint16>(sort_keys[0]), *m_silf, face);
+                                  precontext[0], be::peek<uint16>(sort_keys), *m_silf, face);
         if (!m_cPConstraint) return false;
     }
     if (!readRanges(ranges, numRanges)) return false;
     if (!readRules(rule_map, numEntries,  precontext, sort_keys,
                    o_constraint, rcCode, o_actions, aCode, face)) return false;
     return readStates(start_states, states, o_rule_map);
 }
 
 
-bool Pass::readRules(const uint16 * rule_map, const size_t num_entries,
+bool Pass::readRules(const byte * rule_map, const size_t num_entries,
                      const byte *precontext, const uint16 * sort_key,
                      const uint16 * o_constraint, const byte *rc_data,
                      const uint16 * o_action,     const byte * ac_data,
                      const Face & face)
 {
-    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]);
+    const byte * const ac_data_end = ac_data + be::peek<uint16>(o_action + m_numRules);
+    const byte * const rc_data_end = rc_data + be::peek<uint16>(o_constraint + m_numRules);
 
     if (!(m_rules = new Rule [m_numRules])) return false;
     precontext += m_numRules;
     sort_key   += m_numRules;
     o_constraint += m_numRules;
     o_action += m_numRules;
 
     // Load rules.
     const byte * ac_begin = 0, * rc_begin = 0,
-               * ac_end = ac_data + be::swap<uint16>(*o_action),
-               * rc_end = rc_data + be::swap<uint16>(*o_constraint);
+               * ac_end = ac_data + be::peek<uint16>(o_action),
+               * rc_end = rc_data + be::peek<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       = be::swap<uint16>(*--sort_key);
+        r->sort       = be::peek<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 + be::swap<uint16>(*--o_action);
-        rc_begin      = *--o_constraint ? rc_data + be::swap<uint16>(*o_constraint) : rc_end;
+        ac_begin      = ac_data + be::peek<uint16>(--o_action);
+        rc_begin      = *--o_constraint ? rc_data + be::peek<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)
             return false;
         r->action     = new vm::Machine::Code(false, ac_begin, ac_end, r->preContext, r->sort, *m_silf, face);
         r->constraint = new vm::Machine::Code(true,  rc_begin, rc_end, r->preContext, r->sort, *m_silf, face);
 
         if (!r->action || !r->constraint
                 || r->action->status() != Code::loaded
                 || r->constraint->status() != Code::loaded
                 || !r->constraint->immutable())
             return false;
-
-        logRule(r, sort_key);
     }
 
     // Load the rule entries map
     RuleEntry * re = m_ruleMap = gralloc<RuleEntry>(num_entries);
     for (size_t n = num_entries; n; --n, ++re)
     {
-        const ptrdiff_t rn = be::swap<uint16>(*rule_map++);
+        const ptrdiff_t rn = be::read<uint16>(rule_map);
         if (rn >= m_numRules)  return false;
         re->rule = m_rules + rn;
     }
 
     return true;
 }
 
 static int cmpRuleEntry(const void *a, const void *b) { return (*(RuleEntry *)a < *(RuleEntry *)b ? -1 :
                                                                 (*(RuleEntry *)b < *(RuleEntry *)a ? 1 : 0)); }
 
-bool Pass::readStates(const int16 * starts, const int16 *states, const uint16 * o_rule_map)
+bool Pass::readStates(const byte * starts, const byte *states, const byte * o_rule_map)
 {
     m_startStates = gralloc<State *>(m_maxPreCtxt - m_minPreCtxt + 1);
     m_states      = gralloc<State>(m_sRows);
     m_sTable      = gralloc<State *>(m_sTransition * m_sColumns);
 
     if (!m_startStates || !m_states || !m_sTable) return false;
     // load start states
     for (State * * s = m_startStates,
             * * const s_end = s + m_maxPreCtxt - m_minPreCtxt + 1; s != s_end; ++s)
     {
-        *s = m_states + be::swap<uint16>(*starts++);
+        *s = m_states + be::read<uint16>(starts);
         if (*s < m_states || *s >= m_states + m_sRows) return false; // true;
     }
 
     // load state transition table.
     for (State * * t = m_sTable,
                * * const t_end = t + m_sTransition*m_sColumns; t != t_end; ++t)
     {
-        *t = m_states + be::swap<uint16>(*states++);
+        *t = m_states + be::read<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 + be::swap<uint16>(o_rule_map[m_sSuccess]);
+    const RuleEntry * rule_map_end = m_ruleMap + be::peek<uint16>(o_rule_map + m_sSuccess*sizeof(uint16));
     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 + be::swap<uint16>(*o_rule_map++),
-                  * const end   = s < success_begin ? 0 : m_ruleMap + be::swap<uint16>(*o_rule_map);
+        RuleEntry * const begin = s < success_begin ? 0 : m_ruleMap + be::read<uint16>(o_rule_map),
+                  * const end   = s < success_begin ? 0 : m_ruleMap + be::peek<uint16>(o_rule_map);
 
         if (begin >= rule_map_end || end > rule_map_end || begin > end)
             return false;
 #ifndef NDEBUG
         s->index = (s - m_states);
 #endif
         s->rules = begin;
         s->rules_end = (end - begin <= FiniteStateMachine::MAX_RULES)? end :
             begin + FiniteStateMachine::MAX_RULES;
         qsort(begin, end - begin, sizeof(RuleEntry), &cmpRuleEntry);
     }
 
-    logStates();
     return true;
 }
 
-
-void Pass::logRule(GR_MAYBE_UNUSED const Rule * r, GR_MAYBE_UNUSED const uint16 * sort_key) const
-{
-#ifndef DISABLE_TRACING
-    if (!XmlTraceLog::get().active()) return;
-
-    const size_t lid = r - m_rules;
-    if (r->constraint)
-    {
-        XmlTraceLog::get().openElement(ElementConstraint);
-        XmlTraceLog::get().addAttribute(AttrIndex, lid);
-        XmlTraceLog::get().closeElement(ElementConstraint);
-    }
-    else
-    {
-        XmlTraceLog::get().openElement(ElementRule);
-        XmlTraceLog::get().addAttribute(AttrIndex, lid);
-        XmlTraceLog::get().addAttribute(AttrSortKey, be::swap<uint16>(sort_key[lid]));
-        XmlTraceLog::get().addAttribute(AttrPrecontext, r->preContext);
-        XmlTraceLog::get().closeElement(ElementRule);
-    }
-#endif
-}
-
-void Pass::logStates() const
-{
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        for (int i = 0; i != (m_maxPreCtxt - m_minPreCtxt + 1); ++i)
-        {
-            XmlTraceLog::get().openElement(ElementStartState);
-            XmlTraceLog::get().addAttribute(AttrContextLen, i + m_minPreCtxt);
-            XmlTraceLog::get().addAttribute(AttrState, size_t(m_startStates[i] - m_states));
-            XmlTraceLog::get().closeElement(ElementStartState);
-        }
-
-        for (uint16 i = 0; i != m_sSuccess; ++i)
-        {
-            XmlTraceLog::get().openElement(ElementRuleMap);
-            XmlTraceLog::get().addAttribute(AttrSuccessId, i);
-            for (const RuleEntry *j = m_states[i].rules, *const j_end = m_states[i].rules_end; j != j_end; ++j)
-            {
-                XmlTraceLog::get().openElement(ElementRule);
-                XmlTraceLog::get().addAttribute(AttrRuleId, size_t(j->rule - m_rules));
-                XmlTraceLog::get().closeElement(ElementRule);
-            }
-            XmlTraceLog::get().closeElement(ElementRuleMap);
-        }
-
-        XmlTraceLog::get().openElement(ElementStateTransitions);
-        for (size_t iRow = 0; iRow < m_sTransition; iRow++)
-        {
-            XmlTraceLog::get().openElement(ElementRow);
-            XmlTraceLog::get().addAttribute(AttrIndex, iRow);
-            const State * const * const row = m_sTable + iRow * m_sColumns;
-            for (int i = 0; i != m_sColumns; ++i)
-            {
-                XmlTraceLog::get().openElement(ElementData);
-                XmlTraceLog::get().addAttribute(AttrIndex, i);
-                XmlTraceLog::get().addAttribute(AttrValue, size_t(row[i] - m_states));
-                XmlTraceLog::get().closeElement(ElementData);
-            }
-            XmlTraceLog::get().closeElement(ElementRow);
-        }
-        XmlTraceLog::get().closeElement(ElementStateTransitions);
-    }
-#endif
-}
-
-bool Pass::readRanges(const uint16 *ranges, size_t num_ranges)
+bool Pass::readRanges(const byte * ranges, size_t num_ranges)
 {
     m_cols = gralloc<uint16>(m_numGlyphs);
     memset(m_cols, 0xFF, m_numGlyphs * sizeof(uint16));
     for (size_t n = num_ranges; n; --n)
     {
-        const uint16 first = be::swap<uint16>(*ranges++),
-                     last  = be::swap<uint16>(*ranges++),
-                     col   = be::swap<uint16>(*ranges++);
+        const uint16 first = be::read<uint16>(ranges),
+                     last  = be::read<uint16>(ranges),
+                     col   = be::read<uint16>(ranges);
         uint16 *p;
 
         if (first > last || last >= m_numGlyphs || col >= m_sColumns)
             return false;
 
         for (p = m_cols + first; p <= m_cols + last; )
             *p++ = col;
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-            XmlTraceLog::get().openElement(ElementRange);
-            XmlTraceLog::get().addAttribute(AttrFirstId, first);
-            XmlTraceLog::get().addAttribute(AttrLastId, last);
-            XmlTraceLog::get().addAttribute(AttrColId, col);
-            XmlTraceLog::get().closeElement(ElementRange);
-        }
-#endif
     }
     return true;
 }
 
+
 void Pass::runGraphite(Machine & m, FiniteStateMachine & fsm) const
 {
-    Slot *s = m.slotMap().segment.first();
-    if (!s || !testPassConstraint(m)) return;
+	Slot *s = m.slotMap().segment.first();
+	if (!s || !testPassConstraint(m)) return;
     Slot *currHigh = s->next();
-    
+
+#if !defined GRAPHITE2_NTRACING
+    if (dbgout)  *dbgout << "rules"	<< json::array;
+	json::closer rules_array_closer = dbgout;
+#endif
+
     m.slotMap().highwater(currHigh);
     int lc = m_iMaxLoop;
     do
     {
         findNDoRule(s, m, fsm);
         if (s && (m.slotMap().highpassed() || s == m.slotMap().highwater() || --lc == 0)) {
         	if (!lc)
+        	{
+//        		if (dbgout)	*dbgout << json::item << json::flat << rule_event(-1, s, 1);
         		s = m.slotMap().highwater();
+        	}
         	lc = m_iMaxLoop;
             if (s)
             	m.slotMap().highwater(s->next());
         }
     } while (s);
 }
 
 inline uint16 Pass::glyphToCol(const uint16 gid) const
 {
     return gid < m_numGlyphs ? m_cols[gid] : 0xffffU;
 }
 
 bool Pass::runFSM(FiniteStateMachine& fsm, Slot * slot) const
 {
-    int context = 0;
-    for (; context != m_maxPreCtxt && slot->prev(); ++context, slot = slot->prev());
-    if (context < m_minPreCtxt)
+	fsm.reset(slot, m_maxPreCtxt);
+    if (fsm.slots.context() < m_minPreCtxt)
         return false;
 
-    fsm.setContext(context);
-    const State * state = m_startStates[m_maxPreCtxt - context];
+    const State * state = m_startStates[m_maxPreCtxt - fsm.slots.context()];
     do
     {
         fsm.slots.pushSlot(slot);
         if (fsm.slots.size() >= SlotMap::MAX_SLOTS) return false;
         const uint16 col = glyphToCol(slot->gid());
         if (col == 0xffffU || !state->is_transition()) return true;
 
         state = state->transitions[col];
         if (state->is_success())
             fsm.rules.accumulate_rules(*state);
 
-#ifdef ENABLE_DEEP_TRACING
-        if (col >= m_sColumns && col != 65535)
-        {
-            XmlTraceLog::get().error("Invalid column %d ID %d for slot %d",
-                                     col, slot->gid(), slot);
-        }
-#endif
-
         slot = slot->next();
     } while (state != m_states && slot);
 
     fsm.slots.pushSlot(slot);
     return true;
 }
 
 void Pass::findNDoRule(Slot * & slot, Machine &m, FiniteStateMachine & fsm) const
@@ -441,168 +347,218 @@ void Pass::findNDoRule(Slot * & slot, Ma
 
     if (runFSM(fsm, slot))
     {
         // Search for the first rule which passes the constraint
         const RuleEntry *        r = fsm.rules.begin(),
                         * const re = fsm.rules.end();
         for (; r != re && !testConstraint(*r->rule, m); ++r);
 
-        if (r != re)
+#if !defined GRAPHITE2_NTRACING
+        if (dbgout)
         {
-#ifdef ENABLE_DEEP_TRACING
-            if (XmlTraceLog::get().active())
-            {
-                XmlTraceLog::get().openElement(ElementDoRule);
-                XmlTraceLog::get().addAttribute(AttrNum, size_t(r->rule - m_rules));
-                XmlTraceLog::get().addAttribute(AttrIndex, int(slot - fsm.slots.segment.first()));
-            }
+        	if (fsm.rules.size() != 0)
+        	{
+				*dbgout << json::item << json::object;
+				dumpRuleEventConsidered(fsm, *r);
+				if (r != re)
+				{
+					const int adv = doAction(r->rule->action, slot, m);
+					dumpRuleEventOutput(fsm, *r->rule, slot);
+					if (r->rule->action->deletes()) fsm.slots.collectGarbage();
+					adjustSlot(adv, slot, fsm.slots);
+					*dbgout		<< "cursor" << slotid(slot)
+								<< json::close	// Close "output" object
+							<< json::close; // Close RuelEvent object
+
+					return;
+				}
+				else
+					*dbgout 	<< json::close	// close "considered" array
+							<< "output" << json::object
+								<< "slots" 	<< json::array << json::close
+								<< "cursor"	<< slotid(slot->next())
+								<< json::close
+							<< json::close;
+        	}
+        }
+        else
 #endif
-            doAction(r->rule->action, slot, m);
-#ifdef ENABLE_DEEP_TRACING
-            if (XmlTraceLog::get().active())
-            {
-                XmlTraceLog::get().openElement(ElementPassResult);
-                XmlTraceLog::get().addAttribute(AttrResult, int(slot - fsm.slots.segment.first()));
-                const Slot * s = fsm.slots.segment.first();
-                while (s)
-                {
-                    XmlTraceLog::get().openElement(ElementSlot);
-                    XmlTraceLog::get().addAttribute(AttrGlyphId, s->gid());
-                    XmlTraceLog::get().addAttribute(AttrX, s->origin().x);
-                    XmlTraceLog::get().addAttribute(AttrY, s->origin().y);
-                    XmlTraceLog::get().addAttribute(AttrBefore, s->before());
-                    XmlTraceLog::get().addAttribute(AttrAfter, s->after());
-                    XmlTraceLog::get().closeElement(ElementSlot);
-                    s = s->next();
-                }
-                XmlTraceLog::get().closeElement(ElementPassResult);
-                XmlTraceLog::get().closeElement(ElementDoRule);
-            }
-#endif
-            return;
+        {
+   	        if (r != re)
+			{
+				const int adv = doAction(r->rule->action, slot, m);
+				if (r->rule->action->deletes()) fsm.slots.collectGarbage();
+				adjustSlot(adv, slot, fsm.slots);
+				return;
+			}
         }
     }
 
     slot = slot->next();
 }
 
+#if !defined GRAPHITE2_NTRACING
+
+inline
+Slot * input_slot(const SlotMap &  slots, const int n)
+{
+	Slot * s = slots[slots.context() + n];
+	if (!s->isCopied()) 	return s;
+
+	return s->prev() ? s->prev()->next() :  s->next()->prev();
+}
+
+inline
+Slot * output_slot(const SlotMap &  slots, const int n)
+{
+	Slot * s = slots[slots.context() + n - 1];
+	return s ? s->next() : slots.segment.first();
+}
+
+
+void Pass::dumpRuleEventConsidered(const FiniteStateMachine & fsm, const RuleEntry & re) const
+{
+	*dbgout << "considered" << json::array;
+	for (const RuleEntry *r = fsm.rules.begin(); r != &re; ++r)
+	{
+		if (r->rule->preContext > fsm.slots.context())	continue;
+	*dbgout 	<< json::flat << json::object
+					<< "id" 	<< r->rule - m_rules
+					<< "failed"	<< true
+					<< "input" << json::flat << json::object
+						<< "start" << slotid(input_slot(fsm.slots, -r->rule->preContext))
+						<< "length" << r->rule->sort
+						<< json::close	// close "input"
+					<< json::close;	// close Rule object
+	}
+}
+
+
+void Pass::dumpRuleEventOutput(const FiniteStateMachine & fsm, const Rule & r, Slot * const last_slot) const
+{
+	*dbgout 		<< json::item << json::flat << json::object
+						<< "id" 	<< &r - m_rules
+						<< "failed" << false
+						<< "input" << json::flat << json::object
+							<< "start" << slotid(input_slot(fsm.slots, 0))
+							<< "length" << r.sort - r.preContext
+							<< json::close // close "input"
+						<< json::close	// close Rule object
+				<< json::close // close considered array
+				<< "output" << json::object
+					<< "slots"	<< json::array;
+	fsm.slots.segment.positionSlots(0);
+	for(Slot * slot = output_slot(fsm.slots, 0); slot != last_slot; slot = slot->next())
+		*dbgout 		<< dslot(&fsm.slots.segment, slot);
+	*dbgout 			<< json::close; // close "slots";
+}
+
+#endif
+
 
 inline
 bool Pass::testPassConstraint(Machine & m) const
 {
     if (!m_cPConstraint) return true;
 
     assert(m_cPConstraint.constraint());
 
     vm::slotref * map = m.slotMap().begin();
     *map = m.slotMap().segment.first();
     const uint32 ret = m_cPConstraint.run(m, map);
 
+#if !defined GRAPHITE2_NTRACING
+    if (dbgout)
+    	*dbgout << "constraint" << (ret || m.status() != Machine::finished);
+#endif
+
     return ret || m.status() != Machine::finished;
 }
 
 
 bool Pass::testConstraint(const Rule &r, Machine & m) const
 {
-    if (r.sort - r.preContext > (int)m.slotMap().size() - m.slotMap().context())    return false;
+    if ((r.sort - r.preContext) > (m.slotMap().size() - m.slotMap().context()))    return false;
     if (m.slotMap().context() - r.preContext < 0) return false;
     if (!*r.constraint)                 return true;
     assert(r.constraint->constraint());
 
-#ifdef ENABLE_DEEP_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementTestRule);
-        XmlTraceLog::get().addAttribute(AttrNum, size_t(&r - m_rules));
-    }
-#endif
     vm::slotref * map = m.slotMap().begin() + m.slotMap().context() - r.preContext;
     for (int n = r.sort; n && map; --n, ++map)
     {
-	if (!*map) continue;
+    	if (!*map) continue;
         const int32 ret = r.constraint->run(m, map);
         if (!ret || m.status() != Machine::finished)
-        {
-#ifdef ENABLE_DEEP_TRACING
-            if (XmlTraceLog::get().active())
-            {
-                XmlTraceLog::get().closeElement(ElementTestRule);
-            }
-#endif
             return false;
-        }
     }
 
-#ifdef ENABLE_DEEP_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().closeElement(ElementTestRule);
-    }
-#endif
-
     return true;
 }
 
 
-void Pass::doAction(const Code *codeptr, Slot * & slot_out, vm::Machine & m) const
+void SlotMap::collectGarbage()
+{
+    for(Slot **s = begin(), *const *const se = end() - 1; s != se; ++s) {
+        Slot *& slot = *s;
+        if(slot->isDeleted() || slot->isCopied())
+            segment.freeSlot(slot);
+    }
+}
+
+
+
+int Pass::doAction(const Code *codeptr, Slot * & slot_out, vm::Machine & m) const
 {
     assert(codeptr);
-    if (!*codeptr) return;
+    if (!*codeptr) return 0;
     SlotMap   & smap = m.slotMap();
     vm::slotref * map = &smap[smap.context()];
     smap.highpassed(false);
 
-    Segment & seg = smap.segment;
-    int glyph_diff = -static_cast<int>(seg.slotCount());
     int32 ret = codeptr->run(m, map);
-    glyph_diff += seg.slotCount();
-    if (codeptr->deletes())
+
+    if (m.status() != Machine::finished)
     {
-        for (Slot **s = smap.begin(), *const * const se = smap.end()-1; s != se; ++s)
-        {
-            Slot * & slot = *s;
-            if (slot->isDeleted() || slot->isCopied())
-            {
-            	if (slot == smap.highwater())
-            		smap.highwater(slot->next());
-            	seg.freeSlot(slot);
-            }
-        }
+    	slot_out = NULL;
+    	smap.highwater(0);
+    	return 0;
     }
 
     slot_out = *map;
-    if (ret < 0)
+    return ret;
+}
+
+
+void Pass::adjustSlot(int delta, Slot * & slot_out, SlotMap & smap) const
+{
+    if (delta < 0)
     {
         if (!slot_out)
         {
-            slot_out = seg.last();
-            ++ret;
+            slot_out = smap.segment.last();
+            ++delta;
             if (smap.highpassed() && !smap.highwater())
             	smap.highpassed(false);
         }
-        while (++ret <= 0 && slot_out)
+        while (++delta <= 0 && slot_out)
         {
-            slot_out = slot_out->prev();
             if (smap.highpassed() && smap.highwater() == slot_out)
             	smap.highpassed(false);
+            slot_out = slot_out->prev();
         }
     }
-    else if (ret > 0)
+    else if (delta > 0)
     {
         if (!slot_out)
         {
-            slot_out = seg.first();
-            --ret;
+            slot_out = smap.segment.first();
+            --delta;
         }
-        while (--ret >= 0 && slot_out)
+        while (--delta >= 0 && slot_out)
         {
             slot_out = slot_out->next();
             if (slot_out == smap.highwater() && slot_out)
                 smap.highpassed(true);
         }
     }
-    if (m.status() != Machine::finished)
-    {
-    	slot_out = NULL;
-    	m.slotMap().highwater(0);
-    }
 }
+
deleted file mode 100644
--- a/gfx/graphite2/src/Pass.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include <cstdlib>
-#include "Code.h"
-
-namespace graphite2 {
-
-class Segment;
-class Face;
-class Silf;
-struct Rule;
-struct RuleEntry;
-struct State;
-class FiniteStateMachine;
-
-class Pass
-{   
-public:
-    Pass();
-    ~Pass();
-    
-    bool readPass(void* pPass, size_t pass_length, size_t subtable_base, const Face & face);
-    void runGraphite(vm::Machine & m, FiniteStateMachine & fsm) const;
-    void init(Silf *silf) { m_silf = silf; }
-
-    CLASS_NEW_DELETE
-private:
-    void   findNDoRule(Slot* & iSlot, vm::Machine &, FiniteStateMachine& fsm) const;
-    void   doAction(const vm::Machine::Code* codeptr, Slot * & slot_out, vm::Machine &) const;
-    bool   testPassConstraint(vm::Machine & m) const;
-    bool   testConstraint(const Rule & r, vm::Machine &) const;
-    bool   readFSM(const byte* p, const byte*const pass_start, const size_t max_offset);
-    bool   readRules(const uint16 * rule_map, const size_t num_entries, 
-                     const byte *precontext, const uint16 * sort_key,
-                     const uint16 * o_constraint, const byte *constraint_data, 
-                     const uint16 * o_action, const byte * action_data,
-                     const Face &);
-    void   logRule(const Rule * r, const uint16 * sort_key) const;
-    bool   readStates(const int16 * starts, const int16 * states, const uint16 * o_rule_map);
-    void   logStates() const;
-    bool   readRanges(const uint16* ranges, size_t num_ranges);
-    uint16 glyphToCol(const uint16 gid) const;
-    bool   runFSM(FiniteStateMachine & fsm, Slot * slot) const;
-    
-    const Silf* m_silf;
-    uint16    * m_cols;
-    Rule      * m_rules; // rules
-    RuleEntry * m_ruleMap;
-    State *   * m_startStates; // prectxt length
-    State *   * m_sTable;
-    State     * m_states;
-    
-    bool   m_immutable;
-    byte   m_iMaxLoop;
-    uint16 m_numGlyphs;
-    uint16 m_numRules;
-    uint16 m_sRows;
-    uint16 m_sTransition;
-    uint16 m_sSuccess;
-    uint16 m_sColumns;
-    byte m_minPreCtxt;
-    byte m_maxPreCtxt;
-    vm::Machine::Code m_cPConstraint;
-    
-private:		//defensive
-    Pass(const Pass&);
-    Pass& operator=(const Pass&);
-};
-
-} // namespace graphite2
deleted file mode 100644
--- a/gfx/graphite2/src/Position.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-namespace graphite2 {
-
-class Position
-{
-public:
-    Position() : x(0), y(0) { }
-    Position(float inx, float iny) { x = inx; y = iny; }
-    Position operator + (const Position& a) const { return Position(x + a.x, y + a.y); }
-    Position operator - (const Position& a) const { return Position(x - a.x, y - a.y); }
-    Position operator * (const float m) const { return Position(x * m, y * m); }
-    Position &operator += (const Position &a) { x += a.x; y += a.y; return *this; }
-    Position &operator *= (const float m) { x *= m; y *= m; return *this; }
-
-    float x;
-    float y;
-};
-
-} // namespace graphite2
--- a/gfx/graphite2/src/Rule.cpp
+++ b/gfx/graphite2/src/Rule.cpp
@@ -20,10 +20,10 @@
     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.
 */
 
-#include "Rule.h"
+#include "inc/Rule.h"
 
deleted file mode 100644
--- a/gfx/graphite2/src/Rule.h
+++ /dev/null
@@ -1,275 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-
-#pragma once
-
-#include "Code.h"
-
-namespace graphite2 {
-
-struct Rule {
-  const vm::Machine::Code * constraint, 
-                 * action;
-  unsigned short   sort;
-  byte             preContext;
-#ifndef NDEBUG
-  uint16           rule_idx;
-#endif
-
-  Rule() : constraint(0), action(0) {}
-  ~Rule();
-
-  CLASS_NEW_DELETE;
-};
-
-inline Rule::~Rule()
-{
-  delete constraint;
-  delete action;
-}
-
-
-struct RuleEntry
-{
-  const Rule   * rule;
-
-  inline bool operator < (const RuleEntry &r) const
-  { 
-    const unsigned short lsort = rule->sort, rsort = r.rule->sort; 
-    return lsort > rsort || (lsort == rsort && rule < r.rule);
-  }
-  
-  inline bool operator == (const RuleEntry &r) const
-  {
-    return rule == r.rule;
-  }
-};
-
-
-struct State
-{
-  const RuleEntry     * rules,
-                      * rules_end;
-  const State * const * transitions;
-  
-  size_t size() const;
-  bool   is_success() const;
-  bool   is_transition() const;
-#ifndef NDEBUG
-    uint32 index;
-#endif
-};
-
-inline size_t State::size() const 
-{
-  return rules_end - rules;
-}
-
-inline bool State::is_success() const
-{
-  return (rules != NULL);
-}
-
-inline bool State::is_transition() const
-{
-  return (transitions != NULL);
-}
-
-
-class SlotMap
-{
-public:
-  enum {MAX_SLOTS=64};
-  SlotMap(Segment & seg);
-  
-  Slot       * * begin();
-  Slot       * * end();
-  size_t         size() const;
-  unsigned short context() const;
-  void           setContext(unsigned short);
-  
-  Slot * const & operator[](int n) const;
-  Slot       * & operator [] (int);
-  void           pushSlot(Slot * const slot);
-  Slot         * highwater() { return m_highwater; }
-  void           highwater(Slot *s) { m_highwater = s; }
-  bool			 highpassed() const { return m_highpassed; }
-  void			 highpassed(bool v) { m_highpassed = v; }
-
-  Segment &    segment;
-private:
-  Slot         * m_slot_map[MAX_SLOTS+1];
-  unsigned short m_size;
-  unsigned short m_precontext;
-  Slot         * m_highwater;
-  bool			 m_highpassed;
-};
-
-
-class FiniteStateMachine
-{
-public:
-  enum {MAX_RULES=128};
-
-private:
-  class Rules
-  {
-  public:
-      Rules();
-      void              clear();
-      const RuleEntry * begin() const;
-      const RuleEntry * end() const;
-      size_t            size() const;
-      
-      void accumulate_rules(const State &state);
-
-  private:
-      RuleEntry * m_begin, 
-                * m_end,
-                  m_rules[MAX_RULES*2];
-  };
-
-public:
-  FiniteStateMachine(SlotMap & map);
-  void      setContext(short unsigned int);
-  Rules     rules;
-  SlotMap   & slots;
-};
-
-inline FiniteStateMachine::FiniteStateMachine(SlotMap& map)
-: slots(map)
-{
-}
-
-inline void FiniteStateMachine::setContext(short unsigned int ctxt)
-{
-  rules.clear();
-  slots.setContext(ctxt);
-}
-
-inline FiniteStateMachine::Rules::Rules()
-  : m_begin(m_rules)
-{
-  m_end = m_begin;
-}
-
-inline void FiniteStateMachine::Rules::clear() 
-{
-  m_end = m_begin;
-}
-
-inline const RuleEntry * FiniteStateMachine::Rules::begin() const
-{
-  return m_begin;
-}
-
-inline const RuleEntry * FiniteStateMachine::Rules::end() const
-{
-  return m_end;
-}
-
-inline size_t FiniteStateMachine::Rules::size() const
-{
-  return m_end - m_begin;
-}
-
-inline void FiniteStateMachine::Rules::accumulate_rules(const State &state)
-{
-  // Only bother if there are rules in the State object.
-  if (state.size() == 0) return;
-  
-  // Merge the new sorted rules list into the current sorted result set.
-  const RuleEntry * lre = begin(), * rre = state.rules;
-  RuleEntry * out = m_rules + (m_begin == m_rules)*MAX_RULES;    
-  const RuleEntry * lrend = out + MAX_RULES;
-  m_begin = out; 
-  while (lre != end() && out != lrend)
-  {
-    if (*lre < *rre)      *out++ = *lre++;
-    else if (*rre < *lre) { *out++ = *rre++; }
-    else                { *out++ = *lre++; ++rre; }
-
-    if (rre == state.rules_end) 
-    { 
-      while (lre != end() && out != lrend) { *out++ = *lre++; }
-      m_end = out;
-      return;
-    }
-  }
-  while (rre != state.rules_end && out != lrend) { *out++ = *rre++; }
-  m_end = out;
-}
-
-inline SlotMap::SlotMap(Segment & seg)
-: segment(seg), m_size(0), m_precontext(0)
-{
-    m_slot_map[0] = 0;
-}
-
-inline Slot * * SlotMap::begin()
-{
-  return &m_slot_map[1]; // allow map to go 1 before slot_map when inserting
-                         // at start of segment.
-}
-
-inline Slot * * SlotMap::end()
-{
-  return m_slot_map + m_size + 1;
-}
-
-inline size_t SlotMap::size() const
-{
-  return m_size;
-}
-
-inline short unsigned int SlotMap::context() const
-{
-  return m_precontext;
-}
-
-inline void SlotMap::setContext(short unsigned int ctxt)
-{
-  m_size = 0;
-  m_precontext = ctxt;
-}
-
-inline void SlotMap::pushSlot(Slot*const slot)
-{
-  m_slot_map[m_size++ + 1] = slot;
-}
-
-inline Slot * const & SlotMap::operator[](int n) const
-{
-  return m_slot_map[n + 1];
-}
-
-inline Slot * & SlotMap::operator[](int n)
-{
-  return m_slot_map[n + 1];
-}
-
-} // namespace graphite2
--- a/gfx/graphite2/src/SegCache.cpp
+++ b/gfx/graphite2/src/SegCache.cpp
@@ -20,28 +20,28 @@
     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.
 */
 
-#include "Main.h"
-#include "TtfTypes.h"
-#include "TtfUtil.h"
-#include "SegCache.h"
-#include "SegCacheEntry.h"
-#include "SegCacheStore.h"
-#include "CmapCache.h"
+#include "inc/Main.h"
+#include "inc/TtfTypes.h"
+#include "inc/TtfUtil.h"
+#include "inc/SegCache.h"
+#include "inc/SegCacheEntry.h"
+#include "inc/SegCacheStore.h"
+#include "inc/CmapCache.h"
 
 
 using namespace graphite2;
 
-#ifndef DISABLE_SEGCACHE
+#ifndef GRAPHITE2_NSEGCACHE
 
 SegCache::SegCache(const SegCacheStore * store, const Features & feats)
     :
     m_prefixLength(ePrefixLength),
     m_maxCachedSegLength(eMaxSpliceSize),
     m_segmentCount(0),
     m_features(feats),
     m_totalAccessCount(0l), m_totalMisses(0l),
@@ -67,32 +67,17 @@ void SegCache::freeLevel(SegCacheStore *
             }
         }
     }
     free(prefixes.raw);
 }
 
 void SegCache::clear(SegCacheStore * store)
 {
-    #ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementSegCache);
-        XmlTraceLog::get().addAttribute(AttrNum, m_segmentCount);
-        XmlTraceLog::get().addAttribute(AttrAccessCount, m_totalAccessCount);
-        XmlTraceLog::get().addAttribute(AttrMisses, m_totalMisses);
-    }
-#endif
     freeLevel(store, m_prefixes, 0);
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().closeElement(ElementSegCache);
-    }
-#endif
     m_prefixes.raw = NULL;
 }
 
 SegCache::~SegCache()
 {
     assert(m_prefixes.raw == NULL);
 }
 
deleted file mode 100644
--- a/gfx/graphite2/src/SegCache.h
+++ /dev/null
@@ -1,314 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#ifndef DISABLE_SEGCACHE
-
-#include <graphite2/Segment.h>
-#include "Main.h"
-#include "Slot.h"
-#include "FeatureVal.h"
-#include "SegCacheEntry.h"
-#include "Segment.h"
-
-namespace graphite2 {
-
-class SegCache;
-class SegCacheEntry;
-class SegCacheStore;
-
-/**
- * SegPrefixEntry stores lists of word/syllable segments
- * with one list for each word length. The prefix size should be chosen so that
- * these list sizes stay small since they will be searched iteratively.
- */
-class SegCachePrefixEntry
-{
-public:
-    SegCachePrefixEntry() { memset(this, 0, sizeof(SegCachePrefixEntry)); }
-    ~SegCachePrefixEntry()
-    {
-        for (size_t j = 0; j < eMaxSpliceSize; j++)
-        {
-            if (m_entryCounts[j])
-            {
-                assert(m_entries[j]);
-                for (size_t k = 0; k < m_entryCounts[j]; k++)
-                {
-                    m_entries[j][k].log(j);
-                    m_entries[j][k].clear();
-                }
-                free(m_entries[j]);
-            }
-        }
-    }
-    const SegCacheEntry * find(const uint16 * cmapGlyphs, size_t length) const
-    {
-        if (length <= ePrefixLength)
-        {
-            assert(m_entryCounts[length-1] <= 1);
-            if (m_entries[length-1])
-                return m_entries[length-1];
-            return NULL;
-        }
-        SegCacheEntry * entry = NULL;
-        findPosition(cmapGlyphs, length, &entry);
-        return entry;
-    }
-    SegCacheEntry * cache(const uint16* cmapGlyphs, size_t length, Segment * seg, size_t charOffset, unsigned long long totalAccessCount)
-    {
-        size_t listSize = m_entryBSIndex[length-1]? (m_entryBSIndex[length-1] << 1) - 1 : 0;
-        SegCacheEntry * newEntries = NULL;
-        if (m_entryCounts[length-1] + 1u > listSize)
-        {
-            if (m_entryCounts[length-1] == 0)
-            {
-                listSize = 1;
-            }
-            else
-            {
-                // the problem comes when you get incremental numeric ids in a large doc
-                if (listSize >= eMaxSuffixCount)
-                    return NULL;
-                listSize = (m_entryBSIndex[length-1] << 2) - 1;
-            }
-            newEntries = gralloc<SegCacheEntry>(listSize);
-            if (!newEntries)
-            {
-                return NULL;
-            }
-        }        
-
-        uint16 insertPos = 0;
-        if (m_entryCounts[length-1] > 0)
-        {
-            insertPos = findPosition(cmapGlyphs, length, NULL);
-            if (!newEntries)
-            {
-                // same buffer, shift entries up
-                memmove(m_entries[length-1] + insertPos + 1, m_entries[length-1] + insertPos,
-                    sizeof(SegCacheEntry) * (m_entryCounts[length-1] - insertPos));
-            }
-            else
-            {
-                memcpy(newEntries, m_entries[length-1], sizeof(SegCacheEntry) * (insertPos));
-                memcpy(newEntries + insertPos + 1, m_entries[length-1] + insertPos,
-                   sizeof(SegCacheEntry) * (m_entryCounts[length-1] - insertPos));
-                
-                free(m_entries[length-1]);
-                m_entries[length-1] = newEntries;
-                assert (m_entryBSIndex[length-1]);
-                m_entryBSIndex[length-1] <<= 1;
-            }
-        } 
-        else
-        {
-            m_entryBSIndex[length-1] = 1;
-            m_entries[length-1] = newEntries;
-        }
-        m_entryCounts[length-1] += 1;
-        new (m_entries[length-1] + insertPos)
-            SegCacheEntry(cmapGlyphs, length, seg, charOffset, totalAccessCount);
-        return m_entries[length-1]  + insertPos;
-    }
-    uint32 purge(unsigned long long minAccessCount, unsigned long long oldAccessTime,
-        unsigned long long currentTime);
-    CLASS_NEW_DELETE
-private:
-    uint16 findPosition(const uint16 * cmapGlyphs, uint16 length, SegCacheEntry ** entry) const
-    {
-        int dir = 0;
-        if (m_entryCounts[length-1] == 0)
-        {
-            if (entry) *entry = NULL;
-            return 0;
-        }
-        else if (m_entryCounts[length-1] == 1)
-        {
-            // optimize single entry case
-            for (int i = ePrefixLength; i < length; i++)
-            {
-                if (cmapGlyphs[i] > m_entries[length-1][0].m_unicode[i])
-                {
-                    return 1;
-                }
-                else if (cmapGlyphs[i] < m_entries[length-1][0].m_unicode[i])
-                {
-                    return 0;
-                }
-            }
-            if (entry)
-                *entry = m_entries[length-1];
-            return 0;
-        }
-        uint16 searchIndex = m_entryBSIndex[length-1] - 1;
-        uint16 stepSize = m_entryBSIndex[length-1] >> 1;
-        size_t prevIndex = searchIndex;
-        do
-        {
-            dir = 0;
-            if (searchIndex >= m_entryCounts[length-1])
-            {
-                dir = -1;
-                searchIndex -= stepSize;
-                stepSize >>= 1;
-            }
-            else
-            {
-                for (int i = ePrefixLength; i < length; i++)
-                {
-                    if (cmapGlyphs[i] > m_entries[length-1][searchIndex].m_unicode[i])
-                    {
-                        dir = 1;
-                        searchIndex += stepSize;
-                        stepSize >>= 1;
-                        break;
-                    }
-                    else if (cmapGlyphs[i] < m_entries[length-1][searchIndex].m_unicode[i])
-                    {
-                        dir = -1;
-                        searchIndex -= stepSize;
-                        stepSize >>= 1;
-                        break;
-                    }
-                }
-            }
-            if (prevIndex == searchIndex)
-                break;
-            prevIndex = searchIndex;
-        } while (dir != 0);
-        if (entry)
-        {
-            if (dir == 0)
-                *entry = m_entries[length-1] + searchIndex;
-            else
-                *entry = NULL;
-        }
-        else
-        {
-            // if entry is null, then this is for inserting a new value, which
-            // shouldn't already be in the cache
-            assert(dir != 0);
-            if (dir > 0)
-                ++searchIndex;
-        }
-        return searchIndex;
-    }
-    /** m_entries is a null terminated list of entries */
-    uint16 m_entryCounts[eMaxSpliceSize];
-    uint16 m_entryBSIndex[eMaxSpliceSize];
-    SegCacheEntry * m_entries[eMaxSpliceSize];
-    unsigned long long m_lastPurge;
-};
-
-union SegCachePrefixArray;
-
-#define SEG_CACHE_MIN_INDEX (store->maxCmapGid())
-#define SEG_CACHE_MAX_INDEX (store->maxCmapGid()+1u)
-#define SEG_CACHE_UNSET_INDEX (store->maxCmapGid()+2u)
-
-union SegCachePrefixArray
-{
-    void ** raw;
-    SegCachePrefixArray * array;
-    SegCachePrefixEntry ** prefixEntries;
-    uintptr * range;
-};
-
-class SegCache
-{
-public:
-    SegCache(const SegCacheStore * store, const Features& features);
-    ~SegCache();
-
-    const SegCacheEntry * find(const uint16 * cmapGlyphs, size_t length) const;
-    SegCacheEntry * cache(SegCacheStore * store, const uint16 * cmapGlyphs, size_t length, Segment * seg, size_t charOffset);
-    void purge(SegCacheStore * store);
-
-    long long totalAccessCount() const { return m_totalAccessCount; }
-    size_t segmentCount() const { return m_segmentCount; }
-    const Features & features() const { return m_features; }
-    void clear(SegCacheStore * store);
-
-    CLASS_NEW_DELETE
-private:
-    void freeLevel(SegCacheStore * store, SegCachePrefixArray prefixes, size_t level);
-    void purgeLevel(SegCacheStore * store, SegCachePrefixArray prefixes, size_t level,
-                    unsigned long long minAccessCount, unsigned long long oldAccessTime);
-
-    uint16 m_prefixLength;
-    uint16 m_maxCachedSegLength;
-    size_t m_segmentCount;
-    SegCachePrefixArray m_prefixes;
-    Features m_features;
-    mutable unsigned long long m_totalAccessCount;
-    mutable unsigned long long m_totalMisses;
-    float m_purgeFactor;
-};
-
-inline const SegCacheEntry * SegCache::find(const uint16 * cmapGlyphs, size_t length) const
-{
-    uint16 pos = 0;
-    if (!length || length > eMaxSpliceSize) return NULL;
-    SegCachePrefixArray pEntry = m_prefixes.array[cmapGlyphs[0]];
-    while (++pos < m_prefixLength - 1)
-    {
-        if (!pEntry.raw)
-        {
-            ++m_totalMisses;
-            return NULL;
-        }
-        pEntry = pEntry.array[(pos < length)? cmapGlyphs[pos] : 0];
-    }
-    if (!pEntry.raw)
-    {
-        ++m_totalMisses;
-        return NULL;
-    }
-    SegCachePrefixEntry * prefixEntry = pEntry.prefixEntries[(pos < length)? cmapGlyphs[pos] : 0];
-    if (!prefixEntry)
-    {
-        ++m_totalMisses;
-        return NULL;
-    }
-    const SegCacheEntry * entry = prefixEntry->find(cmapGlyphs, length);
-    if (entry)
-    {
-        ++m_totalAccessCount;
-        entry->accessed(m_totalAccessCount);
-    }
-    else
-    {
-        ++m_totalMisses;
-    }   
-    return entry;
-}
-    
-} // namespace graphite2
-
-#endif
-
--- a/gfx/graphite2/src/SegCacheEntry.cpp
+++ b/gfx/graphite2/src/SegCacheEntry.cpp
@@ -20,40 +20,40 @@
     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.
 */
 
-#ifndef DISABLE_SEGCACHE
+#ifndef GRAPHITE2_NSEGCACHE
 
-#include "Main.h"
-#include "Slot.h"
-#include "Segment.h"
-#include "SegCache.h"
-#include "SegCacheEntry.h"
+#include "inc/Main.h"
+#include "inc/Slot.h"
+#include "inc/Segment.h"
+#include "inc/SegCache.h"
+#include "inc/SegCacheEntry.h"
 
 
 using namespace graphite2;
 
 SegCacheEntry::SegCacheEntry(const uint16* cmapGlyphs, size_t length, Segment * seg, size_t charOffset, long long cacheTime)
     : m_glyphLength(0), m_unicode(gralloc<uint16>(length)), m_glyph(NULL),
     m_attr(NULL),
     m_accessCount(0), m_lastAccess(cacheTime)
 {
     for (uint16 i = 0; i < length; i++)
     {
         m_unicode[i] = cmapGlyphs[i];
     }
     size_t glyphCount = seg->slotCount();
     const Slot * slot = seg->first();
     m_glyph = new Slot[glyphCount];
-    m_attr = gralloc<uint16>(glyphCount * seg->numAttrs());
+    m_attr = gralloc<int16>(glyphCount * seg->numAttrs());
     m_glyphLength = glyphCount;
     Slot * slotCopy = m_glyph;
     m_glyph->prev(NULL);
     struct Index2Slot {
         Index2Slot(uint16 i, const Slot * s) : m_i(i), m_slot(s) {};
         Index2Slot() : m_i(0), m_slot(NULL) {};
         uint16 m_i;
         const Slot * m_slot;
@@ -122,44 +122,16 @@ SegCacheEntry::SegCacheEntry(const uint1
                 {
                     m_glyph[parentGlyphs[j].m_i].child(m_glyph + childGlyphs[i].m_i);
                 }
             }
         }
     }
 }
 
-void SegCacheEntry::log(GR_MAYBE_UNUSED size_t unicodeLength) const
-{
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementSegCacheEntry);
-        XmlTraceLog::get().addAttribute(AttrAccessCount, m_accessCount);
-        XmlTraceLog::get().addAttribute(AttrLastAccess, m_lastAccess);
-        for (size_t i = 0; i < unicodeLength; i++)
-        {
-            XmlTraceLog::get().openElement(ElementText);
-            XmlTraceLog::get().addAttribute(AttrGlyphId, m_unicode[i]);
-            XmlTraceLog::get().closeElement(ElementText);
-        }
-        for (size_t i = 0; i < m_glyphLength; i++)
-        {
-            XmlTraceLog::get().openElement(ElementGlyph);
-            XmlTraceLog::get().addAttribute(AttrGlyphId, m_glyph[i].gid());
-            XmlTraceLog::get().addAttribute(AttrX, m_glyph[i].origin().x);
-            XmlTraceLog::get().addAttribute(AttrY, m_glyph[i].origin().y);
-            XmlTraceLog::get().addAttribute(AttrBefore, m_glyph[i].before());
-            XmlTraceLog::get().addAttribute(AttrAfter, m_glyph[i].after());
-            XmlTraceLog::get().closeElement(ElementGlyph);
-        }
-        XmlTraceLog::get().closeElement(ElementSegCacheEntry);
-    }
-#endif
-}
 
 void SegCacheEntry::clear()
 {
     free(m_unicode);
     free(m_attr);
     delete [] m_glyph;
     m_unicode = NULL;
     m_glyph = NULL;
deleted file mode 100644
--- a/gfx/graphite2/src/SegCacheEntry.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#ifndef DISABLE_SEGCACHE
-
-#include "Main.h"
-
-namespace graphite2 {
-
-class Segment;
-class Slot;
-class SegCacheEntry;
-class SegCachePrefixEntry;
-
-enum SegCacheParameters {
-    /** number of characters used in initial prefix tree */
-    ePrefixLength = 2,
-    /** Segments more recent than maxSegmentCount() / eAgeFactor are kept */
-    eAgeFactor = 4,
-    /** Segments are purged according to the formular:
-     * accessCount < (totalAccesses)/(ePurgeFactor * maxSegments) */
-    ePurgeFactor = 5,
-    /** Maximum number of Segments to store which have the same
-     * prefix. Needed to prevent unique identifiers flooding the cache */
-    eMaxSuffixCount = 15
-
-};
-
-class SegCacheCharInfo
-{
-public:
-    uint16 m_unicode;
-    uint16 m_before;
-    uint16 m_after;
-};
-
-/**
- * SegCacheEntry stores the result of running the engine for specific unicode
- * code points in the typical mid-line situation.
- */
-class SegCacheEntry
-{
-    friend class SegCachePrefixEntry;
-public:
-    SegCacheEntry() :
-        m_glyphLength(0), m_unicode(NULL), m_glyph(NULL), m_attr(NULL),
-        m_accessCount(0), m_lastAccess(0)
-    {}
-    SegCacheEntry(const uint16 * cmapGlyphs, size_t length, Segment * seg, size_t charOffset, long long cacheTime);
-    ~SegCacheEntry() { clear(); };
-    void clear();
-    size_t glyphLength() const { return m_glyphLength; }
-    const Slot * first() const { return m_glyph; }
-    const Slot * last() const { return m_glyph + (m_glyphLength - 1); }
-
-    void log(size_t unicodeLength) const;
-    /** Total number of times this entry has been accessed since creation */
-    unsigned long long accessCount() const { return m_accessCount; }
-    /** "time" of last access where "time" is measured in accesses to the cache owning this entry */
-    void accessed(unsigned long long cacheTime) const
-    {
-        m_lastAccess = cacheTime; ++m_accessCount;
-    };
-
-    int compareRank(const SegCacheEntry & entry) const
-    {
-        if (m_accessCount > entry.m_accessCount) return 1;
-        else if (m_accessCount < entry.m_accessCount) return 1;
-        else if (m_lastAccess > entry.m_lastAccess) return 1;
-        else if (m_lastAccess < entry.m_lastAccess) return -1;
-        return 0;
-    }
-    unsigned long long lastAccess() const { return m_lastAccess; };
-
-    CLASS_NEW_DELETE;
-private:
-
-    size_t m_glyphLength;
-    /** glyph ids resulting from cmap mapping from unicode to glyph before substitution
-     * the length of this array is determined by the position in the SegCachePrefixEntry */
-    uint16 * m_unicode;
-    /** slots after shapping and positioning */
-    Slot * m_glyph;
-    uint16 * m_attr;
-    mutable unsigned long long m_accessCount;
-    mutable unsigned long long m_lastAccess;
-};
-
-} // namespace graphite2
-
-#endif
--- a/gfx/graphite2/src/SegCacheStore.cpp
+++ b/gfx/graphite2/src/SegCacheStore.cpp
@@ -20,20 +20,20 @@
     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.
 */
 
-#ifndef DISABLE_SEGCACHE
+#ifndef GRAPHITE2_NSEGCACHE
 
-#include "SegCacheStore.h"
-#include "Face.h"
+#include "inc/SegCacheStore.h"
+#include "inc/Face.h"
 
 
 using namespace graphite2;
 
 SegCacheStore::SegCacheStore(const Face *face, unsigned int numSilf, size_t maxSegments)
  : m_caches(new SilfSegCache[numSilf]), m_numSilf(numSilf), m_maxSegments(maxSegments),
    m_maxCmapGid(0)
 {
deleted file mode 100644
--- a/gfx/graphite2/src/SegCacheStore.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#ifndef DISABLE_SEGCACHE
-
-#include "Main.h"
-#include "CmapCache.h"
-#include "SegCache.h"
-
-namespace graphite2 {
-
-class SegCache;
-class Face;
-
-class SilfSegCache
-{
-public:
-    SilfSegCache() : m_caches(NULL), m_cacheCount(0) {};
-    ~SilfSegCache()
-    {
-        assert(m_caches == NULL);
-    }
-    void clear(SegCacheStore * cacheStore)
-    {
-        for (size_t i = 0; i < m_cacheCount; i++)
-        {
-            m_caches[i]->clear(cacheStore);
-            delete m_caches[i];
-        }
-        free(m_caches);
-        m_caches = NULL;
-        m_cacheCount = 0;
-    }
-    SegCache * getOrCreate(SegCacheStore * cacheStore, const Features & features)
-    {
-        for (size_t i = 0; i < m_cacheCount; i++)
-        {
-            if (m_caches[i]->features() == features)
-                return m_caches[i];
-        }
-        SegCache ** newData = gralloc<SegCache*>(m_cacheCount+1);
-        if (newData)
-        {
-            if (m_cacheCount > 0)
-            {
-                memcpy(newData, m_caches, sizeof(SegCache*) * m_cacheCount);
-                free(m_caches);
-            }
-            m_caches = newData;
-            m_caches[m_cacheCount] = new SegCache(cacheStore, features);
-            m_cacheCount++;
-            return m_caches[m_cacheCount - 1];
-        }
-        return NULL;
-    }
-    CLASS_NEW_DELETE
-private:
-    SegCache ** m_caches;
-    size_t m_cacheCount;
-};
-
-class SegCacheStore
-{
-public:
-    SegCacheStore(const Face *face, unsigned int numSilf, size_t maxSegments);
-    ~SegCacheStore()
-    {
-        for (size_t i = 0; i < m_numSilf; i++)
-        {
-            m_caches[i].clear(this);
-        }
-        delete [] m_caches;
-        m_caches = NULL;
-    }
-    SegCache * getOrCreate(unsigned int i, const Features & features)
-    {
-        return m_caches[i].getOrCreate(this, features);
-    }
-    bool isSpaceGlyph(uint16 gid) const { return (gid == m_spaceGid) || (gid == m_zwspGid); }
-    uint16 maxCmapGid() const { return m_maxCmapGid; }
-    uint32 maxSegmentCount() const { return m_maxSegments; };
-
-    CLASS_NEW_DELETE
-private:
-    SilfSegCache * m_caches;
-    uint8 m_numSilf;
-    uint32 m_maxSegments;
-    uint16 m_maxCmapGid;
-    uint16 m_spaceGid;
-    uint16 m_zwspGid;
-};
-
-} // namespace graphite2
-
-#endif
-
--- a/gfx/graphite2/src/Segment.cpp
+++ b/gfx/graphite2/src/Segment.cpp
@@ -19,27 +19,26 @@
     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.
 */
-#include "UtfCodec.h"
+#include "inc/UtfCodec.h"
 #include <cstring>
 #include <cstdlib>
 
-#include "Segment.h"
+#include "inc/Segment.h"
 #include "graphite2/Font.h"
-#include "CharInfo.h"
-#include "Slot.h"
-#include "Main.h"
-#include "XmlTraceLog.h"
-#include "CmapCache.h"
+#include "inc/CharInfo.h"
+#include "inc/Slot.h"
+#include "inc/Main.h"
+#include "inc/CmapCache.h"
 #include "graphite2/Segment.h"
 
 
 using namespace graphite2;
 
 Segment::Segment(unsigned int numchars, const Face* face, uint32 script, int textDir) :
         m_freeSlots(NULL),
         m_first(NULL),
@@ -65,17 +64,17 @@ Segment::~Segment()
 {
     for (SlotRope::iterator i = m_slots.begin(); i != m_slots.end(); ++i)
         free(*i);
     for (AttributeRope::iterator j = m_userAttrs.begin(); j != m_userAttrs.end(); ++j)
         free(*j);
     delete[] m_charinfo;
 }
 
-#ifndef DISABLE_SEGCACHE
+#ifndef GRAPHITE2_NSEGCACHE
 SegmentScopeState Segment::setScope(Slot * firstSlot, Slot * lastSlot, size_t subLength)
 {
     SegmentScopeState state;
     state.numGlyphsOutsideScope = m_numGlyphs - subLength;
     state.realFirstSlot = m_first;
     state.slotBeforeScope = firstSlot->prev();
     state.slotAfterScope = lastSlot->next();
     state.realLastSlot = m_last;
@@ -126,17 +125,17 @@ void Segment::append(const Segment &othe
     for (unsigned int i=0 ; i<m_numCharinfo ; ++i)
         pNewCharInfo[i] = other.m_charinfo[i];
  
     m_numCharinfo += other.m_numCharinfo;
     m_numGlyphs += other.m_numGlyphs;
     m_advance = m_advance + other.m_advance;
     m_bbox = m_bbox.widen(bbox);
 }
-#endif // DISABLE_SEGCACHE
+#endif // GRAPHITE2_NSEGCACHE
 
 void Segment::appendSlot(int id, int cid, int gid, int iFeats, size_t coffset)
 {
     Slot *aSlot = newSlot();
     
     m_charinfo[id].init(cid);
     m_charinfo[id].feats(iFeats);
     m_charinfo[id].base(coffset);
@@ -162,17 +161,17 @@ void Segment::appendSlot(int id, int cid
 }
 
 Slot *Segment::newSlot()
 {
     if (!m_freeSlots)
     {
         int numUser = m_silf->numUser();
         Slot *newSlots = grzeroalloc<Slot>(m_bufSize);
-        uint16 *newAttrs = grzeroalloc<uint16>(numUser * m_bufSize);
+        int16 *newAttrs = grzeroalloc<int16>(numUser * m_bufSize);
         newSlots[0].userAttrs(newAttrs);
         for (size_t i = 1; i < m_bufSize - 1; i++)
         {
             newSlots[i].next(newSlots + i + 1);
             newSlots[i].userAttrs(newAttrs + i * numUser);
         }
         newSlots[m_bufSize - 1].userAttrs(newAttrs + (m_bufSize - 1) * numUser);
         newSlots[m_bufSize - 1].next(NULL);
@@ -188,26 +187,28 @@ Slot *Segment::newSlot()
 }
 
 void Segment::freeSlot(Slot *aSlot)
 {
     if (m_last == aSlot) m_last = aSlot->prev();
     if (m_first == aSlot) m_first = aSlot->next();
     // reset the slot incase it is reused
     ::new (aSlot) Slot;
-    memset(aSlot->userAttrs(), 0, m_silf->numUser() * sizeof(uint16));
+    memset(aSlot->userAttrs(), 0, m_silf->numUser() * sizeof(int16));
+    // Update generation counter for debug
+    aSlot->index(aSlot->index()+1);
     // update next pointer
     if (!m_freeSlots)
         aSlot->next(NULL);
     else
         aSlot->next(m_freeSlots);
     m_freeSlots = aSlot;
 }
 
-#ifndef DISABLE_SEGCACHE
+#ifndef GRAPHITE2_NSEGCACHE
 void Segment::splice(size_t offset, size_t length, Slot * startSlot,
                        Slot * endSlot, const Slot * firstSpliceSlot,
                        size_t numGlyphs)
 {
     const Slot * replacement = firstSpliceSlot;
     Slot * slot = startSlot;
     extendLength(numGlyphs - length);
     // insert extra slots if needed
@@ -280,155 +281,76 @@ void Segment::splice(size_t offset, size
                 ++slotPosition;
             }
             slot->child(slotArray[pos]);
         }
         slot = slot->next();
         replacement = replacement->next();
     }
 }
-#endif // DISABLE_SEGCACHE
-        
-void Segment::positionSlots(const Font *font, Slot *iStart, Slot *iEnd)
+#endif // GRAPHITE2_NSEGCACHE
+
+void Segment::linkClusters(Slot *s, Slot * end)
+{
+	end = end->next();
+
+	for (; s != end && !s->isBase(); s = s->next());
+	Slot * ls = s;
+
+	if (m_dir & 1)
+	{
+		for (; s != end; s = s->next())
+		{
+			if (!s->isBase())	continue;
+
+			s->sibling(ls);
+			ls = s;
+		}
+	}
+	else
+	{
+		for (; s != end; s = s->next())
+		{
+			if (!s->isBase())	continue;
+
+			ls->sibling(s);
+			ls = s;
+		}
+	}
+}
+
+Position Segment::positionSlots(const Font *font, Slot * iStart, Slot * iEnd)
 {
     Position currpos(0., 0.);
-    Slot *s, *ls = NULL;
-    int iSlot = 0;
+    Rect bbox;
     float cMin = 0.;
     float clusterMin = 0.;
-    Rect bbox;
 
-    if (!iStart) iStart = m_first;
-    if (!iEnd) iEnd = m_last;
-    
+    if (!iStart)	iStart = m_first;
+    if (!iEnd)		iEnd   = m_last;
+
     if (m_dir & 1)
     {
-        for (s = iEnd, iSlot = m_numGlyphs - 1; s && s != iStart->prev(); s = s->prev(), --iSlot)
+        for (Slot * s = iEnd, * const end = iStart->prev(); s && s != end; s = s->prev())
         {
-            int j = s->before();
-            if (j >= 0)
-            {
-                for ( ; j <= s->after(); j++)
-                {
-                    CharInfo *c = charinfo(j);
-                    if (c->before() == -1 || iSlot < c->before()) c->before(iSlot);
-                    if (c->after() < iSlot) c->after(iSlot);
-                }
-            }
-            s->index(iSlot);
-
             if (s->isBase())
-            {
-                clusterMin = currpos.x;
-                currpos = s->finalise(this, font, &currpos, &bbox, &cMin, 0, &clusterMin);
-                if (ls)
-                    ls->sibling(s);
-                ls = s;
-            }
+                currpos = s->finalise(this, font, currpos, bbox, cMin, 0, clusterMin = currpos.x);
         }
     }
     else
     {
-        for (s = iStart, iSlot = 0; s && s != iEnd->next(); s = s->next(), ++iSlot)
+        for (Slot * s = iStart, * const end = iEnd->next(); s && s != end; s = s->next())
         {
-            int j = s->before();
-            if (j >= 0)
-            {
-                for ( ; j <= s->after(); j++)
-                {
-                    CharInfo *c = charinfo(j);
-                    if (c->before() == -1 || iSlot < c->before()) c->before(iSlot);
-                    if (c->after() < iSlot) c->after(iSlot);
-                }
-            }
-            s->index(iSlot);
-
             if (s->isBase())
-            {
-                clusterMin = currpos.x;
-                currpos = s->finalise(this, font, &currpos, &bbox, &cMin, 0, &clusterMin);
-                if (ls)
-                    ls->sibling(s);
-                ls = s;
-            }
+                currpos = s->finalise(this, font, currpos, bbox, cMin, 0, clusterMin = currpos.x);
         }
     }
-    if (iStart == m_first && iEnd == m_last) m_advance = currpos;
+    return currpos;
 }
 
-#ifndef DISABLE_TRACING
-void Segment::logSegment(gr_encform enc, const void* pStart, size_t nChars) const
-{
-    if (XmlTraceLog::get().active())
-    {
-        if (pStart)
-        {
-            XmlTraceLog::get().openElement(ElementText);
-            XmlTraceLog::get().addAttribute(AttrEncoding, enc);
-            XmlTraceLog::get().addAttribute(AttrLength, nChars);
-            switch (enc)
-            {
-            case gr_utf8:
-                XmlTraceLog::get().writeText(
-                    reinterpret_cast<const char *>(pStart));
-                break;
-            case gr_utf16:
-                for (size_t j = 0; j < nChars; ++j)
-                {
-                    uint32 code = reinterpret_cast<const uint16 *>(pStart)[j];
-                    if (code >= 0xD800 && code <= 0xDBFF) // high surrogate
-                    {
-                        j++;
-                        // append low surrogate
-                        code = (code << 16) + reinterpret_cast<const uint16 *>(pStart)[j];
-                    }
-                    else if (code >= 0xDC00 && code <= 0xDFFF)
-                    {
-                        XmlTraceLog::get().warning("Unexpected low surrogate %x at %d", code, j);
-                    }
-                    XmlTraceLog::get().writeUnicode(code);
-                }
-                break;
-            case gr_utf32:
-                for (size_t j = 0; j < nChars; ++j)
-                {
-                    XmlTraceLog::get().writeUnicode(
-                        reinterpret_cast<const uint32 *>(pStart)[j]);
-                }
-                break;
-            }
-            XmlTraceLog::get().closeElement(ElementText);
-        }
-        logSegment();
-    }
-}
-
-void Segment::logSegment() const
-{
-    if (XmlTraceLog::get().active())
-    {
-        XmlTraceLog::get().openElement(ElementSegment);
-        XmlTraceLog::get().addAttribute(AttrLength, slotCount());
-        XmlTraceLog::get().addAttribute(AttrAdvanceX, advance().x);
-        XmlTraceLog::get().addAttribute(AttrAdvanceY, advance().y);
-        for (Slot *i = m_first; i; i = i->next())
-        {
-            XmlTraceLog::get().openElement(ElementSlot);
-            XmlTraceLog::get().addAttribute(AttrGlyphId, i->gid());
-            XmlTraceLog::get().addAttribute(AttrX, i->origin().x);
-            XmlTraceLog::get().addAttribute(AttrY, i->origin().y);
-            XmlTraceLog::get().addAttribute(AttrBefore, i->before());
-            XmlTraceLog::get().addAttribute(AttrAfter, i->after());
-            XmlTraceLog::get().closeElement(ElementSlot);
-        }
-        XmlTraceLog::get().closeElement(ElementSegment);
-    }
-}
-
-#endif
 
 template <typename utf_iter>
 inline void process_utf_data(Segment & seg, const Face & face, const int fid, utf_iter c, size_t n_chars)
 {
 	const Cmap    & cmap = face.cmap();
 	int slotid = 0;
 
 	const typename utf_iter::codeunit_type * const base = c;
@@ -436,16 +358,17 @@ inline void process_utf_data(Segment & s
 	{
 		const uint32 usv = *c;
 		uint16 gid = cmap[usv];
 		if (!gid)	gid = face.findPseudo(usv);
 		seg.appendSlot(slotid, usv, gid, fid, c - base);
 	}
 }
 
+
 void Segment::read_text(const Face *face, const Features* pFeats/*must not be NULL*/, gr_encform enc, const void* pStart, size_t nChars)
 {
 	assert(face);
 	assert(pFeats);
 
 	switch (enc)
 	{
 	case gr_utf8:	process_utf_data(*this, *face, addFeatures(*pFeats), utf8::const_iterator(pStart), nChars); break;
@@ -456,17 +379,33 @@ void Segment::read_text(const Face *face
 
 void Segment::prepare_pos(const Font * /*font*/)
 {
     // copy key changeable metrics into slot (if any);
 }
 
 void Segment::finalise(const Font *font)
 {
-    positionSlots(font);
+	if (!m_first) return;
+
+    m_advance = positionSlots(font);
+    int i = 0;
+    for (Slot * s = m_first; s; s->index(i++), s = s->next())
+    {
+        int j = s->before();
+        if (j < 0)	continue;
+
+        for (const int after = s->after(); j <= after; ++j)
+		{
+			CharInfo & c = *charinfo(j);
+			if (c.before() == -1 || i < c.before()) 	c.before(i);
+			if (c.after() < i) 							c.after(i);
+		}
+    }
+    linkClusters(m_first, m_last);
 }
 
 void Segment::justify(Slot *pSlot, const Font *font, float width, GR_MAYBE_UNUSED justFlags flags, Slot *pFirst, Slot *pLast)
 {
     Slot *pEnd = pSlot;
     Slot *s, *end;
     int numBase = 0;
     float currWidth = 0.;
deleted file mode 100644
--- a/gfx/graphite2/src/Segment.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include "Main.h"
-
-#include <cassert>
-
-#include "Slot.h"
-#include "CharInfo.h"
-#include "FeatureVal.h"
-#include "XmlTraceLog.h"
-#include "Silf.h"
-
-#include "List.h"
-
-#define MAX_SEG_GROWTH_FACTOR  256
-
-namespace graphite2 {
-
-typedef Vector<Features>        FeatureList;
-typedef Vector<Slot *>          SlotRope;
-typedef Vector<uint16 *>        AttributeRope;
-
-#ifndef DISABLE_SEGCACHE
-class SegmentScopeState;
-#endif
-class Segment;
-
-enum SpliceParam {
-/** sub-Segments longer than this are not cached
- * (in Unicode code points) */
-    eMaxSpliceSize = 16
-};
-
-enum justFlags {
-    gr_justStartInline = 1,
-    gr_justEndInline = 2
-};
-
-class SegmentScopeState
-{
-private:
-    friend class Segment;
-    Slot * realFirstSlot;
-    Slot * slotBeforeScope;
-    Slot * slotAfterScope;
-    Slot * realLastSlot;
-    size_t numGlyphsOutsideScope;
-};
-
-class Segment
-{
-public:
-    unsigned int slotCount() const { return m_numGlyphs; }      //one slot per glyph
-    void extendLength(int num) { m_numGlyphs += num; }
-    Position advance() const { return m_advance; }
-    bool runGraphite() { if (m_silf) return m_face->runGraphite(this, m_silf); else return true;};
-    void chooseSilf(uint32 script) { m_silf = m_face->chooseSilf(script); }
-    const Silf *silf() const { return m_silf; }
-    unsigned int charInfoCount() const { return m_numCharinfo; }
-    const CharInfo *charinfo(unsigned int index) const { return index < m_numCharinfo ? m_charinfo + index : NULL; }
-    CharInfo *charinfo(unsigned int index) { return index < m_numCharinfo ? m_charinfo + index : NULL; }
-    int8 dir() const { return m_dir; }
-
-    Segment(unsigned int numchars, const Face* face, uint32 script, int dir);
-    ~Segment();
-#ifndef DISABLE_SEGCACHE
-    SegmentScopeState setScope(Slot * firstSlot, Slot * lastSlot, size_t subLength);
-    void removeScope(SegmentScopeState & state);
-    void append(const Segment &other);
-    void splice(size_t offset, size_t length, Slot * startSlot, Slot * endSlot, 
-                const Slot * firstSpliceSlot, size_t numGlyphs);
-#endif
-    Slot *first() { return m_first; }
-    void first(Slot *p) { m_first = p; }
-    Slot *last() { return m_last; }
-    void last(Slot *p) { m_last = p; }
-    void appendSlot(int i, int cid, int gid, int fid, size_t coffset);
-    Slot *newSlot();
-    void freeSlot(Slot *);
-    void positionSlots(const Font *font, Slot *iStart = NULL, Slot *iEnd = NULL);
-    uint16 getClassGlyph(uint16 cid, uint16 offset) const { return m_silf->getClassGlyph(cid, offset); }
-    uint16 findClassIndex(uint16 cid, uint16 gid) const { return m_silf->findClassIndex(cid, gid); }
-    int addFeatures(const Features& feats) { m_feats.push_back(feats); return m_feats.size() - 1; }
-    uint16 getFeature(int index, uint8 findex) const { const FeatureRef* pFR=m_face->theSill().theFeatureMap().featureRef(findex); if (!pFR) return 0; else return pFR->getFeatureVal(m_feats[index]); }
-    void dir(int8 val) { m_dir = val; }
-    uint16 glyphAttr(uint16 gid, uint8 gattr) const { return m_face->glyphAttr(gid, gattr); }
-    uint16 getGlyphMetric(Slot *iSlot, uint8 metric, uint8 attrLevel) const {
-        if (attrLevel > 0)
-        {
-            Slot *is = findRoot(iSlot);
-            return is->clusterMetric(this, metric, attrLevel);
-        }
-        else
-            return m_face->getGlyphMetric(iSlot->gid(), metric);
-    }
-    float glyphAdvance(uint16 gid) const { return m_face->getAdvance(gid, 1.0); }
-    const Rect &theGlyphBBoxTemporary(uint16 gid) const { return m_face->theBBoxTemporary(gid); }   //warning value may become invalid when another glyph is accessed
-    Slot *findRoot(Slot *is) const { return is->attachTo() ? findRoot(is->attachTo()) : is; }
-    int numAttrs() { return m_silf->numUser(); }
-    int defaultOriginal() const { return m_defaultOriginal; }
-    const Face * getFace() const { return m_face; }
-    const Features & getFeatures(unsigned int /*charIndex*/) { assert(m_feats.size() == 1); return m_feats[0]; }
-    void bidiPass(uint8 aBidi, int paradir, uint8 aMirror);
-
-    CLASS_NEW_DELETE
-
-#ifndef DISABLE_TRACING
-    void logSegment(gr_encform enc, const void* pStart, size_t nChars) const;
-    void logSegment() const;
-#endif
-
-public:       //only used by: GrSegment* makeAndInitialize(const GrFont *font, const GrFace *face, uint32 script, const FeaturesHandle& pFeats/*must not be IsNull*/, encform enc, const void* pStart, size_t nChars, int dir);
-    void read_text(const Face *face, const Features* pFeats/*must not be NULL*/, gr_encform enc, const void*pStart, size_t nChars);
-    void prepare_pos(const Font *font);
-    void finalise(const Font *font);
-    void justify(Slot *pSlot, const Font *font, float width, enum justFlags flags, Slot *pFirst, Slot *pLast);
-  
-private:
-    SlotRope m_slots;           // std::vector of slot buffers
-    Slot *m_freeSlots;          // linked list of free slots
-    Slot *m_first;              // first slot in segment
-    Slot *m_last;               // last slot in segment
-    unsigned int m_bufSize;     // how big a buffer to create when need more slots
-    unsigned int m_numGlyphs;
-    unsigned int m_numCharinfo; // size of the array and number of input characters
-    int m_defaultOriginal;      // CharInfo index used if all slots have been deleted
-    AttributeRope m_userAttrs;  // std::vector of userAttrs buffers
-    CharInfo *m_charinfo;       // character info, one per input character
-
-    const Face *m_face;       // GrFace
-    const Silf *m_silf;
-    Position m_advance;         // whole segment advance
-    Rect m_bbox;                // ink box of the segment
-    int8 m_dir;
-    FeatureList m_feats;	// feature settings referenced by charinfos in this segment
-
-private:		//defensive on m_charinfo
-    Segment(const Segment&);
-    Segment& operator=(const Segment&);
-};
-
-} // namespace graphite2
-
-struct gr_segment : public graphite2::Segment {};
-
--- a/gfx/graphite2/src/Silf.cpp
+++ b/gfx/graphite2/src/Silf.cpp
@@ -21,25 +21,26 @@
 
 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.
 */
 #include <cstdlib>
 #include "graphite2/Segment.h"
-#include "Endian.h"
-#include "Silf.h"
-#include "XmlTraceLog.h"
-#include "Segment.h"
-#include "Rule.h"
+#include "inc/debug.h"
+#include "inc/Endian.h"
+#include "inc/Silf.h"
+#include "inc/Segment.h"
+#include "inc/Rule.h"
 
 
 using namespace graphite2;
 
+
 Silf::Silf() throw()
 : m_passes(0), m_pseudos(0), m_classOffsets(0), m_classData(0), m_justs(0),
   m_numPasses(0), m_sPass(0), m_pPass(0), m_jPass(0), m_bPass(0), m_flags(0),
   m_aBreak(0), m_aUser(0), m_iMaxComp(0),
   m_aLig(0), m_numPseudo(0), m_nClass(0), m_nLinear(0)
 {
 }
 
@@ -58,217 +59,142 @@ void Silf::releaseBuffers() throw()
     m_passes= 0;
     m_pseudos = 0;
     m_classOffsets = 0;
     m_classData = 0;
     m_justs = 0;
 }
 
 
-bool Silf::readGraphite(void* pSilf, size_t lSilf, const Face& face, uint32 version)
+bool Silf::readGraphite(const void* pSilf, size_t lSilf, const Face& face, uint32 version)
 {
-    const byte *p = (byte *)pSilf;
-    const byte * const eSilf = p + lSilf;
-    uint32 *pPasses;
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().openElement(ElementSilfSub);
-#endif
+    const byte * p = (byte *)pSilf,
+    		   * const eSilf = p + lSilf;
+
     if (version >= 0x00030000)
     {
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-            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; }
+        if (lSilf < 27)		{ releaseBuffers(); return false; }
         p += 8;
     }
-    else if (lSilf < 19) { releaseBuffers(); return false; }
+    else if (lSilf < 19) 	{ releaseBuffers(); return false; }
     p += 2;     // maxGlyphID
     p += 4;     // extra ascent/descent
     m_numPasses = uint8(*p++);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrNumPasses, m_numPasses);
-#endif
     if (m_numPasses > 128)
         return false;
     m_passes = new Pass[m_numPasses];
     m_sPass = uint8(*p++);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrSubPass, m_sPass);
-#endif
     m_pPass = uint8(*p++);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrPosPass, m_pPass);
-#endif
     if (m_pPass < m_sPass) {
         releaseBuffers();
         return false;
     }
     m_jPass = uint8(*p++);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrJustPass, m_jPass);
-#endif
     if (m_jPass < m_pPass) {
         releaseBuffers();
         return false;
     }
     m_bPass = uint8(*p++);     // when do we reorder?
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrBidiPass, m_bPass);
-#endif
     if (m_bPass != 0xFF && (m_bPass < m_jPass || m_bPass > m_numPasses)) {
         releaseBuffers();
         return false;
     }
     m_flags = uint8(*p++);
     p += 2;     // ignore line end contextuals for now
     m_aPseudo = uint8(*p++);
     m_aBreak = uint8(*p++);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrBreakWeight, m_aBreak);
-    XmlTraceLog::get().addAttribute(AttrDirectionality, *p);
-#endif
     m_aBidi = uint8(*p++);
     m_aMirror = uint8(*p++);
     p += 1;     // skip reserved stuff
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrNumJustLevels, *p);
-#endif
     m_numJusts = uint8(*p++);
     m_justs = gralloc<Justinfo>(m_numJusts);
     for (uint8 i = 0; i < m_numJusts; i++)
     {
         ::new(m_justs + i) Justinfo(p[0], p[1], p[2], p[3]);
         p += 8;
     }
 //    p += uint8(*p) * 8 + 1;     // ignore justification for now
     if (p + 9 >= eSilf) { releaseBuffers(); return false; }
     m_aLig = be::read<uint16>(p);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrLigComp, *p);
-#endif
     if (m_aLig > 127) {
         releaseBuffers();
         return false;
     }
     m_aUser = uint8(*p++);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrUserDefn, m_aUser);
-#endif
     m_iMaxComp = uint8(*p++);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrNumLigComp, m_iMaxComp);
-#endif
     p += 5;     // skip direction and reserved
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrNumCritFeatures, *p);
-#endif
     p += uint8(*p) * 2 + 1;        // don't need critical features yet
     p++;        // reserved
     if (p >= eSilf) 
     {
         releaseBuffers();
         return false;
     }
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrNumScripts, *p);
-#endif
     p += uint8(*p) * 4 + 1;        // skip scripts
     p += 2;     // skip lbGID
     
     if (p + 4 * (m_numPasses + 1) + 6 >= eSilf) 
     {
         releaseBuffers(); 
         return false;
     }
-    pPasses = (uint32 *)p;
+    const byte * pPasses = p;
     p += 4 * (m_numPasses + 1);
     m_numPseudo = be::read<uint16>(p);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().addAttribute(AttrNumPseudo, m_numPseudo);
-#endif
     p += 6;
     if (p + m_numPseudo * 6 >= eSilf) 
     {
         releaseBuffers();
         return false;
     }
     m_pseudos = new Pseudo[m_numPseudo];
     for (int i = 0; i < m_numPseudo; i++)
     {
         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);
-        XmlTraceLog::get().addAttribute(AttrGlyphId, m_pseudos[i].uid);
-        XmlTraceLog::get().writeUnicode(m_pseudos[i].uid);
-        XmlTraceLog::get().closeElement(ElementPseudo);
-#endif
     }
     if (p >= eSilf) 
     {
         releaseBuffers();
         return false;
     }
 
-    int clen = readClassMap(p, be::swap<uint32>(*pPasses) - (p - (byte *)pSilf), version);
+    int clen = readClassMap(p, be::peek<uint32>(pPasses) - (p - (byte *)pSilf), version);
     if (clen < 0) {
         releaseBuffers();
         return false;
     }
     p += clen;
 
     for (size_t i = 0; i < m_numPasses; ++i)
     {
-        uint32 pOffset = be::swap<uint32>(pPasses[i]);
-        uint32 pEnd = be::swap<uint32>(pPasses[i + 1]);
+        uint32 pOffset = be::read<uint32>(pPasses);
+        uint32 pEnd = be::peek<uint32>(pPasses);
         if ((uint8 *)pSilf + pEnd > eSilf || pOffset > pEnd)
         {
             releaseBuffers();
             return false;
         }
         m_passes[i].init(this);
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-            XmlTraceLog::get().openElement(ElementPass);
-            XmlTraceLog::get().addAttribute(AttrPassId, i);
-        }
-#endif
         if (!m_passes[i].readPass((char *)pSilf + pOffset, pEnd - pOffset, pOffset, face))
         {
-#ifndef DISABLE_TRACING
-            XmlTraceLog::get().closeElement(ElementPass);
-#endif
-            {
-        releaseBuffers();
-        return false;
-            }
+        	releaseBuffers();
+        	return false;
         }
-#ifndef DISABLE_TRACING
-        XmlTraceLog::get().closeElement(ElementPass);
-#endif
     }
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().closeElement(ElementSilfSub);
-#endif
     return true;
 }
 
 template<typename T> inline uint32 Silf::readClassOffsets(const byte *&p, size_t data_len)
 {
 	const T cls_off = 2*sizeof(uint16) + sizeof(T)*(m_nClass+1);
 	const uint32 max_off = (be::peek<T>(p + sizeof(T)*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<T>(p) != cls_off || max_off > (data_len - cls_off)/sizeof(uint16))
-		return -1;
+		return 0;
 
 	// Read in all the offsets.
 	m_classOffsets = gralloc<uint32>(m_nClass+1);
 	for (uint32 * o = m_classOffsets, * const o_end = o + m_nClass + 1; o != o_end; ++o)
 	{
 		*o = (be::read<T>(p) - cls_off)/sizeof(uint16);
 		if (*o > max_off)
 			return 0;
@@ -367,64 +293,111 @@ uint16 Silf::getClassGlyph(uint16 cid, u
     else        // input class being used for output. Shouldn't happen
     {
         for (unsigned int i = loc + 4; i < m_classOffsets[cid + 1]; i += 2)
             if (m_classData[i + 1] == index) return m_classData[i];
     }
     return 0;
 }
 
+
 bool Silf::runGraphite(Segment *seg, uint8 firstPass, uint8 lastPass) const
 {
     assert(seg != 0);
     SlotMap            map(*seg);
     FiniteStateMachine fsm(map);
     vm::Machine        m(map);
     unsigned int       initSize = seg->slotCount();
 
     if (lastPass == 0)
     {
         if (firstPass == lastPass)
             return true;
         lastPass = m_numPasses;
     }
 
-    for (size_t i = firstPass; i < lastPass; ++i)
+#if !defined GRAPHITE2_NTRACING
+    if (dbgout)
     {
-#ifndef DISABLE_TRACING
-        if (XmlTraceLog::get().active())
-        {
-	        XmlTraceLog::get().openElement(ElementRunPass);
-	        XmlTraceLog::get().addAttribute(AttrNum, i);
-        }
+    	char version[64];
+    	sprintf(version, "%d.%d.%d",
+    			GR2_VERSION_MAJOR, GR2_VERSION_MINOR, GR2_VERSION_BUGFIX);
+    	*dbgout << json::object
+    				<< "version"	<< version
+    				<< "passes"		<< json::array;
+    }
 #endif
 
-        // bidi and mirroring
-        if (i == m_bPass && !(seg->dir() & 2))
-            seg->bidiPass(m_aBidi, seg->dir() & 1, m_aMirror);
-        else if (i == m_bPass && m_aMirror)
+    for (size_t i = firstPass; i < lastPass; ++i)
+    {
+    	// bidi and mirroring
+        if (i == m_bPass)
         {
-            Slot * s;
-            for (s = seg->first(); s; s = s->next())
+#if !defined GRAPHITE2_NTRACING
+        	if (dbgout)
+        	{
+        		*dbgout << json::item << json::object
+        					<< "id"		<< -1
+        					<< "slots"	<< json::array;
+        		seg->positionSlots(0);
+        		for(Slot * s = seg->first(); s; s = s->next())
+        			*dbgout		<< dslot(seg, s);
+        		*dbgout			<< json::close
+        					<< "rules"	<< json::array << json::close
+        					<< json::close;
+        	}
+#endif
+
+        	if (!(seg->dir() & 2))
+            	seg->bidiPass(m_aBidi, seg->dir() & 1, m_aMirror);
+        	else if (m_aMirror)
             {
-                unsigned short g = seg->glyphAttr(s->gid(), m_aMirror);
-                if (g && (!(seg->dir() & 4) || !seg->glyphAttr(s->gid(), m_aMirror + 1)))
-                    s->setGlyph(seg, g);
+                Slot * s;
+                for (s = seg->first(); s; s = s->next())
+                {
+                    unsigned short g = seg->glyphAttr(s->gid(), m_aMirror);
+                    if (g && (!(seg->dir() & 4) || !seg->glyphAttr(s->gid(), m_aMirror + 1)))
+                        s->setGlyph(seg, g);
+                }
             }
         }
 
+#if !defined GRAPHITE2_NTRACING
+    	if (dbgout)
+    	{
+    		*dbgout << json::item << json::object
+    					<< "id"		<< i+1
+    					<< "slots"	<< json::array;
+    		seg->positionSlots(0);
+    		for(Slot * s = seg->first(); s; s = s->next())
+    			*dbgout		<< dslot(seg, s);
+    		*dbgout			<< json::close;
+    	}
+#endif
+
         // test whether to reorder, prepare for positioning
         m_passes[i].runGraphite(m, fsm);
-#ifndef DISABLE_TRACING
-            seg->logSegment();
-        if (XmlTraceLog::get().active())
-        {
-            XmlTraceLog::get().closeElement(ElementRunPass);
-        }
-#endif
         // only subsitution passes can change segment length, cached subsegments are short for their text
         if (m.status() != vm::Machine::finished
         	|| (i < m_pPass && (seg->slotCount() > initSize * MAX_SEG_GROWTH_FACTOR
-                               || (seg->slotCount() && seg->slotCount() * MAX_SEG_GROWTH_FACTOR < initSize))))
+            || (seg->slotCount() && seg->slotCount() * MAX_SEG_GROWTH_FACTOR < initSize))))
             return false;
     }
+#if !defined GRAPHITE2_NTRACING
+	if (dbgout)
+	{
+		*dbgout 			<< json::item
+							<< json::close // Close up the passes array
+				<< "output" << json::array;
+		for(Slot * s = seg->first(); s; s = s->next())
+			*dbgout		<< dslot(seg, s);
+		seg->finalise(0);					// Call this here to fix up charinfo back indexes.
+		*dbgout			<< json::close
+				<< "advance" << seg->advance()
+				<< "chars"	 << json::array;
+		for(size_t i = 0, n = seg->charInfoCount(); i != n; ++i)
+			*dbgout 	<< json::flat << *seg->charinfo(i);
+		*dbgout			<< json::close	// Close up the chars array
+					<< json::close;		// Clsoe up the segment object
+	}
+#endif
     return true;
 }
deleted file mode 100644
--- a/gfx/graphite2/src/Silf.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include "Main.h"
-
-#include "Pass.h"
-
-namespace graphite2 {
-
-class Face;
-class Segment;
-class FeatureVal;
-class VMScratch;
-
-class Pseudo
-{
-public:
-    uint32 uid;
-    uint32 gid;
-    CLASS_NEW_DELETE
-};
-
-class Justinfo
-{
-public:
-    Justinfo(uint8 stretch, uint8 shrink, uint8 step, uint8 weight) :
-        m_astretch(stretch), m_ashrink(shrink), m_astep(step),
-        m_aweight(weight) {};
-private:
-    uint8   m_astretch;
-    uint8   m_ashrink;
-    uint8   m_astep;
-    uint8   m_aweight;
-};
-
-class Silf
-{
-public:
-    Silf() throw();
-    ~Silf() throw();
-    
-    bool readGraphite(void *pSilf, size_t lSilf, const Face &face, uint32 version);
-    bool runGraphite(Segment *seg, uint8 firstPass=0, uint8 lastPass=0) const;
-    uint16 findClassIndex(uint16 cid, uint16 gid) const;
-    uint16 getClassGlyph(uint16 cid, unsigned int index) const;
-    uint16 findPseudo(uint32 uid) const;
-    uint8 numUser() const { return m_aUser; }
-    uint8 aPseudo() const { return m_aPseudo; }
-    uint8 aBreak() const { return m_aBreak; }
-    uint8 aMirror() const {return m_aMirror; }
-    uint8 substitutionPass() const { return m_sPass; }
-    uint8 positionPass() const { return m_pPass; }
-    uint8 justificationPass() const { return m_jPass; }
-    uint8 bidiPass() const { return m_bPass; }
-    uint8 numPasses() const { return m_numPasses; }
-    uint8 maxCompPerLig() const { return m_iMaxComp; }
-    uint16 numClasses() const { return m_nClass; }
-
-    CLASS_NEW_DELETE
-
-private:
-    size_t readClassMap(const byte *p, size_t data_len, uint32 version);
-    template<typename T> inline uint32 readClassOffsets(const byte *&p, size_t data_len);
-
-    Pass          * m_passes;
-    Pseudo        * m_pseudos;
-    uint32        * m_classOffsets;
-    uint16        * m_classData;
-    Justinfo      * m_justs;
-    uint8           m_numPasses;
-    uint8           m_numJusts;
-    uint8           m_sPass, m_pPass, m_jPass, m_bPass,
-                    m_flags;
-
-    uint8   m_aPseudo, m_aBreak, m_aUser, m_aBidi, m_aMirror,
-            m_iMaxComp;
-    uint16  m_aLig,
-            m_numPseudo,
-            m_nClass,
-            m_nLinear;
-    
-    void releaseBuffers() throw();
-    
-private:			//defensive
-    Silf(const Silf&);
-    Silf& operator=(const Silf&);
-};
-
-} // namespace graphite2
--- a/gfx/graphite2/src/Slot.cpp
+++ b/gfx/graphite2/src/Slot.cpp
@@ -19,20 +19,20 @@
     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.
 */
-#include "Segment.h"
-#include "Slot.h"
-#include "CharInfo.h"
-#include "Rule.h"
+#include "inc/Segment.h"
+#include "inc/Slot.h"
+#include "inc/CharInfo.h"
+#include "inc/Rule.h"
 
 
 using namespace graphite2;
 
 Slot::Slot() :
     m_next(NULL), m_prev(NULL),
     m_glyphid(0), m_realglyphid(0), m_original(0), m_before(0), m_after(0),
     m_parent(NULL), m_child(NULL), m_sibling(NULL),
@@ -72,17 +72,17 @@ void Slot::set(const Slot & orig, int ch
 
 void Slot::update(int /*numGrSlots*/, int numCharInfo, Position &relpos)
 {
     m_before += numCharInfo;
     m_after += numCharInfo;
     m_position = m_position + relpos;
 }
 
-Position Slot::finalise(const Segment *seg, const Font *font, Position *base, Rect *bbox, float *cMin, uint8 attrLevel, float * clusterMin)
+Position Slot::finalise(const Segment *seg, const Font *font, Position & base, Rect & bbox, float & cMin, uint8 attrLevel, float & clusterMin)
 {
     if (attrLevel && m_attLevel > attrLevel) return Position(0, 0);
     float scale = 1.0;
     Position shift = m_shift + Position(m_just, 0);
     float tAdvance = m_advance.x + m_just;
     const GlyphFace * glyphFace = seg->getFace()->getGlyphFaceCache()->glyphSafe(glyph());
     if (font)
     {
@@ -95,81 +95,81 @@ Position Slot::finalise(const Segment *s
             else
                 tAdvance = (m_advance.x - seg->glyphAdvance(glyph())) * scale + font->advance(m_glyphid);
         }
         else
             tAdvance *= scale;
     }    
     Position res;
 
-    m_position = *base + shift;
+    m_position = base + shift;
     if (!m_parent)
     {
-        res = *base + Position(tAdvance, m_advance.y * scale);
-        *cMin = 0.;
-        *clusterMin = base->x;
+        res = base + Position(tAdvance, m_advance.y * scale);
+        cMin = 0.;
+        clusterMin = base.x;
     }
     else
     {
         float tAdv;
         m_position += (m_attach - m_with) * scale;
         tAdv = tAdvance > 0.f ? m_position.x + tAdvance - shift.x : 0.f;
         res = Position(tAdv, 0);
-        if (m_position.x < *clusterMin) *clusterMin = m_position.x;
+        if (m_position.x < clusterMin) clusterMin = m_position.x;
     }
 
     if (glyphFace)
     {
         Rect ourBbox = glyphFace->theBBox() * scale + m_position;
-        *bbox = bbox->widen(ourBbox);
+        bbox = bbox.widen(ourBbox);
     }
     //Rect ourBbox = seg->theGlyphBBoxTemporary(glyph()) * scale + m_position;
     //bbox->widen(ourBbox);
 
-    if (m_parent && m_position.x < *cMin) *cMin = m_position.x;
+    if (m_parent && m_position.x < cMin) cMin = m_position.x;
 
     if (m_child && m_child != this && m_child->attachedTo() == this)
     {
-        Position tRes = m_child->finalise(seg, font, &m_position, bbox, cMin, attrLevel, clusterMin);
+        Position tRes = m_child->finalise(seg, font, m_position, bbox, cMin, attrLevel, clusterMin);
         if (tRes.x > res.x) res = tRes;
     }
 
     if (m_parent && m_sibling && m_sibling != this && m_sibling->attachedTo() == m_parent)
     {
         Position tRes = m_sibling->finalise(seg, font, base, bbox, cMin, attrLevel, clusterMin);
         if (tRes.x > res.x) res = tRes;
     }
     
     if (!m_parent)
     {
-        if (*cMin < 0)
+        if (cMin < 0)
         {
-            Position adj = Position(-*cMin, 0.);
+            Position adj = Position(-cMin, 0.);
             res += adj;
             m_position += adj;
             if (m_child) m_child->floodShift(adj);
         }
-        else if ((seg->dir() & 1) && (*clusterMin < base->x))
+        else if ((seg->dir() & 1) && (clusterMin < base.x))
         {
-            Position adj = Position(base->x - *clusterMin, 0.);
+            Position adj = Position(base.x - clusterMin, 0.);
             res += adj;
             m_position += adj;
             if (m_child) m_child->floodShift(adj);
         }
     }
     return res;
 }
 
 uint32 Slot::clusterMetric(const Segment *seg, uint8 metric, uint8 attrLevel)
 {
     Position base;
     Rect bbox = seg->theGlyphBBoxTemporary(gid());
     float cMin = 0.;
     float clusterMin = 0.;
-    Position res = finalise(seg, NULL, &base, &bbox, &cMin, attrLevel, &clusterMin);
+    Position res = finalise(seg, NULL, base, bbox, cMin, attrLevel, clusterMin);
 
     switch (metrics(metric))
     {
     case kgmetLsb :
         return static_cast<uint32>(bbox.bl.x);
     case kgmetRsb :
         return static_cast<uint32>(res.x - bbox.tr.x);
     case kgmetBbTop :
@@ -254,22 +254,16 @@ void Slot::setAttr(Segment *seg, attrCod
         {
             Slot *other = map[idx];
             if (other != this && other->child(this))
             {
                 attachTo(other);
                 m_attach = Position(seg->glyphAdvance(other->gid()), 0);
             }
         }
-        else
-        {
-#ifndef DISABLE_TRACING
-            XmlTraceLog::get().warning("invalid slatAttTo %d", value);
-#endif
-        }
         break;
     }
     case gr_slatAttX :			m_attach.x = value; break;
     case gr_slatAttY :			m_attach.y = value; break;
     case gr_slatAttXOff :
     case gr_slatAttYOff :		break;
     case gr_slatAttWithX :		m_with.x = value; break;
     case gr_slatAttWithY :		m_with.y = value; break;
deleted file mode 100644
--- a/gfx/graphite2/src/Slot.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include "graphite2/Types.h"
-#include "graphite2/Segment.h"
-#include "Main.h"
-#include "Font.h"
-
-
-#define SLOT_DELETED    1
-#define SLOT_INSERT	2
-#define SLOT_COPIED     4
-#define SLOT_POSITIONED 8
-
-namespace graphite2 {
-
-typedef gr_attrCode attrCode;
-
-class Segment;
-
-class Slot
-{
-public:
-    unsigned short gid() const { return m_glyphid; }
-    Position origin() const { return m_position; }
-    float advance() const { return m_advance.x; }
-    Position advancePos() const { return m_advance; }
-    int before() const { return m_before; }
-    int after() const { return m_after; }
-    uint32 index() const { return m_index; }
-    void index(uint32 val) { m_index = val; }
-
-    Slot();
-    void set(const Slot & slot, int charOffset, uint8 numUserAttr);
-    Slot *next() const { return m_next; }
-    void next(Slot *s) { m_next = s; }
-    Slot *prev() const { return m_prev; }
-    void prev(Slot *s) { m_prev = s; }
-    uint16 glyph() const { return m_realglyphid ? m_realglyphid : m_glyphid; }
-    void setGlyph(Segment *seg, uint16 glyphid, const GlyphFace * theGlyph = NULL);
-    void setRealGid(uint16 realGid) { m_realglyphid = realGid; }
-    void adjKern(const Position &pos) { m_shift = m_shift + pos; m_advance = m_advance + pos; }
-    void origin(const Position &pos) { m_position = pos + m_shift; }
-    void originate(int ind) { m_original = ind; }
-    int original() const { return m_original; }
-    void before(int ind) { m_before = ind; }
-    void after(int ind) { m_after = ind; }
-    bool isBase() const { return (!m_parent); }
-    void update(int numSlots, int numCharInfo, Position &relpos);
-    Position finalise(const Segment* seg, const Font* font, Position* base, Rect* bbox, float* cMin, uint8 attrLevel, float *clusterMin);
-    bool isDeleted() const { return (m_flags & SLOT_DELETED) ? true : false; }
-    void markDeleted(bool state) { if (state) m_flags |= SLOT_DELETED; else m_flags &= ~SLOT_DELETED; }
-    bool isCopied() const { return (m_flags & SLOT_COPIED) ? true : false; }
-    void markCopied(bool state) { if (state) m_flags |= SLOT_COPIED; else m_flags &= ~SLOT_COPIED; }
-    bool isPositioned() const { return (m_flags & SLOT_POSITIONED) ? true : false; }
-    void markPositioned(bool state) { if (state) m_flags |= SLOT_POSITIONED; else m_flags &= ~SLOT_POSITIONED; }
-    bool isInsertBefore() const { return !(m_flags & SLOT_INSERT); }
-    uint8 getBidiLevel() const { return m_bidiLevel; }
-    void setBidiLevel(uint8 level) { m_bidiLevel = level; }
-    uint8 getBidiClass() const { return m_bidiCls; }
-    void setBidiClass(uint8 cls) { m_bidiCls = cls; }
-    uint16 *userAttrs() { return m_userAttr; }
-    void userAttrs(uint16 *p) { m_userAttr = p; }
-    void markInsertBefore(bool state) { if (!state) m_flags |= SLOT_INSERT; else m_flags &= ~SLOT_INSERT; }
-    void setAttr(Segment* seg, attrCode ind, uint8 subindex, int16 val, const SlotMap & map);
-    int getAttr(const Segment *seg, attrCode ind, uint8 subindex) const;
-    void attachTo(Slot *ap) { m_parent = ap; }
-    Slot *attachedTo() const { return m_parent; }
-    Slot* firstChild() const { return m_child; }
-    bool child(Slot *ap);
-    Slot* nextSibling() const { return m_sibling; }
-    bool sibling(Slot *ap);
-    Slot *attachTo() const { return m_parent; }
-    uint32 clusterMetric(const Segment* seg, uint8 metric, uint8 attrLevel);
-    void positionShift(Position a) { m_position += a; }
-    void floodShift(Position adj);
-    float just() { return m_just; }
-    void just(float j) { m_just = j; }
-
-    CLASS_NEW_DELETE
-
-private:
-    Slot *m_next;           // linked list of slots
-    Slot *m_prev;
-    unsigned short m_glyphid;        // glyph id
-    uint16 m_realglyphid;
-    uint32 m_original;	    // charinfo that originated this slot (e.g. for feature values)
-    uint32 m_before;        // charinfo index of before association
-    uint32 m_after;         // charinfo index of after association
-    uint32 m_index;         // slot index given to this slot during finalising
-    Slot *m_parent;         // index to parent we are attached to
-    Slot *m_child;          // index to first child slot that attaches to us
-    Slot *m_sibling;        // index to next child that attaches to our parent
-    Position m_position;    // absolute position of glyph
-    Position m_shift;       // .shift slot attribute
-    Position m_advance;     // .advance slot attribute
-    Position m_attach;      // attachment point on us
-    Position m_with;	    // attachment point position on parent
-    float    m_just;        // justification adjustment
-    uint8    m_flags;       // holds bit flags
-    byte     m_attLevel;    // attachment level
-    byte     m_bidiCls;     // bidirectional class
-    byte     m_bidiLevel;   // bidirectional level
-    uint16  *m_userAttr;     // pointer to user attributes
-};
-
-} // namespace graphite2
-
-struct gr_slot : public graphite2::Slot {};
--- a/gfx/graphite2/src/Sparse.cpp
+++ b/gfx/graphite2/src/Sparse.cpp
@@ -20,17 +20,17 @@
     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.
 */
 
-#include "Sparse.h"
+#include "inc/Sparse.h"
 
 using namespace graphite2;
 
 namespace
 {
 	template<typename T>
 	inline unsigned int bit_set_count(T v)
 	{
deleted file mode 100644
--- a/gfx/graphite2/src/Sparse.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include "Main.h"
-
-namespace graphite2 {
-
-
-
-class sparse
-{
-	typedef unsigned long	mask_t;
-
-	static const unsigned char  SIZEOF_CHUNK = (sizeof(mask_t) - sizeof(uint16))*8;
-
-	struct chunk
-	{
-		mask_t			mask:SIZEOF_CHUNK;
-		uint16			offset;
-	};
-
-public:
-	typedef	uint16	key;
-	typedef uint16	value;
-
-	template<typename I>
-	sparse(I first, const I last);
-	sparse() throw();
-	~sparse() throw();
-
-	value 	operator [] (int k) const throw();
-	operator bool () const throw();
-
-	size_t capacity() const throw();
-	size_t size()     const throw();
-
-	size_t _sizeof() const throw();
-	
-	CLASS_NEW_DELETE;
-private:
-	union {
-		chunk * map;
-		value * values;
-	}           m_array;
-	key         m_nchunks;
-};
-
-
-inline
-sparse::sparse() throw() : m_nchunks(0)
-{
-	m_array.map = 0;
-}
-
-
-template <typename I>
-sparse::sparse(I attr, const I last)
-: m_nchunks(0)
-{
-	// Find the maximum extent of the key space.
-	size_t n_values=0;
-	for (I i = attr; i != last; ++i, ++n_values)
-	{
-		const key k = i->id / SIZEOF_CHUNK;
-		if (k >= m_nchunks) m_nchunks = k+1;
-	}
-
-	m_array.values = grzeroalloc<value>((m_nchunks*sizeof(chunk) + sizeof(value)/2)/sizeof(value) + n_values*sizeof(value));
-
-	if (m_array.values == 0 || m_nchunks == 0)
-	{
-		free(m_array.values); m_array.map=0;
-		return;
-	}
-
-	chunk * ci = m_array.map;
-	ci->offset = (m_nchunks*sizeof(chunk) + sizeof(value)-1)/sizeof(value);
-	value * vi = m_array.values + ci->offset;
-	for (; attr != last; ++attr, ++vi)
-	{
-		const typename I::value_type v = *attr;
-		chunk * const ci_ = m_array.map + v.id/SIZEOF_CHUNK;
-
-		if (ci != ci_)
-		{
-			ci = ci_;
-			ci->offset = vi - m_array.values;
-		}
-
-		ci->mask |= 1UL << (SIZEOF_CHUNK - 1 - (v.id % SIZEOF_CHUNK));
-		*vi = v.value;
-	}
-}
-
-
-inline
-sparse::operator bool () const throw()
-{
-	return m_array.map != 0;
-}
-
-
-inline
-size_t sparse::capacity() const throw()
-{
-	return m_nchunks;
-}
-
-
-inline
-size_t sparse::_sizeof() const throw()
-{
-	return sizeof(sparse) + size()*sizeof(value) + m_nchunks*sizeof(chunk);
-}
-
-} // namespace graphite2
deleted file mode 100644
--- a/gfx/graphite2/src/TtfTypes.h
+++ /dev/null
@@ -1,419 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-/*--------------------------------------------------------------------*//*:Ignore this sentence.
-
-File: TtfTypes.h
-Responsibility: Tim Eves
-Last reviewed: Not yet.
-
-Description:
-Provides types required to represent the TTF basic types.
--------------------------------------------------------------------------------*//*:End Ignore*/
-
-
-//**********************************************************************************************
-//	Include files
-//**********************************************************************************************
-namespace graphite2
-{
-namespace TtfUtil
-{
-//**********************************************************************************************
-//	Forward declarations
-//**********************************************************************************************
-
-
-//**********************************************************************************************
-//	Type declarations
-//**********************************************************************************************
-typedef char	uint8;
-typedef char    byte;
-typedef signed char	int8;
-typedef unsigned short	uint16;
-typedef short 	int16;
-typedef unsigned int	uint32;
-typedef int 	int32;
-
-typedef int16	short_frac;
-typedef int32	fixed;
-typedef int16	fword;
-typedef uint16	ufword;
-typedef int16	f2dot14;
-typedef uint32	long_date_time[2];
-
-//**********************************************************************************************
-//	Constants and enum types
-//**********************************************************************************************/
-enum
-{
-	OneFix = 1<<16
-};
-
-//**********************************************************************************************
-//	Table declarations
-//**********************************************************************************************
-namespace Sfnt 
-{
-#pragma pack(1)	// We need this or the structure members aren't alligned 
-                     	// correctly.  Fortunately this form of pragma is supposed
-                     	// to be recongnised by VS C++ too (at least according to 
-                     	// MSDN).
-
-	struct OffsetSubTable
-	{
-		uint32	scaler_type;
-		uint16	num_tables,
-			search_range,
-			entry_selector,
-			range_shift;
-		struct Entry
-		{
-			uint32	tag,
-				checksum,
-				offset,
-				length;
-		} table_directory[1];
-
-		enum ScalerType 
-		{ 
-			TrueTypeMac = 0x74727565U, 
-			TrueTypeWin = 0x00010000U,
-			Type1   = 0x74797031U
-		};
-	};
-
-
-
-	
-	struct CharacterCodeMap
-	{
-		uint16	version,
-			num_subtables;
-		struct
-		{
-			uint16	platform_id,
-				platform_specific_id;
-			uint32	offset;
-		} encoding[1];
-	};
-
-	struct CmapSubTable
-	{
-		uint16	format,
-			length,
-			language;
-	};
-
-	struct CmapSubTableFormat4 : CmapSubTable
-	{
-		uint16	seg_count_x2,
-			search_range,
-			entry_selector,
-			range_shift,
-			end_code[1];
-		// There are arrarys after this which need their
-		// start positions calculated since end_code is 
-		// seg_count uint16s long.
-	};
-
-	struct CmapSubTableFormat12
-	{
-		fixed	format;
-		uint32	length,
-			language,
-			num_groups;
-		struct 
-		{
-			uint32	start_char_code,
-				end_char_code,
-				start_glyph_id;
-		} group[1];
-	};
-
-
-
-	struct FontHeader
-	{
-		fixed	version,
-			font_revision;
-		uint32	check_sum_adjustment,
-			magic_number;
-		uint16	flags,
-			units_per_em;
-		long_date_time	created,
-				modified;
-		fword	x_min,
-			y_min,
-			x_max,
-			y_max;
-		uint16	mac_style,
-			lowest_rec_ppem;
-		int16	font_direction_hint,
-			index_to_loc_format,
-			glyph_data_format;
-		enum 
-		{
-			MagicNumber = 0x5F0F3CF5, 
-			GlypDataFormat = 0
-		};
-		enum {ShortIndexLocFormat, LongIndexLocFormat};
-	};
-
-
-
-
-	struct PostScriptGlyphName
-	{
-		fixed	format,
-			italic_angle;
-		fword	underline_position,
-			underline_thickness;
-		uint32	is_fixed_pitch,
-			min_mem_type42,
-			max_mem_type42,
-			min_mem_type1,
-			max_mem_type1;			
-		enum 
-		{
-			Format1  = 0x10000, 
-			Format2  = 0x20000,
-			Format25 = 0x28000,
-			Format3  = 0x30000,
-			Format4  = 0x40000
-		};
-	};
-	
-	struct PostScriptGlyphName2 : PostScriptGlyphName
-	{
-		uint16	number_of_glyphs,
-			glyph_name_index[1];
-	};
-	
-	struct PostScriptGlyphName25 : PostScriptGlyphName
-	{
-		uint16	number_of_glyphs;
-		int8	offset[1];
-	};
-	
-	struct PostScriptGlyphName3 : PostScriptGlyphName {};
-	
-	struct PostScriptGlyphName4 : PostScriptGlyphName
-	{
-		uint16 glyph_to_char_map[1];
-	};
-	
-	
-	struct HorizontalHeader
-	{
-		fixed	version;
-		fword	ascent,
-			descent,
-			line_gap;
-		ufword	advance_width_max;
-		fword	min_left_side_bearing,
-			max_left_side_bearing,
-			x_max_element;
-		int16	caret_slope_rise,
-			caret_slope_run;
-		fword	caret_offset;
-		int16	reserved[4],
-			metric_data_format;
-		uint16	num_long_hor_metrics;
-	};
-	
-	struct MaximumProfile
-	{
-		fixed	version;
-		uint16	num_glyphs,
-			max_points,
-			max_contours,
-			max_component_points,
-			max_component_contours,
-			max_zones,
-			max_twilight_points,
-			max_storage,
-			max_function_defs,
-			max_instruction_defs,
-			max_stack_elements,
-			max_size_of_instructions,
-			max_component_elements,
-			max_component_depth;
-	};
-
-
-	typedef byte	Panose[10];
-
-	struct Compatibility0
-	{
-		uint16	version;
-		int16	x_avg_char_width;
-		uint16	weight_class,
-			width_class;
-		int16	fs_type,
-			y_subscript_x_size,
-			y_subscript_y_size,
-			y_subscript_x_offset,
-			y_subscript_y_offset,
-			y_superscript_x_size,
-			y_superscript_y_size,
-			y_superscript_x_offset,
-			y_superscript_y_offset,
-			y_strikeout_size,
-			y_strikeout_position,
-			family_class;
-		Panose	panose;
-		uint32	unicode_range[4];
-		int8	ach_vend_id[4];
-		uint16	fs_selection,
-			fs_first_char_index,
-			fs_last_char_index,	// Acording to Apple's spec this is where v0 should end
-			typo_ascender,
-			typo_descender,
-			type_linegap,
-			win_ascent,
-			win_descent;
-		
-		enum 
-		{
-			Italic    =0x01, 
-			Underscore=0x02, 
-			Negative  =0x04, 
-			Outlined  =0x08, 
-			StrikeOut =0x10, 
-			Bold      =0x20
-		};
-	};
-	
-	struct Compatibility1 : Compatibility0
-	{
-		uint32	codepage_range[2];
-	};
-	
-	struct Compatibility2 : Compatibility1
-	{
-    		int16	x_height,
-    			cap_height;
-    		uint16	default_char,
-    			break_char,
-    			max_context;
-	};
-	
-	struct Compatibility3 : Compatibility2 {};
-	
-	typedef Compatibility3	Compatibility;
-	
-	
-	struct NameRecord
-	{
-		uint16	platform_id,
-			platform_specific_id,
-			language_id,
-			name_id,
-			length,
-			offset;
-		enum	{Unicode, Mactintosh, Reserved, Microsoft};
-		enum	
-		{
-			Copyright, Family, Subfamily, UniqueSubfamily, 
-			Fullname, Version, PostScript
-		};
-	};
-
-	struct LangTagRecord
-	{
-		uint16 length,
-			offset;
-	};
-
-	struct FontNames
-	{
-		uint16	format,
-			count,
-			string_offset;
-		NameRecord name_record[1];
-	};
-	
-	
-	struct HorizontalMetric
-	{
-		uint16	advance_width;
-		int16	left_side_bearing;
-	};
-	
-	
-	struct Glyph
-	{
-		int16	number_of_contours;
-		fword	x_min,
-			y_min,
-			x_max,
-			y_max;
-	};
-	
-	struct SimpleGlyph : Glyph
-	{
-		uint16	end_pts_of_contours[1];
-		enum 
-		{
-			OnCurve = 0x01,
-			XShort  = 0x02,
-			YShort  = 0x04,
-			Repeat  = 0x08,
-			XIsSame = 0x10,
-			XIsPos  = 0x10,
-			YIsSame = 0x20,
-			YIsPos  = 0x20
-		};
-	};
-	
-	struct CompoundGlyph : Glyph
-	{
-		uint16	flags,
-			glyph_index;
-		enum 
-		{
-			Arg1Arg2Words   = 0x01,
-			ArgsAreXYValues = 0x02,
-			RoundXYToGrid   = 0x04,
-			HaveScale       = 0x08,
-			MoreComponents  = 0x20,
-			HaveXAndYScale  = 0x40,
-			HaveTwoByTwo    = 0x80,
-			HaveInstructions = 0x100,
-			UseMyMetrics    = 0x200,
-			OverlapCompund  = 0x400,
-			ScaledOffset    = 0x800,
-			UnscaledOffset  = 0x1000
-		};
-	};
-
-#pragma pack()
-} // end of namespace Sfnt
-
-} // end of namespace TtfUtil
-} // end of namespace graphite2
--- a/gfx/graphite2/src/TtfUtil.cpp
+++ b/gfx/graphite2/src/TtfUtil.cpp
@@ -44,19 +44,19 @@ Description
 #include <cassert>
 #include <cstddef>
 #include <cstring>
 #include <climits>
 #include <cwchar>
 //#include <stdexcept>
 // Platform headers
 // Module headers
-#include "TtfUtil.h"
-#include "TtfTypes.h"
-#include "Endian.h"
+#include "inc/TtfUtil.h"
+#include "inc/TtfTypes.h"
+#include "inc/Endian.h"
 
 /***********************************************************************************************
 	Forward declarations
 ***********************************************************************************************/
 
 /***********************************************************************************************
 	Local Constants and static variables
 ***********************************************************************************************/
@@ -192,22 +192,23 @@ bool GetTableDirInfo(const void * pHdr, 
 	Get offset and size of the specified table.
 	Return true if successful, false otherwise. On false, offset and size will be 0.
 ----------------------------------------------------------------------------------------------*/
 bool GetTableInfo(const Tag TableTag, const void * pHdr, const void * pTableDir,
 						   size_t & lOffset, size_t & lSize)
 {
 	const Sfnt::OffsetSubTable * pOffsetTable 
 		= reinterpret_cast<const Sfnt::OffsetSubTable *>(pHdr);
+	const size_t num_tables = be::swap(pOffsetTable->num_tables);
 	const Sfnt::OffsetSubTable::Entry 
 		* entry_itr = reinterpret_cast<const Sfnt::OffsetSubTable::Entry *>(
 			pTableDir),
-		* const  dir_end = entry_itr + be::swap(pOffsetTable->num_tables);
+		* const  dir_end = entry_itr + num_tables;
 
-	if (be::swap(pOffsetTable->num_tables) > 40)
+	if (num_tables > 40)
 		return false;
 
 	for (;entry_itr != dir_end; ++entry_itr) // 40 - safe guard
 	{
 		if (be::swap(entry_itr->tag) == TableTag)
 		{
 			lOffset = be::swap(entry_itr->offset);
 			lSize   = be::swap(entry_itr->length);
@@ -806,20 +807,18 @@ bool HorMetrics(gid16 nGlyphId, const vo
 		// guard against bad glyph id
 		size_t lLsbOffset = sizeof(Sfnt::HorizontalMetric) * cLongHorMetrics +
 			sizeof(int16) * (nGlyphId - cLongHorMetrics); // offset in bytes
 		if (lLsbOffset + 1 >= lHmtxSize) // + 1 because entries are two bytes wide
 		{
 			nLsb = 0;
 			return false;
 		}
-                nAdvWid = be::swap(phmtx[cLongHorMetrics - 1].advance_width);
-		const int16 * pLsb = reinterpret_cast<const int16 *>(phmtx) + 
-			lLsbOffset / sizeof(int16);
-		nLsb = be::swap(*pLsb);
+        nAdvWid = be::swap(phmtx[cLongHorMetrics - 1].advance_width);
+		nLsb = be::peek<int16>(reinterpret_cast<const int16 *>(phmtx) + lLsbOffset);
 	}
 
 	return true;
 }
 
 /*----------------------------------------------------------------------------------------------
 	Return a pointer to the requested cmap subtable. By default find the Microsoft Unicode
 	subtable. Pass nEncoding as -1 to find first table that matches only nPlatformId.
@@ -836,41 +835,41 @@ const void * FindCmapSubtable(const void
         if (be::swap(pTable->encoding[i].platform_id) == nPlatformId &&
                 (nEncodingId == -1 || be::swap(pTable->encoding[i].platform_specific_id) == nEncodingId))
         {
             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 = be::swap(*reinterpret_cast<const uint16*>(pRtn));
+                uint16 format = be::read<uint16>(pRtn);
                 if (format == 4)
                 {
-                    uint16 subTableLength = be::swap(*reinterpret_cast<const uint16*>(pRtn + 2));
+                    uint16 subTableLength = be::peek<uint16>(pRtn);
                     if (i + 1 == csuPlatforms)
                     {
                         if (subTableLength > length - offset)
                             return NULL;
                     }
                     else if (subTableLength > be::swap(pTable->encoding[i+1].offset))
                         return NULL;
                 }
                 if (format == 12)
                 {
-                    uint32 subTableLength = be::swap(*reinterpret_cast<const uint32*>(pRtn + 2));
+                    uint32 subTableLength = be::peek<uint32>(pRtn);
                     if (i + 1 == csuPlatforms)
                     {
                         if (subTableLength > length - offset)
                             return NULL;
                     }
                     else if (subTableLength > be::swap(pTable->encoding[i+1].offset))
                         return NULL;
                 }
             }
-            return const_cast<void *>(reinterpret_cast<const void *>(pRtn));
+            return reinterpret_cast<const uint8 *>(pCmap) + offset;
         }
     }
 
     return 0;
 }
 
 /*----------------------------------------------------------------------------------------------
 	Check the Microsoft Unicode subtable for expected values
@@ -884,17 +883,17 @@ bool CheckCmap31Subtable(const void * pC
     const Sfnt::CmapSubTableFormat4 * pTable4 = reinterpret_cast<const Sfnt::CmapSubTableFormat4 *>(pCmap31);
     uint16 length = be::swap(pTable4->length);
     if (length < sizeof(Sfnt::CmapSubTableFormat4))
         return false;
     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 = be::swap(pTable4->end_code[nRanges-1]);
+    uint16 chEnd = be::peek<uint16>(pTable4->end_code + nRanges - 1);
     return (chEnd == 0xFFFF);
 }
 
 /*----------------------------------------------------------------------------------------------
 	Return the Glyph ID for the given Unicode ID in the Microsoft Unicode subtable.
 	(Actually this code only depends on subtable being format 4.)
 	Return 0 if the Unicode ID is not in the subtable.
 ----------------------------------------------------------------------------------------------*/
@@ -906,32 +905,32 @@ gid16 Cmap31Lookup(const void * pCmap31,
   
 	uint16 n;
     	const uint16 * pLeft, * pMid;
 	uint16 cMid, chStart, chEnd;
 
     if (rangeKey)
     {
         pMid = &(pTable->end_code[rangeKey]);
-        chEnd = be::swap(*pMid);
+        chEnd = be::peek<uint16>(pMid);
         n = rangeKey;
     }
     else
     {
         // Binary search of the endCode[] array
         pLeft = &(pTable->end_code[0]);
         n = nSeg;
         while (n > 0)
         {
             cMid = n >> 1;           // Pick an element in the middle
             pMid = pLeft + cMid;
-            chEnd = be::swap(*pMid);
+            chEnd = be::peek<uint16>(pMid);
             if (nUnicodeId <= chEnd)
             {
-                if (cMid == 0 || nUnicodeId > be::swap(pMid[-1]))
+                if (cMid == 0 || nUnicodeId > be::peek<uint16>(pMid -1))
                         break;          // Must be this seg or none!
                 n = cMid;            // Continue on left side, omitting mid point
             }
             else
             {
                 pLeft = pMid + 1;    // Continue on right side, omitting mid point
                 n -= (cMid + 1);
             }
@@ -939,32 +938,32 @@ gid16 Cmap31Lookup(const void * pCmap31,
 
         if (!n)
         return 0;
     }
 
     // Ok, we're down to one segment and pMid points to the endCode element
     // Either this is it or none is.
 
-    chStart = be::swap(*(pMid += nSeg + 1));
+    chStart = be::peek<uint16>(pMid += nSeg + 1);
     if (chEnd >= nUnicodeId && nUnicodeId >= chStart)
     {
         // Found correct segment. Find Glyph Id
-        int16 idDelta = be::swap(*(pMid += nSeg));
-        uint16 idRangeOffset = be::swap(*(pMid += nSeg));
+        int16 idDelta = be::peek<uint16>(pMid += nSeg);
+        uint16 idRangeOffset = be::peek<uint16>(pMid += nSeg);
 
         if (idRangeOffset == 0)
             return (uint16)(idDelta + nUnicodeId); // must use modulus 2^16
 
         // Look up value in glyphIdArray
         size_t offset = (nUnicodeId - chStart) + (idRangeOffset >> 1) +
                 (reinterpret_cast<const uint16 *>(pMid) - reinterpret_cast<const uint16 *>(pTable));
         if (offset * 2 >= pTable->length)
             return 0;
-        gid16 nGlyphId = be::swap(*(pMid + (nUnicodeId - chStart) + (idRangeOffset >> 1)));
+        gid16 nGlyphId = be::peek<uint16>(pMid + (nUnicodeId - chStart) + (idRangeOffset >> 1));
         // If this value is 0, return 0. Else add the idDelta
         return nGlyphId ? nGlyphId + idDelta : 0;
     }
 
     return 0;
 }
 
 /*----------------------------------------------------------------------------------------------
@@ -985,35 +984,35 @@ unsigned int Cmap31NextCodepoint(const v
 		+ nRange // length of end code array
 		+ 1;   // reserved word
 
 	if (nUnicodePrev == 0)
 	{
 		// return the first codepoint.
 		if (pRangeKey)
 			*pRangeKey = 0;
-		return be::swap(pStartCode[0]);
+		return be::peek<uint16>(pStartCode);
 	}
 	else if (nUnicodePrev >= 0xFFFF)
 	{
 		if (pRangeKey)
 			*pRangeKey = nRange - 1;
 		return 0xFFFF;
 	}
 
 	int iRange = (pRangeKey) ? *pRangeKey : 0;
 	// Just in case we have a bad key:
-	while (iRange > 0 && be::swap(pStartCode[iRange]) > nUnicodePrev)
+	while (iRange > 0 && be::peek<uint16>(pStartCode + iRange) > nUnicodePrev)
 		iRange--;
-	while (be::swap(pTable->end_code[iRange]) < nUnicodePrev)
+	while (be::peek<uint16>(pTable->end_code + iRange) < nUnicodePrev)
 		iRange++;
 
 	// Now iRange is the range containing nUnicodePrev.
-	unsigned int nStartCode = be::swap(pStartCode[iRange]);
-	unsigned int nEndCode = be::swap(pTable->end_code[iRange]);
+	unsigned int nStartCode = be::peek<uint16>(pStartCode + iRange);
+	unsigned int nEndCode = be::peek<uint16>(pTable->end_code + iRange);
 
 	if (nStartCode > nUnicodePrev)
 		// Oops, nUnicodePrev is not in the cmap! Adjust so we get a reasonable
 		// answer this time around.
 		nUnicodePrev = nStartCode - 1;
 
 	if (nEndCode > nUnicodePrev)
 	{
@@ -1023,17 +1022,17 @@ unsigned int Cmap31NextCodepoint(const v
 		return nUnicodePrev + 1;
 	}
 
 	// Otherwise the next codepoint is the first one in the next range.
 	// There is guaranteed to be a next range because there must be one that
 	// ends with 0xFFFF.
 	if (pRangeKey)
 		*pRangeKey = iRange + 1;
-	return be::swap(pStartCode[iRange + 1]);
+	return be::peek<uint16>(pStartCode + iRange + 1);
 }
 
 /*----------------------------------------------------------------------------------------------
 	Check the Microsoft UCS-4 subtable for expected values.
 ----------------------------------------------------------------------------------------------*/
 bool CheckCmap310Subtable(const void *pCmap310)
 {
 	const Sfnt::CmapSubTable * pTable = reinterpret_cast<const Sfnt::CmapSubTable *>(pCmap310);
@@ -1148,26 +1147,26 @@ 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 (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 (be::swap(pShortTable[nGlyphId]) << 1);
+			return (be::peek<uint16>(pShortTable + nGlyphId) << 1);
 		}
 	}
 	
 	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 be::swap(pLongTable[nGlyphId]);
+			return be::peek<uint32>(pLongTable + nGlyphId);
 		}
 	}
 
 	// only get here if glyph id was bad
 	return -1;
 	//throw std::out_of_range("glyph id out of range for font");
 }
 
deleted file mode 100644
--- a/gfx/graphite2/src/TtfUtil.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-/*--------------------------------------------------------------------*//*:Ignore this sentence.
-
-File: TtfUtil.h
-Responsibility: Alan Ward
-Last reviewed: Not yet.
-
-Description:
-    Utility class for handling TrueType font files.
-----------------------------------------------------------------------------------------------*/
-
-
-//#include <cstddef>
-//#include <stdexcept>
-
-namespace graphite2
-{
-namespace TtfUtil
-{
-
-typedef long fontTableId32;
-typedef unsigned short gid16;
-
-#define TTF_TAG(a,b,c,d) ((a << 24UL) + (b << 16UL) + (c << 8UL) + (d))
-
-// Enumeration used to specify a table in a TTF file
-class Tag
-{
-	unsigned long _v;
-public:
-	Tag(const char n[5]) throw()			: _v(TTF_TAG(n[0],n[1],n[2],n[3])) {}
-	Tag(const unsigned long tag) throw()	: _v(tag) {}
-
-	operator unsigned long () const throw () { return _v; }
-
-	enum
-	{
-		Feat = TTF_TAG('F','e','a','t'),
-		Glat = TTF_TAG('G','l','a','t'),
-		Gloc = TTF_TAG('G','l','o','c'),
-		Sile = TTF_TAG('S','i','l','e'),
-		Silf = TTF_TAG('S','i','l','f'),
-		Sill = TTF_TAG('S','i','l','l'),
-		cmap = TTF_TAG('c','m','a','p'),
-		cvt  = TTF_TAG('c','v','t',' '),
-		cryp = TTF_TAG('c','r','y','p'),
-		head = TTF_TAG('h','e','a','d'),
-		fpgm = TTF_TAG('f','p','g','m'),
-		gdir = TTF_TAG('g','d','i','r'),
-		glyf = TTF_TAG('g','l','y','f'),
-		hdmx = TTF_TAG('h','d','m','x'),
-		hhea = TTF_TAG('h','h','e','a'),
-		hmtx = TTF_TAG('h','m','t','x'),
-		loca = TTF_TAG('l','o','c','a'),
-		kern = TTF_TAG('k','e','r','n'),
-		LTSH = TTF_TAG('L','T','S','H'),
-		maxp = TTF_TAG('m','a','x','p'),
-		name = TTF_TAG('n','a','m','e'),
-		OS_2 = TTF_TAG('O','S','/','2'),
-		post = TTF_TAG('p','o','s','t'),
-		prep = TTF_TAG('p','r','e','p')
-	};
-};
-
-/*----------------------------------------------------------------------------------------------
-	Class providing utility methods to parse a TrueType font file (TTF).
-	Callling application handles all file input and memory allocation.
-	Assumes minimal knowledge of TTF file format.
-----------------------------------------------------------------------------------------------*/
-	////////////////////////////////// tools to find & check TTF tables
-	bool GetHeaderInfo(size_t & lOffset, size_t & lSize);
-	bool CheckHeader(const void * pHdr);
-	bool GetTableDirInfo(const void * pHdr, size_t & lOffset, size_t & lSize);
-	bool GetTableInfo(const Tag TableTag, const void * pHdr, const void * pTableDir,
-		size_t & lOffset, size_t & lSize);
-	bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize);
-
-	////////////////////////////////// simple font wide info 
-	size_t  GlyphCount(const void * pMaxp); 
-#ifdef ALL_TTFUTILS
-	size_t  MaxCompositeComponentCount(const void * pMaxp);
-	size_t  MaxCompositeLevelCount(const void * pMaxp);
-	size_t  LocaGlyphCount(size_t lLocaSize, const void * pHead); // throw (std::domain_error); 
-#endif
-	int DesignUnits(const void * pHead);
-#ifdef ALL_TTFUTILS
-	int HeadTableCheckSum(const void * pHead);
-	void HeadTableCreateTime(const void * pHead, unsigned int * pnDateBC, unsigned int * pnDateAD);
-	void HeadTableModifyTime(const void * pHead, unsigned int * pnDateBC, unsigned int * pnDateAD);
-	bool IsItalic(const void * pHead);
-	int FontAscent(const void * pOs2);
-	int FontDescent(const void * pOs2);
-	bool FontOs2Style(const void *pOs2, bool & fBold, bool & fItalic);
-	bool Get31EngFamilyInfo(const void * pName, size_t & lOffset, size_t & lSize);
-	bool Get31EngFullFontInfo(const void * pName, size_t & lOffset, size_t & lSize);
-	bool Get30EngFamilyInfo(const void * pName, size_t & lOffset, size_t & lSize);
-	bool Get30EngFullFontInfo(const void * pName, size_t & lOffset, size_t & lSize);
-	int PostLookup(const void * pPost, size_t lPostSize, const void * pMaxp, 
-		const char * pPostName);
-#endif
-
-	////////////////////////////////// utility methods helpful for name table
-	bool GetNameInfo(const void * pName, int nPlatformId, int nEncodingId,
-		int nLangId, int nNameId, size_t & lOffset, size_t & lSize);
-	//size_t NameTableLength(const byte * pTable);
-#ifdef ALL_TTFUTILS
-	int GetLangsForNames(const void * pName, int nPlatformId, int nEncodingId,
-		int *nameIdList, int cNameIds, short *langIdList);
-	void SwapWString(void * pWStr, size_t nSize = 0); // throw (std::invalid_argument);
-#endif
-
-	////////////////////////////////// cmap lookup tools 
-	const void * FindCmapSubtable(const void * pCmap, int nPlatformId = 3, 
-		int nEncodingId = 1, size_t length = 0);
-	bool CheckCmap31Subtable(const void * pCmap31);
-	gid16 Cmap31Lookup(const void * pCmap31, int nUnicodeId, int rangeKey = 0); 
-	unsigned int Cmap31NextCodepoint(const void *pCmap31, unsigned int nUnicodeId,
-		int * pRangeKey = 0);
-	bool CheckCmap310Subtable(const void *pCmap310);
-	gid16 Cmap310Lookup(const void * pCmap310, unsigned int uUnicodeId, int rangeKey = 0);
-	unsigned int Cmap310NextCodepoint(const void *pCmap310, unsigned int nUnicodeId,
-		int * pRangeKey = 0);
-
-	///////////////////////////////// horizontal metric data for a glyph
-	bool HorMetrics(gid16 nGlyphId, const void * pHmtx, size_t lHmtxSize, 
-		const void * pHhea, int & nLsb, unsigned int & nAdvWid);
-
-	////////////////////////////////// primitives for loca and glyf lookup 
-	size_t LocaLookup(gid16 nGlyphId, const void * pLoca, size_t lLocaSize, 
-		const void * pHead); // throw (std::out_of_range); 
-	void * GlyfLookup(const void * pGlyf, size_t lGlyfOffset, size_t lTableLen);
-
-	////////////////////////////////// primitves for simple glyph data
-	bool GlyfBox(const void * pSimpleGlyf, int & xMin, int & yMin, 
-		int & xMax, int & yMax);
-
-#ifdef ALL_TTFUTILS
-	int GlyfContourCount(const void * pSimpleGlyf); 
-	bool GlyfContourEndPoints(const void * pSimpleGlyf, int * prgnContourEndPoint, 
-		int cnPointsTotal, size_t & cnPoints);
-	bool GlyfPoints(const void * pSimpleGlyf, int * prgnX, int * prgnY, 
-		char * prgbFlag, int cnPointsTotal, int & cnPoints);
-	
-	// primitive to find the glyph ids in a composite glyph
-	bool GetComponentGlyphIds(const void * pSimpleGlyf, int * prgnCompId, 
-		size_t cnCompIdTotal, size_t & cnCompId);
-	// primitive to find the placement data for a component in a composite glyph
-	bool GetComponentPlacement(const void * pSimpleGlyf, int nCompId,
-		bool fOffset, int & a, int & b);						
-	// primitive to find the transform data for a component in a composite glyph
-	bool GetComponentTransform(const void * pSimpleGlyf, int nCompId,
-		float & flt11, float & flt12, float & flt21, float & flt22, bool & fTransOffset);
-#endif
-
-	////////////////////////////////// operate on composite or simple glyph (auto glyf lookup)
-	void * GlyfLookup(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
-		size_t lGlyfSize, size_t lLocaSize, const void * pHead); // primitive used by below methods
-
-#ifdef ALL_TTFUTILS
-	// below are primary user methods for handling glyf data
-	bool IsSpace(gid16 nGlyphId, const void * pLoca, size_t lLocaSize, const void * pHead);
-	bool IsDeepComposite(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
-		size_t lGlyfSize, size_t lLocaSize, const void * pHead);
-
-	bool GlyfBox(gid16 nGlyphId, const void * pGlyf, const void * pLoca, size_t lGlyfSize, size_t lLocaSize, 
-		const void * pHead, int & xMin, int & yMin, int & xMax, int & yMax);
-	bool GlyfContourCount(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
-		size_t lGlyfSize, size_t lLocaSize, const void *pHead, size_t & cnContours);
-	bool GlyfContourEndPoints(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
-		size_t lGlyfSize, size_t lLocaSize, const void * pHead, int * prgnContourEndPoint, size_t cnPoints); 
-	bool GlyfPoints(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
-		size_t lGlyfSize, size_t lLocaSize, const void * pHead, const int * prgnContourEndPoint, size_t cnEndPoints, 
-		int * prgnX, int * prgnY, bool * prgfOnCurve, size_t cnPoints);
-
-	// utitily method used by high-level GlyfPoints 
-	bool SimplifyFlags(char * prgbFlags, int cnPoints);
-	bool CalcAbsolutePoints(int * prgnX, int * prgnY, int cnPoints);
-#endif
-
-} // end of namespace TtfUtil
-} // end of namespace graphite2
--- a/gfx/graphite2/src/UtfCodec.cpp
+++ b/gfx/graphite2/src/UtfCodec.cpp
@@ -19,17 +19,17 @@
     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.
 */
-#include "UtfCodec.h"
+#include "inc/UtfCodec.h"
 //using namespace graphite2;
 
 namespace graphite2 {
 
 }
 
 using namespace graphite2;
 
deleted file mode 100644
--- a/gfx/graphite2/src/UtfCodec.h
+++ /dev/null
@@ -1,208 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-
-#include <iterator>
-#include "Main.h"
-#include "graphite2/Segment.h"
-
-namespace graphite2 {
-
-typedef uint32 	uchar_t;
-
-template <int N>
-struct _utf_codec
-{
-	typedef	uchar_t	codeunit_t;
-
-	static void 	put(codeunit_t * cp, const uchar_t , int8 & len) throw();
-	static uchar_t	get(const codeunit_t * cp, int8 & len) throw();
-};
-
-
-template <>
-struct _utf_codec<32>
-{
-private:
-	static const uchar_t	limit = 0x110000;
-public:
-	typedef	uint32	codeunit_t;
-
-	inline
-	static void put(codeunit_t * cp, const uchar_t usv, int8 & l) throw()
-	{
-		*cp = usv; l = 1;
-	}
-
-	inline
-	static uchar_t get(const codeunit_t * cp, int8 & l) throw()
-	{
-		if (cp[0] < limit)	{ l = 1;  return cp[0]; }
-		else				{ l = -1; return 0xFFFD; }
-	}
-};
-
-
-template <>
-struct _utf_codec<16>
-{
-private:
-	static const int32	lead_offset		 = 0xD800 - (0x10000 >> 10);
-	static const int32	surrogate_offset = 0x10000 - (0xD800 << 10) - 0xDC00;
-public:
-	typedef	uint16	codeunit_t;
-
-	inline
-	static void put(codeunit_t * cp, const uchar_t usv, int8 & l) throw()
-	{
-		if (usv < 0x10000)	{ l = 1; cp[0] = codeunit_t(usv); }
-		else
-		{
-			cp[0] = codeunit_t(lead_offset + (usv >> 10));
-			cp[1] = codeunit_t(0xDC00 + (usv & 0x3FF));
-			l = 2;
-		}
-	}
-
-	inline
-	static uchar_t get(const codeunit_t * cp, int8 & l) throw()
-	{
-		const uint32	uh = cp[0];
-		l = 1;
-
-		if (0xD800 > uh || uh > 0xDFFF)	{ return uh; }
-		const uint32 ul = cp[1];
-		if (uh > 0xDBFF || 0xDC00 > ul || ul > 0xDFFF) { l = -1; return 0xFFFD; }
-		++l;
-		return (uh<<10) + ul + surrogate_offset;
-	}
-};
-
-
-template <>
-struct _utf_codec<8>
-{
-private:
-	static const int8 sz_lut[16];
-	static const byte mask_lut[5];
-
-
-public:
-	typedef	uint8	codeunit_t;
-
-	inline
-	static void put(codeunit_t * cp, const uchar_t usv, int8 & l) throw()
-	{
-		if (usv < 0x80)		{l = 1; cp[0] = usv; return; }
-        if (usv < 0x0800)	{l = 2; cp[0] = 0xC0 + (usv >> 6);  cp[1] = 0x80 + (usv & 0x3F); return; }
-        if (usv < 0x10000)	{l = 3; cp[0] = 0xE0 + (usv >> 12); cp[1] = 0x80 + ((usv >> 6) & 0x3F);  cp[2] = 0x80 + (usv & 0x3F); return; }
-        else				{l = 4; cp[0] = 0xF0 + (usv >> 18); cp[1] = 0x80 + ((usv >> 12) & 0x3F); cp[2] = 0x80 + ((usv >> 6) & 0x3F); cp[3] = 0x80 + (usv & 0x3F); return; }
- 	}
-
-	inline
-	static uchar_t get(const codeunit_t * cp, int8 & l) throw()
-	{
-		const int8 seq_sz = sz_lut[*cp >> 4];
-		uchar_t	u = *cp & mask_lut[seq_sz];
-		l = 1;
-		bool toolong = false;
-
-		switch(seq_sz) {
-			case 4:     u <<= 6; u |= *++cp & 0x3F; if (*cp >> 6 != 2) break; ++l; toolong  = (u < 0x10);
-			case 3:     u <<= 6; u |= *++cp & 0x3F; if (*cp >> 6 != 2) break; ++l; toolong |= (u < 0x20);
-			case 2:     u <<= 6; u |= *++cp & 0x3F; if (*cp >> 6 != 2) break; ++l; toolong |= (u < 0x80);
-			case 1:		break;
-			case 0:     l = -1; return 0xFFFD;
-		}
-
-		if (l != seq_sz || toolong)
-		{
-			l = -l;
-			return 0xFFFD;
-		}
-		return u;
-	}
-};
-
-
-template <typename C>
-class _utf_iterator
-{
-	typedef _utf_codec<sizeof(C)*8>	codec;
-
-	C 	  		  * cp;
-	mutable int8	sl;
-
-public:
-	typedef C 			codeunit_type;
-	typedef uchar_t		value_type;
-	typedef uchar_t	  * pointer;
-
-	class reference
-	{
-		const _utf_iterator & _i;
-
-		reference(const _utf_iterator & i): _i(i) {}
-	public:
-		operator value_type () const throw () 					{ return codec::get(_i.cp, _i.sl); }
-		reference & operator = (const value_type usv) throw() 	{ codec::put(_i.cp, usv, _i.sl); return *this; }
-
-		friend class _utf_iterator;
-	};
-
-
-	_utf_iterator(const void * us=0)	: cp(reinterpret_cast<C *>(const_cast<void *>(us))), sl(1) { }
-
-	_utf_iterator   & operator ++ () 	{ cp += abs(sl); return *this; }
-	_utf_iterator 	operator ++ (int) 	{ _utf_iterator tmp(*this); operator++(); return tmp; }
-
-	bool operator == (const _utf_iterator & rhs) const throw() { return cp >= rhs.cp; }
-	bool operator != (const _utf_iterator & rhs) const throw() { return !operator==(rhs); }
-
-	reference 	operator * () const throw() { return *this; }
-	pointer		operator ->() const throw() { return &operator *(); }
-
-	operator codeunit_type * () const throw() { return cp; }
-
-	bool error() const throw()	{ return sl < 1; }
-};
-
-template <typename C>
-struct utf
-{
-	typedef	typename _utf_codec<sizeof(C)*8>::codeunit_t codeunit_t;
-
-	typedef _utf_iterator<C>		iterator;
-	typedef _utf_iterator<const C>	const_iterator;
-};
-
-
-typedef utf<uint32>	utf32;
-typedef utf<uint16>	utf16;
-typedef utf<uint8>	utf8;
-
-} // namespace graphite2
deleted file mode 100644
--- a/gfx/graphite2/src/XmlTraceLog.h
+++ /dev/null
@@ -1,268 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-// XmlTraceLog - produces a log in XML format
-
-#include <cstdio>
-#include <graphite2/Types.h>
-#include <graphite2/XmlLog.h>
-#include <cassert>
-#include "Main.h"
-#include "XmlTraceLogTags.h"
-
-namespace graphite2 {
-
-#ifndef DISABLE_TRACING
-
-class XmlTraceLog
-{
-    friend bool ::graphite_start_logging(FILE * logFile, GrLogMask mask);
-    friend void ::graphite_stop_logging();
-public:
-    ~XmlTraceLog();
-    bool active() { return (m_file != NULL); };
-    void openElement(XmlTraceLogElement eId);
-    void closeElement(XmlTraceLogElement eId);
-    template<class T> void addArrayElement(XmlTraceLogElement eId, const T *start, int num);
-    //void addArrayElement(XmlTraceLogElement eId, const byte *start, int num);
-    void addSingleElement(XmlTraceLogElement eId, const int value);
-    void addAttribute(XmlTraceLogAttribute aId, const char * value);
-    void addAttribute(XmlTraceLogAttribute aId, float value);
-    void addAttribute(XmlTraceLogAttribute aId, int value);
-    void addAttribute(XmlTraceLogAttribute aId, unsigned int value);
-    void addAttribute(XmlTraceLogAttribute aId, long value);
-    void addAttribute(XmlTraceLogAttribute aId, unsigned long value);
-    void addAttribute(XmlTraceLogAttribute aId, unsigned long long value);
-    void addAttributeFixed(XmlTraceLogAttribute aId, uint32 value);
-    void writeText(const char * utf8);
-    void writeUnicode(const uint32 code);
-    void writeElementArray(XmlTraceLogElement eId, XmlTraceLogAttribute aId, int16 * values, size_t length);
-    void error(const char * msg, ...);
-    void warning(const char * msg, ...);
-    static XmlTraceLog & get()
-    {
-        return *sLog;
-    }
-    CLASS_NEW_DELETE
-private:
-    static XmlTraceLog sm_NullLog;
-    static XmlTraceLog * sLog;
-    XmlTraceLog(FILE * file, const char * ns, GrLogMask logMask);
-private:
-    void escapeIfNeeded(const char * text);
-    enum {
-        MAX_ELEMENT_DEPTH = 256
-    };
-    FILE * m_file;
-    bool m_inElement;
-    bool m_elementEmpty;
-    bool m_lastNodeText;
-    uint32 m_depth;
-    GrLogMask m_mask;
-    XmlTraceLogElement m_elementStack[MAX_ELEMENT_DEPTH];
-};
-
-
-inline void XmlTraceLog::openElement(XmlTraceLogElement eId)
-{
-    if (!m_file) return;
-    if (m_inElement)
-    {
-        if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-            fprintf(m_file, ">");
-    }
-    if (xmlTraceLogElements[eId].mFlags & m_mask)
-    {
-        if (!m_lastNodeText)
-        {
-            fprintf(m_file, "\n");
-            for (size_t i = 0; i < m_depth; i++)
-            {
-                fprintf(m_file, " ");
-            }
-        }
-        fprintf(m_file, "<%s", xmlTraceLogElements[eId].mName);
-    }
-    m_elementStack[m_depth++] = eId;
-    m_inElement = true;
-    m_lastNodeText = false;
-}
-
-
-inline void XmlTraceLog::closeElement(XmlTraceLogElement eId)
-{
-    if (!m_file) return;
-    assert(m_depth > 0);
-    assert(eId == m_elementStack[m_depth-1]);
-    --m_depth;
-    if (xmlTraceLogElements[eId].mFlags & m_mask)
-    {
-        if (m_inElement)
-        {
-            fprintf(m_file, "/>");
-        }
-        else
-        {
-            if (!m_lastNodeText)
-            {
-                fprintf(m_file, "\n");
-                for (size_t i = 0; i < m_depth; i++)
-                    fprintf(m_file, " ");
-            }
-            fprintf(m_file, "</%s>", xmlTraceLogElements[eId].mName);
-        }
-#ifdef ENABLE_DEEP_TRACING
-        fflush(m_file);
-#endif        
-    }
-    m_inElement = false;
-    m_lastNodeText = false;
-}
-
-
-inline void XmlTraceLog::addAttribute(XmlTraceLogAttribute aId, const char * value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        fprintf(m_file, " %s=\"", xmlTraceLogAttributes[aId]);
-        escapeIfNeeded(value);
-        fprintf(m_file, "\"");
-    }
-}
-
-
-inline void XmlTraceLog::addAttribute(XmlTraceLogAttribute aId, float value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        fprintf(m_file, " %s=\"%f\"", xmlTraceLogAttributes[aId], value);
-    }
-}
-
-
-inline void XmlTraceLog::addAttribute(XmlTraceLogAttribute aId, int value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        fprintf(m_file, " %s=\"%d\"", xmlTraceLogAttributes[aId], value);
-    }
-}
-
-
-inline void XmlTraceLog::addAttribute(XmlTraceLogAttribute aId, unsigned int value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        fprintf(m_file, " %s=\"%u\"", xmlTraceLogAttributes[aId], value);
-    }
-}
-
-inline void XmlTraceLog::addAttribute(XmlTraceLogAttribute aId, long value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        fprintf(m_file, " %s=\"%ld\"", xmlTraceLogAttributes[aId], value);
-    }
-}
-
-inline void XmlTraceLog::addAttribute(XmlTraceLogAttribute aId, unsigned long value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        fprintf(m_file, " %s=\"%lu\"", xmlTraceLogAttributes[aId], value);
-    }
-}
-
-inline void XmlTraceLog::addAttribute(XmlTraceLogAttribute aId, unsigned long long value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        fprintf(m_file, " %s=\"%llu\"", xmlTraceLogAttributes[aId], value);
-    }
-}
-
-inline void XmlTraceLog::addAttributeFixed(XmlTraceLogAttribute aId, uint32 value)
-{
-    if (!m_file) return;
-    assert(m_inElement);
-    if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-    {
-        uint32 whole = (value >> 16);
-        float fraction = static_cast<float>(value & 0xFFFF) / static_cast<float>(0x1FFFE);
-        float fixed = whole + fraction;
-        fprintf(m_file, " %s=\"%f\"", xmlTraceLogAttributes[aId], fixed);
-    }
-}
-
-template<class T> void XmlTraceLog::addArrayElement(XmlTraceLogElement eId, const T *start, int num)
-{
-    if (!m_file) return;
-    if (m_inElement)
-    {
-        if (xmlTraceLogElements[m_elementStack[m_depth-1]].mFlags & m_mask)
-            fprintf(m_file, ">");
-    }
-    if (xmlTraceLogElements[eId].mFlags & m_mask)
-    {
-        if (!m_lastNodeText)
-        {
-            fprintf(m_file, "\n");
-            for (size_t i = 0; i < m_depth; i++)
-            {
-                fprintf(m_file, " ");
-            }
-        }
-        fprintf(m_file, "<%s>\n", xmlTraceLogElements[eId].mName);
-        while (num-- > 0)
-        {
-            for (size_t i = 0; i < m_depth + 1; i++) fprintf(m_file, " ");
-            fprintf(m_file, "<val>%d</val>\n", (uint32)*start++);
-        }
-        for (size_t i = 0; i < m_depth; i++) fprintf(m_file, " ");
-            fprintf(m_file, "</%s>", xmlTraceLogElements[eId].mName);
-    }
-    m_inElement = false;
-    m_lastNodeText = false;
-}
-
-#endif // !DISABLE_TRACING
-
-} // namespace graphite2
deleted file mode 100644
--- a/gfx/graphite2/src/XmlTraceLogTags.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/*  GRAPHITE2 LICENSING
-
-    Copyright 2010, SIL International
-    All rights reserved.
-
-    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.
-*/
-#pragma once
-#include "Main.h"
-#include <graphite2/Types.h>
-#include <graphite2/XmlLog.h>
-
-namespace graphite2 {
-
-#ifndef DISABLE_TRACING
-
-// start this at same line number as in XmlTraceLogTags.cpp
-enum XmlTraceLogElement {
-    ElementTopLevel,
-    ElementFace,
-    ElementGlyphs,
-    ElementGlyphFace,
-    ElementAttr,
-    ElementSilf,
-    ElementSilfSub,
-    ElementPass,
-    ElementPseudo,
-    ElementClassMap,
-    ElementLookupClass,
-    ElementLookup,
-    ElementRange,
-    ElementRuleMap,
-    ElementRule,
-    ElementStartState,
-    ElementStateTransitions,
-    ElementRow,
-    ElementData,
-    ElementConstraint,
-    ElementConstraints,
-    ElementActions,
-    ElementAction,
-    ElementFeatures,
-    ElementFeature,
-    ElementFeatureSetting,
-    ElementSegment,
-    ElementSlot,
-    ElementText,
-    ElementOpCode,
-    ElementTestRule,
-    ElementDoRule,
-    ElementRunPass,
-    ElementParams,
-    ElementPush,
-    ElementSubSeg,
-    ElementSegCache,
-    ElementSegCacheEntry,
-    ElementGlyph,
-    ElementPassResult,
-
-    ElementError,
-    ElementWarning,
-    NumElements // Last
-};
-
-
-
-// start this at same line number as in XmlTraceLogTags.cpp
-enum XmlTraceLogAttribute {
-    AttrIndex,
-    AttrVersion,
-    AttrMajor,
-    AttrMinor,
-    AttrNum,
-    AttrGlyphId,
-    AttrAdvance,
-    AttrAdvanceX,
-    AttrAdvanceY,
-    AttrAttrId,
-    AttrAttrVal,
-    AttrCompilerMajor,
-    AttrCompilerMinor,
-    AttrNumPasses,
-    AttrSubPass,
-    AttrPosPass,
-    AttrJustPass,
-    AttrBidiPass,
-    AttrPreContext,
-    AttrPostContext,
-    AttrPseudoGlyph,
-    AttrBreakWeight,
-    AttrDirectionality,
-    AttrNumJustLevels,
-    AttrLigComp,
-    AttrUserDefn,
-    AttrNumLigComp,
-    AttrNumCritFeatures,
-    AttrNumScripts,
-    AttrLBGlyph,
-    AttrNumPseudo,
-    AttrNumClasses,
-    AttrNumLinear,
-    AttrPassId,
-    AttrFlags,
-    AttrMaxRuleLoop,
-    AttrMaxRuleContext,
-    AttrMaxBackup,
-    AttrNumRules,
-    AttrNumRows,
-    AttrNumTransition,
-    AttrNumSuccess,
-    AttrNumColumns,
-    AttrNumRanges,
-    AttrMinPrecontext,
-    AttrMaxPrecontext,
-    AttrFirstId,
-    AttrLastId,
-    AttrColId,
-    AttrSuccessId,
-    AttrRuleId,
-    AttrContextLen,
-    AttrState,
-    AttrValue,
-    AttrSortKey,
-    AttrPrecontext,
-    AttrAction,
-    AttrActionCode,
-    Attr0,
-    Attr1,
-    Attr2,
-    Attr3,
-    Attr4,
-    Attr5,
-    Attr6,
-    Attr7,
-    AttrLabel,
-    AttrLength,
-    AttrX,
-    AttrY,
-    AttrBefore,
-    AttrAfter,
-    AttrEncoding,
-    AttrName,
-    AttrResult,
-    AttrDefault,
-    AttrAccessCount,
-    AttrLastAccess,
-    AttrMisses,
-
-    NumAttributes // Last
-};
-
-struct XmlTraceLogTag
-{
-public:
-    XmlTraceLogTag(const char * name, uint32 flags) : mName(name), mFlags(flags) {}
-    const char * mName;
-    uint32 mFlags;
-};
-
-extern const XmlTraceLogTag xmlTraceLogElements[NumElements];
-extern const char * xmlTraceLogAttributes[NumAttributes];
-
-#endif // !DISABLE_TRACING
-
-} // namespace graphite2
--- a/gfx/graphite2/src/call_machine.cpp
+++ b/gfx/graphite2/src/call_machine.cpp
@@ -30,40 +30,37 @@ of the License or (at your option) any l
 // Build either this interpreter or the direct_machine implementation.
 // The call threaded interpreter is portable across compilers and 
 // architectures as well as being useful to debug (you can set breakpoints on 
 // opcodes) but is slower that the direct threaded interpreter by a factor of 2
 
 #include <cassert>
 #include <cstring>
 #include <graphite2/Segment.h>
-#include "Machine.h"
-#include "Segment.h"
-#include "XmlTraceLog.h"
-#include "Slot.h"
-#include "Rule.h"
+#include "inc/Machine.h"
+#include "inc/Segment.h"
+#include "inc/Slot.h"
+#include "inc/Rule.h"
 
 // Disable the unused parameter warning as th compiler is mistaken since dp
 // is always updated (even if by 0) on every opcode.
 #ifdef __GNUC__
 #pragma GCC diagnostic ignored "-Wunused-parameter"
 #endif
 
 #define registers           const byte * & dp, vm::Machine::stack_t * & sp, \
                             vm::Machine::stack_t * const sb, regbank & reg
 
 // These are required by opcodes.h and should not be changed
 #define STARTOP(name)	    bool name(registers) REGPARM(4);\
-                            bool name(registers) { \
-                                STARTTRACE(name,is);
-#define ENDOP                   ENDTRACE; \
-                                return (sp - sb)/Machine::STACK_MAX==0; \
+                            bool name(registers) {
+#define ENDOP                   return (sp - sb)/Machine::STACK_MAX==0; \
                             }
 
-#define EXIT(status)        { push(status); ENDTRACE; return false; }
+#define EXIT(status)        { push(status); return false; }
 
 // This is required by opcode_table.h
 #define do_(name)           instr(name)
 
 
 using namespace graphite2;
 using namespace vm;
 
@@ -85,17 +82,17 @@ namespace {
 #define smap    reg.smap
 #define seg     smap.segment
 #define is      reg.is
 #define ip      reg.ip
 #define map     reg.map
 #define mapb    reg.map_base
 #define flags   reg.flags
 
-#include "opcodes.h"
+#include "inc/opcodes.h"
 
 #undef smap
 #undef seg
 #undef is
 #undef ip
 #undef map
 #undef mapb
 #undef flags
@@ -124,17 +121,17 @@ Machine::stack_t  Machine::run(const ins
     check_final_stack(sp);
     map = reg.map;
     *map = reg.is;
     return ret;
 }
 
 // Pull in the opcode table
 namespace {
-#include "opcode_table.h"
+#include "inc/opcode_table.h"
 }
 
 const opcode_t * Machine::getOpcodeTable() throw()
 {
     return opcode_table;
 }
 
 
--- a/gfx/graphite2/src/direct_machine.cpp
+++ b/gfx/graphite2/src/direct_machine.cpp
@@ -34,21 +34,20 @@ of the License or (at your option) any l
 // architecture gcc supports. 
 // This is twice as fast as the call threaded model and is likely faster on 
 // inorder processors with short pipelines and little branch prediction such 
 // as the ARM and possibly Atom chips.
 
 
 #include <cassert>
 #include <cstring>
-#include "Machine.h"
-#include "Segment.h"
-#include "XmlTraceLog.h"
-#include "Slot.h"
-#include "Rule.h"
+#include "inc/Machine.h"
+#include "inc/Segment.h"
+#include "inc/Slot.h"
+#include "inc/Rule.h"
 
 #define STARTOP(name)           name: {
 #define ENDOP                   }; goto *((sp - sb)/Machine::STACK_MAX ? &&end : *++ip);
 #define EXIT(status)            { push(status); goto end; }
 
 #define do_(name)               &&name
 
 
@@ -61,17 +60,17 @@ const void * direct_run(const bool      
                         const instr       * program,
                         const byte        * data,
                         Machine::stack_t  * stack,
                         slotref         * & __map,
                         SlotMap           * __smap=0)
 {
     // We need to define and return to opcode table from within this function 
     // other inorder to take the addresses of the instruction bodies.
-    #include "opcode_table.h"
+    #include "inc/opcode_table.h"
     if (get_table_mode)
         return opcode_table;
 
     // Declare virtual machine registers
     const instr       * ip = program;
     const byte        * dp = data;
     Machine::stack_t  * sp = stack + Machine::STACK_GUARD,
                 * const sb = sp;
@@ -81,17 +80,17 @@ const void * direct_run(const bool      
                      * map = __map,
               * const mapb = smap.begin()+smap.context();
     int8             flags = 0;
     
     // start the program
     goto **ip;
 
     // Pull in the opcode definitions
-    #include "opcodes.h"
+    #include "inc/opcodes.h"
     
     end:
     __map  = map;
     *__map = is;
     return sp;
 }
 
 }
--- a/gfx/graphite2/src/files.mk
+++ b/gfx/graphite2/src/files.mk
@@ -35,21 +35,23 @@
 # $(_NS)_SOURCES    List of source files (with .cpp extension)
 # $(_NS)_PRIVATE_HEADERS    List of private header files (with .h extension)
 # $(_NS)_PUBLIC_HEADERS     List of public header files (with .h extension)
 
 
 $(_NS)_SOURCES = \
     $($(_NS)_BASE)/src/$($(_NS)_MACHINE)_machine.cpp \
     $($(_NS)_BASE)/src/gr_char_info.cpp \
+    $($(_NS)_BASE)/src/gr_face.cpp \
     $($(_NS)_BASE)/src/gr_features.cpp \
-    $($(_NS)_BASE)/src/gr_face.cpp \
     $($(_NS)_BASE)/src/gr_font.cpp \
+	$($(_NS)_BASE)/src/gr_logging.cpp \
     $($(_NS)_BASE)/src/gr_segment.cpp \
     $($(_NS)_BASE)/src/gr_slot.cpp \
+    $($(_NS)_BASE)/src/json.cpp \
     $($(_NS)_BASE)/src/Bidi.cpp \
     $($(_NS)_BASE)/src/CachedFace.cpp \
     $($(_NS)_BASE)/src/CmapCache.cpp \
     $($(_NS)_BASE)/src/Code.cpp \
     $($(_NS)_BASE)/src/Face.cpp \
     $($(_NS)_BASE)/src/FeatureMap.cpp \
     $($(_NS)_BASE)/src/Font.cpp \
     $($(_NS)_BASE)/src/GlyphFace.cpp \
@@ -62,48 +64,48 @@
     $($(_NS)_BASE)/src/Segment.cpp \
     $($(_NS)_BASE)/src/Silf.cpp \
     $($(_NS)_BASE)/src/Slot.cpp \
     $($(_NS)_BASE)/src/Sparse.cpp \
     $($(_NS)_BASE)/src/TtfUtil.cpp \
     $($(_NS)_BASE)/src/UtfCodec.cpp
 
 $(_NS)_PRIVATE_HEADERS = \
-    $($(_NS)_BASE)/src/CachedFace.h \
-    $($(_NS)_BASE)/src/CharInfo.h \
-    $($(_NS)_BASE)/src/CmapCache.h \
-    $($(_NS)_BASE)/src/Code.h \
-    $($(_NS)_BASE)/src/Face.h \
-    $($(_NS)_BASE)/src/FeatureMap.h \
-    $($(_NS)_BASE)/src/FeatureVal.h \
-    $($(_NS)_BASE)/src/Font.h \
-    $($(_NS)_BASE)/src/GlyphFaceCache.h \
-    $($(_NS)_BASE)/src/GlyphFace.h \
-    $($(_NS)_BASE)/src/List.h \
-    $($(_NS)_BASE)/src/locale2lcid.h \
-    $($(_NS)_BASE)/src/Machine.h \
-    $($(_NS)_BASE)/src/Main.h \
-    $($(_NS)_BASE)/src/NameTable.h \
-    $($(_NS)_BASE)/src/opcodes.h \
-    $($(_NS)_BASE)/src/opcode_table.h \
-    $($(_NS)_BASE)/src/Pass.h \
-    $($(_NS)_BASE)/src/Position.h \
-    $($(_NS)_BASE)/src/processUTF.h \
-    $($(_NS)_BASE)/src/Rule.h \
-    $($(_NS)_BASE)/src/SegCacheEntry.h \
-    $($(_NS)_BASE)/src/SegCache.h \
-    $($(_NS)_BASE)/src/SegCacheStore.h \
-    $($(_NS)_BASE)/src/Segment.h \
-    $($(_NS)_BASE)/src/Silf.h \
-    $($(_NS)_BASE)/src/Slot.h \
-    $($(_NS)_BASE)/src/Sparse.h \
-    $($(_NS)_BASE)/src/TtfTypes.h \
-    $($(_NS)_BASE)/src/TtfUtil.h \
-    $($(_NS)_BASE)/src/UtfCodec.h \
-    $($(_NS)_BASE)/src/XmlTraceLog.h \
-    $($(_NS)_BASE)/src/XmlTraceLogTags.h 
+    $($(_NS)_BASE)/src/inc/debug.h \
+    $($(_NS)_BASE)/src/inc/json.h \
+    $($(_NS)_BASE)/src/inc/CachedFace.h \
+    $($(_NS)_BASE)/src/inc/CharInfo.h \
+    $($(_NS)_BASE)/src/inc/CmapCache.h \
+    $($(_NS)_BASE)/src/inc/Code.h \
+    $($(_NS)_BASE)/src/inc/Endian.h \
+    $($(_NS)_BASE)/src/inc/Face.h \
+    $($(_NS)_BASE)/src/inc/FeatureMap.h \
+    $($(_NS)_BASE)/src/inc/FeatureVal.h \
+    $($(_NS)_BASE)/src/inc/Font.h \
+    $($(_NS)_BASE)/src/inc/GlyphFace.h \
+    $($(_NS)_BASE)/src/inc/GlyphFaceCache.h \
+    $($(_NS)_BASE)/src/inc/List.h \
+    $($(_NS)_BASE)/src/inc/locale2lcid.h \
+    $($(_NS)_BASE)/src/inc/Machine.h \
+    $($(_NS)_BASE)/src/inc/Main.h \
+    $($(_NS)_BASE)/src/inc/NameTable.h \
+    $($(_NS)_BASE)/src/inc/opcode_table.h \
+    $($(_NS)_BASE)/src/inc/opcodes.h \
+    $($(_NS)_BASE)/src/inc/Pass.h \
+    $($(_NS)_BASE)/src/inc/Position.h \
+    $($(_NS)_BASE)/src/inc/Rule.h \
+    $($(_NS)_BASE)/src/inc/SegCache.h \
+    $($(_NS)_BASE)/src/inc/SegCacheEntry.h \
+    $($(_NS)_BASE)/src/inc/SegCacheStore.h \
+    $($(_NS)_BASE)/src/inc/Segment.h \
+    $($(_NS)_BASE)/src/inc/Silf.h \
+    $($(_NS)_BASE)/src/inc/Slot.h \
+    $($(_NS)_BASE)/src/inc/Sparse.h \
+    $($(_NS)_BASE)/src/inc/TtfTypes.h \
+    $($(_NS)_BASE)/src/inc/TtfUtil.h \
+    $($(_NS)_BASE)/src/inc/UtfCodec.h
 
 $(_NS)_PUBLIC_HEADERS = \
     $($(_NS)_BASE)/include/graphite2/Font.h \
+    $($(_NS)_BASE)/include/graphite2/Log.h \
     $($(_NS)_BASE)/include/graphite2/Segment.h \
-    $($(_NS)_BASE)/include/graphite2/Types.h \
-    $($(_NS)_BASE)/include/graphite2/XmlLog.h
+    $($(_NS)_BASE)/include/graphite2/Types.h
 
--- a/gfx/graphite2/src/gr_char_info.cpp
+++ b/gfx/graphite2/src/gr_char_info.cpp
@@ -21,17 +21,17 @@
 
 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.
 */
 #include <cassert>
 #include "graphite2/Segment.h"
-#include "CharInfo.h"
+#include "inc/CharInfo.h"
 
 extern "C"
 {
 
 unsigned int gr_cinfo_unicode_char(const gr_char_info* p/*not NULL*/)
 {
     assert(p);
     return p->unicodeChar();
--- a/gfx/graphite2/src/gr_face.cpp
+++ b/gfx/graphite2/src/gr_face.cpp
@@ -20,19 +20,18 @@
     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.
 */
 #include "graphite2/Font.h"
-#include "Face.h"
-#include "CachedFace.h"
-#include "XmlTraceLog.h"
+#include "inc/Face.h"
+#include "inc/CachedFace.h"
 
 
 using namespace graphite2;
 
 extern "C" {
 
 
 gr_face* gr_make_face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable, unsigned int faceOptions)
@@ -46,68 +45,65 @@ gr_face* gr_make_face(const void* appFac
 		{
 			delete res;
 			return 0;
 		}
     }
     else
     	faceOptions &= ~gr_face_dumbRendering;
 
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().openElement(ElementFace);
-#endif
     bool valid = true;
     valid &= res->readGlyphs(faceOptions);
     if (!valid) {
         delete res;
         return 0;
     }
     valid &= res->readFeatures();
     valid &= res->readGraphite();
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().closeElement(ElementFace);
-#endif
     
     if (!(faceOptions & gr_face_dumbRendering) && !valid) {
         delete res;
         return 0;
     }
     return static_cast<gr_face *>(res);
 }
 
-#ifndef DISABLE_SEGCACHE
-
+#ifndef GRAPHITE2_NSEGCACHE
 gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable, unsigned int cacheSize, unsigned int faceOptions)
                   //the appFaceHandle must stay alive all the time when the GrFace is alive. When finished with the GrFace, call destroy_face
 {
     CachedFace *res = new CachedFace(appFaceHandle, getTable);
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().openElement(ElementFace);
-#endif
+
+    if (res->getTable(Tag::Silf) == 0)
+    {
+		if (!(faceOptions & gr_face_dumbRendering))
+		{
+			delete res;
+			return 0;
+		}
+    }
+    else
+    	faceOptions &= ~gr_face_dumbRendering;
+
     bool valid = true;
     valid &= res->readGlyphs(faceOptions);
     if (!valid) {
         delete res;
         return 0;
     }
     valid &= res->readFeatures();
     valid &= res->readGraphite();
     valid &= res->setupCache(cacheSize);
 
-#ifndef DISABLE_TRACING
-    XmlTraceLog::get().closeElement(ElementFace);
-#endif
-
     if (!(faceOptions & gr_face_dumbRendering) && !valid) {
         delete res;
         return 0;
     }
     return static_cast<gr_face *>(static_cast<Face *>(res));
 }
-
 #endif
 
 gr_uint32 gr_str_to_tag(const char *str)
 {
     uint32 res = 0;
     int i = strlen(str);
     if (i > 4) i = 4;
     while (--i >= 0)
@@ -204,17 +200,17 @@ uint16 *face_name(const gr_face * pFace,
 #endif
 
 unsigned short gr_face_n_glyphs(const gr_face* pFace)
 {
     return pFace->getGlyphFaceCache()->numGlyphs();
 }
 
 
-#ifndef DISABLE_FILE_FACE
+#ifndef GRAPHITE2_NFILEFACE
 gr_face* gr_make_file_face(const char *filename, unsigned int faceOptions)
 {
     FileFace* pFileFace = new FileFace(filename);
     if (pFileFace->m_pTableDir)
     {
       gr_face* pRes =gr_make_face(pFileFace, &FileFace::table_fn, faceOptions);
       if (pRes)
       {
@@ -224,17 +220,17 @@ gr_face* gr_make_file_face(const char *f
     }
     
     //error when loading
 
     delete pFileFace;
     return NULL;
 }
 
-#ifndef DISABLE_SEGCACHE
+#ifndef GRAPHITE2_NSEGCACHE
 gr_face* gr_make_file_face_with_seg_cache(const char* filename, unsigned int segCacheMaxSize, unsigned int faceOptions)   //returns NULL on failure. //TBD better error handling
                   //when finished with, call destroy_face
 {
     FileFace* pFileFace = new FileFace(filename);
     if (pFileFace->m_pTableDir)
     {
       gr_face* pRes = gr_make_face_with_seg_cache(pFileFace, &FileFace::table_fn, segCacheMaxSize, faceOptions);
       if (pRes)
@@ -245,14 +241,14 @@ gr_face* gr_make_file_face_with_seg_cach
     }
 
     //error when loading
 
     delete pFileFace;
     return NULL;
 }
 #endif
-#endif      //!DISABLE_FILE_FACE
+#endif      //!GRAPHITE2_NFILEFACE
 
 
 } // extern "C"
 
 
--- a/gfx/graphite2/src/gr_features.cpp
+++ b/gfx/graphite2/src/gr_features.cpp
@@ -20,20 +20,20 @@
     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.
 */
 #include "graphite2/Font.h"
-#include "Face.h"
-#include "FeatureMap.h"
-#include "FeatureVal.h"
-#include "NameTable.h"
+#include "inc/Face.h"
+#include "inc/FeatureMap.h"
+#include "inc/FeatureVal.h"
+#include "inc/NameTable.h"
 
 using namespace graphite2;
 
 extern "C" {
 
 
 gr_uint16 gr_fref_feature_value(const gr_feature_ref* pfeatureref, const gr_feature_val* feats)    //returns 0 if either pointer is NULL
 {
--- a/gfx/graphite2/src/gr_font.cpp
+++ b/gfx/graphite2/src/gr_font.cpp
@@ -20,17 +20,17 @@
     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.
 */
 #include "graphite2/Font.h"
-#include "Font.h"
+#include "inc/Font.h"
 
 
 using namespace graphite2;
 
 extern "C" {
 
 void gr_engine_version(int *nMajor, int *nMinor, int *nBugFix)
 {
--- a/gfx/graphite2/src/gr_logging.cpp
+++ b/gfx/graphite2/src/gr_logging.cpp
@@ -19,44 +19,112 @@
     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.
 */
-#include "XmlTraceLog.h"
-// #include "graphite2/XmlLog.h"
-
+#include "graphite2/Log.h"
+#include "inc/debug.h"
+#include "inc/CharInfo.h"
+#include "inc/Slot.h"
+#include "inc/Segment.h"
 
 using namespace graphite2;
 
 extern "C" {
 
 
-bool graphite_start_logging(GR_MAYBE_UNUSED FILE * logFile, GR_MAYBE_UNUSED GrLogMask mask)
+bool graphite_start_logging(FILE * logFile, GrLogMask mask)
 {
-#ifdef DISABLE_TRACING
-    return false;
-#else	//!DISABLE_TRACING
-    if (XmlTraceLog::sLog != &XmlTraceLog::sm_NullLog)
-    {
-        delete XmlTraceLog::sLog;
-    }
-    XmlTraceLog::sLog = new XmlTraceLog(logFile, "http://projects.palaso.org/graphite2", mask);
-    return (XmlTraceLog::sLog != NULL);
-#endif		//!DISABLE_TRACING
+	if (!logFile || !mask)	return false;
+
+#if !defined GRAPHITE2_NTRACING
+	dbgout = new json(logFile);
+	return dbgout;
+#else
+	return false;
+#endif
 }
 
 void graphite_stop_logging()
 {
-#ifndef DISABLE_TRACING
-    if (XmlTraceLog::sLog && XmlTraceLog::sLog != &XmlTraceLog::sm_NullLog)
-    {
-        delete XmlTraceLog::sLog;
-        XmlTraceLog::sLog = &XmlTraceLog::sm_NullLog;
-    }
-#endif		//!DISABLE_TRACING
+#if !defined GRAPHITE2_NTRACING
+	delete dbgout;
+#endif
 }
 
 
 } // extern "C"
+
+#if !defined GRAPHITE2_NTRACING
+
+json *graphite2::dbgout = 0;
+
+
+json & graphite2::operator << (json & j, const CharInfo & ci) throw()
+{
+	return j << json::object
+				<< "offset"			<< ci.base()
+				<< "unicode"		<< ci.unicodeChar()
+				<< "break"			<< ci.breakWeight()
+				<< "slot" << json::flat << json::object
+					<< "before"	<< ci.before()
+					<< "after"	<< ci.after()
+					<< json::close
+				<< json::close;
+}
+
+
+json & graphite2::operator << (json & j, const dslot & ds) throw()
+{
+	assert(ds.first);
+	assert(ds.second);
+	Segment & seg = *ds.first;
+	Slot & s = *ds.second;
+
+	j << json::object
+		<< "id"				<< slotid(&s)
+		<< "gid"			<< s.gid()
+		<< "charinfo" << json::flat << json::object
+			<< "original"		<< s.original()
+			<< "before"			<< s.before()
+			<< "after" 			<< s.after()
+			<< json::close
+		<< "origin"			<< s.origin()
+		<< "shift"			<< Position(s.getAttr(0, gr_slatShiftX, 0), s.getAttr(0, gr_slatShiftY, 0))
+		<< "advance"		<< s.advancePos()
+		<< "insert"			<< s.isInsertBefore()
+		<< "break"			<< s.getAttr(&seg, gr_slatBreak, 0);
+	if (s.just() > 0)
+		j << "justification"	<< s.just();
+	if (s.getBidiLevel() > 0)
+		j << "bidi"		<< s.getBidiLevel();
+	if (!s.isBase())
+		j << "parent" << json::flat << json::object
+			<< "id"				<< slotid(s.attachedTo())
+			<< "level"			<< s.getAttr(0, gr_slatAttLevel, 0)
+			<< "offset"			<< s.attachOffset()
+			<< json::close;
+	j << "user" << json::flat << json::array;
+	for (int n = 0; n!= seg.numAttrs(); ++n)
+		j	<< s.userAttrs()[n];
+		j 	<< json::close;
+	if (s.firstChild())
+	{
+		j	<< "children" << json::flat << json::array;
+		for (const Slot *c = s.firstChild(); c; c = c->nextSibling())  j << slotid(c);
+		j		<< json::close;
+	}
+	return j << json::close;
+}
+
+
+graphite2::slotid::slotid(const Slot * const p) throw()
+{
+	uint32 s = reinterpret_cast<size_t>(p);
+	sprintf(name, "%.4x-%.2x-%.4hx", uint16(s >> 16), uint16(p ? p->index() : 0), uint16(s));
+	name[sizeof name-1] = 0;
+}
+
+#endif
--- a/gfx/graphite2/src/gr_segment.cpp
+++ b/gfx/graphite2/src/gr_segment.cpp
@@ -20,18 +20,18 @@
     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.
 */
 #include "graphite2/Segment.h"
-#include "UtfCodec.h"
-#include "Segment.h"
+#include "inc/UtfCodec.h"
+#include "inc/Segment.h"
 
 using namespace graphite2;
 
 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)
   {
@@ -48,19 +48,17 @@ namespace
         delete pRes;
         return NULL;
       }
       // run the line break passes
       // run the substitution passes
       pRes->prepare_pos(font);
       // run the positioning passes
       pRes->finalise(font);
-  #ifndef DISABLE_TRACING
-      pRes->logSegment(enc, pStart, nChars);
-  #endif
+
       return static_cast<gr_segment*>(pRes);
   }
 
 
 }
 
 
 template <typename utf_iter>
@@ -165,13 +163,12 @@ const gr_slot* gr_seg_last_slot(gr_segme
     assert(pSeg);
     return static_cast<const gr_slot*>(pSeg->last());
 }
 
 void gr_seg_justify(gr_segment* pSeg/*not NULL*/, gr_slot* pSlot/*not NULL*/, const gr_font *pFont, double width, enum gr_justFlags flags, gr_slot *pFirst, gr_slot *pLast)
 {
     assert(pSeg);
     assert(pSlot);
-    printf("[%f]", width);
     pSeg->justify(pSlot, pFont, width, justFlags(flags), pFirst, pLast);
 }
 
 } // extern "C"
--- a/gfx/graphite2/src/gr_slot.cpp
+++ b/gfx/graphite2/src/gr_slot.cpp
@@ -20,19 +20,19 @@
     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.
 */
 #include "graphite2/Segment.h"
-#include "Segment.h"
-#include "Slot.h"
-#include "Font.h"
+#include "inc/Segment.h"
+#include "inc/Slot.h"
+#include "inc/Font.h"
 
 
 extern "C" {
 
 
 const gr_slot* gr_slot_next_in_segment(const gr_slot* p/*not NULL*/)
 {
     assert(p);
@@ -43,17 +43,17 @@ const gr_slot* gr_slot_prev_in_segment(c
 {
     assert(p);
     return static_cast<const gr_slot*>(p->prev());
 }
 
 const gr_slot* gr_slot_attached_to(const gr_slot* p/*not NULL*/)        //returns NULL iff base. If called repeatedly on result, will get to a base
 {
     assert(p);
-    return static_cast<const gr_slot*>(p->attachTo());
+    return static_cast<const gr_slot*>(p->attachedTo());
 }
 
 
 const gr_slot* gr_slot_first_attachment(const gr_slot* p/*not NULL*/)        //returns NULL iff no attachments.
 {        //if slot_first_attachment(p) is not NULL, then slot_attached_to(slot_first_attachment(p))==p.
     assert(p);
     return static_cast<const gr_slot*>(p->firstChild());
 }
@@ -151,18 +151,18 @@ int gr_slot_original(const gr_slot* p/*n
     assert(p);
     return p->original();
 }
 
 void gr_slot_linebreak_before(gr_slot* p/*not NULL*/)
 {
     assert(p);
     gr_slot *prev = (gr_slot *)p->prev();
+    prev->sibling(NULL);
     prev->next(NULL);
-    prev->sibling(NULL);
     p->prev(NULL);
 }
 
 #if 0       //what should this be
 size_t id(const gr_slot* p/*not NULL*/)
 {
     return (size_t)p->id();
 }
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/src/inc/CachedFace.h
@@ -0,0 +1,52 @@
+/*  GRAPHITE2 LICENSING
+
+    Copyright 2010, SIL International
+    All rights reserved.
+
+    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.
+*/
+#pragma once
+
+#ifndef GRAPHITE2_NSEGCACHE
+
+#include "inc/Face.h"
+
+namespace graphite2 {
+
+class SegCacheStore;
+
+class CachedFace : public Face
+{
+public:
+    CachedFace(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable2);
+    bool setupCache(unsigned int cacheSize);
+    virtual ~CachedFace();
+    virtual bool runGraphite(Segment *seg, const Silf *silf) const;
+    SegCacheStore * cacheStore() { return m_cacheStore; }
+private:
+    SegCacheStore * m_cacheStore;
+};
+
+} // namespace graphite2
+
+#endif
+
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/src/inc/CharInfo.h
@@ -0,0 +1,64 @@
+/*  GRAPHITE2 LICENSING
+
+    Copyright 2010, SIL International
+    All rights reserved.
+
+    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.
+*/
+#pragma once
+#include "inc/Main.h"
+
+
+namespace graphite2 {
+
+class CharInfo
+{
+
+public:
+    CharInfo() : m_before(-1), m_after(0) {}
+    void init(int cid) { m_char = cid; }
+    unsigned int unicodeChar() const { return m_char; }
+    void feats(int offset) { m_featureid = offset; }
+    int fid() const { return m_featureid; }
+    int breakWeight() const { return m_break; }
+    void breakWeight(int val) { m_break = val; }
+    int after() const { return m_after; }
+    void after(int val) { m_after = val; }
+    int before() const { return m_before; }
+    void before(int val) { m_before = val; }
+    size_t base() const { return m_base; }
+    void base(size_t offset) { m_base = offset; }
+
+    CLASS_NEW_DELETE
+private:
+    int m_char;     // Unicode character from character stream
+    int m_before;   // slot index before us, comes before
+    int m_after;    // slot index after us, comes after
+    size_t  m_base; // offset into input string corresponding to this charinfo
+    uint8 m_featureid;	// index into features list in the segment
+    int8 m_break;	// breakweight coming from lb table
+};
+
+} // namespace graphite2
+
+struct gr_char_info : public graphite2::CharInfo {};
+
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/src/inc/CmapCache.h
@@ -0,0 +1,73 @@
+/*  GRAPHITE2 LICENSING
+
+    Copyright 2010, SIL International
+    All rights reserved.
+
+    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.
+*/
+#pragma once
+
+#include "inc/Main.h"
+
+namespace graphite2 {
+
+class Face;
+
+class Cmap
+{
+public:
+	virtual ~Cmap() throw() {}
+
+	virtual uint16 operator [] (const uint32) const throw() { return 0; }
+
+	virtual operator bool () const throw() { return false; }
+
+	CLASS_NEW_DELETE;
+};
+
+class DirectCmap : public Cmap
+{
+public:
+	DirectCmap(const void* cmap, size_t length);
+	virtual uint16 operator [] (const uint32 usv) const throw();
+	virtual operator bool () const throw();
+
+    CLASS_NEW_DELETE;
+private:
+    const void *_stable,
+    		   *_ctable;
+};
+
+class CmapCache : public Cmap
+{
+public:
+	CmapCache(const void * cmapTable, size_t length);
+	virtual ~CmapCache() throw();
+	virtual uint16 operator [] (const uint32 usv) const throw();
+	virtual operator bool () const throw();
+    CLASS_NEW_DELETE;
+private:
+    bool m_isBmpOnly;
+    uint16 ** m_blocks;
+};
+
+} // namespace graphite2
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/src/inc/Code.h
@@ -0,0 +1,172 @@
+/*  GRAPHITE2 LICENSING
+
+    Copyright 2010, SIL International
+    All rights reserved.
+
+    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.
+*/
+// This class represents loaded graphite stack machine code.  It performs 
+// basic sanity checks, on the incoming code to prevent more obvious problems
+// from crashing graphite.
+// Author: Tim Eves
+
+#pragma once
+
+#include <cassert>
+#include <graphite2/Types.h>
+#include "inc/Main.h"
+#include "inc/Machine.h"
+
+namespace graphite2 {
+
+class Silf;
+class Face;
+
+namespace vm {
+
+class Machine::Code
+{
+public:
+    enum status_t 
+    {
+        loaded,
+        alloc_failed, 
+        invalid_opcode, 
+        unimplemented_opcode_used,
+        out_of_range_data,
+        jump_past_end,
+        arguments_exhausted,
+        missing_return
+    };
+
+private:
+    class decoder;
+
+    instr *     _code;
+    byte  *     _data;
+    size_t      _data_size,
+                _instr_count;
+    byte        _max_ref;
+    mutable status_t _status;
+    bool        _constraint,
+                _modify,
+                _delete;
+    mutable bool _own;
+
+    void release_buffers() throw ();
+    void failure(const status_t) throw();
+
+public:
+    Code() throw();
+    Code(bool is_constraint, const byte * bytecode_begin, const byte * const bytecode_end,
+         uint8 pre_context, uint16 rule_length, const Silf &, const Face &);
+    Code(const Machine::Code &) throw();
+    ~Code() throw();
+    
+    Code & operator=(const Code &rhs) throw();
+    operator bool () const throw();
+    status_t      status() const throw();
+    bool          constraint() const throw();
+    size_t        dataSize() const throw();
+    size_t        instructionCount() const throw();
+    bool          immutable() const throw();
+    bool          deletes() const throw();
+    size_t        maxRef() const throw();
+
+    int32 run(Machine &m, slotref * & map) const;
+    
+    CLASS_NEW_DELETE;
+};
+
+inline Machine::Code::Code() throw()
+: _code(0), _data(0), _data_size(0), _instr_count(0), _max_ref(0),
+  _status(loaded), _own(false) {
+}
+
+inline Machine::Code::Code(const Machine::Code &obj) throw ()
+ :  _code(obj._code), 
+    _data(obj._data), 
+    _data_size(obj._data_size), 
+    _instr_count(obj._instr_count),
+    _max_ref(obj._max_ref),
+    _status(obj._status), 
+    _constraint(obj._constraint),
+    _modify(obj._modify),
+    _delete(obj._delete),
+    _own(obj._own) 
+{
+    obj._own = false;
+}
+
+inline Machine::Code & Machine::Code::operator=(const Machine::Code &rhs) throw() {
+    if (_instr_count > 0)
+        release_buffers();
+    _code        = rhs._code; 
+    _data        = rhs._data;
+    _data_size   = rhs._data_size; 
+    _instr_count = rhs._instr_count;
+    _status      = rhs._status; 
+    _constraint  = rhs._constraint;
+    _modify      = rhs._modify;
+    _delete      = rhs._delete;
+    _own         = rhs._own; 
+    rhs._own = false;
+    return *this;
+}
+
+inline Machine::Code::operator bool () const throw () {
+    return _code && status() == loaded;
+}
+
+inline Machine::Code::status_t Machine::Code::status() const throw() {
+    return _status;
+}
+
+inline bool Machine::Code::constraint() const throw() {
+    return _constraint;
+}
+
+inline size_t Machine::Code::dataSize() const throw() {
+    return _data_size;
+}
+
+inline size_t Machine::Code::instructionCount() const throw() {
+    return _instr_count;
+}
+
+inline bool Machine::Code::immutable() const throw()
+{
+  return !(_delete || _modify);
+}
+
+inline bool Machine::Code::deletes() const throw()
+{
+  return _delete;
+}
+
+inline size_t Machine::Code::maxRef() const throw()
+{
+	return _max_ref;
+}
+
+} // namespace vm
+} // namespace graphite2
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/src/inc/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 void * p) {
+		return T(_peek<sizeof(T)>(static_cast<const unsigned char *>(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 void * p) {
+		return T(_peek<sizeof(T)>(static_cast<const unsigned char *>(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; }
+
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/src/inc/Face.h
@@ -0,0 +1,176 @@
+/*  GRAPHITE2 LICENSING
+
+    Copyright 2010, SIL International
+    All rights reserved.
+
+    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.
+*/
+#pragma once
+
+#include "inc/Main.h"
+#include "inc/GlyphFace.h"
+#include "inc/Silf.h"
+#include "inc/TtfUtil.h"
+#include "inc/Main.h"
+#include "graphite2/Font.h"
+#include "inc/FeatureMap.h"
+#include "inc/GlyphFaceCache.h"
+
+#ifndef GRAPHITE2_NFILEFACE
+#include <cstdio>
+#include <cassert>
+#include "inc/TtfTypes.h"
+#endif      //!GRAPHITE2_NFILEFACE
+
+namespace graphite2 {
+
+class Segment;
+class FeatureVal;
+class NameTable;
+class Cmap;
+
+using TtfUtil::Tag;
+
+// These are the actual tags, as distinct from the consecutive IDs in TtfUtil.h
+
+#ifndef GRAPHITE2_NFILEFACE
+class TableCacheItem
+{
+public:
+    TableCacheItem(char * theData, size_t theSize) : m_data(theData), m_size(theSize) {}
+    TableCacheItem() : m_data(0), m_size(0) {}
+    ~TableCacheItem()
+    {
+        if (m_size) free(m_data);
+    }
+    void set(char * theData, size_t theSize) { m_data = theData; m_size = theSize; }
+    const void * data() const { return m_data; }
+    size_t size() const { return m_size; }
+private:
+    char * m_data;
+    size_t m_size;
+};
+#endif      //!GRAPHITE2_NFILEFACE
+
+
+
+
+class FileFace
+{
+#ifndef GRAPHITE2_NFILEFACE
+public:
+    static const void *table_fn(const void* appFaceHandle, unsigned int name, size_t *len);
+  
+    FileFace(const char *filename);
+    ~FileFace();
+//    virtual const void *getTable(unsigned int name, size_t *len) const;
+    bool isValid() const { return m_pfile && m_pHeader && m_pTableDir; }
+
+    CLASS_NEW_DELETE
+public:     //for local convenience    
+    FILE* m_pfile;
+    unsigned int m_lfile;
+    mutable TableCacheItem m_tables[18];
+    TtfUtil::Sfnt::OffsetSubTable* m_pHeader;
+    TtfUtil::Sfnt::OffsetSubTable::Entry* m_pTableDir;       //[] number of elements is determined by m_pHeader->num_tables
+#endif      //!GRAPHITE2_NFILEFACE
+   
+private:        //defensive
+    FileFace(const FileFace&);
+    FileFace& operator=(const FileFace&);
+};
+
+class Face
+{
+public:
+    const byte *getTable(const Tag name, size_t  * len = 0) const {
+    	size_t tbl_len=0;
+    	const byte * const tbl = reinterpret_cast<const byte *>((*m_getTable)(m_appFaceHandle, name, &tbl_len));
+    	if (len) *len = tbl_len;
+    	return TtfUtil::CheckTable(name, tbl, tbl_len) ? tbl : 0;
+    }
+    float advance(unsigned short id) const { return m_pGlyphFaceCache->glyph(id)->theAdvance().x; }
+    const Silf *silf(int i) const { return ((i < m_numSilf) ? m_silfs + i : (const Silf *)NULL); }
+    virtual bool runGraphite(Segment *seg, const Silf *silf) const;
+    uint16 findPseudo(uint32 uid) const { return (m_numSilf) ? m_silfs[0].findPseudo(uid) : 0; }
+
+public:
+    Face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable2) : 
+        m_appFaceHandle(appFaceHandle), m_getTable(getTable2), m_pGlyphFaceCache(NULL),
+        m_cmap(NULL), m_numSilf(0), m_silfs(NULL), m_pFileFace(NULL),
+        m_pNames(NULL) {}
+    virtual ~Face();
+public:
+    float getAdvance(unsigned short glyphid, float scale) const { return advance(glyphid) * scale; }
+    const Rect &theBBoxTemporary(uint16 gid) const { return m_pGlyphFaceCache->glyph(gid)->theBBox(); }   //warning value may become invalid when another glyph is accessed
+    unsigned short upem() const { return m_upem; }
+    uint16 glyphAttr(uint16 gid, uint8 gattr) const { return m_pGlyphFaceCache->glyphAttr(gid, gattr); }
+
+private:
+    friend class Font;
+    unsigned short numGlyphs() const { return m_pGlyphFaceCache->m_nGlyphs; }
+
+public:
+    bool readGlyphs(uint32 faceOptions);
+    bool readGraphite();
+    bool readFeatures() { return m_Sill.readFace(*this); }
+    const Silf *chooseSilf(uint32 script) const;
+    const SillMap& theSill() const { return m_Sill; }
+    uint16 numFeatures() const { return m_Sill.m_FeatureMap.numFeats(); }
+    const FeatureRef *featureById(uint32 id) const { return m_Sill.m_FeatureMap.findFeatureRef(id); }
+    const FeatureRef *feature(uint16 index) const { return m_Sill.m_FeatureMap.feature(index); }
+    uint16 getGlyphMetric(uint16 gid, uint8 metric) const;
+
+    const GlyphFaceCache* getGlyphFaceCache() const { return m_pGlyphFaceCache; }      //never NULL
+    void takeFileFace(FileFace* pFileFace/*takes ownership*/);
+    Cmap & cmap() const { return *m_cmap; };
+    NameTable * nameTable() const;
+    uint16 languageForLocale(const char * locale) const;
+
+    CLASS_NEW_DELETE
+private:
+    const void* m_appFaceHandle/*non-NULL*/;
+    gr_get_table_fn m_getTable;
+    uint16 m_ascent;
+    uint16 m_descent;
+    // unsigned short *m_glyphidx;     // index for each glyph id in the font
+    // unsigned short m_readglyphs;    // how many glyphs have we in m_glyphs?
+    // unsigned short m_capacity;      // how big is m_glyphs
+    mutable GlyphFaceCache* m_pGlyphFaceCache;      //owned - never NULL
+    mutable Cmap * m_cmap; // cmap cache if available
+    unsigned short m_upem;          // design units per em
+protected:
+    unsigned short m_numSilf;       // number of silf subtables in the silf table
+    Silf *m_silfs;                   // silf subtables.
+private:
+    SillMap m_Sill;
+    FileFace* m_pFileFace;      //owned
+    mutable NameTable* m_pNames;
+    
+private:        //defensive on m_pGlyphFaceCache, m_pFileFace and m_silfs
+    Face(const Face&);
+    Face& operator=(const Face&);
+};
+
+} // namespace graphite2
+
+struct gr_face : public graphite2::Face {};
new file mode 100644
--- /dev/null
+++ b/gfx/graphite2/src/inc/FeatureMap.h
@@ -0,0 +1,202 @@
+/*  GRAPHITE2 LICENSING
+
+    Copyright 2010, SIL International
+    All rights reserved.
+
+    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.
+*/
+#pragma once
+// #include <cstring>
+// #include "graphite2/Types.h"
+#include "graphite2/Font.h"
+#include "inc/Main.h"
+#include "inc/FeatureVal.h"
+
+namespace graphite2 {
+
+// Forward declarations for implmentation types
+class FeatureMap;
+class Face;
+
+
+class FeatureSetting
+{
+public:
+    FeatureSetting(uint16 labelId, int16 theValue) : m_label(labelId), m_value(theValue) {};
+    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;
+};
+
+class FeatureRef
+{
+public:
+    FeatureRef() :
+        m_nameValues(NULL), m_pFace(NULL)
+      {}
+    FeatureRef(byte bits, byte index, uint32 mask, uint16 flags,
+               uint32 name, uint16 uiName, uint16 numSet,
+               FeatureSetting *uiNames, const Face* pFace/*not NULL*/) throw()
+      : m_mask(mask), m_id(name), m_max((uint16)(mask >> bits)), m_bits(bits), m_index(index),
+      m_nameid(uiName), m_nameValues(uiNames), m_pFace(pFace), m_flags(flags),
+      m_numSet(numSet)
+      {}
+    FeatureRef(const FeatureRef & toCopy)
+        : m_mask(toCopy.m_mask), m_id(toCopy.m_id), m_max(toCopy.m_max),
+        m_bits(toCopy.m_bits), m_index(toCopy.m_index),
+        m_nameid(toCopy.m_nameid),
+        m_nameValues((toCopy.m_nameValues)? gralloc<FeatureSetting>(toCopy.m_numSet) : NULL),
+        m_pFace(toCopy.m_pFace), m_flags(toCopy.m_flags),
+        m_numSet(toCopy.m_numSet)
+    {
+        // most of the time these name values aren't used, so NULL might be acceptable
+        if (toCopy.m_nameValues)
+        {
+            memcpy(m_nameValues, toCopy.m_nameValues, sizeof(FeatureSetting) * m_numSet);
+        }
+    }