Bug 1483566 - Update Graphite2 to version 1.3.12. r=jfkthame
authorRyan VanderMeulen <ryanvm@gmail.com>
Tue, 21 Aug 2018 13:58:42 +0000
changeset 830658 34520af4d56552c7beb2547be1cbd58dfebf9a27
parent 830657 8d88272387d127eaf0abd274bdba7dd5787c07bc
child 830659 3d50f935615c9ba9179e8ab0dbb244ca65626967
push id118847
push userbmo:hskupin@gmail.com
push dateWed, 22 Aug 2018 09:09:03 +0000
reviewersjfkthame
bugs1483566
milestone63.0a1
Bug 1483566 - Update Graphite2 to version 1.3.12. r=jfkthame Differential Revision: https://phabricator.services.mozilla.com/D3426
gfx/graphite2/COPYING
gfx/graphite2/ChangeLog
gfx/graphite2/README.md
gfx/graphite2/README.mozilla
gfx/graphite2/include/graphite2/Font.h
gfx/graphite2/include/graphite2/Log.h
gfx/graphite2/include/graphite2/Segment.h
gfx/graphite2/include/graphite2/Types.h
gfx/graphite2/moz-gr-update.sh
gfx/graphite2/src/CMakeLists.txt
gfx/graphite2/src/CachedFace.cpp
gfx/graphite2/src/Code.cpp
gfx/graphite2/src/Collider.cpp
gfx/graphite2/src/Decompressor.cpp
gfx/graphite2/src/Face.cpp
gfx/graphite2/src/FeatureMap.cpp
gfx/graphite2/src/FileFace.cpp
gfx/graphite2/src/Font.cpp
gfx/graphite2/src/GlyphCache.cpp
gfx/graphite2/src/GlyphFace.cpp
gfx/graphite2/src/Intervals.cpp
gfx/graphite2/src/Justifier.cpp
gfx/graphite2/src/NameTable.cpp
gfx/graphite2/src/Pass.cpp
gfx/graphite2/src/Position.cpp
gfx/graphite2/src/SegCache.cpp
gfx/graphite2/src/SegCacheEntry.cpp
gfx/graphite2/src/SegCacheStore.cpp
gfx/graphite2/src/Segment.cpp
gfx/graphite2/src/Silf.cpp
gfx/graphite2/src/Slot.cpp
gfx/graphite2/src/TtfUtil.cpp
gfx/graphite2/src/UtfCodec.cpp
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/Code.h
gfx/graphite2/src/inc/Collider.h
gfx/graphite2/src/inc/Compression.h
gfx/graphite2/src/inc/Decompressor.h
gfx/graphite2/src/inc/Endian.h
gfx/graphite2/src/inc/Error.h
gfx/graphite2/src/inc/Face.h
gfx/graphite2/src/inc/FeatureMap.h
gfx/graphite2/src/inc/FeatureVal.h
gfx/graphite2/src/inc/FileFace.h
gfx/graphite2/src/inc/Font.h
gfx/graphite2/src/inc/GlyphCache.h
gfx/graphite2/src/inc/GlyphFace.h
gfx/graphite2/src/inc/Intervals.h
gfx/graphite2/src/inc/List.h
gfx/graphite2/src/inc/Main.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/bits.h
gfx/graphite2/src/inc/json.h
gfx/graphite2/src/inc/opcode_table.h
gfx/graphite2/src/inc/opcodes.h
gfx/graphite2/src/json.cpp
gfx/graphite2/src/moz.build
--- a/gfx/graphite2/COPYING
+++ b/gfx/graphite2/COPYING
@@ -10,17 +10,17 @@
 
     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 
+    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, you may use this library under the terms of the Mozilla
     Public License (http://mozilla.org/MPL) or under the GNU General Public
     License, as published by the Free Sofware Foundation; either version
     2 of the license or (at your option) any later version.
 */
old mode 100755
new mode 100644
--- a/gfx/graphite2/ChangeLog
+++ b/gfx/graphite2/ChangeLog
@@ -1,8 +1,26 @@
+1.3.12
+    . Graphite no longer does dumb rendering for fonts with no smarts
+    . Segment caching code removed. Anything attempting to use the segment cache gets given a regular face instead
+    . Add libfuzzer support
+    . Builds now require C++11
+    . Improvements to Windows 64 bit builds
+    . Support different versions of python including 32 bit and python 3
+    . Various minor bug fixes
+
+1.3.11
+    . Fixes due to security review
+    . Minor collision avoidance fixes
+    . Fix LZ4 decompressor against high compression
+
+1.3.10
+    . Address floating point build parameters to give consistent positioning results across platforms
+    . Various bug fixes
+
 1.3.9
     . Add Collision COLL_ISSPACE to allow for visible spaces in collision avoidance
     . Add segment and pass direction information to tracing output
     . Bug fix rule length testing in 32-bit
     . Increase slanted margin distances for collision avoidance
     . Change kerning algorithm to simple outline expansion. Seems to make no visible difference.
     . Add trace2svg to test tools
 
--- a/gfx/graphite2/README.md
+++ b/gfx/graphite2/README.md
@@ -1,16 +1,15 @@
 # Graphite engine
 
-## Project CI status 
-Linux -- Intel 64bit:[![Build Status](http://build.palaso.org/app/rest/builds/buildType:bt124/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=bt124&guest=1)
-Intel 32bit:[![Build Status](http://build.palaso.org/app/rest/builds/buildType:bt123/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=bt123&guest=1)
-ARM 32bit:[![Build Status](http://build.palaso.org/app/rest/builds/buildType:Graphite_Linux32bitArm/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=Graphite_Linux32bitArm&guest=1)
-
-Windows -- Intel 64bit:[![Build Status](http://build.palaso.org/app/rest/builds/buildType:Graphite_Windows64bitProduction/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=Graphite_Windows64bitProduction&guest=1)
+## Project CI status
+| OS      | Intel 64 bit | Intel 32 bit | Arm 32 bit |
+|---------|:------------:|:------------:|:----------:|
+| Linux   | [![Build Status](http://build.palaso.org/app/rest/builds/buildType:bt124/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=bt124&guest=1) | [![Build Status](http://build.palaso.org/app/rest/builds/buildType:bt123/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=bt123&guest=1) | [![Build Status](http://build.palaso.org/app/rest/builds/buildType:Graphite_Linux32bitArm/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=Graphite_Linux32bitArm&guest=1) |
+| Windows | [![Build Status](http://build.palaso.org/app/rest/builds/buildType:Graphite_Windows64bitProduction/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=Graphite_Windows64bitProduction&guest=1) | [![Build Status](http://build.palaso.org/app/rest/builds/buildType:bt91/statusIcon)](http://build.palaso.org/viewType.html?buildTypeId=bt91&guest=1)| |
 
 ## What is Graphite?
 
 Graphite is a system that can be used to create “smart fonts” capable of displaying writing systems with various complex behaviors. A smart font contains not only letter shapes but also additional instructions indicating how to combine and position the letters in complex ways.
 
 Graphite was primarily developed to provide the flexibility needed for minority languages which often need to be written according to slightly different rules than well-known languages that use the same script.
 
 Examples of complex script behaviors Graphite can handle include:
--- a/gfx/graphite2/README.mozilla
+++ b/gfx/graphite2/README.mozilla
@@ -1,7 +1,3 @@
-This directory contains the Graphite2 library release 1.3.11 from
-https://github.com/silnrsi/graphite/releases/download/1.3.11/graphite2-minimal-1.3.11.tgz
+This directory contains the Graphite2 library release 1.3.12 from
+https://github.com/silnrsi/graphite/releases/download/1.3.12/graphite2-minimal-1.3.12.tgz
 See ./gfx/graphite2/moz-gr-update.sh for update procedure.
-
-Note (2018-03-10):
-Cherry-picked 6e24eb7edbd0872b46441d7397e8b87cccfede73 from upstream to fix memory leak
-as noted in bug https://bugzilla.mozilla.org/show_bug.cgi?id=1443095.
\ No newline at end of file
--- a/gfx/graphite2/include/graphite2/Font.h
+++ b/gfx/graphite2/include/graphite2/Font.h
@@ -25,17 +25,17 @@
     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_MINOR   3
-#define GR2_VERSION_BUGFIX  11
+#define GR2_VERSION_BUGFIX  12
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
 typedef struct gr_face          gr_face;
 typedef struct gr_font          gr_font;
@@ -46,22 +46,22 @@ typedef struct gr_feature_val   gr_featu
 * Returns version information on this engine
 */
 GR2_API void gr_engine_version(int *nMajor, int *nMinor, int *nBugFix);
 
 /**
 * The Face Options allow the application to require that certain tables are
 * read during face construction. This may be of concern if the appFaceHandle
 * used in the gr_get_table_fn may change.
-* The values can be combined 
+* The values can be combined
 */
 enum gr_face_options {
     /** No preload, no cmap caching, fail if the graphite tables are invalid */
     gr_face_default = 0,
-    /** Dumb rendering will be enabled if the graphite tables are invalid */
+    /** Dumb rendering will be enabled if the graphite tables are invalid. @deprecated Since 1.311 */
     gr_face_dumbRendering = 1,
     /** preload glyphs at construction time */
     gr_face_preloadGlyphs = 2,
     /** Cache the lookup from code point to glyph ID at construction time */
     gr_face_cacheCmap = 4,
     /** Preload everything */
     gr_face_preloadAll = gr_face_preloadGlyphs | gr_face_cacheCmap
 };
@@ -108,70 +108,72 @@ typedef void (*gr_release_table_fn)(cons
 struct gr_face_ops
 {
         /** size in bytes of this structure */
     size_t              size;
         /** a pointer to a function to request a table from the client. */
 	gr_get_table_fn 	get_table;
         /** is a pointer to a function to notify the client the a table can be released.
           * This can be NULL to signify that the client does not wish to do any release handling. */
-	gr_release_table_fn	release_table;  
+	gr_release_table_fn	release_table;
 };
 typedef struct gr_face_ops	gr_face_ops;
 
 /** Create a gr_face object given application information and a table functions.
   *
   * @return gr_face or NULL if the font fails to load for some reason.
   * @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 face_ops      Pointer to face specific callback structure for table
   *                      management. Must stay alive for the duration of the
   *                      call only.
   * @param faceOptions   Bitfield describing various options. See enum gr_face_options for details.
   */
 GR2_API gr_face* gr_make_face_with_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *face_ops, unsigned int faceOptions);
 
-/** Create a gr_face object given application information and a getTable function. This function is deprecated as of v1.2.0 in
-  * favour of gr_make_face_with_ops.
+/** @deprecated Since v1.2.0 in favour of gr_make_face_with_ops.
+  * Create a gr_face object given application information and a getTable function.
   *
   * @return gr_face or NULL if the font fails to load for some reason.
   * @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      Callback function to get table data.
   * @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);
+GR2_DEPRECATED_API gr_face* gr_make_face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable, unsigned int faceOptions);
 
-//#ifndef GRAPHITE2_NSEGCACHE
-/** Create a gr_face object given application information, with subsegmental caching support
+/** @deprecated   Since 1.3.7 this function is now an alias for gr_make_face_with_ops().
+  *
+  * 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 face_ops      Pointer to face specific callback structure for table management. Must stay
   *                      alive for the duration of the call only.
-  * @param segCacheMaxSize   How large the segment cache is.
+  * @param segCacheMaxSize Unused.
   * @param faceOptions   Bitfield of values from enum gr_face_options
   */
-GR2_API gr_face* gr_make_face_with_seg_cache_and_ops(const void* appFaceHandle, const gr_face_ops *face_ops, unsigned int segCacheMaxSize, unsigned int faceOptions);
+GR2_DEPRECATED_API gr_face* gr_make_face_with_seg_cache_and_ops(const void* appFaceHandle, const gr_face_ops *face_ops, unsigned int segCacheMaxSize, unsigned int faceOptions);
 
-/** Create a gr_face object given application information, with subsegmental caching support.
+/** @deprecated   Since 1.3.7 this function is now an alias for gr_make_face().
+  *
+  * Create a gr_face object given application information, with subsegmental caching support.
   * This function is deprecated as of v1.2.0 in favour of gr_make_face_with_seg_cache_and_ops.
   *
   * @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
+GR2_DEPRECATED_API gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle, gr_get_table_fn getTable, unsigned int segCacheMaxSize, unsigned int faceOptions);
 
 /** 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);
 
@@ -238,26 +240,26 @@ GR2_API int gr_face_is_char_supported(co
 /** 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 GRAPHITE2_NSEGCACHE
-/** Create gr_face from a font file, with subsegment caching support.
+/** @deprecated   Since 1.3.7. This function is now an alias for gr_make_file_face().
+  *
+  * 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
+GR2_DEPRECATED_API gr_face* gr_make_file_face_with_seg_cache(const char *filename, unsigned int segCacheMaxSize, unsigned int faceOptions);
 #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.
   */
@@ -342,17 +344,17 @@ GR2_API gr_uint32 gr_fref_id(const gr_fe
 GR2_API gr_uint16 gr_fref_n_values(const gr_feature_ref* pfeatureref);
 
 /** Returns the value associated with a particular value in a feature
   *
   * @return value
   * @param pfeatureref gr_feature_ref of the feature of interest
   * @param settingno   Index up to the return value of gr_fref_n_values() of the value
   */
-GR2_API gr_int16 gr_fref_value(const gr_feature_ref* pfeatureref, gr_uint16 settingno);   
+GR2_API gr_int16 gr_fref_value(const gr_feature_ref* pfeatureref, gr_uint16 settingno);
 
 /** Returns a string of the UI name of a feature
   *
   * @return string of the UI name, in the encoding form requested. Call gr_label_destroy() after use.
   * @param pfeatureref   gr_feature_ref of the feature
   * @param langId    This is a pointer since the face may not support a string in the requested
   *                  language. The actual language of the string is returned in langId
   * @param utf   Encoding form for the string
@@ -380,9 +382,8 @@ GR2_API void gr_label_destroy(void * lab
 GR2_API gr_feature_val* gr_featureval_clone(const gr_feature_val* pfeatures);
 
 /** Destroys a gr_feature_val **/
 GR2_API void gr_featureval_destroy(gr_feature_val *pfeatures);
 
 #ifdef __cplusplus
 }
 #endif
-
--- a/gfx/graphite2/include/graphite2/Log.h
+++ b/gfx/graphite2/include/graphite2/Log.h
@@ -37,17 +37,17 @@ extern "C"
 
 /** deprecated mechanism that doesn't do anything now. */
 typedef enum {
     GRLOG_NONE = 0x0,
     GRLOG_FACE = 0x01,
     GRLOG_SEGMENT = 0x02,
     GRLOG_PASS = 0x04,
     GRLOG_CACHE = 0x08,
-    
+
     GRLOG_OPCODE = 0x80,
     GRLOG_ALL = 0xFF
 } GrLogMask;
 
 /** Start logging all segment creation and updates on the provided face.  This
   * is logged to a JSON file, see "Segment JSON Schema.txt" for a precise
   * definition of the file
   *
--- a/gfx/graphite2/include/graphite2/Segment.h
+++ b/gfx/graphite2/include/graphite2/Segment.h
@@ -57,73 +57,73 @@ enum gr_justFlags {
     gr_justStartInline = 1,
     /// Indicates that the end of the slot list is not at the end of a line
     gr_justEndInline = 2
 };
 
 /** Used for looking up slot attributes. Most are already available in other functions **/
 enum gr_attrCode {
     /// adjusted glyph advance in x direction in design units
-    gr_slatAdvX = 0,        
+    gr_slatAdvX = 0,
     /// adjusted glyph advance in y direction (usually 0) in design units
-    gr_slatAdvY,            
+    gr_slatAdvY,
     /// returns 0. Deprecated.
-    gr_slatAttTo,           
+    gr_slatAttTo,
     /// This slot attaches to its parent at the given design units in the x direction
-    gr_slatAttX,            
+    gr_slatAttX,
     /// This slot attaches to its parent at the given design units in the y direction
-    gr_slatAttY,            
+    gr_slatAttY,
     /// This slot attaches to its parent at the given glyph point (not implemented)
-    gr_slatAttGpt,          
+    gr_slatAttGpt,
     /// x-direction adjustment from the given glyph point (not implemented)
-    gr_slatAttXOff,         
+    gr_slatAttXOff,
     /// y-direction adjustment from the given glyph point (not implemented)
-    gr_slatAttYOff,         
+    gr_slatAttYOff,
     /// Where on this glyph should align with the attachment point on the parent glyph in the x-direction.
-    gr_slatAttWithX,        
+    gr_slatAttWithX,
     /// Where on this glyph should align with the attachment point on the parent glyph in the y-direction
-    gr_slatAttWithY,        
+    gr_slatAttWithY,
     /// Which glyph point on this glyph should align with the attachment point on the parent glyph (not implemented).
-    gr_slatWithGpt,         
+    gr_slatWithGpt,
     /// Adjustment to gr_slatWithGpt in x-direction (not implemented)
-    gr_slatAttWithXOff,     
+    gr_slatAttWithXOff,
     /// Adjustment to gr_slatWithGpt in y-direction (not implemented)
-    gr_slatAttWithYOff,     
+    gr_slatAttWithYOff,
     /// Attach at given nesting level (not implemented)
-    gr_slatAttLevel,        
+    gr_slatAttLevel,
     /// Line break breakweight for this glyph
-    gr_slatBreak,           
+    gr_slatBreak,
     /// Ligature component reference (not implemented)
-    gr_slatCompRef,         
+    gr_slatCompRef,
     /// bidi directionality of this glyph (not implemented)
-    gr_slatDir,             
+    gr_slatDir,
     /// Whether insertion is allowed before this glyph
     gr_slatInsert,
     /// Final positioned position of this glyph relative to its parent in x-direction in pixels
-    gr_slatPosX,            
+    gr_slatPosX,
     /// Final positioned position of this glyph relative to its parent in y-direction in pixels
-    gr_slatPosY,            
+    gr_slatPosY,
     /// Amount to shift glyph by in x-direction design units
-    gr_slatShiftX,          
+    gr_slatShiftX,
     /// Amount to shift glyph by in y-direction design units
-    gr_slatShiftY,          
+    gr_slatShiftY,
     /// attribute user1
-    gr_slatUserDefnV1,      
+    gr_slatUserDefnV1,
     /// not implemented
-    gr_slatMeasureSol,      
+    gr_slatMeasureSol,
     /// not implemented
-    gr_slatMeasureEol,      
+    gr_slatMeasureEol,
     /// Amount this slot can stretch (not implemented)
-    gr_slatJStretch,        
+    gr_slatJStretch,
     /// Amount this slot can shrink (not implemented)
-    gr_slatJShrink,         
+    gr_slatJShrink,
     /// Granularity by which this slot can stretch or shrink (not implemented)
-    gr_slatJStep,           
+    gr_slatJStep,
     /// Justification weight for this glyph (not implemented)
-    gr_slatJWeight,         
+    gr_slatJWeight,
     /// Amount this slot mush shrink or stretch in design units
     gr_slatJWidth = 29,
     /// SubSegment split point
     gr_slatSegSplit = gr_slatJStretch + 29,
     /// User defined attribute, see subattr for user attr number
     gr_slatUserDefn,
     /// Bidi level
     gr_slatBidiLevel = 56,
@@ -154,21 +154,21 @@ enum gr_attrCode {
     gr_slatSeqProxClass,
     gr_slatSeqOrder,
     gr_slatSeqAboveXoff,
     gr_slatSeqAboveWt,
     gr_slatSeqBelowXlim,
     gr_slatSeqBelowWt,
     gr_slatSeqValignHt,
     gr_slatSeqValignWt,
-                            
+
     /// not implemented
-    gr_slatMax,             
+    gr_slatMax,
     /// not implemented
-    gr_slatNoEffect = gr_slatMax + 1    
+    gr_slatNoEffect = gr_slatMax + 1
 };
 
 enum gr_bidirtl {
     /// Underlying paragraph direction is RTL
     gr_rtl = 1,
     /// Set this to not run the bidi pass internally, even if the font asks for it.
     /// This presumes that the segment is in a single direction. Most of the time
     /// this bit should be set unless you know you are passing full paragraphs of text.
@@ -177,23 +177,23 @@ enum gr_bidirtl {
     gr_nomirror = 4
 };
 
 typedef struct gr_char_info     gr_char_info;
 typedef struct gr_segment       gr_segment;
 typedef struct gr_slot          gr_slot;
 
 /** Returns Unicode character for a charinfo.
-  * 
+  *
   * @param p Pointer to charinfo to return information on.
   */
 GR2_API unsigned int gr_cinfo_unicode_char(const gr_char_info* p/*not NULL*/);
 
 /** Returns breakweight for a charinfo.
-  * 
+  *
   * @return Breakweight is a number between -50 and 50 indicating the cost of a
   * break before or after this character. If the value < 0, the absolute value
   * is this character's contribution to the overall breakweight before it. If the value
   * > 0, then the value is this character's contribution to the overall breakweight after it.
   * The overall breakweight between two characters is the maximum of the breakweight
   * contributions from the characters either side of it. If a character makes no
   * contribution to the breakweight on one side of it, the contribution is considered
   * to be 0.
--- a/gfx/graphite2/include/graphite2/Types.h
+++ b/gfx/graphite2/include/graphite2/Types.h
@@ -35,38 +35,45 @@ typedef unsigned short  gr_uint16;
 typedef short           gr_int16;
 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__
-  #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
-    #if defined __GNUC__
-      #define GR2_API    __attribute__((dllimport))
-    #else
-      #define GR2_API    __declspec(dllimport)
-    #endif
-  #endif
-  #define GR2_LOCAL
-#elif __GNUC__ >= 4
-  #if defined GRAPHITE2_STATIC
-    #define GR2_API      __attribute__ ((visibility("hidden")))
-  #else
-    #define GR2_API      __attribute__ ((visibility("default")))
-  #endif
-  #define GR2_LOCAL      __attribute__ ((visibility("hidden")))
-#else
-  #define GR2_API
-  #define GR2_LOCAL
+
+// Define API function declspec/attributes and how each supported compiler or OS
+// allows us to specify them.
+#if defined __GNUC__
+  #define _gr2_and ,
+  #define _gr2_tag_fn(a)        __attribute__((a))
+  #define _gr2_deprecated_flag  deprecated
+  #define _gr2_export_flag      visibility("default")
+  #define _gr2_import_flag      visibility("default")
+  #define _gr2_static_flag      visibility("hidden")
 #endif
 
+#if defined _WIN32 || defined __CYGWIN__
+  #if defined __GNUC__  // These three will be redefined for Windows
+    #undef _gr2_export_flag
+    #undef _gr2_import_flag
+    #undef _gr2_static_flag
+  #else  // How MSVC sepcifies function level attributes adn deprecation
+    #define _gr2_and
+    #define _gr2_tag_fn(a)       __declspec(a)
+    #define _gr2_deprecated_flag deprecated
+  #endif
+  #define _gr2_export_flag     dllexport
+  #define _gr2_import_flag     dllimport
+  #define _gr2_static_flag
+#endif
+
+#if defined GRAPHITE2_STATIC
+  #define GR2_API             _gr2_tag_fn(_gr2_static_flag)
+  #define GR2_DEPRECATED_API  _gr2_tag_fn(_gr2_deprecated_flag _gr2_and _gr2_static_flag)
+#elif defined GRAPHITE2_EXPORTING
+  #define GR2_API             _gr2_tag_fn(_gr2_export_flag)
+  #define GR2_DEPRECATED_API  _gr2_tag_fn(_gr2_deprecated_flag _gr2_and _gr2_export_flag)
+#else
+  #define GR2_API             _gr2_tag_fn(_gr2_import_flag)
+  #define GR2_DEPRECATED_API  _gr2_tag_fn(_gr2_deprecated_flag _gr2_and _gr2_import_flag)
+#endif
old mode 100644
new mode 100755
--- a/gfx/graphite2/moz-gr-update.sh
+++ b/gfx/graphite2/moz-gr-update.sh
@@ -17,17 +17,17 @@ if [ "x$RELEASE" == "x" ]
 then
     echo "Must provide the version number to be used."
     exit 1
 fi
 
 TARBALL="https://github.com/silnrsi/graphite/releases/download/$RELEASE/graphite2-minimal-$RELEASE.tgz"
 
 foo=`basename $0`
-TMPFILE=`mktemp -t ${foo}` || exit 1
+TMPFILE=`mktemp -t ${foo}.XXX` || exit 1
 
 curl -L "$TARBALL" -o "$TMPFILE"
 tar -x -z -C gfx/graphite2/ --strip-components 1 -f "$TMPFILE" || exit 1
 rm "$TMPFILE"
 
 echo "This directory contains the Graphite2 library release $RELEASE from" > gfx/graphite2/README.mozilla
 echo "$TARBALL" >> gfx/graphite2/README.mozilla
 echo ""
--- a/gfx/graphite2/src/CMakeLists.txt
+++ b/gfx/graphite2/src/CMakeLists.txt
@@ -10,41 +10,35 @@
 #
 #    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 
+#    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.
 
 CMAKE_MINIMUM_REQUIRED(VERSION 2.8.0 FATAL_ERROR)
 project(graphite2_core)
 cmake_policy(SET CMP0012 NEW)
 INCLUDE(CheckCXXSourceCompiles)
 
 set(GRAPHITE_API_CURRENT 3)
-set(GRAPHITE_API_REVISION 0)
+set(GRAPHITE_API_REVISION 2)
 set(GRAPHITE_API_AGE 1)
 set(GRAPHITE_VERSION ${GRAPHITE_API_CURRENT}.${GRAPHITE_API_REVISION}.${GRAPHITE_API_AGE})
 set(GRAPHITE_SO_VERSION ${GRAPHITE_API_CURRENT})
 
 include(TestBigEndian)
 
 include_directories(${PROJECT_SOURCE_DIR})
 
-set(SEGCACHE SegCache.cpp SegCacheEntry.cpp SegCacheStore.cpp)
-if (GRAPHITE2_NSEGCACHE)
-    add_definitions(-DGRAPHITE2_NSEGCACHE)
-    set(SEGCACHE)
-endif (GRAPHITE2_NSEGCACHE)
-
 set(FILEFACE FileFace.cpp)
 if (GRAPHITE2_NFILEFACE)
     add_definitions(-DGRAPHITE2_NFILEFACE)
     set(FILEFACE)
 endif (GRAPHITE2_NFILEFACE)
 
 set(TRACING json.cpp)
 if (GRAPHITE2_NTRACING)
@@ -55,35 +49,34 @@ endif (GRAPHITE2_NTRACING)
 if (GRAPHITE2_TELEMETRY)
     add_definitions(-DGRAPHITE2_TELEMETRY)
 endif (GRAPHITE2_TELEMETRY)
 
 if (NOT BUILD_SHARED_LIBS)
     add_definitions(-DGRAPHITE2_STATIC)
 endif (NOT BUILD_SHARED_LIBS)
 
-set(GRAPHITE_HEADERS 
+set(GRAPHITE_HEADERS
     ../include/graphite2/Font.h
     ../include/graphite2/Segment.h
     ../include/graphite2/Types.h
     ../include/graphite2/Log.h
     )
 
-file(GLOB PRIVATE_HEADERS inc/*.h) 
+file(GLOB PRIVATE_HEADERS inc/*.h)
 
 add_library(graphite2
     ${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
-    CachedFace.cpp
     CmapCache.cpp
     Code.cpp
     Collider.cpp
     Decompressor.cpp
     Face.cpp
     FeatureMap.cpp
     Font.cpp
     GlyphFace.cpp
@@ -95,17 +88,16 @@ add_library(graphite2
     Position.cpp
     Segment.cpp
     Silf.cpp
     Slot.cpp
     Sparse.cpp
     TtfUtil.cpp
     UtfCodec.cpp
     ${FILEFACE}
-    ${SEGCACHE}
     ${TRACING})
 
 set_target_properties(graphite2 PROPERTIES  PUBLIC_HEADER "${GRAPHITE_HEADERS}"
                                             SOVERSION ${GRAPHITE_SO_VERSION}
                                             VERSION ${GRAPHITE_VERSION}
                                             LT_VERSION_CURRENT ${GRAPHITE_API_CURRENT}
                                             LT_VERSION_REVISION ${GRAPHITE_API_REVISION}
                                             LT_VERSION_AGE ${GRAPHITE_API_AGE})
@@ -118,31 +110,31 @@ if  (${CMAKE_SYSTEM_NAME} STREQUAL "Linu
     if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "x86|i.86")
         add_definitions(-mfpmath=sse -msse2)
     endif (${CMAKE_SYSTEM_PROCESSOR} MATCHES "x86|i.86")
     if (CMAKE_COMPILER_IS_GNUCXX)
         add_definitions(-Wdouble-promotion)
     endif (CMAKE_COMPILER_IS_GNUCXX)
     message(STATUS "Compiler ID is: ${CMAKE_CXX_COMPILER_ID}")
     if (${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang")
-        add_definitions(-Wimplicit-fallthrough)
+        add_definitions(-Wimplicit-fallthrough -Wshorten-64-to-32)
     endif (${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang")
     if (${CMAKE_CXX_COMPILER} MATCHES  ".*mingw.*")
         target_link_libraries(graphite2 kernel32 msvcr90 mingw32 gcc user32)
     else (${CMAKE_CXX_COMPILER} MATCHES  ".*mingw.*")
-        if (GRAPHITE2_ASAN)
+        if (GRAPHITE2_SANITIZERS)
             target_link_libraries(graphite2 c gcc_s)
-        else (GRAPHITE2_ASAN)
+        else ()
             target_link_libraries(graphite2 c gcc)
-        endif (GRAPHITE2_ASAN)
-        include(Graphite)
-        if (BUILD_SHARED_LIBS)
-            nolib_test(stdc++ $<TARGET_SONAME_FILE:graphite2>)
-        endif (BUILD_SHARED_LIBS)
+        endif ()
     endif (${CMAKE_CXX_COMPILER} MATCHES  ".*mingw.*")
+    include(Graphite)
+    if (BUILD_SHARED_LIBS)
+        nolib_test(stdc++ $<TARGET_SONAME_FILE:graphite2>)
+    endif ()
     set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "")
     CREATE_LIBTOOL_FILE(graphite2 "/lib${LIB_SUFFIX}")
 endif (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
 
 if  (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin")
     set_target_properties(graphite2 PROPERTIES
         COMPILE_FLAGS   "-Wall -Wextra -Wno-unknown-pragmas -Wimplicit-fallthrough -Wendif-labels -Wshadow -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor -fno-rtti -fno-exceptions -fvisibility=hidden -fvisibility-inlines-hidden -mfpmath=sse -msse2"
         LINK_FLAGS      "-nodefaultlibs"
@@ -150,15 +142,15 @@ if  (${CMAKE_SYSTEM_NAME} STREQUAL "Darw
     target_link_libraries(graphite2 c)
     include(Graphite)
     nolib_test(stdc++ $<TARGET_SONAME_FILE:graphite2>)
     set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "")
     CREATE_LIBTOOL_FILE(graphite2 "/lib${LIB_SUFFIX}")
 endif (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin")
 
 if  (${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
-    set_target_properties(graphite2 PROPERTIES 
+    set_target_properties(graphite2 PROPERTIES
         COMPILE_DEFINITIONS "_SCL_SECURE_NO_WARNINGS;_CRT_SECURE_NO_WARNINGS;UNICODE;GRAPHITE2_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_)
deleted file mode 100644
--- a/gfx/graphite2/src/CachedFace.cpp
+++ /dev/null
@@ -1,127 +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.
-*/
-
-#ifndef GRAPHITE2_NSEGCACHE
-
-#include <graphite2/Segment.h>
-#include "inc/CachedFace.h"
-#include "inc/SegCacheStore.h"
-
-
-using namespace graphite2;
-
-CachedFace::CachedFace(const void* appFaceHandle/*non-NULL*/, const gr_face_ops & ops)
-: Face(appFaceHandle, ops), m_cacheStore(0)
-{
-}
-
-CachedFace::~CachedFace()
-{
-    delete m_cacheStore;
-}
-
-bool CachedFace::setupCache(unsigned int cacheSize)
-{
-    m_cacheStore = new SegCacheStore(*this, m_numSilf, cacheSize);
-    return bool(m_cacheStore);
-}
-
-
-bool CachedFace::runGraphite(Segment *seg, const Silf *pSilf) const
-{
-    assert(pSilf);
-    pSilf->runGraphite(seg, 0, pSilf->substitutionPass());
-
-    unsigned int silfIndex = 0;
-    for (; silfIndex < m_numSilf && &(m_silfs[silfIndex]) != pSilf; ++silfIndex);
-    if (silfIndex == m_numSilf)  return false;
-    SegCache * const segCache = m_cacheStore->getOrCreate(silfIndex, seg->getFeatures(0));
-    if (!segCache)
-        return false;
-
-    assert(m_cacheStore);
-    // find where the segment can be broken
-    Slot * subSegStartSlot = seg->first();
-    Slot * subSegEndSlot = subSegStartSlot;
-    uint16 cmapGlyphs[eMaxSpliceSize];
-    int subSegStart = 0;
-    for (unsigned int i = 0; i < seg->charInfoCount() && subSegEndSlot; ++i)
-    {
-        const unsigned int length = i - subSegStart + 1;
-        if (length < eMaxSpliceSize && subSegEndSlot->gid() < m_cacheStore->maxCmapGid())
-            cmapGlyphs[length-1] = subSegEndSlot->gid();
-        else return false;
-        const bool spaceOnly = m_cacheStore->isSpaceGlyph(subSegEndSlot->gid());
-        // at this stage the character to slot mapping is still 1 to 1
-        const int   breakWeight = seg->charinfo(i)->breakWeight(),
-                    nextBreakWeight = (i + 1 < seg->charInfoCount())?
-                            seg->charinfo(i+1)->breakWeight() : 0;
-        const uint8 f = seg->charinfo(i)->flags();
-        if (((spaceOnly
-                || (breakWeight > 0 && breakWeight <= gr_breakWord)
-                || i + 1 == seg->charInfoCount()
-                || ((nextBreakWeight < 0 && nextBreakWeight >= gr_breakBeforeWord)
-                    || (subSegEndSlot->next() && m_cacheStore->isSpaceGlyph(subSegEndSlot->next()->gid()))))
-                && f != 1)
-            || f == 2)
-        {
-            // record the next slot before any splicing
-            Slot * nextSlot = subSegEndSlot->next();
-            // spaces should be left untouched by graphite rules in any sane font
-            if (!spaceOnly)
-            {
-                // found a break position, check for a cache of the sub sequence
-                const SegCacheEntry * entry = segCache->find(cmapGlyphs, length);
-                // TODO disable cache for words at start/end of line with contextuals
-                if (!entry)
-                {
-                    SegmentScopeState scopeState = seg->setScope(subSegStartSlot, subSegEndSlot, length);
-                    pSilf->runGraphite(seg, pSilf->substitutionPass(), pSilf->numPasses());
-                    if (length < eMaxSpliceSize)
-                    {
-                        seg->associateChars(subSegStart, length);
-                        segCache->cache(m_cacheStore, cmapGlyphs, length, seg, subSegStart);
-                    }
-                    seg->removeScope(scopeState);
-                }
-                else
-                    seg->splice(subSegStart, length, subSegStartSlot, subSegEndSlot,
-                        entry->first(), entry->glyphLength());
-            }
-            subSegStartSlot = subSegEndSlot = nextSlot;
-            subSegStart = i + 1;
-        }
-        else
-        {
-            subSegEndSlot = subSegEndSlot->next();
-        }
-    }
-    return true;
-}
-
-#endif
-
--- a/gfx/graphite2/src/Code.cpp
+++ b/gfx/graphite2/src/Code.cpp
@@ -10,26 +10,26 @@
 
     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 
+    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 
+// 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>
@@ -62,52 +62,52 @@ inline bool is_return(const instr i) {
                 ret_zero = *opmap[RET_ZERO].impl,
                 ret_true = *opmap[RET_TRUE].impl;
     return i == pop_ret || i == ret_zero || i == ret_true;
 }
 
 struct context
 {
     context(uint8 ref=0) : codeRef(ref) {flags.changed=false; flags.referenced=false;}
-    struct { 
+    struct {
         uint8   changed:1,
                 referenced:1;
     } flags;
     uint8       codeRef;
 };
 
 } // end namespace
 
 
 class Machine::Code::decoder
 {
 public:
     struct limits;
     static const int NUMCONTEXTS = 256;
-    
+
     decoder(limits & lims, Code &code, enum passtype pt) throw();
-    
+
     bool        load(const byte * bc_begin, const byte * bc_end);
     void        apply_analysis(instr * const code, instr * code_end);
     byte        max_ref() { return _max_ref; }
     int         out_index() const { return _out_index; }
-    
+
 private:
     void        set_ref(int index) throw();
     void        set_noref(int index) throw();
     void        set_changed(int index) throw();
     opcode      fetch_opcode(const byte * bc);
     void        analyse_opcode(const opcode, const int8 * const dp) throw();
     bool        emit_opcode(opcode opc, const byte * & bc);
     bool        validate_opcode(const byte opc, const byte * const bc);
     bool        valid_upto(const uint16 limit, const uint16 x) const throw();
     bool        test_context() const throw();
     bool        test_ref(int8 index) const throw();
     void        failure(const status_t s) const throw() { _code.failure(s); }
-    
+
     Code              & _code;
     int                 _out_index;
     uint16              _out_length;
     instr             * _instr;
     byte              * _data;
     limits            & _max;
     enum passtype       _passtype;
     int                 _stack_depth;
@@ -123,28 +123,28 @@ struct Machine::Code::decoder::limits
   const byte       * bytecode;
   const uint8        pre_context;
   const uint16       rule_length,
                      classes,
                      glyf_attrs,
                      features;
   const byte         attrid[gr_slatMax];
 };
-   
+
 inline Machine::Code::decoder::decoder(limits & lims, Code &code, enum passtype pt) throw()
 : _code(code),
-  _out_index(code._constraint ? 0 : lims.pre_context), 
-  _out_length(code._constraint ? 1 : lims.rule_length), 
+  _out_index(code._constraint ? 0 : lims.pre_context),
+  _out_length(code._constraint ? 1 : lims.rule_length),
   _instr(code._code), _data(code._data), _max(lims), _passtype(pt),
   _stack_depth(0),
   _in_ctxt_item(false),
   _slotref(0),
   _max_ref(0)
 { }
-    
+
 
 
 Machine::Code::Code(bool is_constraint, const byte * bytecode_begin, const byte * const bytecode_end,
            uint8 pre_context, uint16 rule_length, const Silf & silf, const Face & face,
            enum passtype pt, byte * * const _out)
  :  _code(0), _data(0), _data_size(0), _instr_count(0), _max_ref(0), _status(loaded),
     _constraint(is_constraint), _modify(false), _delete(false), _own(_out==0)
 {
@@ -154,68 +154,68 @@ Machine::Code::Code(bool is_constraint, 
     assert(bytecode_begin != 0);
     if (bytecode_begin == bytecode_end)
     {
       // ::new (this) Code();
       return;
     }
     assert(bytecode_end > bytecode_begin);
     const opcode_t *    op_to_fn = Machine::getOpcodeTable();
-    
+
     // Allocate code and data target buffers, these sizes are a worst case
     // estimate.  Once we know their real sizes the we'll shrink them.
     if (_out)   _code = reinterpret_cast<instr *>(*_out);
     else        _code = static_cast<instr *>(malloc(estimateCodeDataOut(bytecode_end-bytecode_begin, 1, is_constraint ? 0 : rule_length)));
     _data = reinterpret_cast<byte *>(_code + (bytecode_end - bytecode_begin));
-    
+
     if (!_code || !_data) {
         failure(alloc_failed);
         return;
     }
-    
+
     decoder::limits lims = {
         bytecode_end,
         pre_context,
         rule_length,
         silf.numClasses(),
         face.glyphs().numAttrs(),
-        face.numFeatures(), 
-        {1,1,1,1,1,1,1,1, 
+        face.numFeatures(),
+        {1,1,1,1,1,1,1,1,
          1,1,1,1,1,1,1,255,
-         1,1,1,1,1,1,1,1, 
-         1,1,1,1,1,1,0,0, 
-         0,0,0,0,0,0,0,0, 
-         0,0,0,0,0,0,0,0, 
+         1,1,1,1,1,1,1,1,
+         1,1,1,1,1,1,0,0,
+         0,0,0,0,0,0,0,0,
+         0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0, silf.numUser()}
     };
-    
+
     decoder dec(lims, *this, pt);
     if(!dec.load(bytecode_begin, bytecode_end))
        return;
-    
+
     // Is this an empty program?
     if (_instr_count == 0)
     {
       release_buffers();
       ::new (this) Code();
       return;
     }
-    
+
     // When we reach the end check we've terminated it correctly
     if (!is_return(_code[_instr_count-1])) {
         failure(missing_return);
         return;
     }
 
     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 
+    // 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));
     memmove(_code + (_instr_count+1), _data, _data_size*sizeof(byte));
     size_t const total_sz = ((_instr_count+1) + (_data_size + sizeof(instr)-1)/sizeof(instr))*sizeof(instr);
     if (_out)
         *_out += total_sz;
     else
@@ -250,37 +250,37 @@ Machine::Code::~Code() throw ()
 bool Machine::Code::decoder::load(const byte * bc, const byte * bc_end)
 {
     _max.bytecode = bc_end;
     while (bc < bc_end)
     {
         const opcode opc = fetch_opcode(bc++);
         if (opc == vm::MAX_OPCODE)
             return false;
-        
+
         analyse_opcode(opc, reinterpret_cast<const int8 *>(bc));
-        
+
         if (!emit_opcode(opc, bc))
             return false;
     }
-    
+
     return bool(_code);
 }
 
 // Validation check and fixups.
 //
 
 opcode Machine::Code::decoder::fetch_opcode(const byte * bc)
 {
     const byte opc = *bc++;
 
     // Do some basic sanity checks based on what we know about the opcode
     if (!validate_opcode(opc, bc))  return MAX_OPCODE;
 
-    // And check it's arguments as far as possible
+    // And check its arguments as far as possible
     switch (opcode(opc))
     {
         case NOP :
             break;
         case PUSH_BYTE :
         case PUSH_BYTEU :
         case PUSH_SHORT :
         case PUSH_SHORTU :
@@ -504,25 +504,25 @@ void Machine::Code::decoder::analyse_opc
     case IATTR_SET :
     case IATTR_ADD :
     case IATTR_SUB :
       set_noref(0);
       break;
     case NEXT :
     case COPY_NEXT :
       ++_slotref;
-      _contexts[_slotref] = context(_code._instr_count+1);
+      _contexts[_slotref] = context(uint8(_code._instr_count+1));
       // if (_analysis.slotref > _analysis.max_ref) _analysis.max_ref = _analysis.slotref;
       break;
     case INSERT :
       if (_slotref >= 0) --_slotref;
       _code._modify = true;
       break;
     case PUT_SUBS_8BIT_OBS :    // slotref on 1st parameter
-    case PUT_SUBS : 
+    case PUT_SUBS :
       _code._modify = true;
       set_changed(0);
       GR_FALLTHROUGH;
       // no break
     case PUT_COPY :
       if (arg[0] != 0) { set_changed(0); _code._modify = true; }
       set_ref(arg[0]);
       break;
@@ -554,28 +554,28 @@ bool Machine::Code::decoder::emit_opcode
     {
         failure(unimplemented_opcode_used);
         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]; 
+    *_instr++ = op.impl[_code._constraint];
     ++_code._instr_count;
 
     // Grab the parameters
     if (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 
+
+    // recursively decode a context item so we can split the skip into
     // instruction and data portions.
     if (opc == CNTXT_ITEM)
     {
         assert(_out_index == 0);
         _in_ctxt_item = true;
         _out_index = _max.pre_context + int8(_data[-2]);
         _slotref = int8(_data[-2]);
         _out_length = _max.rule_length;
@@ -584,56 +584,56 @@ bool Machine::Code::decoder::emit_opcode
         byte & instr_skip = _data[-1];
         byte & data_skip  = *_data++;
         ++_code._data_size;
         const byte *curr_end = _max.bytecode;
 
         if (load(bc, bc + instr_skip))
         {
             bc += instr_skip;
-            data_skip  = instr_skip - (_code._instr_count - ctxt_start);
-            instr_skip = _code._instr_count - ctxt_start;
+            data_skip  = instr_skip - byte(_code._instr_count - ctxt_start);
+            instr_skip =  byte(_code._instr_count - ctxt_start);
             _max.bytecode = curr_end;
 
             _out_length = 1;
             _out_index = 0;
             _slotref = 0;
             _in_ctxt_item = false;
         }
         else
         {
             _out_index = 0;
             _slotref = 0;
             return false;
         }
     }
-    
+
     return bool(_code);
 }
 
 
 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 = _contexts, * const ce = c + _slotref; c < ce; ++c)
     {
         if (!c->flags.referenced || !c->flags.changed) continue;
-        
-        instr * const tip = code + c->codeRef + tempcount;        
+
+        instr * const tip = code + c->codeRef + tempcount;
         memmove(tip+1, tip, (code_end - tip) * sizeof(instr));
         *tip = temp_copy;
         ++code_end;
         ++tempcount;
         _code._delete = true;
     }
-    
+
     _code._instr_count = code_end - code;
 }
 
 
 inline
 bool Machine::Code::decoder::validate_opcode(const byte opc, const byte * const bc)
 {
     if (opc >= MAX_OPCODE)
@@ -690,17 +690,17 @@ bool Machine::Code::decoder::test_contex
     if (_out_index >= _out_length || _out_index < 0 || _slotref >= NUMCONTEXTS - 1)
     {
         failure(out_of_range_data);
         return false;
     }
     return true;
 }
 
-inline 
+inline
 void Machine::Code::failure(const status_t s) throw() {
     release_buffers();
     _status = s;
 }
 
 
 inline
 void Machine::Code::decoder::set_ref(int index) throw() {
@@ -745,9 +745,8 @@ int32 Machine::Code::run(Machine & m, sl
     {
         m._status = Machine::slot_offset_out_bounds;
         return 1;
 //        return m.run(_code, _data, map);
     }
 
     return  m.run(_code, _data, map);
 }
-
--- a/gfx/graphite2/src/Collider.cpp
+++ b/gfx/graphite2/src/Collider.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <algorithm>
@@ -32,17 +32,17 @@ of the License or (at your option) any l
 #include "inc/Collider.h"
 #include "inc/Segment.h"
 #include "inc/Slot.h"
 #include "inc/GlyphCache.h"
 #include "inc/Sparse.h"
 
 #define ISQRT2 0.707106781f
 
-// Possible rounding error for subbox boundaries: 0.016 = 1/64 = 1/256 * 4 
+// Possible rounding error for subbox boundaries: 0.016 = 1/64 = 1/256 * 4
 // (values in font range from 0..256)
 // #define SUBBOX_RND_ERR 0.016
 
 using namespace graphite2;
 
 ////    SHIFT-COLLIDER    ////
 
 // Initialize the Collider to hold the basic movement limits for the
@@ -113,17 +113,17 @@ bool ShiftCollider::initSlot(Segment *se
         //_limit.tr.x = -1 * limit.bl.x;
     }
     _currOffset = currOffset;
     _currShift = currShift;
     _origin = aSlot->origin() - currOffset;     // the original anchor position of the glyph
 
 	_margin = margin;
 	_marginWt = marginWeight;
-    
+
     SlotCollision *c = seg->collisionInfo(aSlot);
     _seqClass = c->seqClass();
 	_seqProxClass = c->seqProxClass();
     _seqOrder = c->seqOrder();
     return true;
 }
 
 template <class O>
@@ -161,17 +161,17 @@ void ShiftCollider::addBox_slope(bool is
             if (box.bl.x < org.x + bb.xa && box.tr.x > org.x + bb.xi && box.height() > 0)
             {
                 a = org.x + 0.5f * (bb.xi + bb.xa);
                 c = 0.5f * (bb.yi + bb.ya);
                 if (isx)
                     _ranges[axis].weighted<XY>(box.bl.y - c, box.tr.y - c, weight, a, 0, 0, org.x,
                                                 m * (a * a + sqr((minright ? box.tr.x : box.bl.x) - 0.5f * (bb.xi + bb.xa))), false);
                 else
-                    _ranges[axis].weighted<XY>(box.bl.y - c, box.tr.y - c, weight, a, m, 
+                    _ranges[axis].weighted<XY>(box.bl.y - c, box.tr.y - c, weight, a, m,
                                                 (minright ? box.tr.y : box.bl.y) - c, a, 0, false);
             }
             break;
         case 2 :
             if (box.bl.x - box.tr.y < org.x - org.y + sb.da && box.tr.x - box.bl.y > org.x - org.y + sb.di)
             {
                 float d = org.x - org.y + 0.5f * (sb.di + sb.da);
                 c = 0.5f * (sb.si + sb.sa);
@@ -225,29 +225,29 @@ inline void ShiftCollider::removeBox(con
         case 1 :
             if (box.bl.x < org.x + bb.xa && box.tr.x > org.x + bb.xi && box.height() > 0)
             {
                 c = 0.5f * (bb.yi + bb.ya);
                 _ranges[axis].exclude(box.bl.y - c, box.tr.y - c);
             }
             break;
         case 2 :
-            if (box.bl.x - box.tr.y < org.x - org.y + sb.da && box.tr.x - box.bl.y > org.x - org.y + sb.di 
+            if (box.bl.x - box.tr.y < org.x - org.y + sb.da && box.tr.x - box.bl.y > org.x - org.y + sb.di
                 && box.width() > 0 && box.height() > 0)
             {
                 float di = org.x - org.y + sb.di;
                 float da = org.x - org.y + sb.da;
                 float smax = sdm(di, da, box.tr.x, box.tr.y, std::greater<float>());
                 float smin = sdm(da, di, box.bl.x, box.bl.y, std::less<float>());
                 c = 0.5f * (sb.si + sb.sa);
                 _ranges[axis].exclude(smin - c, smax - c);
             }
             break;
         case 3 :
-            if (box.bl.x + box.bl.y < org.x + org.y + sb.sa && box.tr.x + box.tr.y > org.x + org.y + sb.si 
+            if (box.bl.x + box.bl.y < org.x + org.y + sb.sa && box.tr.x + box.tr.y > org.x + org.y + sb.si
                 && box.width() > 0 && box.height() > 0)
             {
                 float si = org.x + org.y + sb.si;
                 float sa = org.x + org.y + sb.sa;
                 float dmax = sdm(si, sa, box.tr.x, -box.bl.y, std::greater<float>());
                 float dmin = sdm(sa, si, box.bl.x, -box.tr.y, std::less<float>());
                 c = 0.5f * (sb.di + sb.da);
                 _ranges[axis].exclude(dmin - c, dmax - c);
@@ -280,17 +280,17 @@ bool ShiftCollider::mergeSlot(Segment *s
     const unsigned short gid = slot->gid();
     if (!gc.check(gid))
         return false;
     const BBox &bb = gc.getBoundingBBox(gid);
 
     // SlotCollision * cslot = seg->collisionInfo(slot);
     int orderFlags = 0;
     bool sameClass = _seqProxClass == 0 && cslot->seqClass() == _seqClass;
-    if (sameCluster && _seqClass 
+    if (sameCluster && _seqClass
         && (sameClass || (_seqProxClass != 0 && cslot->seqClass() == _seqProxClass)))
 		// Force the target glyph to be in the specified direction from the slot we're testing.
         orderFlags = _seqOrder;
 
     // short circuit if only interested in direct collision and we are out of range
     if (orderFlags || (sx + bb.xa + _margin >= _limit.bl.x && sx + bb.xi - _margin <= _limit.tr.x)
                     || (sy + bb.ya + _margin >= _limit.bl.y && sy + bb.yi - _margin <= _limit.tr.y))
 
@@ -373,17 +373,17 @@ bool ShiftCollider::mergeSlot(Segment *s
                     torg = _currOffset.x - _currOffset.y;
                     cmin = _limit.bl.x - _limit.tr.y + torg;
                     cmax = _limit.tr.x - _limit.bl.y - tsb.di + tsb.da + torg;
                     lmargin = _margin / ISQRT2;
                     break;
                 default :
                     continue;
             }
-            
+
 #if !defined GRAPHITE2_NTRACING
             if (dbgout)
                 dbgout->setenv(1, reinterpret_cast<void *>(-1));
 #define DBGTAG(x) if (dbgout) dbgout->setenv(1, reinterpret_cast<void *>(-x));
 #else
 #define DBGTAG(x)
 #endif
 
@@ -395,17 +395,17 @@ bool ShiftCollider::mergeSlot(Segment *s
                 float ypinf = _limit.tr.y + _currOffset.y + tbb.ya;
                 float yminf = _limit.bl.y + _currOffset.y + tbb.yi;
                 switch (orderFlags) {
                     case SlotCollision::SEQ_ORDER_RIGHTUP :
                     {
                         float r1Xedge = cslot->seqAboveXoff() + 0.5f * (bb.xi + bb.xa) + sx;
                         float r3Xedge = cslot->seqBelowXlim() + bb.xa + sx + 0.5f * (tbb.xa - tbb.xi);
                         float r2Yedge = 0.5f * (bb.yi + bb.ya) + sy;
-                        
+
                         // DBGTAG(1x) means the regions are up and right
                         // region 1
                         DBGTAG(11)
                         addBox_slope(true, Rect(Position(xminf, r2Yedge), Position(r1Xedge, ypinf)),
                                         tbb, tsb, org, 0, seq_above_wt, true, i);
                         // region 2
                         DBGTAG(12)
                         removeBox(Rect(Position(xminf, yminf), Position(r3Xedge, r2Yedge)), tbb, tsb, org, i);
@@ -447,17 +447,17 @@ bool ShiftCollider::mergeSlot(Segment *s
                         // region 5
                         DBGTAG(25)
                         addBox_slope(false, Rect(Position(xminf, r2Yedge - cslot->seqValignHt()),
                                         Position(sx + bb.xa, r2Yedge)), tbb, tsb, org, seq_below_wt, seq_valign_wt, false, i);
                         break;
                     }
                     case SlotCollision::SEQ_ORDER_NOABOVE : // enforce neighboring glyph being above
                         DBGTAG(31);
-                        removeBox(Rect(Position(bb.xi - tbb.xa + sx, sy + bb.ya), 
+                        removeBox(Rect(Position(bb.xi - tbb.xa + sx, sy + bb.ya),
                                         Position(bb.xa - tbb.xi + sx, ypinf)), tbb, tsb, org, i);
                         break;
                     case SlotCollision::SEQ_ORDER_NOBELOW :	// enforce neighboring glyph being below
                         DBGTAG(32);
                         removeBox(Rect(Position(bb.xi - tbb.xa + sx, yminf),
                                         Position(bb.xa - tbb.xi + sx, sy + bb.yi)), tbb, tsb, org, i);
                         break;
                     case SlotCollision::SEQ_ORDER_NOLEFT :  // enforce neighboring glyph being to the left
@@ -564,17 +564,17 @@ bool ShiftCollider::mergeSlot(Segment *s
         Position exclOrigin(slot->origin() + cslot->exclOffset());
         exclSlot->origin(exclOrigin);
         SlotCollision exclInfo(seg, exclSlot);
         res &= mergeSlot(seg, exclSlot, &exclInfo, currShift, isAfter, sameCluster, isCol, true, dbgout );
         seg->freeSlot(exclSlot);
     }
     hasCol |= isCol;
     return res;
-    
+
 }   // end of ShiftCollider::mergeSlot
 
 
 // Figure out where to move the target glyph to, and return the amount to shift by.
 Position ShiftCollider::resolve(GR_MAYBE_UNUSED Segment *seg, bool &isCol, GR_MAYBE_UNUSED json * const dbgout)
 {
     float tbase;
     float totalCost = (float)(std::numeric_limits<float>::max() / 2);
@@ -661,17 +661,17 @@ void ShiftCollider::outputJsonDbg(json *
         *dbgout << "ranges" << json::array;
         axis = 0;
         axisMax = 3;
     }
     for (int iAxis = axis; iAxis <= axisMax; ++iAxis)
     {
         *dbgout << json::flat << json::array << _ranges[iAxis].position();
         for (Zones::const_iterator s = _ranges[iAxis].begin(), e = _ranges[iAxis].end(); s != e; ++s)
-            *dbgout << json::flat << json::array 
+            *dbgout << json::flat << json::array
                         << Position(s->x, s->xm) << s->sm << s->smx << s->c
                     << json::close;
         *dbgout << json::close;
     }
     if (axis < axisMax) // looped through the _ranges array for all axes
         *dbgout << json::close; // ranges array
 }
 
@@ -698,34 +698,34 @@ void ShiftCollider::outputJsonDbgEndSlot
     << "result" << resultPos
 	//<< "scraping" << _scraping[bestAxis]
 	<< "bestAxis" << bestAxis
     << "stillBad" << isCol
     << json::close; // slot object
 }
 
 void ShiftCollider::outputJsonDbgOneVector(json * const dbgout, Segment *seg, int axis,
-	float tleft, float bestCost, float bestVal) 
+	float tleft, float bestCost, float bestVal)
 {
 	const char * label;
 	switch (axis)
 	{
 		case 0:	label = "x";			break;
 		case 1:	label = "y";			break;
 		case 2:	label = "sum (NE-SW)";	break;
 		case 3:	label = "diff (NW-SE)";	break;
 		default: label = "???";			break;
 	}
 
 	*dbgout << json::object // vector
 		<< "direction" << label
 		<< "targetMin" << tleft;
-            
+
 	outputJsonDbgRemovals(dbgout, axis, seg);
-    	
+
     *dbgout << "ranges";
     outputJsonDbg(dbgout, seg, axis);
 
     *dbgout << "bestCost" << bestCost
         << "bestVal" << bestVal + tleft
         << json::close; // vectors object
 }
 
@@ -751,17 +751,17 @@ static float localmax (float al, float a
 }
 
 inline
 static float localmin(float al, float au, float bl, float bu, float x)
 {
     if (bl > al)
     { if (bu > au) return bl > x ? bl : x; }
     else if (au > bu) return al > x ? al : x;
-    return x;        
+    return x;
 }
 
 // Return the given edge of the glyph at height y, taking any slant box into account.
 static float get_edge(Segment *seg, const Slot *s, const Position &shift, float y, float width, float margin, bool isRight)
 {
     const GlyphCache &gc = seg->getFace()->glyphs();
     unsigned short gid = s->gid();
     float sx = s->origin().x + shift.x;
@@ -830,17 +830,17 @@ bool KernCollider::initSlot(Segment *seg
     const Slot *s;
     int numSlices;
     while (base->attachedTo())
         base = base->attachedTo();
     if (margin < 10) margin = 10;
 
     _limit = limit;
     _offsetPrev = offsetPrev; // kern from a previous pass
-    
+
     // Calculate the height of the glyph and how many horizontal slices to use.
     if (_maxy >= 1e37f)
     {
         _sliceWidth = margin / 1.5f;
         _maxy = ymax + margin;
         _miny = ymin - margin;
         numSlices = int((_maxy - _miny + 2) / (_sliceWidth / 1.5f) + 1.f);  // +2 helps with rounding errors
         _edges.clear();
@@ -872,27 +872,27 @@ bool KernCollider::initSlot(Segment *seg
             else if (numSlices < (int)_edges.size())   // this shouldn't fire since we always grow the range
             {
                 while ((int)_edges.size() > numSlices)
                     _edges.pop_back();
             }
         }
         goto done;
     }
-    numSlices = _edges.size();
+    numSlices = int(_edges.size());
 
 #if !defined GRAPHITE2_NTRACING
     // Debugging
     _seg = seg;
     _slotNear.clear();
     _slotNear.insert(_slotNear.begin(), numSlices, NULL);
     _nearEdges.clear();
     _nearEdges.insert(_nearEdges.begin(), numSlices, (dir & 1) ? -1e38f : +1e38f);
 #endif
-    
+
     // Determine the trailing edge of each slice (ie, left edge for a RTL glyph).
     for (s = base; s; s = s->nextInCluster(s))
     {
         SlotCollision *c = seg->collisionInfo(s);
         if (!gc.check(s->gid()))
             return false;
         const BBox &bs = gc.getBoundingBBox(s->gid());
         float x = s->origin().x + c->shift().x + ((dir & 1) ? bs.xi : bs.xa);
@@ -992,17 +992,17 @@ bool KernCollider::mergeSlot(Segment *se
         else
             nooverlap = false;
     }
     if (nooverlap)
         _mingap = max(_mingap, _xbound + currSpace + _margin - x);
     if (collides && !nooverlap)
         _hit = true;
     return collides | nooverlap;   // note that true is not a necessarily reliable value
-    
+
 }   // end of KernCollider::mergeSlot
 
 
 // Return the amount to kern by.
 Position KernCollider::resolve(GR_MAYBE_UNUSED Segment *seg, GR_MAYBE_UNUSED Slot *slot,
         int dir, GR_MAYBE_UNUSED json * const dbgout)
 {
     float resultNeeded = (1 - 2 * (dir & 1)) * _mingap;
@@ -1022,41 +1022,41 @@ Position KernCollider::resolve(GR_MAYBE_
                 << "target" << json::object
                     << "origin" << _target->origin()
                     //<< "currShift" << _currShift
                     << "offsetPrev" << _offsetPrev
                     << "bbox" << seg->theGlyphBBoxTemporary(_target->gid())
                     << "slantBox" << seg->getFace()->glyphs().slant(_target->gid())
                     << "fix" << "kern"
                     << json::close; // target object
-        
+
         *dbgout << "slices" << json::array;
         for (int is = 0; is < (int)_edges.size(); is++)
         {
-            *dbgout << json::flat << json::object 
-                << "i" << is 
+            *dbgout << json::flat << json::object
+                << "i" << is
                 << "targetEdge" << _edges[is]
                 << "neighbor" << objectid(dslot(seg, _slotNear[is]))
-                << "nearEdge" << _nearEdges[is] 
+                << "nearEdge" << _nearEdges[is]
                 << json::close;
         }
         *dbgout << json::close; // slices array
-            
+
         *dbgout
             << "xbound" << _xbound
             << "minGap" << _mingap
             << "needed" << resultNeeded
             << "result" << result
             << "stillBad" << (result != resultNeeded)
             << json::close; // slot object
     }
 #endif
 
     return Position(result, 0.);
-    
+
 }   // end of KernCollider::resolve
 
 void KernCollider::shift(const Position &mv, int dir)
 {
     for (Vector<float>::iterator e = _edges.begin(); e != _edges.end(); ++e)
         *e += mv.x;
     _xbound += (1 - 2 * (dir & 1)) * mv.x;
 }
@@ -1067,17 +1067,17 @@ void KernCollider::shift(const Position 
 SlotCollision::SlotCollision(Segment *seg, Slot *slot)
 {
     initFromSlot(seg, slot);
 }
 
 void SlotCollision::initFromSlot(Segment *seg, Slot *slot)
 {
     // Initialize slot attributes from glyph attributes.
-	// The order here must match the order in the grcompiler code, 
+	// The order here must match the order in the grcompiler code,
 	// GrcSymbolTable::AssignInternalGlyphAttrIDs.
     uint16 gid = slot->gid();
     uint16 aCol = seg->silf()->aCollision(); // flags attr ID
     const GlyphFace * glyphFace = seg->getFace()->glyphs().glyphSafe(gid);
     if (!glyphFace)
         return;
     const sparse &p = glyphFace->attrs();
     _flags = p[aCol];
@@ -1089,17 +1089,17 @@ void SlotCollision::initFromSlot(Segment
     _seqClass = p[aCol+7];
 	_seqProxClass = p[aCol+8];
     _seqOrder = p[aCol+9];
 	_seqAboveXoff = p[aCol+10];
 	_seqAboveWt = p[aCol+11];
 	_seqBelowXlim = p[aCol+12];
 	_seqBelowWt = p[aCol+13];
 	_seqValignHt = p[aCol+14];
-	_seqValignWt = p[aCol+15];    
+	_seqValignWt = p[aCol+15];
 
     // These attributes do not have corresponding glyph attribute:
     _exclGlyph = 0;
     _exclOffset = Position(0, 0);
 }
 
 float SlotCollision::getKern(int dir) const
 {
--- a/gfx/graphite2/src/Decompressor.cpp
+++ b/gfx/graphite2/src/Decompressor.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <cassert>
@@ -42,40 +42,40 @@ u32 read_literal(u8 const * &s, u8 const
     }
     return l;
 }
 
 bool read_sequence(u8 const * &src, u8 const * const end, u8 const * &literal,
                     u32 & literal_len, u32 & match_len, u32 & match_dist)
 {
     u8 const token = *src++;
-    
+
     literal_len = read_literal(src, end, token >> 4);
     literal = src;
     src += literal_len;
 
     // Normal exit for end of stream, wrap arround check and parital match check.
     if (src > end - sizeof(u16) || src < literal)
         return false;
-    
+
     match_dist  = *src++;
     match_dist |= *src++ << 8;
     match_len = read_literal(src, end, token & 0xf) + MINMATCH;
 
     // Malformed stream check.
     return src <= end-MINCODA;
 }
 
 }
 
 int lz4::decompress(void const *in, size_t in_size, void *out, size_t out_size)
 {
     if (out_size <= in_size || in_size < MINSRCSIZE)
         return -1;
-    
+
     u8 const *       src     = static_cast<u8 const *>(in),
              *       literal = 0,
              * const src_end = src + in_size;
 
     u8 *       dst     = static_cast<u8*>(out),
        * const dst_end = dst + out_size;
 
     // Check the in and out size hasn't wrapped around.
@@ -95,17 +95,17 @@ int lz4::decompress(void const *in, size
             // match plus the coda (1 + 2 + 5) must be 8 bytes or more allowing
             // us to remain within the src buffer for an overrun_copy on
             // machines upto 64 bits.
             if (align(literal_len) > out_size)
                 return -1;
             dst = overrun_copy(dst, literal, literal_len);
             out_size -= literal_len;
         }
-        
+
         // Copy, possibly repeating, match from earlier in the
         //  decoded output.
         u8 const * const pcpy = dst - match_dist;
         if (pcpy < static_cast<u8*>(out)
               || match_len > unsigned(out_size - LASTLITERALS)
               // Wrap around checks:
               || out_size < LASTLITERALS || pcpy >= dst)
             return -1;
@@ -115,12 +115,11 @@ int lz4::decompress(void const *in, size
         else
             dst = safe_copy(dst, pcpy, match_len);
         out_size -= match_len;
     }
 
     if (literal > src_end - literal_len || literal_len > out_size)
         return -1;
     dst = fast_copy(dst, literal, literal_len);
-    
-    return dst - (u8*)out;
+
+    return int(dst - (u8*)out);
 }
-
--- a/gfx/graphite2/src/Face.cpp
+++ b/gfx/graphite2/src/Face.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <cstring>
@@ -29,17 +29,16 @@ of the License or (at your option) any l
 #include "inc/CmapCache.h"
 #include "inc/debug.h"
 #include "inc/Decompressor.h"
 #include "inc/Endian.h"
 #include "inc/Face.h"
 #include "inc/FileFace.h"
 #include "inc/GlyphFace.h"
 #include "inc/json.h"
-#include "inc/SegCacheStore.h"
 #include "inc/Segment.h"
 #include "inc/NameTable.h"
 #include "inc/Error.h"
 
 using namespace graphite2;
 
 namespace
 {
@@ -137,17 +136,17 @@ bool Face::readGraphite(const Table & si
 
     bool havePasses = false;
     m_silfs = new Silf[m_numSilf];
     if (e.test(!m_silfs, E_OUTOFMEM)) return error(e);
     for (int i = 0; i < m_numSilf; i++)
     {
         error_context(EC_ASILF + (i << 8));
         const uint32 offset = be::read<uint32>(p),
-                     next   = i == m_numSilf - 1 ? silf.size() : be::peek<uint32>(p);
+                     next   = i == m_numSilf - 1 ? uint32(silf.size()) : be::peek<uint32>(p);
         if (e.test(next > silf.size() || offset >= next, E_BADSIZE))
             return error(e);
 
         if (!m_silfs[i].readGraphite(silf + offset, next - offset, *this, version))
             return false;
 
         if (m_silfs[i].numPasses())
             havePasses = true;
@@ -196,17 +195,17 @@ bool Face::runGraphite(Segment *seg, con
                 << "outputdir" << (seg->currdir() ? "rtl" : "ltr")
                 << "output" << json::array;
         for(Slot * s = seg->first(); s; s = s->next())
             *dbgout     << dslot(seg, s);
         *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::flat << *seg->charinfo(int(i));
         *dbgout         << json::close  // Close up the chars array
                     << json::close;     // Close up the segment object
     }
 #endif
 
     return res;
 }
 
@@ -234,28 +233,28 @@ uint16 Face::findPseudo(uint32 uid) cons
 }
 
 int32 Face::getGlyphMetric(uint16 gid, uint8 metric) const
 {
     switch (metrics(metric))
     {
         case kgmetAscent : return m_ascent;
         case kgmetDescent : return m_descent;
-        default: 
+        default:
             if (gid >= glyphs().numGlyphs()) return 0;
             return glyphs().glyph(gid)->getMetric(metric);
     }
 }
 
 void Face::takeFileFace(FileFace* pFileFace GR_MAYBE_UNUSED/*takes ownership*/)
 {
 #ifndef GRAPHITE2_NFILEFACE
     if (m_pFileFace==pFileFace)
       return;
-    
+
     delete m_pFileFace;
     m_pFileFace = pFileFace;
 #endif
 }
 
 NameTable * Face::nameTable() const
 {
     if (m_pNames) return m_pNames;
@@ -271,47 +270,44 @@ uint16 Face::languageForLocale(const cha
     if (m_pNames)
         return m_pNames->getLanguageId(locale);
     return 0;
 }
 
 
 
 Face::Table::Table(const Face & face, const Tag n, uint32 version) throw()
-: _f(&face), _compressed(false)
+: _f(&face), _sz(0), _compressed(false)
 {
-    size_t sz = 0;
-    _p = static_cast<const byte *>((*_f->m_ops.get_table)(_f->m_appFaceHandle, n, &sz));
-    _sz = uint32(sz);
+    _p = static_cast<const byte *>((*_f->m_ops.get_table)(_f->m_appFaceHandle, n, &_sz));
 
     if (!TtfUtil::CheckTable(n, _p, _sz))
     {
-        releaseBuffers();     // Make sure we release the table buffer even if the table failed it's checks
+        release();     // Make sure we release the table buffer even if the table failed its checks
         return;
     }
 
     if (be::peek<uint32>(_p) >= version)
         decompress();
 }
 
-void Face::Table::releaseBuffers()
+void Face::Table::release()
 {
     if (_compressed)
         free(const_cast<byte *>(_p));
     else if (_p && _f->m_ops.release_table)
         (*_f->m_ops.release_table)(_f->m_appFaceHandle, _p);
     _p = 0; _sz = 0;
 }
 
-Face::Table & Face::Table::operator = (const Table & rhs) throw()
+Face::Table & Face::Table::operator = (const Table && rhs) throw()
 {
-    if (_p == rhs._p)   return *this;
-
-    this->~Table();
-    new (this) Table(rhs);
+    if (this == &rhs)   return *this;
+    release();
+    new (this) Table(std::move(rhs));
     return *this;
 }
 
 Error Face::Table::decompress()
 {
     Error e;
     if (e.test(_sz < 5 * sizeof(uint32), E_BADSIZE))
         return e;
@@ -348,17 +344,17 @@ Error Face::Table::decompress()
     // Check the uncompressed version number against the original.
     if (!e)
         // coverity[forward_null : FALSE] - uncompressed_table has already been tested so can't be null
         // coverity[checked_return : FALSE] - we test e later
         e.test(be::peek<uint32>(uncompressed_table) != version, E_SHRINKERFAILED);
 
     // Tell the provider to release the compressed form since were replacing
     //   it anyway.
-    releaseBuffers();
+    release();
 
     if (e)
     {
         free(uncompressed_table);
         uncompressed_table = 0;
         uncompressed_size  = 0;
     }
 
--- a/gfx/graphite2/src/FeatureMap.cpp
+++ b/gfx/graphite2/src/FeatureMap.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <cstring>
--- a/gfx/graphite2/src/FileFace.cpp
+++ b/gfx/graphite2/src/FileFace.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <cstring>
@@ -43,28 +43,28 @@ FileFace::FileFace(const char *filename)
     if (fseek(_file, 0, SEEK_END)) return;
     _file_len = ftell(_file);
     if (fseek(_file, 0, SEEK_SET)) return;
 
     size_t tbl_offset, tbl_len;
 
     // Get the header.
     if (!TtfUtil::GetHeaderInfo(tbl_offset, tbl_len)) return;
-    if (fseek(_file, tbl_offset, SEEK_SET)) return;
+    if (fseek(_file, long(tbl_offset), SEEK_SET)) return;
     _header_tbl = (TtfUtil::Sfnt::OffsetSubTable*)gralloc<char>(tbl_len);
     if (_header_tbl)
     {
         if (fread(_header_tbl, 1, tbl_len, _file) != tbl_len) return;
         if (!TtfUtil::CheckHeader(_header_tbl)) return;
     }
 
     // Get the table directory
     if (!TtfUtil::GetTableDirInfo(_header_tbl, tbl_offset, tbl_len)) return;
     _table_dir = (TtfUtil::Sfnt::OffsetSubTable::Entry*)gralloc<char>(tbl_len);
-    if (fseek(_file, tbl_offset, SEEK_SET)) return;
+    if (fseek(_file, long(tbl_offset), SEEK_SET)) return;
     if (_table_dir && fread(_table_dir, 1, tbl_len, _file) != tbl_len)
     {
         free(_table_dir);
         _table_dir = NULL;
     }
     return;
 }
 
@@ -83,17 +83,17 @@ const void *FileFace::get_table_fn(const
     const FileFace & file_face = *static_cast<const FileFace *>(appFaceHandle);
 
     void *tbl;
     size_t tbl_offset, tbl_len;
     if (!TtfUtil::GetTableInfo(name, file_face._header_tbl, file_face._table_dir, tbl_offset, tbl_len))
         return 0;
 
     if (tbl_offset > file_face._file_len || tbl_len > file_face._file_len - tbl_offset
-            || fseek(file_face._file, tbl_offset, SEEK_SET) != 0)
+            || fseek(file_face._file, long(tbl_offset), SEEK_SET) != 0)
         return 0;
 
     tbl = malloc(tbl_len);
     if (!tbl || fread(tbl, 1, tbl_len, file_face._file) != tbl_len)
     {
         free(tbl);
         return 0;
     }
--- a/gfx/graphite2/src/Font.cpp
+++ b/gfx/graphite2/src/Font.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "inc/Face.h"
@@ -51,11 +51,8 @@ Font::Font(float ppm, const Face & f, co
     }
 }
 
 
 /*virtual*/ Font::~Font()
 {
     free(m_advances);
 }
-
-
-
--- a/gfx/graphite2/src/GlyphCache.cpp
+++ b/gfx/graphite2/src/GlyphCache.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "graphite2/Font.h"
@@ -41,17 +41,17 @@ namespace
     //    +-+-+-+-+-+-+-+-+-+-+                +-+-+-+-+-+-+-+-+-+-+-+-+
     // v1 |k|n|v1 |v2 |...|vN |     or    v2   | k | n |v1 |v2 |...|vN |
     //    +-+-+-+-+-+-+-+-+-+-+                +-+-+-+-+-+-+-+-+-+-+-+-+
     // variable length structures.
 
     template<typename W>
     class _glat_iterator : public std::iterator<std::input_iterator_tag, std::pair<sparse::key_type, sparse::mapped_type> >
     {
-        unsigned short  key() const             { return be::peek<W>(_e) + _n; }
+        unsigned short  key() const             { return uint16(be::peek<W>(_e) + _n); }
         unsigned int    run() const             { return be::peek<W>(_e+sizeof(W)); }
         void            advance_entry()         { _n = 0; _e = _v; be::skip<W>(_v,2); }
     public:
         _glat_iterator(const void * glat=0) : _e(reinterpret_cast<const byte *>(glat)), _v(_e+2*sizeof(W)), _n(0) {}
 
         _glat_iterator<W> & operator ++ () {
             ++_n; be::skip<uint16>(_v);
             if (_n == run()) advance_entry();
@@ -79,17 +79,17 @@ namespace
 }
 
 const SlantBox SlantBox::empty = {0,0,0,0};
 
 
 class GlyphCache::Loader
 {
 public:
-    Loader(const Face & face, const bool dumb_font);    //return result indicates success. Do not use if failed.
+    Loader(const Face & face);    //return result indicates success. Do not use if failed.
 
     operator bool () const throw();
     unsigned short int units_per_em() const throw();
     unsigned short int num_glyphs() const throw();
     unsigned short int num_attrs() const throw();
     bool has_boxes() const throw();
 
     const GlyphFace * read_glyph(unsigned short gid, GlyphFace &, int *numsubs) const throw();
@@ -110,17 +110,17 @@ private:
     unsigned short  _num_glyphs_graphics,        //i.e. boundary box and advance
                     _num_glyphs_attributes,
                     _num_attrs;                    // number of glyph attributes per glyph
 };
 
 
 
 GlyphCache::GlyphCache(const Face & face, const uint32 face_options)
-: _glyph_loader(new Loader(face, bool(face_options & gr_face_dumbRendering))),
+: _glyph_loader(new Loader(face)),
   _glyphs(_glyph_loader && *_glyph_loader && _glyph_loader->num_glyphs()
         ? grzeroalloc<const GlyphFace *>(_glyph_loader->num_glyphs()) : 0),
   _boxes(_glyph_loader && _glyph_loader->has_boxes() && _glyph_loader->num_glyphs()
         ? grzeroalloc<GlyphBox *>(_glyph_loader->num_glyphs()) : 0),
   _num_glyphs(_glyphs ? _glyph_loader->num_glyphs() : 0),
   _num_attrs(_glyphs ? _glyph_loader->num_attrs() : 0),
   _upem(_glyphs ? _glyph_loader->units_per_em() : 0)
 {
@@ -205,17 +205,17 @@ GlyphCache::~GlyphCache()
         else
             free(_boxes[0]);
         free(_boxes);
     }
     delete _glyph_loader;
 }
 
 const GlyphFace *GlyphCache::glyph(unsigned short glyphid) const      //result may be changed by subsequent call with a different glyphid
-{ 
+{
     if (glyphid >= numGlyphs())
         return _glyphs[0];
     const GlyphFace * & p = _glyphs[glyphid];
     if (p == 0 && _glyph_loader)
     {
         int numsubs = 0;
         GlyphFace * g = new GlyphFace();
         if (g)  p = _glyph_loader->read_glyph(glyphid, *g, &numsubs);
@@ -234,17 +234,17 @@ const GlyphFace *GlyphCache::glyph(unsig
             }
         }
     }
     return p;
 }
 
 
 
-GlyphCache::Loader::Loader(const Face & face, const bool dumb_font)
+GlyphCache::Loader::Loader(const Face & face)
 : _head(face, Tag::head),
   _hhea(face, Tag::hhea),
   _hmtx(face, Tag::hmtx),
   _glyf(face, Tag::glyf),
   _loca(face, Tag::loca),
   _long_fmt(false),
   _has_boxes(false),
   _num_glyphs_graphics(0),
@@ -252,70 +252,67 @@ GlyphCache::Loader::Loader(const Face & 
   _num_attrs(0)
 {
     if (!operator bool())
         return;
 
     const Face::Table maxp = Face::Table(face, Tag::maxp);
     if (!maxp) { _head = Face::Table(); return; }
 
-    _num_glyphs_graphics = TtfUtil::GlyphCount(maxp);
+    _num_glyphs_graphics = static_cast<unsigned short>(TtfUtil::GlyphCount(maxp));
     // This will fail if the number of glyphs is wildly out of range.
     if (_glyf && TtfUtil::LocaLookup(_num_glyphs_graphics-1, _loca, _loca.size(), _head) == size_t(-2))
     {
         _head = Face::Table();
         return;
     }
 
-    if (!dumb_font)
+    if ((m_pGlat = Face::Table(face, Tag::Glat, 0x00030000)) == NULL
+        || (m_pGloc = Face::Table(face, Tag::Gloc)) == NULL
+        || m_pGloc.size() < 8)
     {
-        if ((m_pGlat = Face::Table(face, Tag::Glat, 0x00030000)) == NULL
-            || (m_pGloc = Face::Table(face, Tag::Gloc)) == NULL
-            || m_pGloc.size() < 8)
-        {
-            _head = Face::Table();
-            return;
-        }
-        const byte    * p = m_pGloc;
-        int       version = be::read<uint32>(p);
-        const uint16    flags = be::read<uint16>(p);
-        _num_attrs = be::read<uint16>(p);
-        // We can accurately calculate the number of attributed glyphs by
-        //  subtracting the length of the attribids array (numAttribs long if present)
-        //  and dividing by either 2 or 4 depending on shor or lonf format
-        _long_fmt              = flags & 1;
-        int tmpnumgattrs       = (m_pGloc.size()
-                                   - (p - m_pGloc)
-                                   - sizeof(uint16)*(flags & 0x2 ? _num_attrs : 0))
-                                       / (_long_fmt ? sizeof(uint32) : sizeof(uint16)) - 1;
+        _head = Face::Table();
+        return;
+    }
+    const byte    * p = m_pGloc;
+    int       version = be::read<uint32>(p);
+    const uint16    flags = be::read<uint16>(p);
+    _num_attrs = be::read<uint16>(p);
+    // We can accurately calculate the number of attributed glyphs by
+    //  subtracting the length of the attribids array (numAttribs long if present)
+    //  and dividing by either 2 or 4 depending on shor or lonf format
+    _long_fmt              = flags & 1;
+    ptrdiff_t tmpnumgattrs       = (m_pGloc.size()
+                               - (p - m_pGloc)
+                               - sizeof(uint16)*(flags & 0x2 ? _num_attrs : 0))
+                                   / (_long_fmt ? sizeof(uint32) : sizeof(uint16)) - 1;
 
-        if (version >= 0x00020000 || tmpnumgattrs < 0 || tmpnumgattrs > 65535
-            || _num_attrs == 0 || _num_attrs > 0x3000  // is this hard limit appropriate?
-            || _num_glyphs_graphics > tmpnumgattrs
-            || m_pGlat.size() < 4)
-        {
-            _head = Face::Table();
-            return;
-        }
+    if (version >= 0x00020000 || tmpnumgattrs < 0 || tmpnumgattrs > 65535
+        || _num_attrs == 0 || _num_attrs > 0x3000  // is this hard limit appropriate?
+        || _num_glyphs_graphics > tmpnumgattrs
+        || m_pGlat.size() < 4)
+    {
+        _head = Face::Table();
+        return;
+    }
 
-        _num_glyphs_attributes = static_cast<unsigned short>(tmpnumgattrs);
-        p = m_pGlat;
-        version = be::read<uint32>(p);
-        if (version >= 0x00040000 || (version >= 0x00030000 && m_pGlat.size() < 8))       // reject Glat tables that are too new
-        {
-            _head = Face::Table();
-            return;
-        }
-        else if (version >= 0x00030000)
-        {
-            unsigned int glatflags = be::read<uint32>(p);
-            _has_boxes = glatflags & 1;
-            // delete this once the compiler is fixed
-            _has_boxes = true;
-        }
+    _num_glyphs_attributes = static_cast<unsigned short>(tmpnumgattrs);
+    p = m_pGlat;
+    version = be::read<uint32>(p);
+    if (version >= 0x00040000 || (version >= 0x00030000 && m_pGlat.size() < 8))       // reject Glat tables that are too new
+    {
+        _head = Face::Table();
+        return;
+    }
+    else if (version >= 0x00030000)
+    {
+        unsigned int glatflags = be::read<uint32>(p);
+        _has_boxes = glatflags & 1;
+        // delete this once the compiler is fixed
+        _has_boxes = true;
     }
 }
 
 inline
 GlyphCache::Loader::operator bool () const throw()
 {
     return _head && _hhea && _hmtx && !(bool(_glyf) != bool(_loca));
 }
@@ -481,12 +478,11 @@ GlyphBox * GlyphCache::Loader::read_box(
     if (glocs + 6 + num * 8 >= gloce)
         return 0;
 
     for (int i = 0; i < num * 2; ++i)
     {
         Rect box = readbox((i & 1) ? diamax : bbox, p[0], p[2], p[1], p[3]);
         curr->addSubBox(i >> 1, i & 1, &box);
         be::skip<uint8>(p, 4);
-    } 
+    }
     return (GlyphBox *)((char *)(curr) + sizeof(GlyphBox) + 2 * num * sizeof(Rect));
 }
-
--- a/gfx/graphite2/src/GlyphFace.cpp
+++ b/gfx/graphite2/src/GlyphFace.cpp
@@ -10,39 +10,39 @@
 
     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 
+    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.
 */
 #include "inc/GlyphFace.h"
 
 
 using namespace graphite2;
 
 int32 GlyphFace::getMetric(uint8 metric) const
 {
     switch (metrics(metric))
     {
-        case kgmetLsb       : return m_bbox.bl.x;
-        case kgmetRsb       : return m_advance.x - m_bbox.tr.x;
-        case kgmetBbTop     : return m_bbox.tr.y;
-        case kgmetBbBottom  : return m_bbox.bl.y;
-        case kgmetBbLeft    : return m_bbox.bl.x;
-        case kgmetBbRight   : return m_bbox.tr.x;
-        case kgmetBbHeight  : return m_bbox.tr.y - m_bbox.bl.y;
-        case kgmetBbWidth   : return m_bbox.tr.x - m_bbox.bl.x;
-        case kgmetAdvWidth  : return m_advance.x;
-        case kgmetAdvHeight : return m_advance.y;
+        case kgmetLsb       : return int32(m_bbox.bl.x);
+        case kgmetRsb       : return int32(m_advance.x - m_bbox.tr.x);
+        case kgmetBbTop     : return int32(m_bbox.tr.y);
+        case kgmetBbBottom  : return int32(m_bbox.bl.y);
+        case kgmetBbLeft    : return int32(m_bbox.bl.x);
+        case kgmetBbRight   : return int32(m_bbox.tr.x);
+        case kgmetBbHeight  : return int32(m_bbox.tr.y - m_bbox.bl.y);
+        case kgmetBbWidth   : return int32(m_bbox.tr.x - m_bbox.bl.x);
+        case kgmetAdvWidth  : return int32(m_advance.x);
+        case kgmetAdvHeight : return int32(m_advance.y);
         default : return 0;
     }
 }
--- a/gfx/graphite2/src/Intervals.cpp
+++ b/gfx/graphite2/src/Intervals.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <algorithm>
@@ -178,26 +178,26 @@ void Zones::remove(float x, float xm)
 
         ie = _exclusions.end();
     }
 }
 
 
 Zones::const_iterator Zones::find_exclusion_under(float x) const
 {
-    int l = 0, h = _exclusions.size();
+    size_t l = 0, h = _exclusions.size();
 
     while (l < h)
     {
-        int const p = (l+h) >> 1;
+        size_t const p = (l+h) >> 1;
         switch (_exclusions[p].outcode(x))
         {
         case 0 : return _exclusions.begin()+p;
         case 1 : h = p; break;
-        case 2 : 
+        case 2 :
         case 3 : l = p+1; break;
         }
     }
 
     return _exclusions.begin()+l;
 }
 
 
@@ -282,18 +282,17 @@ void Zones::jsonDbgOut(Segment *seg) con
         {
             *_dbg << json::flat << json::array
                 << objectid(dslot(seg, (Slot *)(s->_env[0])))
                 << reinterpret_cast<ptrdiff_t>(s->_env[1]);
             if (s->_isdel)
                 *_dbg << "remove" << Position(s->_excl.x, s->_excl.xm);
             else
                 *_dbg << "exclude" << json::flat << json::array
-                    << s->_excl.x << s->_excl.xm 
+                    << s->_excl.x << s->_excl.xm
                     << s->_excl.sm << s->_excl.smx << s->_excl.c
                     << json::close;
             *_dbg << json::close;
         }
     }
 }
 
 #endif
-
--- a/gfx/graphite2/src/Justifier.cpp
+++ b/gfx/graphite2/src/Justifier.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 
@@ -57,79 +57,80 @@ void JustifyTotal::accumulate(Slot *s, S
     m_tStretch += s->getJustify(seg, level, 0);
     m_tShrink += s->getJustify(seg, level, 1);
     m_tStep += s->getJustify(seg, level, 2);
     m_tWeight += s->getJustify(seg, level, 3);
 }
 
 float Segment::justify(Slot *pSlot, const Font *font, float width, GR_MAYBE_UNUSED justFlags jflags, Slot *pFirst, Slot *pLast)
 {
-    Slot *s, *end;
+    Slot *end = last();
     float currWidth = 0.0;
     const float scale = font ? font->scale() : 1.0f;
     Position res;
 
     if (width < 0 && !(silf()->flags()))
         return width;
 
     if ((m_dir & 1) != m_silf->dir() && m_silf->bidiPass() != m_silf->numPasses())
     {
         reverseSlots();
-        s = pFirst;
-        pFirst = pLast;
-        pLast = s;
+        std::swap(pFirst, pLast);
     }
     if (!pFirst) pFirst = pSlot;
     while (!pFirst->isBase()) pFirst = pFirst->attachedTo();
     if (!pLast) pLast = last();
     while (!pLast->isBase()) pLast = pLast->attachedTo();
     const float base = pFirst->origin().x / scale;
     width = width / scale;
     if ((jflags & gr_justEndInline) == 0)
     {
-        do {
+        while (pLast != pFirst && pLast)
+        {
             Rect bbox = theGlyphBBoxTemporary(pLast->glyph());
             if (bbox.bl.x != 0.f || bbox.bl.y != 0.f || bbox.tr.x != 0.f || bbox.tr.y == 0.f)
                 break;
             pLast = pLast->prev();
-        } while (pLast != pFirst);
+        }
     }
 
-    end = pLast->nextSibling();
-    pFirst = pFirst->nextSibling();
+    if (pLast)
+        end = pLast->nextSibling();
+    if (pFirst)
+        pFirst = pFirst->nextSibling();
 
     int icount = 0;
     int numLevels = silf()->numJustLevels();
     if (!numLevels)
     {
-        for (s = pSlot; s && s != end; s = s->nextSibling())
+        for (Slot *s = pSlot; s && s != end; s = s->nextSibling())
         {
             CharInfo *c = charinfo(s->before());
             if (isWhitespace(c->unicodeChar()))
             {
                 s->setJustify(this, 0, 3, 1);
                 s->setJustify(this, 0, 2, 1);
                 s->setJustify(this, 0, 0, -1);
                 ++icount;
             }
         }
         if (!icount)
         {
-            for (s = pSlot; s && s != end; s = s->nextSibling())
+            for (Slot *s = pSlot; s && s != end; s = s->nextSibling())
             {
                 s->setJustify(this, 0, 3, 1);
                 s->setJustify(this, 0, 2, 1);
                 s->setJustify(this, 0, 0, -1);
             }
         }
         ++numLevels;
     }
 
     Vector<JustifyTotal> stats(numLevels);
-    for (s = pFirst; s && s != end; s = s->nextSibling())
+    for (Slot *s = pFirst; s && s != end; s = s->nextSibling())
     {
         float w = s->origin().x / scale + s->advance() - base;
         if (w > currWidth) currWidth = w;
         for (int j = 0; j < numLevels; ++j)
             stats[j].accumulate(s, this, j);
         s->just(0);
     }
 
@@ -141,17 +142,17 @@ float Segment::justify(Slot *pSlot, cons
         int tWeight = stats[i].weight();
         if (tWeight == 0) continue;
 
         do {
             error = 0.;
             diff = width - currWidth;
             diffpw = diff / tWeight;
             tWeight = 0;
-            for (s = pFirst; s && s != end; s = s->nextSibling()) // don't include final glyph
+            for (Slot *s = pFirst; s && s != end; s = s->nextSibling()) // don't include final glyph
             {
                 int w = s->getJustify(this, i, 3);
                 float pref = diffpw * w + error;
                 int step = s->getJustify(this, i, 2);
                 if (!step) step = 1;        // handle lazy font developers
                 if (pref > 0)
                 {
                     float max = uint16(s->getJustify(this, i, 0));
@@ -219,18 +220,20 @@ float Segment::justify(Slot *pSlot, cons
         *dbgout         << json::close << json::close;
     }
 #endif
 
     res = positionSlots(font, pSlot, pLast, m_dir);
 
     if (silf()->flags() & 1)
     {
-        delLineEnd(m_first);
-        delLineEnd(m_last);
+        if (m_first)
+            delLineEnd(m_first);
+        if (m_last)
+            delLineEnd(m_last);
     }
     m_first = oldFirst;
     m_last = oldLast;
 
     if ((m_dir & 1) != m_silf->dir() && m_silf->bidiPass() != m_silf->numPasses())
         reverseSlots();
     return res.x;
 }
@@ -272,9 +275,8 @@ void Segment::delLineEnd(Slot *s)
         nSlot->prev(s->prev());
         if (s->prev())
             s->prev()->next(nSlot);
     }
     else
         s->prev()->next(NULL);
     freeSlot(s);
 }
-
--- a/gfx/graphite2/src/NameTable.cpp
+++ b/gfx/graphite2/src/NameTable.cpp
@@ -46,17 +46,17 @@ NameTable::NameTable(const void* data, s
         (length > sizeof(TtfUtil::Sfnt::FontNames) +
          sizeof(TtfUtil::Sfnt::NameRecord) * ( be::swap<uint16>(m_table->count) - 1)))
     {
         uint16 offset = be::swap<uint16>(m_table->string_offset);
         if (offset < length)
         {
             m_nameData = reinterpret_cast<const uint8*>(pdata) + offset;
             setPlatformEncoding(platformId, encodingID);
-            m_nameDataLength = length - offset;
+            m_nameDataLength = uint16(length - offset);
             return;
         }
     }
     free(const_cast<TtfUtil::Sfnt::FontNames*>(m_table));
     m_table = NULL;
 }
 
 uint16 NameTable::setPlatformEncoding(uint16 platformId, uint16 encodingID)
@@ -175,17 +175,17 @@ void* NameTable::getName(uint16& languag
             free(utf16Name);
             languageId = 0;
             length = 0;
             return NULL;
         }
         utf8::iterator d = uniBuffer;
         for (utf16::const_iterator s = utf16Name, e = utf16Name + utf16Length; s != e; ++s, ++d)
             *d = *s;
-        length = d - uniBuffer;
+        length = uint32(d - uniBuffer);
         uniBuffer[length] = 0;
         free(utf16Name);
         return uniBuffer;
     }
     case gr_utf16:
         length = utf16Length;
         return utf16Name;
     case gr_utf32:
@@ -196,17 +196,17 @@ void* NameTable::getName(uint16& languag
             free(utf16Name);
             languageId = 0;
             length = 0;
             return NULL;
         }
         utf32::iterator d = uniBuffer;
         for (utf16::const_iterator s = utf16Name, e = utf16Name + utf16Length; s != e; ++s, ++d)
             *d = *s;
-        length = d - uniBuffer;
+        length = uint32(d - uniBuffer);
         uniBuffer[length] = 0;
         free(utf16Name);
         return uniBuffer;
     }
     }
     free(utf16Name);
     languageId = 0;
     length = 0;
@@ -247,9 +247,8 @@ uint16 NameTable::getLanguageId(const ch
                     if (match)
                         return 0x8000 + i;
                 }
             }
         }
     }
     return localeId;
 }
-
--- a/gfx/graphite2/src/Pass.cpp
+++ b/gfx/graphite2/src/Pass.cpp
@@ -92,20 +92,20 @@ Pass::~Pass()
 
 bool Pass::readPass(const byte * const pass_start, size_t pass_length, size_t subtable_base,
         GR_MAYBE_UNUSED Face & face, passtype pt, GR_MAYBE_UNUSED uint32 version, Error &e)
 {
     const byte * p              = pass_start,
                * const pass_end = p + pass_length;
     size_t numRanges;
 
-    if (e.test(pass_length < 40, E_BADPASSLENGTH)) return face.error(e); 
+    if (e.test(pass_length < 40, E_BADPASSLENGTH)) return face.error(e);
     // Read in basic values
     const byte flags = be::read<byte>(p);
-    if (e.test((flags & 0x1f) && 
+    if (e.test((flags & 0x1f) &&
             (pt < PASS_TYPE_POSITIONING || !m_silf->aCollision() || !face.glyphs().hasBoxes() || !(m_silf->flags() & 0x20)),
             E_BADCOLLISIONPASS))
         return face.error(e);
     m_numCollRuns = flags & 0x7;
     m_kernColls   = (flags >> 3) & 0x3;
     m_isReverseDir = (flags >> 5) & 0x1;
     m_iMaxLoop = be::read<byte>(p);
     if (m_iMaxLoop < 1) m_iMaxLoop = 1;
@@ -186,17 +186,17 @@ bool Pass::readPass(const byte * const p
 
     // We should be at the end or within the pass
     if (e.test(p > pass_end, E_BADPASSLENGTH)) return face.error(e);
 
     // Load the pass constraint if there is one.
     if (pass_constraint_len)
     {
         face.error_context(face.error_context() + 1);
-        m_cPConstraint = vm::Machine::Code(true, pcCode, pcCode + pass_constraint_len, 
+        m_cPConstraint = vm::Machine::Code(true, pcCode, pcCode + pass_constraint_len,
                                   precontext[0], be::peek<uint16>(sort_keys), *m_silf, face, PASS_TYPE_UNKNOWN);
         if (e.test(!m_cPConstraint, E_OUTOFMEM)
                 || e.test(m_cPConstraint.status() != Code::loaded, m_cPConstraint.status() + E_CODEFAILURE))
             return face.error(e);
         face.error_context(face.error_context() - 1);
     }
     if (m_numRules)
     {
@@ -241,21 +241,21 @@ bool Pass::readRules(const byte * rule_m
     m_progs = gralloc<byte>(prog_pool_sz);
     byte * prog_pool_free = m_progs,
          * prog_pool_end  = m_progs + prog_pool_sz;
     if (e.test(!(m_rules && m_codes && m_progs), E_OUTOFMEM)) return face.error(e);
 
     Rule * r = m_rules + m_numRules - 1;
     for (size_t n = m_numRules; r >= m_rules; --n, --r, ac_end = ac_begin, rc_end = rc_begin)
     {
-        face.error_context((face.error_context() & 0xFFFF00) + EC_ARULE + ((n - 1) << 24));
+        face.error_context((face.error_context() & 0xFFFF00) + EC_ARULE + int((n - 1) << 24));
         r->preContext = *--precontext;
         r->sort       = be::peek<uint16>(--sort_key);
 #ifndef NDEBUG
-        r->rule_idx   = n - 1;
+        r->rule_idx   = uint16(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::peek<uint16>(--o_action);
         --o_constraint;
         rc_begin      = be::peek<uint16>(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
@@ -286,17 +286,17 @@ bool Pass::readRules(const byte * rule_m
         {
             c->externalProgramMoved(moved_progs - m_progs);
         }
         m_progs = moved_progs;
     }
 
     // Load the rule entries map
     face.error_context((face.error_context() & 0xFFFF00) + EC_APASS);
-    //TODO: Coverty: 1315804: FORWARD_NULL
+    //TODO: Coverity: 1315804: FORWARD_NULL
     RuleEntry * re = m_ruleMap = gralloc<RuleEntry>(num_entries);
     if (e.test(!re, E_OUTOFMEM)) return face.error(e);
     for (size_t n = num_entries; n; --n, ++re)
     {
         const ptrdiff_t rn = be::read<uint16>(rule_map);
         if (e.test(rn >= m_numRules, E_BADRULENUM))  return face.error(e);
         re->rule = m_rules + rn;
     }
@@ -325,44 +325,44 @@ bool Pass::readStates(const byte * start
     if (e.test(!m_startStates || !m_states || !m_transitions, E_OUTOFMEM)) return face.error(e);
     // load start states
     for (uint16 * s = m_startStates,
                 * const s_end = s + m_maxPreCtxt - m_minPreCtxt + 1; s != s_end; ++s)
     {
         *s = be::read<uint16>(starts);
         if (e.test(*s >= m_numStates, E_BADSTATE))
         {
-            face.error_context((face.error_context() & 0xFFFF00) + EC_ASTARTS + ((s - m_startStates) << 24));
+            face.error_context((face.error_context() & 0xFFFF00) + EC_ASTARTS + int((s - m_startStates) << 24));
             return face.error(e); // true;
         }
     }
 
     // load state transition table.
     for (uint16 * t = m_transitions,
                 * const t_end = t + m_numTransition*m_numColumns; t != t_end; ++t)
     {
         *t = be::read<uint16>(states);
         if (e.test(*t >= m_numStates, E_BADSTATE))
         {
-            face.error_context((face.error_context() & 0xFFFF00) + EC_ATRANS + (((t - m_transitions) / m_numColumns) << 8));
+            face.error_context((face.error_context() & 0xFFFF00) + EC_ATRANS + int(((t - m_transitions) / m_numColumns) << 8));
             return face.error(e);
         }
     }
 
     State * s = m_states,
           * const success_begin = m_states + m_numStates - m_numSuccess;
     const RuleEntry * rule_map_end = m_ruleMap + be::peek<uint16>(o_rule_map + m_numSuccess*sizeof(uint16));
     for (size_t n = m_numStates; n; --n, ++s)
     {
         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 (e.test(begin >= rule_map_end || end > rule_map_end || begin > end, E_BADRULEMAPPING))
         {
-            face.error_context((face.error_context() & 0xFFFF00) + EC_ARULEMAP + (n << 24));
+            face.error_context((face.error_context() & 0xFFFF00) + EC_ARULEMAP + int(n << 24));
             return face.error(e);
         }
         s->rules = begin;
         s->rules_end = (end - begin <= FiniteStateMachine::MAX_RULES)? end :
             begin + FiniteStateMachine::MAX_RULES;
         if (begin)      // keep UBSan happy can't call qsort with null begin
             qsort(begin, end - begin, sizeof(RuleEntry), &cmpRuleEntry);
     }
@@ -769,17 +769,17 @@ bool Pass::collisionShift(Segment *seg, 
             }
         }
 
 #if !defined GRAPHITE2_NTRACING
         if (dbgout)
             *dbgout << json::close << json::close; // phase-1
 #endif
 
-        // phase 2 : loop until happy. 
+        // phase 2 : loop until happy.
         for (int i = 0; i < m_numCollRuns - 1; ++i)
         {
             if (hasCollisions || moved)
             {
 
 #if !defined GRAPHITE2_NTRACING
                 if (dbgout)
                     *dbgout << json::object << "phase" << "2a" << "loop" << i << "moves" << json::array;
@@ -815,20 +815,20 @@ bool Pass::collisionShift(Segment *seg, 
                 }
 
 #if !defined GRAPHITE2_NTRACING
                 if (dbgout)
                     *dbgout << json::close << json::close // phase 2a
                         << json::object << "phase" << "2b" << "loop" << i << "moves" << json::array;
 #endif
 
-                // phase 2b : redo basic diacritic positioning pass for ALL glyphs. Each successive loop adjusts 
-                // glyphs from their current adjusted position, which has the effect of gradually minimizing the  
-                // resulting adjustment; ie, the final result will be gradually closer to the original location.  
-                // Also it allows more flexibility in the final adjustment, since it is moving along the  
+                // phase 2b : redo basic diacritic positioning pass for ALL glyphs. Each successive loop adjusts
+                // glyphs from their current adjusted position, which has the effect of gradually minimizing the
+                // resulting adjustment; ie, the final result will be gradually closer to the original location.
+                // Also it allows more flexibility in the final adjustment, since it is moving along the
                 // possible 8 vectors from successively different starting locations.
                 if (moved)
                 {
                     moved = false;
                     for (Slot *s = start; s != end; s = s->next())
                     {
                         SlotCollision * c = seg->collisionInfo(s);
                         if (start && (c->flags() & (SlotCollision::COLL_FIX | SlotCollision::COLL_TEMPLOCK
@@ -957,17 +957,17 @@ bool Pass::resolveCollisions(Segment *se
     // When we're processing forward, ignore kernable glyphs that preceed the target glyph.
     // When processing backward, don't ignore these until we pass slotFix.
     bool ignoreForKern = !isRev;
     bool rtl = dir & 1;
     Slot *base = slotFix;
     while (base->attachedTo())
         base = base->attachedTo();
     Position zero(0., 0.);
-    
+
     // Look for collisions with the neighboring glyphs.
     for (nbor = start; nbor; nbor = isRev ? nbor->prev() : nbor->next())
     {
         SlotCollision *cNbor = seg->collisionInfo(nbor);
         bool sameCluster = nbor->isChildOf(base);
         if (nbor != slotFix         						// don't process if this is the slot of interest
                       && !(cNbor->ignore())    				// don't process if ignoring
                       && (nbor == base || sameCluster       // process if in the same cluster as slotFix
@@ -977,17 +977,17 @@ bool Pass::resolveCollisions(Segment *se
                             || !(cNbor->flags() & SlotCollision::COLL_FIX)     // merge in immovable stuff
                             || ((cNbor->flags() & SlotCollision::COLL_KERN) && !sameCluster)     // ignore other kernable clusters
                             || (cNbor->flags() & SlotCollision::COLL_ISCOL))   // test against other collided glyphs
                       && !coll.mergeSlot(seg, nbor, cNbor, cNbor->shift(), !ignoreForKern, sameCluster, collides, false, dbgout))
             return false;
         else if (nbor == slotFix)
             // Switching sides of this glyph - if we were ignoring kernable stuff before, don't anymore.
             ignoreForKern = !ignoreForKern;
-            
+
         if (nbor != start && (cNbor->flags() & (isRev ? SlotCollision::COLL_START : SlotCollision::COLL_END)))
             break;
     }
     bool isCol = false;
     if (collides || cFix->shift().x != 0.f || cFix->shift().y != 0.f)
     {
         Position shift = coll.resolve(seg, isCol, dbgout);
         // isCol has been set to true if a collision remains.
@@ -1006,17 +1006,17 @@ bool Pass::resolveCollisions(Segment *se
         }
     }
     else
     {
         // This glyph is not colliding with anything.
 #if !defined GRAPHITE2_NTRACING
         if (dbgout)
         {
-            *dbgout << json::object 
+            *dbgout << json::object
                             << "missed" << objectid(dslot(seg, slotFix));
             coll.outputJsonDbg(dbgout, seg, -1);
             *dbgout << json::close;
         }
 #endif
     }
 
     // Set the is-collision flag bit.
@@ -1067,17 +1067,17 @@ float Pass::resolveKern(Segment *seg, Sl
             if (m_kernColls == InWord)
                 break;
             // Add space for a space glyph.
             currSpace += nbor->advance();
             ++space_count;
         }
         else
         {
-            space_count = 0; 
+            space_count = 0;
             if (nbor != slotFix && !cNbor->ignore())
             {
                 seenEnd = true;
                 if (!isInit)
                 {
                     if (!coll.initSlot(seg, slotFix, cFix->limit(), cFix->margin(),
                                     cFix->shift(), cFix->offset(), dir, ymin, ymax, dbgout))
                         return 0.;
@@ -1100,9 +1100,8 @@ float Pass::resolveKern(Segment *seg, Sl
         coll.shift(mv, dir);
         Position delta = slotFix->advancePos() + mv - cFix->shift();
         slotFix->advance(delta);
         cFix->setShift(mv);
         return mv.x;
     }
     return 0.;
 }
-
--- a/gfx/graphite2/src/Position.cpp
+++ b/gfx/graphite2/src/Position.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "inc/Position.h"
@@ -90,9 +90,8 @@ Position Rect::constrainedAvoid(Position
     { res = Position(is, is); beste = SQRT2 * (eis); }
     if (SQRT2 * (ead) < beste)
     { res = Position(ad, ad); beste = SQRT2 * (ead); }
     if (SQRT2 * (eid) < beste)
     { res = Position(id, id); beste = SQRT2 * (eid); }
     return res;
 }
 #endif
-
deleted file mode 100644
--- a/gfx/graphite2/src/SegCache.cpp
+++ /dev/null
@@ -1,224 +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.
-*/
-
-#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 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),
-  m_purgeFactor(1.0f / (ePurgeFactor * store->maxSegmentCount()))
-{
-    m_prefixes.raw = grzeroalloc<void*>(store->maxCmapGid() + 2);
-    m_prefixes.range[SEG_CACHE_MIN_INDEX] = SEG_CACHE_UNSET_INDEX;
-    m_prefixes.range[SEG_CACHE_MAX_INDEX] = SEG_CACHE_UNSET_INDEX;
-}
-
-void SegCache::freeLevel(SegCacheStore * store, SegCachePrefixArray prefixes, size_t level)
-{
-    for (size_t i = 0; i < store->maxCmapGid(); i++)
-    {
-        if (prefixes.array[i].raw)
-        {
-            if (level + 1 < ePrefixLength)
-                freeLevel(store, prefixes.array[i], level + 1);
-            else
-            {
-                SegCachePrefixEntry * prefixEntry = prefixes.prefixEntries[i];
-                delete prefixEntry;
-            }
-        }
-    }
-    free(prefixes.raw);
-}
-
-void SegCache::clear(SegCacheStore * store)
-{
-    freeLevel(store, m_prefixes, 0);
-    m_prefixes.raw = NULL;
-}
-
-SegCache::~SegCache()
-{
-    assert(m_prefixes.raw == NULL);
-}
-
-SegCacheEntry* SegCache::cache(SegCacheStore * store, const uint16* cmapGlyphs, size_t length, Segment * seg, size_t charOffset)
-{
-    uint16 pos = 0;
-    if (!length) return NULL;
-//    assert(length < m_maxCachedSegLength);
-    SegCachePrefixArray pArray = m_prefixes;
-    while (pos + 1 < m_prefixLength)
-    {
-        uint16 gid = (pos < length)? cmapGlyphs[pos] : 0;
-        if (!pArray.array[gid].raw)
-        {
-            pArray.array[gid].raw = grzeroalloc<void*>(store->maxCmapGid() + 2);
-            if (!pArray.array[gid].raw)
-                return NULL; // malloc failed
-            if (pArray.range[SEG_CACHE_MIN_INDEX] == SEG_CACHE_UNSET_INDEX)
-            {
-                pArray.range[SEG_CACHE_MIN_INDEX] = gid;
-                pArray.range[SEG_CACHE_MAX_INDEX] = gid;
-            }
-            else
-            {
-                if (gid < pArray.range[SEG_CACHE_MIN_INDEX])
-                    pArray.range[SEG_CACHE_MIN_INDEX] = gid;
-                else if (gid > pArray.range[SEG_CACHE_MAX_INDEX])
-                    pArray.range[SEG_CACHE_MAX_INDEX] = gid;
-            }
-        }
-        pArray = pArray.array[gid];
-        ++pos;
-    }
-    uint16 gid = (pos < length)? cmapGlyphs[pos] : 0;
-    SegCachePrefixEntry * prefixEntry = pArray.prefixEntries[gid];
-    if (!prefixEntry)
-    {
-        prefixEntry = new SegCachePrefixEntry();
-        pArray.prefixEntries[gid] = prefixEntry;
-        if (pArray.range[SEG_CACHE_MIN_INDEX] == SEG_CACHE_UNSET_INDEX)
-        {
-            pArray.range[SEG_CACHE_MIN_INDEX] = gid;
-            pArray.range[SEG_CACHE_MAX_INDEX] = gid;
-        }
-        else
-        {
-            if (gid < pArray.range[SEG_CACHE_MIN_INDEX])
-                pArray.range[SEG_CACHE_MIN_INDEX] = gid;
-            else if (gid > pArray.range[SEG_CACHE_MAX_INDEX])
-                pArray.range[SEG_CACHE_MAX_INDEX] = gid;
-        }
-    }
-    if (!prefixEntry) return NULL;
-    // if the cache is full run a purge - this is slow, since it walks the tree
-    if (m_segmentCount + 1 > store->maxSegmentCount())
-    {
-        purge(store);
-        assert(m_segmentCount < store->maxSegmentCount());
-    }
-    SegCacheEntry * pEntry = prefixEntry->cache(cmapGlyphs, length, seg, charOffset, m_totalAccessCount);
-    if (pEntry) ++m_segmentCount;
-    return pEntry;
-}
-
-void SegCache::purge(SegCacheStore * store)
-{
-    unsigned long long minAccessCount = static_cast<unsigned long long>(m_totalAccessCount * m_purgeFactor + 1);
-    if (minAccessCount < 2) minAccessCount = 2;
-    unsigned long long oldAccessTime = m_totalAccessCount - store->maxSegmentCount() / eAgeFactor;
-    purgeLevel(store, m_prefixes, 0, minAccessCount, oldAccessTime);
-}
-
-void SegCache::purgeLevel(SegCacheStore * store, SegCachePrefixArray prefixes, size_t level,
-                          unsigned long long minAccessCount, unsigned long long oldAccessTime)
-{
-    if (prefixes.range[SEG_CACHE_MIN_INDEX] == SEG_CACHE_UNSET_INDEX) return;
-    size_t maxGlyphCached = prefixes.range[SEG_CACHE_MAX_INDEX];
-    for (size_t i = prefixes.range[SEG_CACHE_MIN_INDEX]; i <= maxGlyphCached; i++)
-    {
-        if (prefixes.array[i].raw)
-        {
-            if (level + 1 < ePrefixLength)
-                purgeLevel(store, prefixes.array[i], level + 1, minAccessCount, oldAccessTime);
-            else
-            {
-                SegCachePrefixEntry * prefixEntry = prefixes.prefixEntries[i];
-                m_segmentCount -= prefixEntry->purge(minAccessCount,
-                    oldAccessTime, m_totalAccessCount);
-            }
-        }
-    }
-}
-
-uint32 SegCachePrefixEntry::purge(unsigned long long minAccessCount,
-                                              unsigned long long oldAccessTime,
-                                              unsigned long long currentTime)
-{
-    // ignore the purge request if another has been done recently
-    //if (m_lastPurge > oldAccessTime)
-    //    return 0;
-
-    uint32 totalPurged = 0;
-    // real length is length + 1 in this loop
-    for (uint16 length = 0; length < eMaxSpliceSize; length++)
-    {
-        if (m_entryCounts[length] == 0)
-            continue;
-        uint16 purgeCount = 0;
-        uint16 newIndex = 0;
-        for (uint16 j = 0; j < m_entryCounts[length]; j++)
-        {
-            SegCacheEntry & tempEntry = m_entries[length][j];
-            // purge entries with a low access count which haven't been
-            // accessed recently
-            if (tempEntry.accessCount() <= minAccessCount &&
-                tempEntry.lastAccess() <= oldAccessTime)
-            {
-                tempEntry.clear();
-                ++purgeCount;
-            }
-            else
-            {
-                memcpy(m_entries[length] + newIndex++, m_entries[length] + j, sizeof(SegCacheEntry));
-            }
-        }
-        if (purgeCount == m_entryCounts[length])
-        {
-            assert(newIndex == 0);
-            m_entryCounts[length] = 0;
-            m_entryBSIndex[length] = 0;
-            free(m_entries[length]);
-            m_entries[length] = NULL;
-        }
-        else if (purgeCount > 0)
-        {
-            assert(m_entryCounts[length] == newIndex + purgeCount);
-            m_entryCounts[length] = newIndex;
-        }
-        totalPurged += purgeCount;
-    }
-    m_lastPurge = currentTime;
-    return totalPurged;
-}
-
-#endif
deleted file mode 100644
--- a/gfx/graphite2/src/SegCacheEntry.cpp
+++ /dev/null
@@ -1,108 +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.
-*/
-
-#ifndef GRAPHITE2_NSEGCACHE
-
-#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_justs(NULL),
-    m_accessCount(0), m_lastAccess(cacheTime)
-{
-    if (m_unicode)
-        for (size_t i = 0; i < length; i++)
-            m_unicode[i] = cmapGlyphs[i];
-
-    const size_t    glyphCount = seg->slotCount(),
-                    sizeof_sjust = SlotJustify::size_of(seg->silf()->numJustLevels());
-    if (!glyphCount) return;
-    size_t num_justs = 0,
-           justs_pos = 0;
-    if (seg->hasJustification())
-    {
-        for (const Slot * s = seg->first(); s; s = s->next())
-        {
-            if (s->m_justs == 0)    continue;
-            ++num_justs;
-        }
-        m_justs = gralloc<byte>(sizeof_sjust * num_justs);
-    }
-    const Slot * slot = seg->first();
-    m_glyph = new Slot[glyphCount];
-    m_attr = gralloc<int16>(glyphCount * seg->numAttrs());
-    if (!m_glyph || (!m_attr && seg->numAttrs())) return;
-    m_glyphLength = glyphCount;
-    Slot * slotCopy = m_glyph;
-    m_glyph->prev(NULL);
-
-    uint16 pos = 0;
-    while (slot)
-    {
-        slotCopy->userAttrs(m_attr + pos * seg->numAttrs());
-        slotCopy->m_justs = m_justs ? reinterpret_cast<SlotJustify *>(m_justs + justs_pos++ * sizeof_sjust) : 0;
-        slotCopy->set(*slot, -static_cast<int32>(charOffset), seg->numAttrs(), seg->silf()->numJustLevels(), length);
-        slotCopy->index(pos);
-        if (slot->firstChild())
-            slotCopy->m_child = m_glyph + slot->firstChild()->index();
-        if (slot->attachedTo())
-            slotCopy->attachTo(m_glyph + slot->attachedTo()->index());
-        if (slot->nextSibling())
-            slotCopy->m_sibling = m_glyph + slot->nextSibling()->index();
-        slot = slot->next();
-        ++slotCopy;
-        ++pos;
-        if (slot)
-        {
-            slotCopy->prev(slotCopy-1);
-            (slotCopy-1)->next(slotCopy);
-        }
-    }
-}
-
-
-void SegCacheEntry::clear()
-{
-    free(m_unicode);
-    free(m_attr);
-    free(m_justs);
-    delete [] m_glyph;
-    m_unicode = NULL;
-    m_glyph = NULL;
-    m_glyphLength = 0;
-    m_attr = NULL;
-}
-
-#endif
-
deleted file mode 100644
--- a/gfx/graphite2/src/SegCacheStore.cpp
+++ /dev/null
@@ -1,47 +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.
-*/
-
-#ifndef GRAPHITE2_NSEGCACHE
-
-#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(face.glyphs().numGlyphs()),
-  m_spaceGid(face.cmap()[0x20]),
-  m_zwspGid(face.cmap()[0x200B])
-{
-}
-
-#endif
-
--- a/gfx/graphite2/src/Segment.cpp
+++ b/gfx/graphite2/src/Segment.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "inc/UtfCodec.h"
@@ -37,138 +37,71 @@ of the License or (at your option) any l
 #include "inc/Main.h"
 #include "inc/CmapCache.h"
 #include "inc/Collider.h"
 #include "graphite2/Segment.h"
 
 
 using namespace graphite2;
 
-Segment::Segment(unsigned int numchars, const Face* face, uint32 script, int textDir)
+Segment::Segment(size_t numchars, const Face* face, uint32 script, int textDir)
 : m_freeSlots(NULL),
   m_freeJustifies(NULL),
   m_charinfo(new CharInfo[numchars]),
   m_collisions(NULL),
   m_face(face),
   m_silf(face->chooseSilf(script)),
   m_first(NULL),
   m_last(NULL),
   m_bufSize(numchars + 10),
   m_numGlyphs(numchars),
   m_numCharinfo(numchars),
-  m_passBits(m_silf->aPassBits() ? -1 : 0),
   m_defaultOriginal(0),
   m_dir(textDir),
-  m_flags(((m_silf->flags() & 0x20) != 0) << 1)
+  m_flags(((m_silf->flags() & 0x20) != 0) << 1),
+  m_passBits(m_silf->aPassBits() ? -1 : 0)
 {
-    Slot *s = newSlot();
-    if (s)
-        freeSlot(s);
+    freeSlot(newSlot());
     m_bufSize = log_binary(numchars)+1;
 }
 
 Segment::~Segment()
 {
     for (SlotRope::iterator i = m_slots.begin(); i != m_slots.end(); ++i)
         free(*i);
     for (AttributeRope::iterator i = m_userAttrs.begin(); i != m_userAttrs.end(); ++i)
         free(*i);
     for (JustifyRope::iterator i = m_justifies.begin(); i != m_justifies.end(); ++i)
         free(*i);
     delete[] m_charinfo;
     free(m_collisions);
 }
 
-#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;
-    firstSlot->prev(NULL);
-    lastSlot->next(NULL);
-    assert(m_defaultOriginal == 0);
-    m_defaultOriginal = firstSlot->original();
-    m_numGlyphs = subLength;
-    m_first = firstSlot;
-    m_last = lastSlot;
-    return state;
-}
-
-void Segment::removeScope(SegmentScopeState & state)
-{
-    m_numGlyphs = state.numGlyphsOutsideScope + m_numGlyphs;
-    if (state.slotBeforeScope)
-    {
-        state.slotBeforeScope->next(m_first);
-        m_first->prev(state.slotBeforeScope);
-        m_first = state.realFirstSlot;
-    }
-    if (state.slotAfterScope)
-    {
-        state.slotAfterScope->prev(m_last);
-        m_last->next(state.slotAfterScope);
-        m_last = state.realLastSlot;
-    }
-    m_defaultOriginal = 0;
-}
-
-#if 0
-void Segment::append(const Segment &other)
-{
-    Rect bbox = other.m_bbox + m_advance;
-
-    m_slots.insert(m_slots.end(), other.m_slots.begin(), other.m_slots.end());
-    CharInfo* pNewCharInfo = new CharInfo[m_numCharinfo+other.m_numCharinfo];       //since CharInfo has no constructor, this doesn't do much
-    for (unsigned int i=0 ; i<m_numCharinfo ; ++i)
-    pNewCharInfo[i] = m_charinfo[i];
-    m_last->next(other.m_first);
-    other.m_last->prev(m_last);
-    m_userAttrs.insert(m_userAttrs.end(), other.m_userAttrs.begin(), other.m_userAttrs.end());
-    
-    delete[] m_charinfo;
-    m_charinfo = pNewCharInfo;
-    pNewCharInfo += m_numCharinfo ;
-    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);
-    m_passBits &= other.passBits();
-}
-#endif
-#endif // GRAPHITE2_NSEGCACHE
-
 void Segment::appendSlot(int id, int cid, int gid, int iFeats, size_t coffset)
 {
     Slot *aSlot = newSlot();
-    
+
     if (!aSlot) return;
     m_charinfo[id].init(cid);
     m_charinfo[id].feats(iFeats);
     m_charinfo[id].base(coffset);
     const GlyphFace * theGlyph = m_face->glyphs().glyphSafe(gid);
     m_charinfo[id].breakWeight(theGlyph ? theGlyph->attrs()[m_silf->aBreak()] : 0);
-    
+
     aSlot->child(NULL);
     aSlot->setGlyph(this, gid, theGlyph);
     aSlot->originate(id);
     aSlot->before(id);
     aSlot->after(id);
     if (m_last) m_last->next(aSlot);
     aSlot->prev(m_last);
     m_last = aSlot;
     if (!m_first) m_first = aSlot;
     if (theGlyph && m_silf->aPassBits())
-        m_passBits &= theGlyph->attrs()[m_silf->aPassBits()] 
+        m_passBits &= theGlyph->attrs()[m_silf->aPassBits()]
                     | (m_silf->numPasses() > 16 ? (theGlyph->attrs()[m_silf->aPassBits() + 1] << 16) : 0);
 }
 
 Slot *Segment::newSlot()
 {
     if (!m_freeSlots)
     {
         // check that the segment doesn't grow indefinintely
@@ -201,54 +134,55 @@ Slot *Segment::newSlot()
     Slot *res = m_freeSlots;
     m_freeSlots = m_freeSlots->next();
     res->next(NULL);
     return res;
 }
 
 void Segment::freeSlot(Slot *aSlot)
 {
+    if (aSlot == nullptr) return;
     if (m_last == aSlot) m_last = aSlot->prev();
     if (m_first == aSlot) m_first = aSlot->next();
     if (aSlot->attachedTo())
         aSlot->attachedTo()->removeChild(aSlot);
     while (aSlot->firstChild())
     {
         if (aSlot->firstChild()->attachedTo() == aSlot)
         {
-            aSlot->firstChild()->attachTo(NULL);
+            aSlot->firstChild()->attachTo(nullptr);
             aSlot->removeChild(aSlot->firstChild());
         }
         else
-            aSlot->firstChild(NULL);
+            aSlot->firstChild(nullptr);
     }
     // reset the slot incase it is reused
     ::new (aSlot) Slot(aSlot->userAttrs());
     memset(aSlot->userAttrs(), 0, m_silf->numUser() * sizeof(int16));
     // Update generation counter for debug
 #if !defined GRAPHITE2_NTRACING
     if (m_face->logger())
         ++aSlot->userAttrs()[m_silf->numUser()];
 #endif
     // update next pointer
     if (!m_freeSlots)
-        aSlot->next(NULL);
+        aSlot->next(nullptr);
     else
         aSlot->next(m_freeSlots);
     m_freeSlots = aSlot;
 }
 
 SlotJustify *Segment::newJustify()
 {
     if (!m_freeJustifies)
     {
         const size_t justSize = SlotJustify::size_of(m_silf->numJustLevels());
         byte *justs = grzeroalloc<byte>(justSize * m_bufSize);
         if (!justs) return NULL;
-        for (int i = m_bufSize - 2; i >= 0; --i)
+        for (ptrdiff_t i = m_bufSize - 2; i >= 0; --i)
         {
             SlotJustify *p = reinterpret_cast<SlotJustify *>(justs + justSize * i);
             SlotJustify *next = reinterpret_cast<SlotJustify *>(justs + justSize * (i + 1));
             p->next = next;
         }
         m_freeJustifies = (SlotJustify *)justs;
         m_justifies.push_back(m_freeJustifies);
     }
@@ -262,74 +196,16 @@ void Segment::freeJustify(SlotJustify *a
 {
     int numJust = m_silf->numJustLevels();
     if (m_silf->numJustLevels() <= 0) numJust = 1;
     aJustify->next = m_freeJustifies;
     memset(aJustify->values, 0, numJust*SlotJustify::NUMJUSTPARAMS*sizeof(int16));
     m_freeJustifies = aJustify;
 }
 
-#ifndef GRAPHITE2_NSEGCACHE
-void Segment::splice(size_t offset, size_t length, Slot * const startSlot,
-                       Slot * endSlot, const Slot * srcSlot,
-                       const size_t numGlyphs)
-{
-    size_t numChars = length;
-    extendLength(numGlyphs - length);
-    // remove any extra
-    if (numGlyphs < length)
-    {
-        Slot * end = endSlot->next();
-        do
-        {
-            endSlot = endSlot->prev();
-            freeSlot(endSlot->next());
-        } while (numGlyphs < --length);
-        endSlot->next(end);
-        if (end)
-            end->prev(endSlot);
-    }
-    else
-    {
-        // insert extra slots if needed
-        while (numGlyphs > length)
-        {
-            Slot * extra = newSlot();
-            if (!extra) return;
-            extra->prev(endSlot);
-            extra->next(endSlot->next());
-            endSlot->next(extra);
-            if (extra->next())
-                extra->next()->prev(extra);
-            if (m_last == endSlot)
-                m_last = extra;
-            endSlot = extra;
-            ++length;
-        }
-    }
-
-    endSlot = endSlot->next();
-    assert(numGlyphs == length);
-    assert(offset + numChars <= m_numCharinfo);
-    Slot * indexmap[eMaxSpliceSize*3];
-    assert(numGlyphs < sizeof indexmap/sizeof *indexmap);
-    Slot * slot = startSlot;
-    for (uint16 i=0; i < numGlyphs; slot = slot->next(), ++i)
-        indexmap[i] = slot;
-
-    for (slot = startSlot; slot != endSlot; slot = slot->next(), srcSlot = srcSlot->next())
-    {
-        slot->set(*srcSlot, offset, m_silf->numUser(), m_silf->numJustLevels(), numChars);
-        if (srcSlot->attachedTo())  slot->attachTo(indexmap[srcSlot->attachedTo()->index()]);
-        if (srcSlot->nextSibling()) slot->m_sibling = indexmap[srcSlot->nextSibling()->index()];
-        if (srcSlot->firstChild())  slot->m_child = indexmap[srcSlot->firstChild()->index()];
-    }
-}
-#endif // GRAPHITE2_NSEGCACHE
-
 // reverse the slots but keep diacritics in their same position after their bases
 void Segment::reverseSlots()
 {
     m_dir = m_dir ^ 64;                 // invert the reverse flag
     if (m_first == m_last) return;      // skip 0 or 1 glyph runs
 
     Slot *t = 0;
     Slot *curr = m_first;
@@ -447,17 +323,17 @@ Position Segment::positionSlots(const Fo
         }
     }
     if (reorder)
         reverseSlots();
     return currpos;
 }
 
 
-void Segment::associateChars(int offset, int numChars)
+void Segment::associateChars(int offset, size_t numChars)
 {
     int i = 0, j = 0;
     CharInfo *c, *cend;
     for (c = m_charinfo + offset, cend = m_charinfo + offset + numChars; c != cend; ++c)
     {
         c->before(-1);
         c->after(-1);
     }
@@ -471,17 +347,17 @@ void Segment::associateChars(int offset,
             c = charinfo(j);
             if (c->before() == -1 || i < c->before())   c->before(i);
             if (c->after() < i)                         c->after(i);
         }
     }
     for (Slot *s = m_first; s; s = s->next())
     {
         int a;
-        for (a = s->after() + 1; a < offset + numChars && charinfo(a)->after() < 0; ++a)
+        for (a = s->after() + 1; a < offset + int(numChars) && charinfo(a)->after() < 0; ++a)
         { charinfo(a)->after(s->index()); }
         --a;
         s->after(a);
 
         for (a = s->before() - 1; a >= offset && charinfo(a)->before() < 0; --a)
         { charinfo(a)->before(s->index()); }
         ++a;
         s->before(a);
--- a/gfx/graphite2/src/Silf.cpp
+++ b/gfx/graphite2/src/Silf.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <cstdlib>
@@ -194,18 +194,18 @@ bool Silf::readGraphite(const byte * con
     if (e || e.test(clen > unsigned(passes_start + silf_start - p), E_BADPASSESSTART)
           || e.test(!m_passes, E_OUTOFMEM))
     { releaseBuffers(); return face.error(e); }
 
     for (size_t i = 0; i < m_numPasses; ++i)
     {
         uint32 pass_start = be::read<uint32>(o_passes);
         uint32 pass_end = be::peek<uint32>(o_passes);
-        face.error_context((face.error_context() & 0xFF00) + EC_ASILF + (i << 16));
-        if (e.test(pass_start > pass_end, E_BADPASSSTART) 
+        face.error_context((face.error_context() & 0xFF00) + EC_ASILF + unsigned(i << 16));
+        if (e.test(pass_start > pass_end, E_BADPASSSTART)
                 || e.test(pass_start < passes_start, E_BADPASSSTART)
                 || e.test(pass_end > lSilf, E_BADPASSEND)) {
             releaseBuffers(); return face.error(e);
         }
 
         enum passtype pt = PASS_TYPE_UNKNOWN;
         if (i >= m_jPass) pt = PASS_TYPE_JUSTIFICATION;
         else if (i >= m_pPass) pt = PASS_TYPE_POSITIONING;
@@ -228,19 +228,19 @@ bool Silf::readGraphite(const byte * con
     m_silfinfo.line_ends = (m_flags & 1);
     m_silfinfo.space_contextuals = gr_faceinfo::gr_space_contextuals((m_flags >> 2) & 0x7);
     return true;
 }
 
 template<typename T> inline uint32 Silf::readClassOffsets(const byte *&p, size_t data_len, Error &e)
 {
     const T cls_off = 2*sizeof(uint16) + sizeof(T)*(m_nClass+1);
-    const size_t max_off = (be::peek<T>(p + sizeof(T)*m_nClass) - cls_off)/sizeof(uint16);
+    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 (e.test(be::peek<T>(p) != cls_off, E_MISALIGNEDCLASSES) 
+    if (e.test(be::peek<T>(p) != cls_off, E_MISALIGNEDCLASSES)
             || e.test(max_off > (data_len - cls_off)/sizeof(uint16), E_HIGHCLASSOFFSET))
         return ERROROFFSET;
 
     // Read in all the offsets.
     m_classOffsets = gralloc<uint32>(m_nClass+1);
     if (e.test(!m_classOffsets, E_OUTOFMEM)) return ERROROFFSET;
     for (uint32 * o = m_classOffsets, * const o_end = o + m_nClass + 1; o != o_end; ++o)
     {
@@ -352,17 +352,17 @@ uint16 Silf::getClassGlyph(uint16 cid, u
     }
     return 0;
 }
 
 
 bool Silf::runGraphite(Segment *seg, uint8 firstPass, uint8 lastPass, int dobidi) const
 {
     assert(seg != 0);
-    unsigned int       maxSize = seg->slotCount() * MAX_SEG_GROWTH_FACTOR;
+    size_t             maxSize = seg->slotCount() * MAX_SEG_GROWTH_FACTOR;
     SlotMap            map(*seg, m_dir, maxSize);
     FiniteStateMachine fsm(map, seg->getFace()->logger());
     vm::Machine        m(map);
     uint8              lbidi = m_bPass;
 #if !defined GRAPHITE2_NTRACING
     json * const dbgout = seg->getFace()->logger();
 #endif
 
--- a/gfx/graphite2/src/Slot.cpp
+++ b/gfx/graphite2/src/Slot.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "inc/Segment.h"
@@ -35,34 +35,34 @@ of the License or (at your option) any l
 using namespace graphite2;
 
 Slot::Slot(int16 *user_attrs) :
     m_next(NULL), m_prev(NULL),
     m_glyphid(0), m_realglyphid(0), m_original(0), m_before(0), m_after(0),
     m_index(0), m_parent(NULL), m_child(NULL), m_sibling(NULL),
     m_position(0, 0), m_shift(0, 0), m_advance(0, 0),
     m_attach(0, 0), m_with(0, 0), m_just(0.),
-    m_flags(0), m_attLevel(0), m_bidiCls(-1), m_bidiLevel(0), 
+    m_flags(0), m_attLevel(0), m_bidiCls(-1), m_bidiLevel(0),
     m_userAttr(user_attrs), m_justs(NULL)
 {
 }
 
 // take care, this does not copy any of the GrSlot pointer fields
 void Slot::set(const Slot & orig, int charOffset, size_t sizeAttr, size_t justLevels, size_t numChars)
 {
     // leave m_next and m_prev unchanged
     m_glyphid = orig.m_glyphid;
     m_realglyphid = orig.m_realglyphid;
     m_original = orig.m_original + charOffset;
     if (charOffset + int(orig.m_before) < 0)
         m_before = 0;
     else
         m_before = orig.m_before + charOffset;
     if (charOffset <= 0 && orig.m_after + charOffset >= numChars)
-        m_after = numChars - 1;
+        m_after = int(numChars) - 1;
     else
         m_after = orig.m_after + charOffset;
     m_parent = NULL;
     m_child = NULL;
     m_sibling = NULL;
     m_position = orig.m_position;
     m_shift = orig.m_shift;
     m_advance = orig.m_advance;
@@ -102,17 +102,17 @@ Position Slot::finalise(const Segment *s
     if (font)
     {
         scale = font->scale();
         shift *= scale;
         if (font->isHinted() && glyphFace)
             tAdvance = (m_advance.x - glyphFace->theAdvance().x + m_just) * scale + font->advance(glyph());
         else
             tAdvance *= scale;
-    }    
+    }
     Position res;
 
     m_position = base + shift;
     if (!m_parent)
     {
         res = base + Position(tAdvance, m_advance.y * scale);
         clusterMin = m_position.x;
     }
@@ -137,17 +137,17 @@ Position Slot::finalise(const Segment *s
         if ((!m_parent || m_advance.x >= 0.5f) && 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, attrLevel, clusterMin, rtl, isFinal, depth + 1);
         if (tRes.x > res.x) res = tRes;
     }
-    
+
     if (!m_parent && clusterMin < base.x)
     {
         Position adj = Position(m_position.x - clusterMin, 0.);
         res += adj;
         m_position += adj;
         if (m_child) m_child->floodShift(adj);
     }
     return res;
@@ -160,52 +160,45 @@ int32 Slot::clusterMetric(const Segment 
         return 0;
     Rect bbox = seg->theGlyphBBoxTemporary(glyph());
     float clusterMin = 0.;
     Position res = finalise(seg, NULL, base, bbox, attrLevel, clusterMin, rtl, false);
 
     switch (metrics(metric))
     {
     case kgmetLsb :
-        return bbox.bl.x;
+        return int32(bbox.bl.x);
     case kgmetRsb :
-        return res.x - bbox.tr.x;
+        return int32(res.x - bbox.tr.x);
     case kgmetBbTop :
-        return bbox.tr.y;
+        return int32(bbox.tr.y);
     case kgmetBbBottom :
-        return bbox.bl.y;
+        return int32(bbox.bl.y);
     case kgmetBbLeft :
-        return bbox.bl.x;
+        return int32(bbox.bl.x);
     case kgmetBbRight :
-        return bbox.tr.x;
+        return int32(bbox.tr.x);
     case kgmetBbWidth :
-        return bbox.tr.x - bbox.bl.x;
+        return int32(bbox.tr.x - bbox.bl.x);
     case kgmetBbHeight :
-        return bbox.tr.y - bbox.bl.y;
+        return int32(bbox.tr.y - bbox.bl.y);
     case kgmetAdvWidth :
-        return res.x;
+        return int32(res.x);
     case kgmetAdvHeight :
-        return res.y;
+        return int32(res.y);
     default :
         return 0;
     }
 }
 
 #define SLOTGETCOLATTR(x) { SlotCollision *c = seg->collisionInfo(this); return c ? int(c-> x) : 0; }
 
 int Slot::getAttr(const Segment *seg, attrCode ind, uint8 subindex) const
 {
-    if (ind == gr_slatUserDefnV1)
-    {
-        ind = gr_slatUserDefn;
-        subindex = 0;
-        if (seg->numAttrs() == 0)
-            return 0;
-    }
-    else if (ind >= gr_slatJStretch && ind < gr_slatJStretch + 20 && ind != gr_slatJWidth)
+    if (ind >= gr_slatJStretch && ind < gr_slatJStretch + 20 && ind != gr_slatJWidth)
     {
         int indx = ind - gr_slatJStretch;
         return getJustify(seg, indx / 5, indx % 5);
     }
 
     switch (ind)
     {
     case gr_slatAdvX :      return int(m_advance.x);
@@ -226,40 +219,42 @@ int Slot::getAttr(const Segment *seg, at
     case gr_slatInsert :    return isInsertBefore();
     case gr_slatPosX :      return int(m_position.x); // but need to calculate it
     case gr_slatPosY :      return int(m_position.y);
     case gr_slatShiftX :    return int(m_shift.x);
     case gr_slatShiftY :    return int(m_shift.y);
     case gr_slatMeasureSol: return -1; // err what's this?
     case gr_slatMeasureEol: return -1;
     case gr_slatJWidth:     return int(m_just);
-    case gr_slatUserDefn :  return m_userAttr[subindex];
+    case gr_slatUserDefnV1: subindex = 0; GR_FALLTHROUGH;
+      // no break
+    case gr_slatUserDefn :  return subindex < seg->numAttrs() ?  m_userAttr[subindex] : 0;
     case gr_slatSegSplit :  return seg->charinfo(m_original)->flags() & 3;
     case gr_slatBidiLevel:  return m_bidiLevel;
     case gr_slatColFlags :		{ SlotCollision *c = seg->collisionInfo(this); return c ? c->flags() : 0; }
-    case gr_slatColLimitblx :	SLOTGETCOLATTR(limit().bl.x)
-    case gr_slatColLimitbly :	SLOTGETCOLATTR(limit().bl.y)
-    case gr_slatColLimittrx :	SLOTGETCOLATTR(limit().tr.x)
-    case gr_slatColLimittry :	SLOTGETCOLATTR(limit().tr.y)
-    case gr_slatColShiftx :		SLOTGETCOLATTR(offset().x)
-    case gr_slatColShifty :		SLOTGETCOLATTR(offset().y)
-    case gr_slatColMargin :		SLOTGETCOLATTR(margin())
-    case gr_slatColMarginWt :	SLOTGETCOLATTR(marginWt())
-    case gr_slatColExclGlyph :	SLOTGETCOLATTR(exclGlyph())
-    case gr_slatColExclOffx :	SLOTGETCOLATTR(exclOffset().x)
-    case gr_slatColExclOffy :	SLOTGETCOLATTR(exclOffset().y)
-    case gr_slatSeqClass :		SLOTGETCOLATTR(seqClass())
-	case gr_slatSeqProxClass :	SLOTGETCOLATTR(seqProxClass())
-    case gr_slatSeqOrder :		SLOTGETCOLATTR(seqOrder())
-    case gr_slatSeqAboveXoff :	SLOTGETCOLATTR(seqAboveXoff())
-    case gr_slatSeqAboveWt :	SLOTGETCOLATTR(seqAboveWt())
-    case gr_slatSeqBelowXlim :	SLOTGETCOLATTR(seqBelowXlim())
-    case gr_slatSeqBelowWt :	SLOTGETCOLATTR(seqBelowWt())
-    case gr_slatSeqValignHt :	SLOTGETCOLATTR(seqValignHt())
-    case gr_slatSeqValignWt :	SLOTGETCOLATTR(seqValignWt())
+    case gr_slatColLimitblx:SLOTGETCOLATTR(limit().bl.x)
+    case gr_slatColLimitbly:SLOTGETCOLATTR(limit().bl.y)
+    case gr_slatColLimittrx:SLOTGETCOLATTR(limit().tr.x)
+    case gr_slatColLimittry:SLOTGETCOLATTR(limit().tr.y)
+    case gr_slatColShiftx :	SLOTGETCOLATTR(offset().x)
+    case gr_slatColShifty :	SLOTGETCOLATTR(offset().y)
+    case gr_slatColMargin :	SLOTGETCOLATTR(margin())
+    case gr_slatColMarginWt:SLOTGETCOLATTR(marginWt())
+    case gr_slatColExclGlyph:SLOTGETCOLATTR(exclGlyph())
+    case gr_slatColExclOffx:SLOTGETCOLATTR(exclOffset().x)
+    case gr_slatColExclOffy:SLOTGETCOLATTR(exclOffset().y)
+    case gr_slatSeqClass :	SLOTGETCOLATTR(seqClass())
+    case gr_slatSeqProxClass:SLOTGETCOLATTR(seqProxClass())
+    case gr_slatSeqOrder :	SLOTGETCOLATTR(seqOrder())
+    case gr_slatSeqAboveXoff:SLOTGETCOLATTR(seqAboveXoff())
+    case gr_slatSeqAboveWt: SLOTGETCOLATTR(seqAboveWt())
+    case gr_slatSeqBelowXlim:SLOTGETCOLATTR(seqBelowXlim())
+    case gr_slatSeqBelowWt:	SLOTGETCOLATTR(seqBelowWt())
+    case gr_slatSeqValignHt:SLOTGETCOLATTR(seqValignHt())
+    case gr_slatSeqValignWt:SLOTGETCOLATTR(seqValignWt())
     default : return 0;
     }
 }
 
 #define SLOTCOLSETATTR(x) { \
         SlotCollision *c = seg->collisionInfo(this); \
         if (c) { c-> x ; c->setFlags(c->flags() & ~SlotCollision::COLL_KNOWN); } \
         break; }
@@ -475,17 +470,17 @@ void Slot::setGlyph(Segment *seg, uint16
     if (m_realglyphid)
     {
         aGlyph = seg->getFace()->glyphs().glyphSafe(m_realglyphid);
         if (!aGlyph) aGlyph = theGlyph;
     }
     m_advance = Position(aGlyph->theAdvance().x, 0.);
     if (seg->silf()->aPassBits())
     {
-        seg->mergePassBits(theGlyph->attrs()[seg->silf()->aPassBits()]);
+        seg->mergePassBits(uint8(theGlyph->attrs()[seg->silf()->aPassBits()]));
         if (seg->silf()->numPasses() > 16)
             seg->mergePassBits(theGlyph->attrs()[seg->silf()->aPassBits()+1] << 16);
     }
 }
 
 void Slot::floodShift(Position adj, int depth)
 {
     if (depth > 100)
@@ -527,9 +522,8 @@ Slot * Slot::nextInCluster(const Slot *s
 
 bool Slot::isChildOf(const Slot *base) const
 {
     for (Slot *p = m_parent; p; p = p->m_parent)
         if (p == base)
             return true;
     return false;
 }
-
--- a/gfx/graphite2/src/TtfUtil.cpp
+++ b/gfx/graphite2/src/TtfUtil.cpp
@@ -10,33 +10,33 @@
 
     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 
+    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.
 */
 /*--------------------------------------------------------------------*//*:Ignore this sentence.
 
 File: TtfUtil.cpp
 Responsibility: Alan Ward
 Last reviewed: Not yet.
 
 Description
-    Implements the methods for TtfUtil class. This file should remain portable to any C++ 
+    Implements the methods for TtfUtil class. This file should remain portable to any C++
     environment by only using standard C++ and the TTF structurs defined in Tt.h.
 -------------------------------------------------------------------------------*//*:End Ignore*/
 
 
 /***********************************************************************************************
     Include files
 ***********************************************************************************************/
 // Language headers
@@ -55,17 +55,17 @@ Description
 
 /***********************************************************************************************
     Forward declarations
 ***********************************************************************************************/
 
 /***********************************************************************************************
     Local Constants and static variables
 ***********************************************************************************************/
-namespace 
+namespace
 {
 #ifdef ALL_TTFUTILS
     // max number of components allowed in composite glyphs
     const int kMaxGlyphComponents = 8;
 #endif
 
     template <int R, typename T>
     inline float fixed_to_float(const T f) {
@@ -74,77 +74,77 @@ namespace
 
 /*----------------------------------------------------------------------------------------------
     Table of standard Postscript glyph names. From Martin Hosken. Disagress with ttfdump.exe
 ---------------------------------------------------------------------------------------------*/
 #ifdef ALL_TTFUTILS
     const int kcPostNames = 258;
 
     const char * rgPostName[kcPostNames] = {
-        ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign", 
-        "dollar", "percent", "ampersand", "quotesingle", "parenleft", 
-        "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", 
-        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", 
-        "nine", "colon", "semicolon", "less", "equal", "greater", "question", 
-        "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
-        "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", 
-        "bracketleft", "backslash", "bracketright", "asciicircum", 
-        "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", "i", 
-        "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", 
-        "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", 
-        "Adieresis", "Aring", "Ccedilla", "Eacute", "Ntilde", "Odieresis", 
-        "Udieresis", "aacute", "agrave", "acircumflex", "adieresis", "atilde", 
-        "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis", 
-        "iacute", "igrave", "icircumflex", "idieresis", "ntilde", "oacute", 
-        "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", 
-        "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling", 
-        "section", "bullet", "paragraph", "germandbls", "registered", 
-        "copyright", "trademark", "acute", "dieresis", "notequal", "AE", 
-        "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", "yen", 
-        "mu", "partialdiff", "summation", "product", "pi", "integral", 
-        "ordfeminine", "ordmasculine", "Omega", "ae", "oslash", "questiondown", 
-        "exclamdown", "logicalnot", "radical", "florin", "approxequal", 
-        "Delta", "guillemotleft", "guillemotright", "ellipsis", "nonbreakingspace", 
-        "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", 
-        "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", 
-        "lozenge", "ydieresis", "Ydieresis", "fraction", "currency", 
-        "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", 
-        "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex", 
-        "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute", 
-        "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", 
-        "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi", 
-        "circumflex", "tilde", "macron", "breve", "dotaccent", "ring", 
-        "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash", 
-        "Scaron", "scaron", "Zcaron", "zcaron", "brokenbar", "Eth", "eth", 
-        "Yacute", "yacute", "Thorn", "thorn", "minus", "multiply", 
-        "onesuperior", "twosuperior", "threesuperior", "onehalf", "onequarter", 
-        "threequarters", "franc", "Gbreve", "gbreve", "Idotaccent", "Scedilla", 
-        "scedilla", "Cacute", "cacute", "Ccaron", "ccaron", 
+        ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign",
+        "dollar", "percent", "ampersand", "quotesingle", "parenleft",
+        "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash",
+        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
+        "nine", "colon", "semicolon", "less", "equal", "greater", "question",
+        "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
+        "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
+        "bracketleft", "backslash", "bracketright", "asciicircum",
+        "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", "i",
+        "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
+        "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde",
+        "Adieresis", "Aring", "Ccedilla", "Eacute", "Ntilde", "Odieresis",
+        "Udieresis", "aacute", "agrave", "acircumflex", "adieresis", "atilde",
+        "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis",
+        "iacute", "igrave", "icircumflex", "idieresis", "ntilde", "oacute",
+        "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave",
+        "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling",
+        "section", "bullet", "paragraph", "germandbls", "registered",
+        "copyright", "trademark", "acute", "dieresis", "notequal", "AE",
+        "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", "yen",
+        "mu", "partialdiff", "summation", "product", "pi", "integral",
+        "ordfeminine", "ordmasculine", "Omega", "ae", "oslash", "questiondown",
+        "exclamdown", "logicalnot", "radical", "florin", "approxequal",
+        "Delta", "guillemotleft", "guillemotright", "ellipsis", "nonbreakingspace",
+        "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash",
+        "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide",
+        "lozenge", "ydieresis", "Ydieresis", "fraction", "currency",
+        "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered",
+        "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex",
+        "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute",
+        "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex",
+        "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi",
+        "circumflex", "tilde", "macron", "breve", "dotaccent", "ring",
+        "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash",
+        "Scaron", "scaron", "Zcaron", "zcaron", "brokenbar", "Eth", "eth",
+        "Yacute", "yacute", "Thorn", "thorn", "minus", "multiply",
+        "onesuperior", "twosuperior", "threesuperior", "onehalf", "onequarter",
+        "threequarters", "franc", "Gbreve", "gbreve", "Idotaccent", "Scedilla",
+        "scedilla", "Cacute", "cacute", "Ccaron", "ccaron",
         "dcroat" };
 #endif
 
 } // end of namespace
 
 /***********************************************************************************************
     Methods
 ***********************************************************************************************/
 
 /* Note on error processing: The code guards against bad glyph ids being used to look up data
-in open ended tables (loca, hmtx). If the glyph id comes from a cmap this shouldn't happen 
-but it seems prudent to check for user errors here. The code does assume that data obtained 
-from the TTF file is valid otherwise (though the CheckTable method seeks to check for 
-obvious problems that might accompany a change in table versions). For example an invalid 
+in open ended tables (loca, hmtx). If the glyph id comes from a cmap this shouldn't happen
+but it seems prudent to check for user errors here. The code does assume that data obtained
+from the TTF file is valid otherwise (though the CheckTable method seeks to check for
+obvious problems that might accompany a change in table versions). For example an invalid
 offset in the loca table which could exceed the size of the glyf table is NOT trapped.
-Likewise if numberOf_LongHorMetrics in the hhea table is wrong, this will NOT be trapped, 
+Likewise if numberOf_LongHorMetrics in the hhea table is wrong, this will NOT be trapped,
 which could cause a lookup in the hmtx table to exceed the table length. Of course, TTF tables
 that are completely corrupt will cause unpredictable results. */
 
 /* Note on composite glyphs: Glyphs that have components that are themselves composites
-are not supported. IsDeepComposite can be used to test for this. False is returned from many 
-of the methods in this cases. It is unclear how to build composite glyphs in some cases, 
+are not supported. IsDeepComposite can be used to test for this. False is returned from many
+of the methods in this cases. It is unclear how to build composite glyphs in some cases,
 so this code represents my best guess until test cases can be found. See notes on the high-
 level GlyfPoints method. */
 namespace graphite2
 {
 namespace TtfUtil
 {
 
 
@@ -162,17 +162,17 @@ bool GetHeaderInfo(size_t & lOffset, siz
 }
 
 /*----------------------------------------------------------------------------------------------
     Check the offset table for expected data.
     Return true if success, false otherwise.
 ----------------------------------------------------------------------------------------------*/
 bool CheckHeader(const void * pHdr)
 {
-    const Sfnt::OffsetSubTable * pOffsetTable  
+    const Sfnt::OffsetSubTable * pOffsetTable
         = reinterpret_cast<const Sfnt::OffsetSubTable *>(pHdr);
 
     return pHdr && be::swap(pOffsetTable->scaler_type) == Sfnt::OffsetSubTable::TrueTypeWin;
 }
 
 /*----------------------------------------------------------------------------------------------
     Get offset and size of the table directory.
     Return true if successful, false otherwise.
@@ -180,32 +180,32 @@ bool CheckHeader(const void * pHdr)
 bool GetTableDirInfo(const void * pHdr, size_t & lOffset, size_t & lSize)
 {
     const Sfnt::OffsetSubTable * pOffsetTable
         = reinterpret_cast<const Sfnt::OffsetSubTable *>(pHdr);
 
     lOffset = offsetof(Sfnt::OffsetSubTable, table_directory);
     lSize   = be::swap(pOffsetTable->num_tables)
         * sizeof(Sfnt::OffsetSubTable::Entry);
-    
+
     return true;
 }
 
 
 /*----------------------------------------------------------------------------------------------
     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 
+    const Sfnt::OffsetSubTable * pOffsetTable
         = reinterpret_cast<const Sfnt::OffsetSubTable *>(pHdr);
     const size_t num_tables = be::swap(pOffsetTable->num_tables);
-    const Sfnt::OffsetSubTable::Entry 
+    const Sfnt::OffsetSubTable::Entry
         * entry_itr = reinterpret_cast<const Sfnt::OffsetSubTable::Entry *>(
             pTableDir),
         * const  dir_end = entry_itr + num_tables;
 
     if (num_tables > 40)
         return false;
 
     for (;entry_itr != dir_end; ++entry_itr) // 40 - safe guard
@@ -223,101 +223,101 @@ bool GetTableInfo(const Tag TableTag, co
 
 /*----------------------------------------------------------------------------------------------
     Check the specified table. Tests depend on the table type.
     Return true if successful, false otherwise.
 ----------------------------------------------------------------------------------------------*/
 bool CheckTable(const Tag TableId, const void * pTable, size_t lTableSize)
 {
     using namespace Sfnt;
-    
+
     if (pTable == 0 || lTableSize < 4) return false;
 
     switch(TableId)
     {
     case Tag::cmap: // cmap
     {
-        const Sfnt::CharacterCodeMap * const pCmap 
+        const Sfnt::CharacterCodeMap * const pCmap
             = reinterpret_cast<const Sfnt::CharacterCodeMap *>(pTable);
         if (lTableSize < sizeof(Sfnt::CharacterCodeMap))
             return false;
         return be::swap(pCmap->version) == 0;
     }
 
     case Tag::head: // head
     {
-        const Sfnt::FontHeader * const pHead 
+        const Sfnt::FontHeader * const pHead
             = reinterpret_cast<const Sfnt::FontHeader *>(pTable);
         if (lTableSize < sizeof(Sfnt::FontHeader))
             return false;
         bool r = be::swap(pHead->version) == OneFix
             && be::swap(pHead->magic_number) == FontHeader::MagicNumber
             && be::swap(pHead->glyph_data_format)
-                    == FontHeader::GlypDataFormat 
+                    == FontHeader::GlypDataFormat
             && (be::swap(pHead->index_to_loc_format)
-                    == FontHeader::ShortIndexLocFormat 
+                    == FontHeader::ShortIndexLocFormat
                 || be::swap(pHead->index_to_loc_format)
-                    == FontHeader::LongIndexLocFormat) 
+                    == FontHeader::LongIndexLocFormat)
             && sizeof(FontHeader) <= lTableSize;
         return r;
     }
 
     case Tag::post: // post
     {
-        const Sfnt::PostScriptGlyphName * const pPost 
+        const Sfnt::PostScriptGlyphName * const pPost
             = reinterpret_cast<const Sfnt::PostScriptGlyphName *>(pTable);
         if (lTableSize < sizeof(Sfnt::PostScriptGlyphName))
             return false;
         const fixed format = be::swap(pPost->format);
-        bool r = format == PostScriptGlyphName::Format1 
-            || format == PostScriptGlyphName::Format2 
-            || format == PostScriptGlyphName::Format3 
+        bool r = format == PostScriptGlyphName::Format1
+            || format == PostScriptGlyphName::Format2
+            || format == PostScriptGlyphName::Format3
             || format == PostScriptGlyphName::Format25;
         return r;
     }
 
     case Tag::hhea: // hhea
     {
-        const Sfnt::HorizontalHeader * pHhea = 
+        const Sfnt::HorizontalHeader * pHhea =
             reinterpret_cast<const Sfnt::HorizontalHeader *>(pTable);
         if (lTableSize < sizeof(Sfnt::HorizontalHeader))
             return false;
         bool r = be::swap(pHhea->version) == OneFix
             && be::swap(pHhea->metric_data_format) == 0
             && sizeof (Sfnt::HorizontalHeader) <= lTableSize;
         return r;
     }
 
     case Tag::maxp: // maxp
     {
-        const Sfnt::MaximumProfile * pMaxp = 
+        const Sfnt::MaximumProfile * pMaxp =
             reinterpret_cast<const Sfnt::MaximumProfile *>(pTable);
         if (lTableSize < sizeof(Sfnt::MaximumProfile))
             return false;
         bool r = be::swap(pMaxp->version) == OneFix
             && sizeof(Sfnt::MaximumProfile) <= lTableSize;
         return r;
     }
 
     case Tag::OS_2: // OS/2
     {
-        const Sfnt::Compatibility * pOs2 
+        const Sfnt::Compatibility * pOs2
             = reinterpret_cast<const Sfnt::Compatibility *>(pTable);
         if (be::swap(pOs2->version) == 0)
         { // OS/2 table version 1 size
-//          if (sizeof(Sfnt::Compatibility) 
-//                  - sizeof(uint32)*2 - sizeof(int16)*2 
+//          if (sizeof(Sfnt::Compatibility)
+//                  - sizeof(uint32)*2 - sizeof(int16)*2
 //                  - sizeof(uint16)*3 <= lTableSize)
             if (sizeof(Sfnt::Compatibility0) <= lTableSize)
                 return true;
         }
         else if (be::swap(pOs2->version) == 1)
         { // OS/2 table version 2 size
-//          if (sizeof(Sfnt::Compatibility) 
-//                  - sizeof(int16) *2 
+//          if (sizeof(Sfnt::Compatibility)
+//                  - sizeof(int16) *2
 //                  - sizeof(uint16)*3 <= lTableSize)
             if (sizeof(Sfnt::Compatibility1) <= lTableSize)
                 return true;
         }
         else if (be::swap(pOs2->version) == 2)
         { // OS/2 table version 3 size
             if (sizeof(Sfnt::Compatibility2) <= lTableSize)
                 return true;
@@ -329,17 +329,17 @@ bool CheckTable(const Tag TableId, const
         }
         else
             return false;
         break;
     }
 
     case Tag::name:
     {
-        const Sfnt::FontNames * pName 
+        const Sfnt::FontNames * pName
             = reinterpret_cast<const Sfnt::FontNames *>(pTable);
         if (lTableSize < sizeof(Sfnt::FontNames))
             return false;
         return be::swap(pName->format) == 0;
     }
 
     case Tag::glyf:
     {
@@ -355,136 +355,136 @@ bool CheckTable(const Tag TableId, const
 
 /*----------------------------------------------------------------------------------------------
     Return the number of glyphs in the font. Should never be less than zero.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 size_t GlyphCount(const void * pMaxp)
 {
-    const Sfnt::MaximumProfile * pTable = 
+    const Sfnt::MaximumProfile * pTable =
             reinterpret_cast<const Sfnt::MaximumProfile *>(pMaxp);
     return be::swap(pTable->num_glyphs);
 }
 
 #ifdef ALL_TTFUTILS
 /*----------------------------------------------------------------------------------------------
     Return the maximum number of components for any composite glyph in the font.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 size_t  MaxCompositeComponentCount(const void * pMaxp)
 {
-    const Sfnt::MaximumProfile * pTable = 
+    const Sfnt::MaximumProfile * pTable =
             reinterpret_cast<const Sfnt::MaximumProfile *>(pMaxp);
     return be::swap(pTable->max_component_elements);
 }
 
 /*----------------------------------------------------------------------------------------------
     Composite glyphs can be composed of glyphs that are themselves composites.
     This method returns the maximum number of levels like this for any glyph in the font.
     A non-composite glyph has a level of 1.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 size_t  MaxCompositeLevelCount(const void * pMaxp)
 {
-    const Sfnt::MaximumProfile * pTable = 
+    const Sfnt::MaximumProfile * pTable =
             reinterpret_cast<const Sfnt::MaximumProfile *>(pMaxp);
     return be::swap(pTable->max_component_depth);
 }
 
 /*----------------------------------------------------------------------------------------------
     Return the number of glyphs in the font according to a differt source.
     Should never be less than zero. Return -1 on failure.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 size_t LocaGlyphCount(size_t lLocaSize, const void * pHead) //throw(std::domain_error)
 {
 
-    const Sfnt::FontHeader * pTable 
+    const Sfnt::FontHeader * pTable
         = reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 
     if (be::swap(pTable->index_to_loc_format)
         == Sfnt::FontHeader::ShortIndexLocFormat)
     // loca entries are two bytes and have been divided by two
         return (lLocaSize >> 1) - 1;
-    
+
     if (be::swap(pTable->index_to_loc_format)
         == Sfnt::FontHeader::LongIndexLocFormat)
      // loca entries are four bytes
         return (lLocaSize >> 2) - 1;
 
     return -1;
     //throw std::domain_error("head table in inconsistent state. The font may be corrupted");
 }
 #endif
 
 /*----------------------------------------------------------------------------------------------
     Return the design units the font is designed with
 ----------------------------------------------------------------------------------------------*/
 int DesignUnits(const void * pHead)
 {
-    const Sfnt::FontHeader * pTable = 
+    const Sfnt::FontHeader * pTable =
             reinterpret_cast<const Sfnt::FontHeader *>(pHead);
-    
+
     return be::swap(pTable->units_per_em);
 }
 
 #ifdef ALL_TTFUTILS
 /*----------------------------------------------------------------------------------------------
     Return the checksum from the head table, which serves as a unique identifer for the font.
 ----------------------------------------------------------------------------------------------*/
 int HeadTableCheckSum(const void * pHead)
 {
-    const Sfnt::FontHeader * pTable = 
+    const Sfnt::FontHeader * pTable =
             reinterpret_cast<const Sfnt::FontHeader *>(pHead);
-    
+
     return be::swap(pTable->check_sum_adjustment);
 }
 
 /*----------------------------------------------------------------------------------------------
     Return the create time from the head table. This consists of a 64-bit integer, which
     we return here as two 32-bit integers.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 void HeadTableCreateTime(const void * pHead,
     unsigned int * pnDateBC, unsigned int * pnDateAD)
 {
-    const Sfnt::FontHeader * pTable = 
+    const Sfnt::FontHeader * pTable =
             reinterpret_cast<const Sfnt::FontHeader *>(pHead);
-    
+
     *pnDateBC = be::swap(pTable->created[0]);
     *pnDateAD = be::swap(pTable->created[1]);
 }
 
 /*----------------------------------------------------------------------------------------------
     Return the modify time from the head table.This consists of a 64-bit integer, which
     we return here as two 32-bit integers.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 void HeadTableModifyTime(const void * pHead,
     unsigned int * pnDateBC, unsigned int *pnDateAD)
 {
-    const Sfnt::FontHeader * pTable = 
+    const Sfnt::FontHeader * pTable =
             reinterpret_cast<const Sfnt::FontHeader *>(pHead);
-   ; 
+   ;
     *pnDateBC = be::swap(pTable->modified[0]);
     *pnDateAD = be::swap(pTable->modified[1]);
 }
 
 /*----------------------------------------------------------------------------------------------
     Return true if the font is italic.
 ----------------------------------------------------------------------------------------------*/
 bool IsItalic(const void * pHead)
 {
-    const Sfnt::FontHeader * pTable = 
+    const Sfnt::FontHeader * pTable =
             reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 
     return ((be::swap(pTable->mac_style) & 0x00000002) != 0);
 }
 
 /*----------------------------------------------------------------------------------------------
     Return the ascent for the font
 ----------------------------------------------------------------------------------------------*/
@@ -513,17 +513,17 @@ int FontDescent(const void * pOs2)
         the sub-family name in the name table (though this can contain oblique, dark, etc too)
 ----------------------------------------------------------------------------------------------*/
 bool FontOs2Style(const void *pOs2, bool & fBold, bool & fItalic)
 {
     const Sfnt::Compatibility * pTable = reinterpret_cast<const Sfnt::Compatibility *>(pOs2);
 
     fBold = (be::swap(pTable->fs_selection) & Sfnt::Compatibility::Bold) != 0;
     fItalic = (be::swap(pTable->fs_selection) & Sfnt::Compatibility::Italic) != 0;
-    
+
     return true;
 }
 #endif
 
 /*----------------------------------------------------------------------------------------------
     Method for searching name table.
 ----------------------------------------------------------------------------------------------*/
 bool GetNameInfo(const void * pName, int nPlatformId, int nEncodingId,
@@ -610,74 +610,74 @@ int GetLangsForNames(const void * pName,
 
 /*----------------------------------------------------------------------------------------------
     Get the offset and size of the font family name in English for the MS Platform with Unicode
     writing system. The offset is within the pName data. The string is double byte with MSB
     first.
 ----------------------------------------------------------------------------------------------*/
 bool Get31EngFamilyInfo(const void * pName, size_t & lOffset, size_t & lSize)
 {
-    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 1, 1033, 
+    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 1, 1033,
         Sfnt::NameRecord::Family, lOffset, lSize);
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the offset and size of the full font name in English for the MS Platform with Unicode
     writing system. The offset is within the pName data. The string is double byte with MSB
     first.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 bool Get31EngFullFontInfo(const void * pName, size_t & lOffset, size_t & lSize)
 {
-    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 1, 1033, 
+    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 1, 1033,
         Sfnt::NameRecord::Fullname, lOffset, lSize);
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the offset and size of the font family name in English for the MS Platform with Symbol
     writing system. The offset is within the pName data. The string is double byte with MSB
     first.
 ----------------------------------------------------------------------------------------------*/
 bool Get30EngFamilyInfo(const void * pName, size_t & lOffset, size_t & lSize)
 {
-    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 0, 1033, 
+    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 0, 1033,
         Sfnt::NameRecord::Family, lOffset, lSize);
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the offset and size of the full font name in English for the MS Platform with Symbol
     writing system. The offset is within the pName data. The string is double byte with MSB
     first.
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
 bool Get30EngFullFontInfo(const void * pName, size_t & lOffset, size_t & lSize)
 {
-    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 0, 1033, 
+    return GetNameInfo(pName, Sfnt::NameRecord::Microsoft, 0, 1033,
         Sfnt::NameRecord::Fullname, lOffset, lSize);
 }
 
 /*----------------------------------------------------------------------------------------------
     Return the Glyph ID for a given Postscript name. This method finds the first glyph which
-    matches the requested Postscript name. Ideally every glyph should have a unique Postscript 
+    matches the requested Postscript name. Ideally every glyph should have a unique Postscript
     name (except for special names such as .notdef), but this is not always true.
     On failure return value less than zero.
        -1 - table search failed
        -2 - format 3 table (no Postscript glyph info)
        -3 - other failures
 
     Note: this method is not currently used by the Graphite engine.
 ----------------------------------------------------------------------------------------------*/
-int PostLookup(const void * pPost, size_t lPostSize, const void * pMaxp, 
+int PostLookup(const void * pPost, size_t lPostSize, const void * pMaxp,
                         const char * pPostName)
 {
     using namespace Sfnt;
-    
-    const Sfnt::PostScriptGlyphName * pTable 
+
+    const Sfnt::PostScriptGlyphName * pTable
         = reinterpret_cast<const Sfnt::PostScriptGlyphName *>(pPost);
     fixed format = be::swap(pTable->format);
 
     if (format == PostScriptGlyphName::Format3)
     { // format 3 - no Postscript glyph info in font
         return -2;
     }
 
@@ -691,39 +691,39 @@ int PostLookup(const void * pPost, size_
             break;
         }
     }
 
     if (format == PostScriptGlyphName::Format1)
     { // format 1 - use standard Postscript names
         return iPostName;
     }
-    
+
     if (format == PostScriptGlyphName::Format25)
-    { 
+    {
         if (iPostName == -1)
             return -1;
-        
-        const PostScriptGlyphName25 * pTable25 
+
+        const PostScriptGlyphName25 * pTable25
             = static_cast<const PostScriptGlyphName25 *>(pTable);
         int cnGlyphs = GlyphCount(pMaxp);
-        for (gid16 nGlyphId = 0; nGlyphId < cnGlyphs && nGlyphId < kcPostNames; 
+        for (gid16 nGlyphId = 0; nGlyphId < cnGlyphs && nGlyphId < kcPostNames;
                 nGlyphId++)
         { // glyph_name_index25 contains bytes so no byte swapping needed
-          // search for first glyph id that uses the standard name 
+          // search for first glyph id that uses the standard name
             if (nGlyphId + pTable25->offset[nGlyphId] == iPostName)
                 return nGlyphId;
         }
     }
 
     if (format == PostScriptGlyphName::Format2)
     { // format 2
-        const PostScriptGlyphName2 * pTable2 
+        const PostScriptGlyphName2 * pTable2
             = static_cast<const PostScriptGlyphName2 *>(pTable);
-        
+
         int cnGlyphs = be::swap(pTable2->number_of_glyphs);
 
         if (iPostName != -1)
         { // did match a standard name, look for first glyph id mapped to that name
             for (gid16 nGlyphId = 0; nGlyphId < cnGlyphs; nGlyphId++)
             {
                 if (be::swap(pTable2->glyph_name_index[nGlyphId]) == iPostName)
                     return nGlyphId;
@@ -732,19 +732,19 @@ int PostLookup(const void * pPost, size_
 
         { // did not match a standard name, search font specific names
             size_t nStrSizeGoal = strlen(pPostName);
             const char * pFirstGlyphName = reinterpret_cast<const char *>(
                 &pTable2->glyph_name_index[0] + cnGlyphs);
             const char * pGlyphName = pFirstGlyphName;
             int iInNames = 0; // index in font specific names
             bool fFound = false;
-            const char * const endOfTable 
+            const char * const endOfTable
                 = reinterpret_cast<const char *>(pTable2) + lPostSize;
-            while (pGlyphName < endOfTable && !fFound) 
+            while (pGlyphName < endOfTable && !fFound)
             { // search Pascal strings for first matching name
                 size_t nStringSize = size_t(*pGlyphName);
                 if (nStrSizeGoal != nStringSize ||
                     strncmp(pGlyphName + 1, pPostName, nStringSize))
                 { // did not match
                     ++iInNames;
                     pGlyphName += nStringSize + 1;
                 }
@@ -765,22 +765,22 @@ int PostLookup(const void * pPost, size_
             return -1; // no glyph mapped to this index (very strange)
         }
     }
 
     return -3;
 }
 
 /*----------------------------------------------------------------------------------------------
-    Convert a Unicode character string from big endian (MSB first, Motorola) format to little 
-    endian (LSB first, Intel) format. 
-    nSize is the number of Unicode characters in the string. It should not include any 
-    terminating null. If nSize is 0, it is assumed the string is null terminated. nSize 
+    Convert a Unicode character string from big endian (MSB first, Motorola) format to little
+    endian (LSB first, Intel) format.
+    nSize is the number of Unicode characters in the string. It should not include any
+    terminating null. If nSize is 0, it is assumed the string is null terminated. nSize
     defaults to 0.
-    Return true if successful, false otherwise. 
+    Return true if successful, false otherwise.
 ----------------------------------------------------------------------------------------------*/
 void SwapWString(void * pWStr, size_t nSize /* = 0 */) //throw (std::invalid_argument)
 {
     if (pWStr == 0)
     {
 //      throw std::invalid_argument("null pointer given");
         return;
     }
@@ -798,27 +798,27 @@ void SwapWString(void * pWStr, size_t nS
 //      }
 }
 #endif
 
 /*----------------------------------------------------------------------------------------------
     Get the left-side bearing and and advance width based on the given tables and Glyph ID
     Return true if successful, false otherwise. On false, one or both value could be INT_MIN
 ----------------------------------------------------------------------------------------------*/
-bool HorMetrics(gid16 nGlyphId, const void * pHmtx, size_t lHmtxSize, const void * pHhea, 
+bool HorMetrics(gid16 nGlyphId, const void * pHmtx, size_t lHmtxSize, const void * pHhea,
                          int & nLsb, unsigned int & nAdvWid)
 {
-    const Sfnt::HorizontalMetric * phmtx = 
+    const Sfnt::HorizontalMetric * phmtx =
         reinterpret_cast<const Sfnt::HorizontalMetric *>(pHmtx);
 
-    const Sfnt::HorizontalHeader * phhea = 
+    const Sfnt::HorizontalHeader * phhea =
         reinterpret_cast<const Sfnt::HorizontalHeader *>(pHhea);
 
     size_t cLongHorMetrics = be::swap(phhea->num_long_hor_metrics);
-    if (nGlyphId < cLongHorMetrics) 
+    if (nGlyphId < cLongHorMetrics)
     {   // glyph id is acceptable
         if ((nGlyphId + 1) * sizeof(Sfnt::HorizontalMetric) > lHmtxSize) return false;
         nAdvWid = be::swap(phmtx[nGlyphId].advance_width);
         nLsb = be::swap(phmtx[nGlyphId].left_side_bearing);
     }
     else
     {
         // guard against bad glyph id
@@ -894,17 +894,17 @@ const void * FindCmapSubtable(const void
 /*----------------------------------------------------------------------------------------------
     Check the Microsoft Unicode subtable for expected values
 ----------------------------------------------------------------------------------------------*/
 bool CheckCmapSubtable4(const void * pCmapSubtable4, const void * pCmapEnd /*, unsigned int maxgid*/)
 {
     size_t table_len = (const byte *)pCmapEnd - (const byte *)pCmapSubtable4;
     if (!pCmapSubtable4) return false;
     const Sfnt::CmapSubTable * pTable = reinterpret_cast<const Sfnt::CmapSubTable *>(pCmapSubtable4);
-    // Bob H say some freeware TT fonts have version 1 (eg, CALIGULA.TTF) 
+    // Bob H say some freeware TT fonts have version 1 (eg, CALIGULA.TTF)
     // so don't check subtable version. 21 Mar 2002 spec changes version to language.
     if (table_len < sizeof(*pTable) || be::swap(pTable->format) != 4) return false;
     const Sfnt::CmapSubTableFormat4 * pTable4 = reinterpret_cast<const Sfnt::CmapSubTableFormat4 *>(pCmapSubtable4);
     if (table_len < sizeof(*pTable4))
         return false;
     uint16 length = be::swap(pTable4->length);
     if (length > table_len)
         return false;
@@ -953,17 +953,17 @@ bool CheckCmapSubtable4(const void * pCm
     (Actually this code only depends on subtable being format 4.)
     Return 0 if the Unicode ID is not in the subtable.
 ----------------------------------------------------------------------------------------------*/
 gid16 CmapSubtable4Lookup(const void * pCmapSubtabel4, unsigned int nUnicodeId, int rangeKey)
 {
     const Sfnt::CmapSubTableFormat4 * pTable = reinterpret_cast<const Sfnt::CmapSubTableFormat4 *>(pCmapSubtabel4);
 
     uint16 nSeg = be::swap(pTable->seg_count_x2) >> 1;
-  
+
     uint16 n;
     const uint16 * pLeft, * pMid;
     uint16 cMid, chStart, chEnd;
 
     if (rangeKey)
     {
         pMid = &(pTable->end_code[rangeKey]);
         chEnd = be::peek<uint16>(pMid);
@@ -1206,18 +1206,18 @@ unsigned int CmapSubtable12NextCodepoint
 
 /*----------------------------------------------------------------------------------------------
     Return the offset stored in the loca table for the given Glyph ID.
     (This offset is into the glyf table.)
     Return -1 if the lookup failed.
     Technically this method should return an unsigned long but it is unlikely the offset will
         exceed 2^31.
 ----------------------------------------------------------------------------------------------*/
-size_t LocaLookup(gid16 nGlyphId, 
-        const void * pLoca, size_t lLocaSize, 
+size_t LocaLookup(gid16 nGlyphId,
+        const void * pLoca, size_t lLocaSize,
         const void * pHead) // throw (std::out_of_range)
 {
     const Sfnt::FontHeader * pTable = reinterpret_cast<const Sfnt::FontHeader *>(pHead);
     size_t res = -2;
 
     // 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
@@ -1247,26 +1247,26 @@ size_t LocaLookup(gid16 nGlyphId,
 
 /*----------------------------------------------------------------------------------------------
     Return a pointer into the glyf table based on the given offset (from LocaLookup).
     Return NULL on error.
 ----------------------------------------------------------------------------------------------*/
 void * GlyfLookup(const void * pGlyf, size_t nGlyfOffset, size_t nTableLen)
 {
     const uint8 * pByte = reinterpret_cast<const uint8 *>(pGlyf);
-        if (nGlyfOffset + pByte < pByte || nGlyfOffset >= nTableLen - sizeof(Sfnt::Glyph))
-            return NULL;
+    if (OVERFLOW_OFFSET_CHECK(pByte, nGlyfOffset) || nGlyfOffset >= nTableLen - sizeof(Sfnt::Glyph))
+        return NULL;
     return const_cast<uint8 *>(pByte + nGlyfOffset);
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the bounding box coordinates for a simple glyf entry (non-composite).
     Return true if successful, false otherwise.
 ----------------------------------------------------------------------------------------------*/
-bool GlyfBox(const void * pSimpleGlyf, int & xMin, int & yMin, 
+bool GlyfBox(const void * pSimpleGlyf, int & xMin, int & yMin,
                       int & xMax, int & yMax)
 {
     const Sfnt::Glyph * pGlyph = reinterpret_cast<const Sfnt::Glyph *>(pSimpleGlyf);
 
     xMin = be::swap(pGlyph->x_min);
     yMin = be::swap(pGlyph->y_min);
     xMax = be::swap(pGlyph->x_max);
     yMax = be::swap(pGlyph->y_max);
@@ -1282,24 +1282,24 @@ bool GlyfBox(const void * pSimpleGlyf, i
 int GlyfContourCount(const void * pSimpleGlyf)
 {
     const Sfnt::Glyph * pGlyph = reinterpret_cast<const Sfnt::Glyph *>(pSimpleGlyf);
     return be::swap(pGlyph->number_of_contours); // -1 means composite glyph
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the point numbers for the end points of the glyph contours for a simple
-    glyf entry (non-composite). 
+    glyf entry (non-composite).
     cnPointsTotal - count of contours from GlyfContourCount(); (same as number of end points)
     prgnContourEndPoints - should point to a buffer large enough to hold cnPoints integers
     cnPoints - count of points placed in above range
     Return true if successful, false otherwise.
         False could indicate a multi-level composite glyphs.
 ----------------------------------------------------------------------------------------------*/
-bool GlyfContourEndPoints(const void * pSimpleGlyf, int * prgnContourEndPoint, 
+bool GlyfContourEndPoints(const void * pSimpleGlyf, int * prgnContourEndPoint,
                                    int cnPointsTotal, int & cnPoints)
 {
     const Sfnt::SimpleGlyph * pGlyph = reinterpret_cast<const Sfnt::SimpleGlyph *>(pSimpleGlyf);
 
     int cContours = be::swap(pGlyph->number_of_contours);
     if (cContours < 0)
         return false; // this method isn't supposed handle composite glyphs
 
@@ -1311,42 +1311,42 @@ bool GlyfContourEndPoints(const void * p
     cnPoints = cContours;
     return true;
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the points for a simple glyf entry (non-composite)
     cnPointsTotal - count of points from largest end point obtained from GlyfContourEndPoints
     prgnX & prgnY - should point to buffers large enough to hold cnPointsTotal integers
-        The ranges are parallel so that coordinates for point(n) are found at offset n in both 
+        The ranges are parallel so that coordinates for point(n) are found at offset n in both
         ranges. This is raw point data with relative coordinates.
     prgbFlag - should point to a buffer a large enough to hold cnPointsTotal bytes
         This range is parallel to the prgnX & prgnY
     cnPoints - count of points placed in above ranges
-    Return true if successful, false otherwise. 
+    Return true if successful, false otherwise.
         False could indicate a composite glyph
 ----------------------------------------------------------------------------------------------*/
-bool GlyfPoints(const void * pSimpleGlyf, int * prgnX, int * prgnY, 
+bool GlyfPoints(const void * pSimpleGlyf, int * prgnX, int * prgnY,
         char * prgbFlag, int cnPointsTotal, int & cnPoints)
 {
     using namespace Sfnt;
-    
+
     const Sfnt::SimpleGlyph * pGlyph = reinterpret_cast<const Sfnt::SimpleGlyph *>(pSimpleGlyf);
     int cContours = be::swap(pGlyph->number_of_contours);
     // return false for composite glyph
     if (cContours <= 0)
         return false;
     int cPts = be::swap(pGlyph->end_pts_of_contours[cContours - 1]) + 1;
     if (cPts > cnPointsTotal)
         return false;
 
     // skip over bounding box data & point to byte count of instructions (hints)
     const uint8 * pbGlyph = reinterpret_cast<const uint8 *>
         (&pGlyph->end_pts_of_contours[cContours]);
-    
+
     // skip over hints & point to first flag
     int cbHints = be::swap(*(uint16 *)pbGlyph);
     pbGlyph += sizeof(uint16);
     pbGlyph += cbHints;
 
     // load flags & point to first x coordinate
     int iFlag = 0;
     while (iFlag < cPts)
@@ -1398,17 +1398,17 @@ bool GlyfPoints(const void * pSimpleGlyf
             else
             {
                 prgnX[iFlag] = be::swap(*(int16 *)pbGlyph);
                 pbGlyph += sizeof(int16);
             }
         }
         iFlag++;
     }
-        
+
     // load y coordinates
     iFlag = 0;
     while (iFlag < cPts)
     {
         if (prgbFlag[iFlag] & SimpleGlyph::YShort)
         {
             prgnY[iFlag] = *pbGlyph;
             if (!(prgbFlag[iFlag] & SimpleGlyph::YIsPos))
@@ -1427,51 +1427,51 @@ bool GlyfPoints(const void * pSimpleGlyf
             else
             {
                 prgnY[iFlag] = be::swap(*(int16 *)pbGlyph);
                 pbGlyph += sizeof(int16);
             }
         }
         iFlag++;
     }
-        
+
     cnPoints = cPts;
     return true;
 }
 
 /*----------------------------------------------------------------------------------------------
     Fill prgnCompId with the component Glyph IDs from pSimpleGlyf.
     Client must allocate space before calling.
     pSimpleGlyf - assumed to point to a composite glyph
-    cCompIdTotal - the number of elements in prgnCompId 
+    cCompIdTotal - the number of elements in prgnCompId
     cCompId  - the total number of Glyph IDs stored in prgnCompId
     Return true if successful, false otherwise
         False could indicate a non-composite glyph or the input array was not big enough
 ----------------------------------------------------------------------------------------------*/
-bool GetComponentGlyphIds(const void * pSimpleGlyf, int * prgnCompId, 
+bool GetComponentGlyphIds(const void * pSimpleGlyf, int * prgnCompId,
         size_t cnCompIdTotal, size_t & cnCompId)
 {
     using namespace Sfnt;
-    
+
     if (GlyfContourCount(pSimpleGlyf) >= 0)
         return false;
 
     const Sfnt::SimpleGlyph * pGlyph = reinterpret_cast<const Sfnt::SimpleGlyph *>(pSimpleGlyf);
     // for a composite glyph, the special data begins here
     const uint8 * pbGlyph = reinterpret_cast<const uint8 *>(&pGlyph->end_pts_of_contours[0]);
 
     uint16 GlyphFlags;
     size_t iCurrentComp = 0;
-    do 
+    do
     {
         GlyphFlags = be::swap(*((uint16 *)pbGlyph));
         pbGlyph += sizeof(uint16);
         prgnCompId[iCurrentComp++] = be::swap(*((uint16 *)pbGlyph));
         pbGlyph += sizeof(uint16);
-        if (iCurrentComp >= cnCompIdTotal) 
+        if (iCurrentComp >= cnCompIdTotal)
             return false;
         int nOffset = 0;
         nOffset += GlyphFlags & CompoundGlyph::Arg1Arg2Words ? 4 : 2;
         nOffset += GlyphFlags & CompoundGlyph::HaveScale ? 2 : 0;
         nOffset += GlyphFlags & CompoundGlyph::HaveXAndYScale  ? 4 : 0;
         nOffset += GlyphFlags & CompoundGlyph::HaveTwoByTwo  ? 8 :  0;
         pbGlyph += nOffset;
     } while (GlyphFlags & CompoundGlyph::MoreComponents);
@@ -1490,26 +1490,26 @@ bool GetComponentGlyphIds(const void * p
                 preceding glyph
     Return true if successful, false otherwise
         False could indicate a non-composite glyph or that component wasn't found
 ----------------------------------------------------------------------------------------------*/
 bool GetComponentPlacement(const void * pSimpleGlyf, int nCompId,
                                     bool fOffset, int & a, int & b)
 {
     using namespace Sfnt;
-    
+
     if (GlyfContourCount(pSimpleGlyf) >= 0)
         return false;
 
     const Sfnt::SimpleGlyph * pGlyph = reinterpret_cast<const Sfnt::SimpleGlyph *>(pSimpleGlyf);
     // for a composite glyph, the special data begins here
     const uint8 * pbGlyph = reinterpret_cast<const uint8 *>(&pGlyph->end_pts_of_contours[0]);
 
     uint16 GlyphFlags;
-    do 
+    do
     {
         GlyphFlags = be::swap(*((uint16 *)pbGlyph));
         pbGlyph += sizeof(uint16);
         if (be::swap(*((uint16 *)pbGlyph)) == nCompId)
         {
             pbGlyph += sizeof(uint16); // skip over glyph id of component
             fOffset = (GlyphFlags & CompoundGlyph::ArgsAreXYValues) == CompoundGlyph::ArgsAreXYValues;
 
@@ -1543,48 +1543,48 @@ bool GetComponentPlacement(const void * 
     return false;
 }
 
 /*----------------------------------------------------------------------------------------------
     Return info on how a component glyph is to be transformed
     pSimpleGlyph - assumed to point to a composite glyph
     nCompId - glyph id for component of interest
     flt11, flt11, flt11, flt11 - a 2x2 matrix giving the transform
-    bTransOffset - whether to transform the offset from above method 
+    bTransOffset - whether to transform the offset from above method
         The spec is unclear about the meaning of this flag
         Currently - initialize to true for MS rasterizer and false for Mac rasterizer, then
             on return it will indicate whether transform should apply to offset (MSDN CD 10/99)
     Return true if successful, false otherwise
         False could indicate a non-composite glyph or that component wasn't found
 ----------------------------------------------------------------------------------------------*/
-bool GetComponentTransform(const void * pSimpleGlyf, int nCompId, 
-                                    float & flt11, float & flt12, float & flt21, float & flt22, 
+bool GetComponentTransform(const void * pSimpleGlyf, int nCompId,
+                                    float & flt11, float & flt12, float & flt21, float & flt22,
                                     bool & fTransOffset)
 {
     using namespace Sfnt;
-    
+
     if (GlyfContourCount(pSimpleGlyf) >= 0)
         return false;
 
     const Sfnt::SimpleGlyph * pGlyph = reinterpret_cast<const Sfnt::SimpleGlyph *>(pSimpleGlyf);
     // for a composite glyph, the special data begins here
     const uint8 * pbGlyph = reinterpret_cast<const uint8 *>(&pGlyph->end_pts_of_contours[0]);
 
     uint16 GlyphFlags;
-    do 
+    do
     {
         GlyphFlags = be::swap(*((uint16 *)pbGlyph));
         pbGlyph += sizeof(uint16);
         if (be::swap(*((uint16 *)pbGlyph)) == nCompId)
         {
             pbGlyph += sizeof(uint16); // skip over glyph id of component
             pbGlyph += GlyphFlags & CompoundGlyph::Arg1Arg2Words  ? 4 : 2; // skip over placement data
 
             if (fTransOffset) // MS rasterizer
-                fTransOffset = !(GlyphFlags & CompoundGlyph::UnscaledOffset); 
+                fTransOffset = !(GlyphFlags & CompoundGlyph::UnscaledOffset);
             else // Apple rasterizer
                 fTransOffset = (GlyphFlags & CompoundGlyph::ScaledOffset) != 0;
 
             if (GlyphFlags & CompoundGlyph::HaveScale)
             {
                 flt11 = fixed_to_float<14>(be::swap(*(uint16 *)pbGlyph));
                 pbGlyph += sizeof(uint16);
                 flt12 = 0;
@@ -1639,23 +1639,23 @@ bool GetComponentTransform(const void * 
 }
 #endif
 
 /*----------------------------------------------------------------------------------------------
     Return a pointer into the glyf table based on the given tables and Glyph ID
     Since this method doesn't check for spaces, it is good to call IsSpace before using it.
     Return NULL on error.
 ----------------------------------------------------------------------------------------------*/
-void * GlyfLookup(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
+void * GlyfLookup(gid16 nGlyphId, const void * pGlyf, const void * pLoca,
                            size_t lGlyfSize, size_t lLocaSize, const void * pHead)
 {
     // test for valid glyph id
     // CheckTable verifies the index_to_loc_format is valid
-    
-    const Sfnt::FontHeader * pTable 
+
+    const Sfnt::FontHeader * pTable
         = reinterpret_cast<const Sfnt::FontHeader *>(pHead);
 
     if (be::swap(pTable->index_to_loc_format) == Sfnt::FontHeader::ShortIndexLocFormat)
     { // loca entries are two bytes (and have been divided by two)
         if (nGlyphId >= (lLocaSize >> 1) - 1) // don't allow nGlyphId to access sentinel
         {
 //          throw std::out_of_range("glyph id out of range for font");
             return NULL;
@@ -1665,40 +1665,40 @@ void * GlyfLookup(gid16 nGlyphId, const 
     { // loca entries are four bytes
         if (nGlyphId >= (lLocaSize >> 2) - 1)
         {
 //          throw std::out_of_range("glyph id out of range for font");
             return NULL;
         }
     }
 
-    long lGlyfOffset = LocaLookup(nGlyphId, pLoca, lLocaSize, pHead);
+    size_t lGlyfOffset = LocaLookup(nGlyphId, pLoca, lLocaSize, pHead);
     void * pSimpleGlyf = GlyfLookup(pGlyf, lGlyfOffset, lGlyfSize); // invalid loca offset returns null
     return pSimpleGlyf;
 }
 
 #ifdef ALL_TTFUTILS
 /*----------------------------------------------------------------------------------------------
     Determine if a particular Glyph ID has any data in the glyf table. If it is white space,
     there will be no glyf data, though there will be metric data in hmtx, etc.
 ----------------------------------------------------------------------------------------------*/
 bool IsSpace(gid16 nGlyphId, const void * pLoca, size_t lLocaSize, const void * pHead)
 {
     size_t lGlyfOffset = LocaLookup(nGlyphId, pLoca, lLocaSize, pHead);
-    
+
     // the +1 should always work because there is a sentinel value at the end of the loca table
     size_t lNextGlyfOffset = LocaLookup(nGlyphId + 1, pLoca, lLocaSize, pHead);
 
     return (lNextGlyfOffset - lGlyfOffset) == 0;
 }
 
 /*----------------------------------------------------------------------------------------------
     Determine if a particular Glyph ID is a multi-level composite.
 ----------------------------------------------------------------------------------------------*/
-bool IsDeepComposite(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
+bool IsDeepComposite(gid16 nGlyphId, const void * pGlyf, const void * pLoca,
                     size_t lGlyfSize, long lLocaSize, const void * pHead)
 {
     if (IsSpace(nGlyphId, pLoca, lLocaSize, pHead)) {return false;}
 
     void * pSimpleGlyf = GlyfLookup(nGlyphId, pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
     if (pSimpleGlyf == NULL)
         return false; // no way to really indicate an error occured here
 
@@ -1709,34 +1709,34 @@ bool IsDeepComposite(gid16 nGlyphId, con
     size_t cCompIdTotal = kMaxGlyphComponents;
     size_t cCompId = 0;
 
     if (!GetComponentGlyphIds(pSimpleGlyf, rgnCompId, cCompIdTotal, cCompId))
         return false;
 
     for (size_t i = 0; i < cCompId; i++)
     {
-        pSimpleGlyf = GlyfLookup(static_cast<gid16>(rgnCompId[i]), 
+        pSimpleGlyf = GlyfLookup(static_cast<gid16>(rgnCompId[i]),
                             pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
         if (pSimpleGlyf == NULL) {return false;}
 
         if (GlyfContourCount(pSimpleGlyf) < 0)
             return true;
     }
 
     return false;
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the bounding box coordinates based on the given tables and Glyph ID
     Handles both simple and composite glyphs.
     Return true if successful, false otherwise. On false, all point values will be INT_MIN
         False may indicate a white space glyph
 ----------------------------------------------------------------------------------------------*/
-bool GlyfBox(gid16  nGlyphId, const void * pGlyf, const void * pLoca, 
+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)
 {
     xMin = yMin = xMax = yMax = INT_MIN;
 
     if (IsSpace(nGlyphId, pLoca, lLocaSize, pHead)) {return false;}
 
     void * pSimpleGlyf = GlyfLookup(nGlyphId, pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
     if (pSimpleGlyf == NULL) {return false;}
@@ -1745,88 +1745,88 @@ bool GlyfBox(gid16  nGlyphId, const void
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the number of contours based on the given tables and Glyph ID
     Handles both simple and composite glyphs.
     Return true if successful, false otherwise. On false, cnContours will be INT_MIN
         False may indicate a white space glyph or a multi-level composite glyph.
 ----------------------------------------------------------------------------------------------*/
-bool GlyfContourCount(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
+bool GlyfContourCount(gid16 nGlyphId, const void * pGlyf, const void * pLoca,
     size_t lGlyfSize, size_t lLocaSize, const void * pHead, size_t & cnContours)
 {
     cnContours = static_cast<size_t>(INT_MIN);
 
     if (IsSpace(nGlyphId, pLoca, lLocaSize, pHead)) {return false;}
 
     void * pSimpleGlyf = GlyfLookup(nGlyphId, pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
     if (pSimpleGlyf == NULL) {return false;}
 
     int cRtnContours = GlyfContourCount(pSimpleGlyf);
     if (cRtnContours >= 0)
     {
         cnContours = size_t(cRtnContours);
         return true;
     }
-        
+
     //handle composite glyphs
 
     int rgnCompId[kMaxGlyphComponents]; // assumes no glyph will be made of more than 8 components
     size_t cCompIdTotal = kMaxGlyphComponents;
     size_t cCompId = 0;
 
     if (!GetComponentGlyphIds(pSimpleGlyf, rgnCompId, cCompIdTotal, cCompId))
         return false;
 
     cRtnContours = 0;
     int cTmp = 0;
     for (size_t i = 0; i < cCompId; i++)
     {
         if (IsSpace(static_cast<gid16>(rgnCompId[i]), pLoca, lLocaSize, pHead)) {return false;}
-        pSimpleGlyf = GlyfLookup(static_cast<gid16>(rgnCompId[i]), 
+        pSimpleGlyf = GlyfLookup(static_cast<gid16>(rgnCompId[i]),
                                  pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
         if (pSimpleGlyf == 0) {return false;}
         // return false on multi-level composite
-        if ((cTmp = GlyfContourCount(pSimpleGlyf)) < 0) 
+        if ((cTmp = GlyfContourCount(pSimpleGlyf)) < 0)
             return false;
         cRtnContours += cTmp;
     }
 
     cnContours = size_t(cRtnContours);
     return true;
 }
 
 /*----------------------------------------------------------------------------------------------
-    Get the point numbers for the end points of the glyph contours based on the given tables 
+    Get the point numbers for the end points of the glyph contours based on the given tables
     and Glyph ID
     Handles both simple and composite glyphs.
     cnPoints - count of contours from GlyfContourCount (same as number of end points)
     prgnContourEndPoints - should point to a buffer large enough to hold cnPoints integers
     Return true if successful, false otherwise. On false, all end points are INT_MIN
         False may indicate a white space glyph or a multi-level composite glyph.
 ----------------------------------------------------------------------------------------------*/
-bool GlyfContourEndPoints(gid16 nGlyphId, const void * pGlyf, const void * pLoca, 
+bool GlyfContourEndPoints(gid16 nGlyphId, const void * pGlyf, const void * pLoca,
     size_t lGlyfSize, size_t lLocaSize, const void * pHead,
     int * prgnContourEndPoint, size_t cnPoints)
 {
         memset(prgnContourEndPoint, 0xFF, cnPoints * sizeof(int));
     // std::fill_n(prgnContourEndPoint, cnPoints, INT_MIN);
 
     if (IsSpace(nGlyphId, pLoca, lLocaSize, pHead)) {return false;}
 
     void * pSimpleGlyf = GlyfLookup(nGlyphId, pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
     if (pSimpleGlyf == NULL) {return false;}
 
     int cContours = GlyfContourCount(pSimpleGlyf);
     int cActualPts = 0;
     if (cContours > 0)
         return GlyfContourEndPoints(pSimpleGlyf, prgnContourEndPoint, cnPoints, cActualPts);
-    
+
     // handle composite glyphs
-    
+
     int rgnCompId[kMaxGlyphComponents]; // assumes no glyph will be made of more than 8 components
     size_t cCompIdTotal = kMaxGlyphComponents;
     size_t cCompId = 0;
 
     if (!GetComponentGlyphIds(pSimpleGlyf, rgnCompId, cCompIdTotal, cCompId))
         return false;
 
     int * prgnCurrentEndPoint = prgnContourEndPoint;
@@ -1853,41 +1853,41 @@ bool GlyfContourEndPoints(gid16 nGlyphId
     return true;
 }
 
 /*----------------------------------------------------------------------------------------------
     Get the points for a glyph based on the given tables and Glyph ID
     Handles both simple and composite glyphs.
     cnPoints - count of points from largest end point obtained from GlyfContourEndPoints
     prgnX & prgnY - should point to buffers large enough to hold cnPoints integers
-        The ranges are parallel so that coordinates for point(n) are found at offset n in 
+        The ranges are parallel so that coordinates for point(n) are found at offset n in
         both ranges. These points are in absolute coordinates.
     prgfOnCurve - should point to a buffer a large enough to hold cnPoints bytes (bool)
         This range is parallel to the prgnX & prgnY
     Return true if successful, false otherwise. On false, all points may be INT_MIN
         False may indicate a white space glyph, a multi-level composite, or a corrupt font
-        It's not clear from the TTF spec when the transforms should be applied. Should the 
-        transform be done before or after attachment point calcs? (current code - before) 
-        Should the transform be applied to other offsets? (currently - no; however commented 
-        out code is in place so that if CompoundGlyph::UnscaledOffset on the MS rasterizer is 
-        clear (typical) then yes, and if CompoundGlyph::ScaledOffset on the Apple rasterizer is 
+        It's not clear from the TTF spec when the transforms should be applied. Should the
+        transform be done before or after attachment point calcs? (current code - before)
+        Should the transform be applied to other offsets? (currently - no; however commented
+        out code is in place so that if CompoundGlyph::UnscaledOffset on the MS rasterizer is
+        clear (typical) then yes, and if CompoundGlyph::ScaledOffset on the Apple rasterizer is
         clear (typical?) then no). See GetComponentTransform.
-        It's also unclear where point numbering with attachment poinst starts 
-        (currently - first point number is relative to whole glyph, second point number is 
-        relative to current glyph). 
+        It's also unclear where point numbering with attachment poinst starts
+        (currently - first point number is relative to whole glyph, second point number is
+        relative to current glyph).
 ----------------------------------------------------------------------------------------------*/
 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)
 {
         memset(prgnX, 0x7F, cnPoints * sizeof(int));
         memset(prgnY, 0x7F, cnPoints * sizeof(int));
 
-    if (IsSpace(nGlyphId, pLoca, lLocaSize, pHead)) 
+    if (IsSpace(nGlyphId, pLoca, lLocaSize, pHead))
         return false;
 
     void * pSimpleGlyf = GlyfLookup(nGlyphId, pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
     if (pSimpleGlyf == NULL)
         return false;
 
     int cContours = GlyfContourCount(pSimpleGlyf);
     int cActualPts;
@@ -1895,17 +1895,17 @@ bool GlyfPoints(gid16 nGlyphId, const vo
     {
         if (!GlyfPoints(pSimpleGlyf, prgnX, prgnY, (char *)prgfOnCurve, cnPoints, cActualPts))
             return false;
         CalcAbsolutePoints(prgnX, prgnY, cnPoints);
         SimplifyFlags((char *)prgfOnCurve, cnPoints);
         return true;
     }
 
-    // handle composite glyphs  
+    // handle composite glyphs
     int rgnCompId[kMaxGlyphComponents]; // assumes no glyph will be made of more than 8 components
     size_t cCompIdTotal = kMaxGlyphComponents;
     size_t cCompId = 0;
 
     // this will fail if there are more components than there is room for
     if (!GetComponentGlyphIds(pSimpleGlyf, rgnCompId, cCompIdTotal, cCompId))
         return false;
 
@@ -1919,22 +1919,22 @@ bool GlyfPoints(gid16 nGlyphId, const vo
     // int * prgnPrevX = prgnX; // in case first att pt number relative to preceding glyph
     // int * prgnPrevY = prgnY;
     for (size_t i = 0; i < cCompId; i++)
     {
         if (IsSpace(static_cast<gid16>(rgnCompId[i]), pLoca, lLocaSize, pHead)) {return false;}
         void * pCompGlyf = GlyfLookup(static_cast<gid16>(rgnCompId[i]), pGlyf, pLoca, lGlyfSize, lLocaSize, pHead);
         if (pCompGlyf == NULL) {return false;}
         // returns false on multi-level composite
-        if (!GlyfPoints(pCompGlyf, prgnCurrentX, prgnCurrentY, prgbCurrentFlag, 
+        if (!GlyfPoints(pCompGlyf, prgnCurrentX, prgnCurrentY, prgbCurrentFlag,
             cCurrentPoints, cActualPts))
-            return false; 
+            return false;
         if (!GetComponentPlacement(pSimpleGlyf, rgnCompId[i], fOffset, a, b))
             return false;
-        if (!GetComponentTransform(pSimpleGlyf, rgnCompId[i], 
+        if (!GetComponentTransform(pSimpleGlyf, rgnCompId[i],
             flt11, flt12, flt21, flt22, fTransOff))
             return false;
         bool fIdTrans = flt11 == 1.0 && flt12 == 0.0 && flt21 == 0.0 && flt22 == 1.0;
 
         // convert points to absolute coordinates
         // do before transform and attachment point placement are applied
         CalcAbsolutePoints(prgnCurrentX, prgnCurrentY, cActualPts);
 
@@ -1943,28 +1943,28 @@ bool GlyfPoints(gid16 nGlyphId, const vo
         if (!fIdTrans)
             for (int j = 0; j < cActualPts; j++)
             {
                 int x = prgnCurrentX[j]; // store before transform applied
                 int y = prgnCurrentY[j];
                 prgnCurrentX[j] = (int)(x * flt11 + y * flt12);
                 prgnCurrentY[j] = (int)(x * flt21 + y * flt22);
             }
-            
+
         // apply placement - see main method note above
         int nXOff, nYOff;
         if (fOffset) // explicit x & y offsets
-        { 
+        {
             /* ignore fTransOff for now
-            if (fTransOff && !fIdTrans) 
+            if (fTransOff && !fIdTrans)
             {   // transform x & y offsets
                 nXOff = (int)(a * flt11 + b * flt12);
                 nYOff = (int)(a * flt21 + b * flt22);
             }
-            else */ 
+            else */
             { // don't transform offset
                 nXOff = a;
                 nYOff = b;
             }
         }
         else  // attachment points
         {   // in case first point is relative to preceding glyph and second relative to current
             // nXOff = prgnPrevX[a] - prgnCurrentX[b];
@@ -1999,17 +1999,17 @@ bool SimplifyFlags(char * prgbFlags, int
 {
     for (int i = 0; i < cnPoints; i++)
         prgbFlags[i] = static_cast<char>(prgbFlags[i] & Sfnt::SimpleGlyph::OnCurve);
     return true;
 }
 
 /*----------------------------------------------------------------------------------------------
     Convert relative point coordinates to absolute coordinates
-    Points are stored in the font such that they are offsets from one another except for the 
+    Points are stored in the font such that they are offsets from one another except for the
         first point of a glyph.
 ---------------------------------------------------------------------------------------------*/
 bool CalcAbsolutePoints(int * prgnX, int * prgnY, int cnPoints)
 {
     int nX = prgnX[0];
     int nY = prgnY[0];
     for (int i = 1; i < cnPoints; i++)
     {
--- a/gfx/graphite2/src/UtfCodec.cpp
+++ b/gfx/graphite2/src/UtfCodec.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "inc/UtfCodec.h"
--- a/gfx/graphite2/src/call_machine.cpp
+++ b/gfx/graphite2/src/call_machine.cpp
@@ -10,31 +10,31 @@
 
     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 
+    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 call threaded interpreter implmentation for machine.h
 // Author: Tim Eves
 
 // 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 
+// 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 "inc/Machine.h"
 #include "inc/Segment.h"
 #include "inc/Slot.h"
@@ -112,17 +112,17 @@ Machine::stack_t  Machine::run(const ins
 
     // Declare virtual machine registers
     const instr   * ip = program-1;
     const byte    * dp = data;
     stack_t       * sp = _stack + Machine::STACK_GUARD,
             * const sb = sp;
     regbank         reg = {*map, map, _map, _map.begin()+_map.context(), ip, _map.dir(), 0, _status};
 
-    // Run the program        
+    // Run the program
     while ((reinterpret_cast<ip_t>(*++ip))(dp, sp, sb, reg)) {}
     const stack_t ret = sp == _stack+STACK_GUARD+1 ? *sp-- : 0;
 
     check_final_stack(sp);
     map = reg.map;
     *map = reg.is;
     return ret;
 }
@@ -131,10 +131,8 @@ Machine::stack_t  Machine::run(const ins
 namespace {
 #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
@@ -10,35 +10,35 @@
 
     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 
+    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 direct threaded interpreter implmentation for machine.h
 // Author: Tim Eves
 
 // Build either this interpreter or the call_machine implementation.
-// The direct threaded interpreter is relies upon a gcc feature called 
-// labels-as-values so is only portable to compilers that support the 
+// The direct threaded interpreter is relies upon a gcc feature called
+// labels-as-values so is only portable to compilers that support the
 // extension (gcc only as far as I know) however it should build on any
-// 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 
+// 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 "inc/Machine.h"
 #include "inc/Segment.h"
 #include "inc/Slot.h"
@@ -60,17 +60,17 @@ const void * direct_run(const bool      
                         const instr       * program,
                         const byte        * data,
                         Machine::stack_t  * stack,
                         slotref         * & __map,
                         uint8                _dir,
                         Machine::status_t & status,
                         SlotMap           * __smap=0)
 {
-    // We need to define and return to opcode table from within this function 
+    // We need to define and return to opcode table from within this function
     // other inorder to take the addresses of the instruction bodies.
     #include "inc/opcode_table.h"
     if (get_table_mode)
         return opcode_table;
 
     // Declare virtual machine registers
     const instr           * ip = program;
     const byte            * dp = data;
@@ -78,23 +78,23 @@ const void * direct_run(const bool      
                     * const sb = sp;
     SlotMap             & smap = *__smap;
     Segment              & seg = smap.segment;
     slotref                 is = *__map,
                          * map = __map,
                   * const mapb = smap.begin()+smap.context();
     uint8                  dir = _dir;
     int8                 flags = 0;
-    
+
     // start the program
     goto **ip;
 
     // Pull in the opcode definitions
     #include "inc/opcodes.h"
-    
+
     end:
     __map  = map;
     *__map = is;
     return sp;
 }
 
 }
 
@@ -106,16 +106,15 @@ const opcode_t * Machine::getOpcodeTable
 }
 
 
 Machine::stack_t  Machine::run(const instr   * program,
                                const byte    * data,
                                slotref     * & is)
 {
     assert(program != 0);
-    
+
     const stack_t *sp = static_cast<const stack_t *>(
                 direct_run(false, program, data, _stack, is, _map.dir(), _status, &_map));
     const stack_t ret = sp == _stack+STACK_GUARD+1 ? *sp-- : 0;
     check_final_stack(sp);
     return ret;
 }
-
--- a/gfx/graphite2/src/files.mk
+++ b/gfx/graphite2/src/files.mk
@@ -10,18 +10,18 @@
 #
 #    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 
+#    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.
 
 # Makefile helper file for those wanting to build Graphite2 using make
@@ -58,19 +58,16 @@
     $($(_NS)_BASE)/src/Font.cpp \
     $($(_NS)_BASE)/src/GlyphCache.cpp \
     $($(_NS)_BASE)/src/GlyphFace.cpp \
     $($(_NS)_BASE)/src/Intervals.cpp \
     $($(_NS)_BASE)/src/Justifier.cpp \
     $($(_NS)_BASE)/src/NameTable.cpp \
     $($(_NS)_BASE)/src/Pass.cpp \
     $($(_NS)_BASE)/src/Position.cpp \
-    $($(_NS)_BASE)/src/SegCache.cpp \
-    $($(_NS)_BASE)/src/SegCacheEntry.cpp \
-    $($(_NS)_BASE)/src/SegCacheStore.cpp \
     $($(_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 = \
@@ -99,25 +96,21 @@
     $($(_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
-
--- a/gfx/graphite2/src/gr_char_info.cpp
+++ b/gfx/graphite2/src/gr_char_info.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <cassert>
--- a/gfx/graphite2/src/gr_face.cpp
+++ b/gfx/graphite2/src/gr_face.cpp
@@ -10,30 +10,29 @@
 
     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 
+    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.
 */
 #include "graphite2/Font.h"
 #include "inc/Face.h"
 #include "inc/FileFace.h"
 #include "inc/GlyphCache.h"
-#include "inc/CachedFace.h"
 #include "inc/CmapCache.h"
 #include "inc/Silf.h"
 #include "inc/json.h"
 
 using namespace graphite2;
 
 #if !defined GRAPHITE2_NTRACING
 extern json *global_log;
@@ -42,18 +41,17 @@ extern json *global_log;
 namespace
 {
     bool load_face(Face & face, unsigned int options)
     {
 #ifdef GRAPHITE2_TELEMETRY
         telemetry::category _misc_cat(face.tele.misc);
 #endif
         Face::Table silf(face, Tag::Silf, 0x00050000);
-        if (silf)   options &= ~gr_face_dumbRendering;
-        else if (!(options &  gr_face_dumbRendering))
+        if (!silf)
             return false;
 
         if (!face.readGlyphs(options))
             return false;
 
         if (silf)
         {
             if (!face.readFeatures() || !face.readGraphite(silf))
@@ -69,24 +67,34 @@ namespace
                 }
 #endif
                 return false;
             }
             else
                 return true;
         }
         else
-            return options & gr_face_dumbRendering;
+            return false;
+    }
+
+    inline
+    uint32 zeropad(const uint32 x)
+    {
+        if (x == 0x20202020)                    return 0;
+        if ((x & 0x00FFFFFF) == 0x00202020)     return x & 0xFF000000;
+        if ((x & 0x0000FFFF) == 0x00002020)     return x & 0xFFFF0000;
+        if ((x & 0x000000FF) == 0x00000020)     return x & 0xFFFFFF00;
+        return x;
     }
 }
 
 extern "C" {
 
 gr_face* gr_make_face_with_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int faceOptions)
-                  //the appFaceHandle must stay alive all the time when the gr_face is alive. When finished with the gr_face, call destroy_face    
+                  //the appFaceHandle must stay alive all the time when the gr_face is alive. When finished with the gr_face, call destroy_face
 {
     if (ops == 0)   return 0;
 
     Face *res = new Face(appFaceHandle, *ops);
     if (res && load_face(*res, faceOptions))
         return static_cast<gr_face *>(res);
 
     delete res;
@@ -94,66 +102,51 @@ gr_face* gr_make_face_with_ops(const voi
 }
 
 gr_face* gr_make_face(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn tablefn, unsigned int faceOptions)
 {
     const gr_face_ops ops = {sizeof(gr_face_ops), tablefn, NULL};
     return gr_make_face_with_ops(appFaceHandle, &ops, faceOptions);
 }
 
-#ifndef GRAPHITE2_NSEGCACHE
-gr_face* gr_make_face_with_seg_cache_and_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, 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
+
+gr_face* gr_make_face_with_seg_cache_and_ops(const void* appFaceHandle/*non-NULL*/, const gr_face_ops *ops, unsigned int , unsigned int faceOptions)
 {
-    if (ops == 0)   return 0;
-
-    CachedFace *res = new CachedFace(appFaceHandle, *ops);
-    if (res && load_face(*res, faceOptions)
-            && res->setupCache(cacheSize))
-        return static_cast<gr_face *>(static_cast<Face *>(res));
-
-    delete res;
-    return 0;
+  return gr_make_face_with_ops(appFaceHandle, ops, faceOptions);
 }
 
-gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn getTable, unsigned int cacheSize, unsigned int faceOptions)
+gr_face* gr_make_face_with_seg_cache(const void* appFaceHandle/*non-NULL*/, gr_get_table_fn tablefn, unsigned int, unsigned int faceOptions)
 {
-    const gr_face_ops ops = {sizeof(gr_face_ops), getTable, NULL};
-    return gr_make_face_with_seg_cache_and_ops(appFaceHandle, &ops, cacheSize, faceOptions);
+  const gr_face_ops ops = {sizeof(gr_face_ops), tablefn, NULL};
+  return gr_make_face_with_ops(appFaceHandle, &ops, faceOptions);
 }
-#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)
-        res = (res >> 8) + (str[i] << 24);
+    switch(max(strlen(str),size_t(4)))
+    {
+        case 4: res |= str[3];       GR_FALLTHROUGH;
+        case 3: res |= str[2] << 8;  GR_FALLTHROUGH;
+        case 2: res |= str[1] << 16; GR_FALLTHROUGH;
+        case 1: res |= str[0] << 24; GR_FALLTHROUGH;
+        default:  break;
+    }
     return res;
 }
 
 void gr_tag_to_str(gr_uint32 tag, char *str)
 {
-    int i = 4;
-    while (--i >= 0)
-    {
-        str[i] = tag & 0xFF;
-        tag >>= 8;
-    }
-}
+    if (!str) return;
 
-inline
-uint32 zeropad(const uint32 x)
-{
-    if (x == 0x20202020)                    return 0;
-    if ((x & 0x00FFFFFF) == 0x00202020)     return x & 0xFF000000;
-    if ((x & 0x0000FFFF) == 0x00002020)     return x & 0xFFFF0000;
-    if ((x & 0x000000FF) == 0x00000020)     return x & 0xFFFFFF00;
-    return x;
+    *str++ = char(tag >> 24);
+    *str++ = char(tag >> 16);
+    *str++ = char(tag >> 8);
+    *str++ = char(tag);
+    *str = '\0';
 }
 
 gr_feature_val* gr_face_featureval_for_lang(const gr_face* pFace, gr_uint32 langname/*0 means clone default*/) //clones the features. if none for language, clones the default
 {
     assert(pFace);
     langname = zeropad(langname);
     return static_cast<gr_feature_val *>(pFace->theSill().cloneFeatures(langname));
 }
@@ -241,42 +234,23 @@ gr_face* gr_make_file_face(const char *f
     {
       gr_face* pRes = gr_make_face_with_ops(pFileFace, &FileFace::ops, faceOptions);
       if (pRes)
       {
         pRes->takeFileFace(pFileFace);        //takes ownership
         return pRes;
       }
     }
-    
+
     //error when loading
 
     delete pFileFace;
     return NULL;
 }
 
-#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
+gr_face* gr_make_file_face_with_seg_cache(const char* filename, unsigned int, unsigned int faceOptions)   //returns NULL on failure. //TBD better error handling
                   //when finished with, call destroy_face
 {
-    FileFace* pFileFace = new FileFace(filename);
-    if (*pFileFace)
-    {
-      gr_face * pRes = gr_make_face_with_seg_cache_and_ops(pFileFace, &FileFace::ops, segCacheMaxSize, faceOptions);
-      if (pRes)
-      {
-        pRes->takeFileFace(pFileFace);        //takes ownership
-        return pRes;
-      }
-    }
-
-    //error when loading
-
-    delete pFileFace;
-    return NULL;
+    return gr_make_file_face(filename, faceOptions);
 }
-#endif
 #endif      //!GRAPHITE2_NFILEFACE
 
-
 } // extern "C"
-
-
--- a/gfx/graphite2/src/gr_features.cpp
+++ b/gfx/graphite2/src/gr_features.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "graphite2/Font.h"
@@ -41,26 +41,26 @@ gr_uint16 gr_fref_feature_value(const gr
 
     return pfeatureref->getFeatureVal(*feats);
 }
 
 
 int gr_fref_set_feature_value(const gr_feature_ref* pfeatureref, gr_uint16 val, gr_feature_val* pDest)
 {
     if (!pfeatureref || !pDest) return 0;
-    
+
     return pfeatureref->applyValToFeature(val, *pDest);
 }
 
 
 gr_uint32 gr_fref_id(const gr_feature_ref* pfeatureref)    //returns 0 if pointer is NULL
 {
   if (!pfeatureref)
     return 0;
-  
+
   return pfeatureref->getId();
 }
 
 
 gr_uint16 gr_fref_n_values(const gr_feature_ref* pfeatureref)
 {
     if(!pfeatureref)
         return 0;
@@ -120,19 +120,19 @@ void* gr_fref_value_label(const gr_featu
 
 
 void gr_label_destroy(void * label)
 {
     free(label);
 }
 
 gr_feature_val* gr_featureval_clone(const gr_feature_val* pfeatures/*may be NULL*/)
-{                      //When finished with the Features, call features_destroy    
+{                      //When finished with the Features, call features_destroy
     return static_cast<gr_feature_val*>(pfeatures ? new Features(*pfeatures) : new Features);
 }
-  
+
 void gr_featureval_destroy(gr_feature_val *p)
 {
     delete static_cast<Features*>(p);
 }
 
 
 } // extern "C"
--- a/gfx/graphite2/src/gr_font.cpp
+++ b/gfx/graphite2/src/gr_font.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "graphite2/Font.h"
@@ -41,17 +41,17 @@ void gr_engine_version(int *nMajor, int 
 
 gr_font* gr_make_font(float ppm/*pixels per em*/, const gr_face *face)
 {
     return gr_make_font_with_advance_fn(ppm, 0, 0, face);
 }
 
 
 gr_font* gr_make_font_with_ops(float ppm/*pixels per em*/, const void* appFontHandle/*non-NULL*/, const gr_font_ops * font_ops, const gr_face * face/*needed for scaling*/)
-{                 //the appFontHandle must stay alive all the time when the gr_font is alive. When finished with the gr_font, call destroy_gr_font    
+{                 //the appFontHandle must stay alive all the time when the gr_font is alive. When finished with the gr_font, call destroy_gr_font
     if (face == 0 || ppm <= 0)  return 0;
 
     Font * const res = new Font(ppm, *face, appFontHandle, font_ops);
     if (*res)
         return static_cast<gr_font*>(res);
     else
     {
         delete res;
@@ -67,12 +67,8 @@ gr_font* gr_make_font_with_advance_fn(fl
 
 void gr_font_destroy(gr_font *font)
 {
     delete static_cast<Font*>(font);
 }
 
 
 } // extern "C"
-
-
-
-
--- a/gfx/graphite2/src/gr_logging.cpp
+++ b/gfx/graphite2/src/gr_logging.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include <cstdio>
@@ -220,17 +220,17 @@ json & graphite2::operator << (json & j,
     {
         j   << "children" << json::flat << json::array;
         for (const Slot *c = s.firstChild(); c; c = c->nextSibling())
             j   << objectid(dslot(&seg, c));
         j       << json::close;
     }
     if (cslot)
     {
-		// Note: the reason for using Positions to lump together related attributes is to make the 
+		// Note: the reason for using Positions to lump together related attributes is to make the
 		// JSON output slightly more compact.
         j << "collision" << json::flat << json::object
 //              << "shift" << cslot->shift() -- not used pass level, only within the collision routine itself
               << "offset" << cslot->offset()
               << "limit" << cslot->limit()
               << "flags" << cslot->flags()
               << "margin" << Position(cslot->margin(), cslot->marginWt())
               << "exclude" << cslot->exclGlyph()
@@ -247,21 +247,21 @@ json & graphite2::operator << (json & j,
     }
     return j << json::close;
 }
 
 
 graphite2::objectid::objectid(const dslot & ds) throw()
 {
     const Slot * const p = ds.second;
-    uint32 s = reinterpret_cast<size_t>(p);
+    uint32 s = uint32(reinterpret_cast<size_t>(p));
     sprintf(name, "%.4x-%.2x-%.4hx", uint16(s >> 16), uint16(p ? p->userAttrs()[ds.first->silf()->numUser()] : 0), uint16(s));
     name[sizeof name-1] = 0;
 }
 
 graphite2::objectid::objectid(const Segment * const p) throw()
 {
-    uint32 s = reinterpret_cast<size_t>(p);
+    uint32 s = uint32(reinterpret_cast<size_t>(p));
     sprintf(name, "%.4x-%.2x-%.4hx", uint16(s >> 16), 0, uint16(s));
     name[sizeof name-1] = 0;
 }
 
 #endif
--- a/gfx/graphite2/src/gr_segment.cpp
+++ b/gfx/graphite2/src/gr_segment.cpp
@@ -10,82 +10,85 @@
 
     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 
+    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.
 */
 #include "graphite2/Segment.h"
 #include "inc/UtfCodec.h"
 #include "inc/Segment.h"
 
 using namespace graphite2;
 
-namespace 
+namespace
 {
 
   gr_segment* makeAndInitialize(const Font *font, const Face *face, uint32 script, const Features* pFeats/*must not be NULL*/, gr_encform enc, const void* pStart, size_t nChars, int dir)
   {
       if (script == 0x20202020) script = 0;
       else if ((script & 0x00FFFFFF) == 0x00202020) script = script & 0xFF000000;
       else if ((script & 0x0000FFFF) == 0x00002020) script = script & 0xFFFF0000;
       else if ((script & 0x000000FF) == 0x00000020) script = script & 0xFFFFFF00;
       // if (!font) return NULL;
       Segment* pRes=new Segment(nChars, face, script, dir);
 
-      
+
       if (!pRes->read_text(face, pFeats, enc, pStart, nChars) || !pRes->runGraphite())
       {
         delete pRes;
         return NULL;
       }
       pRes->finalise(font, true);
 
       return static_cast<gr_segment*>(pRes);
   }
 
+  template <typename utf_iter>
+  inline size_t count_unicode_chars(utf_iter first, const utf_iter last, const void **error)
+  {
+      size_t n_chars = 0;
+      uint32 usv = 0;
 
+      if (last)
+      {
+          if (!first.validate(last))
+          {
+              if (error)  *error = last - 1;
+              return 0;
+          }
+          for (;first != last; ++first, ++n_chars)
+              if ((usv = *first) == 0 || first.error()) break;
+      }
+      else
+      {
+          while ((usv = *first) != 0 && !first.error())
+          {
+              ++first;
+              ++n_chars;
+          }
+      }
+
+      if (error)  *error = first.error() ? first : 0;
+      return n_chars;
+  }
 }
 
 
-template <typename utf_iter>
-inline size_t count_unicode_chars(utf_iter first, const utf_iter last, const void **error)
-{
-    size_t n_chars = 0;
-    uint32 usv = 0;
-
-    if (last)
-    {
-        for (;first != last; ++first, ++n_chars)
-            if ((usv = *first) == 0 || first.error()) break;
-    }
-    else
-    {
-        while ((usv = *first) != 0 && !first.error())
-        {
-            ++first;
-            ++n_chars;
-        }
-    }
-
-    if (error)  *error = first.error() ? first : 0;
-    return n_chars;
-}
-
 extern "C" {
 
 size_t gr_count_unicode_characters(gr_encform enc, const void* buffer_begin, const void* buffer_end/*don't go on or past end, If NULL then ignored*/, const void** pError)   //Also stops on nul. Any nul is not in the count
 {
     assert(buffer_begin);
 
     switch (enc)
     {
@@ -94,16 +97,18 @@ size_t gr_count_unicode_characters(gr_en
     case gr_utf32:  return count_unicode_chars<utf32::const_iterator>(buffer_begin, buffer_end, pError); break;
     default:        return 0;
     }
 }
 
 
 gr_segment* gr_make_seg(const gr_font *font, const gr_face *face, gr_uint32 script, const gr_feature_val* pFeats, gr_encform enc, const void* pStart, size_t nChars, int dir)
 {
+    if (!face) return nullptr;
+
     const gr_feature_val * tmp_feats = 0;
     if (pFeats == 0)
         pFeats = tmp_feats = static_cast<const gr_feature_val*>(face->theSill().cloneFeatures(0));
     gr_segment * seg = makeAndInitialize(font, face, script, pFeats, enc, pStart, nChars, dir);
     delete static_cast<const FeatureVal*>(tmp_feats);
 
     return seg;
 }
@@ -127,30 +132,30 @@ float gr_seg_advance_Y(const gr_segment*
     assert(pSeg);
     return pSeg->advance().y;
 }
 
 
 unsigned int gr_seg_n_cinfo(const gr_segment* pSeg/*not NULL*/)
 {
     assert(pSeg);
-    return pSeg->charInfoCount();
+    return static_cast<unsigned int>(pSeg->charInfoCount());
 }
 
 
 const gr_char_info* gr_seg_cinfo(const gr_segment* pSeg/*not NULL*/, unsigned int index/*must be <number_of_CharInfo*/)
 {
     assert(pSeg);
     return static_cast<const gr_char_info*>(pSeg->charinfo(index));
 }
 
 unsigned int gr_seg_n_slots(const gr_segment* pSeg/*not NULL*/)
 {
     assert(pSeg);
-    return pSeg->slotCount();
+    return static_cast<unsigned int>(pSeg->slotCount());
 }
 
 const gr_slot* gr_seg_first_slot(gr_segment* pSeg/*not NULL*/)
 {
     assert(pSeg);
     return static_cast<const gr_slot*>(pSeg->first());
 }
 
--- a/gfx/graphite2/src/gr_slot.cpp
+++ b/gfx/graphite2/src/gr_slot.cpp
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 #include "graphite2/Segment.h"
@@ -53,17 +53,17 @@ const gr_slot* gr_slot_attached_to(const
 
 
 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());
 }
 
-    
+
 const gr_slot* gr_slot_next_sibling_attachment(const gr_slot* p/*not NULL*/)        //returns NULL iff no more attachments.
 {        //if slot_next_sibling_attachment(p) is not NULL, then slot_attached_to(slot_next_sibling_attachment(p))==slot_attached_to(p).
     assert(p);
     return static_cast<const gr_slot*>(p->nextSibling());
 }
 
 
 unsigned short gr_slot_gid(const gr_slot* p/*not NULL*/)
@@ -107,17 +107,17 @@ float gr_slot_advance_Y(const gr_slot *p
 {
     assert(p);
     float res = p->advancePos().y;
     if (font)
         return res * font->scale();
     else
         return res;
 }
-        
+
 int gr_slot_before(const gr_slot* p/*not NULL*/)
 {
     assert(p);
     return p->before();
 }
 
 
 int gr_slot_after(const gr_slot* p/*not NULL*/)
@@ -165,9 +165,8 @@ void gr_slot_linebreak_before(gr_slot* p
 size_t id(const gr_slot* p/*not NULL*/)
 {
     return (size_t)p->id();
 }
 #endif
 
 
 } // extern "C"
-
deleted file mode 100644
--- a/gfx/graphite2/src/inc/CachedFace.h
+++ /dev/null
@@ -1,56 +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 GRAPHITE2_NSEGCACHE
-
-#include "inc/Face.h"
-
-namespace graphite2 {
-
-class SegCacheStore;
-class SegCache;
-
-class CachedFace : public Face
-{
-    CachedFace(const CachedFace &);
-    CachedFace & operator = (const CachedFace &);
-
-public:
-    CachedFace(const void* appFaceHandle/*non-NULL*/, const gr_face_ops & ops);
-    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
-
--- a/gfx/graphite2/src/inc/CharInfo.h
+++ b/gfx/graphite2/src/inc/CharInfo.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -59,9 +59,8 @@ private:
     uint8 m_featureid;  // index into features list in the segment
     int8 m_break;   // breakweight coming from lb table
     uint8 m_flags;  // 0,1 segment split.
 };
 
 } // namespace graphite2
 
 struct gr_char_info : public graphite2::CharInfo {};
-
--- a/gfx/graphite2/src/inc/Code.h
+++ b/gfx/graphite2/src/inc/Code.h
@@ -10,26 +10,26 @@
 
     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 
+    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 
+// 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>
@@ -49,21 +49,21 @@ enum passtype {
     PASS_TYPE_JUSTIFICATION
 };
 
 namespace vm {
 
 class Machine::Code
 {
 public:
-    enum status_t 
+    enum status_t
     {
         loaded,
-        alloc_failed, 
-        invalid_opcode, 
+        alloc_failed,
+        invalid_opcode,
         unimplemented_opcode_used,
         out_of_range_data,
         jump_past_end,
         arguments_exhausted,
         missing_return,
         nested_context_item,
         underfull_stack
     };
@@ -89,30 +89,30 @@ public:
     static size_t estimateCodeDataOut(size_t num_bytecodes, int nRules, int nSlots);
 
     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 &,
          enum passtype pt, byte * * const _out = 0);
     Code(const Machine::Code &) throw();
     ~Code() throw();
-    
+
     Code & operator=(const Code &rhs) throw();
     operator bool () const throw()                  { return _code && status() == loaded; }
     status_t      status() const throw()            { return _status; }
     bool          constraint() const throw()        { return _constraint; }
     size_t        dataSize() const throw()          { return _data_size; }
     size_t        instructionCount() const throw()  { return _instr_count; }
     bool          immutable() const throw()         { return !(_delete || _modify); }
     bool          deletes() const throw()           { return _delete; }
     size_t        maxRef() const throw()            { return _max_ref; }
     void          externalProgramMoved(ptrdiff_t) throw();
 
     int32 run(Machine &m, slotref * & map) const;
-    
+
     CLASS_NEW_DELETE;
 };
 
 inline
 size_t  Machine::Code::estimateCodeDataOut(size_t n_bc, int nRules, int nSlots)
 {
     // max is: all codes are instructions + 1 for each rule + max tempcopies
     // allocate space for separate maximal code and data then merge them later
@@ -123,42 +123,42 @@ size_t  Machine::Code::estimateCodeDataO
 inline Machine::Code::Code() throw()
 : _code(0), _data(0), _data_size(0), _instr_count(0), _max_ref(0),
   _status(loaded), _constraint(false), _modify(false), _delete(false),
   _own(false)
 {
 }
 
 inline Machine::Code::Code(const Machine::Code &obj) throw ()
- :  _code(obj._code), 
-    _data(obj._data), 
-    _data_size(obj._data_size), 
+ :  _code(obj._code),
+    _data(obj._data),
+    _data_size(obj._data_size),
     _instr_count(obj._instr_count),
     _max_ref(obj._max_ref),
-    _status(obj._status), 
+    _status(obj._status),
     _constraint(obj._constraint),
     _modify(obj._modify),
     _delete(obj._delete),
-    _own(obj._own) 
+    _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; 
+    _code        = rhs._code;
     _data        = rhs._data;
-    _data_size   = rhs._data_size; 
+    _data_size   = rhs._data_size;
     _instr_count = rhs._instr_count;
-    _status      = rhs._status; 
+    _status      = rhs._status;
     _constraint  = rhs._constraint;
     _modify      = rhs._modify;
     _delete      = rhs._delete;
-    _own         = rhs._own; 
+    _own         = rhs._own;
     rhs._own = false;
     return *this;
 }
 
 inline void Machine::Code::externalProgramMoved(ptrdiff_t dist) throw()
 {
     if (_code && !_own)
     {
--- a/gfx/graphite2/src/inc/Collider.h
+++ b/gfx/graphite2/src/inc/Collider.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -54,31 +54,31 @@ public:
         COLL_KERN = 16,     // collisions with this glyph are fixed by adding kerning space after it
         COLL_ISCOL = 32,    // this glyph has a collision
         COLL_KNOWN = 64,    // we've figured out what's happening with this glyph
         COLL_ISSPACE = 128,		// treat this glyph as a space with regard to kerning
         COLL_TEMPLOCK = 256,    // Lock glyphs that have been given priority positioning
         ////COLL_JUMPABLE = 128,    // moving glyphs may jump this stationary glyph in any direction - DELETE
         ////COLL_OVERLAP = 256,    // use maxoverlap to restrict - DELETE
     };
-    
+
     // Behavior for the collision.order attribute. To GDL this is an enum, to us it's a bitfield, with only 1 bit set
     // Allows for easier inversion.
     enum {
         SEQ_ORDER_LEFTDOWN = 1,
         SEQ_ORDER_RIGHTUP = 2,
         SEQ_ORDER_NOABOVE = 4,
         SEQ_ORDER_NOBELOW = 8,
         SEQ_ORDER_NOLEFT = 16,
         SEQ_ORDER_NORIGHT = 32
     };
-    
+
     SlotCollision(Segment *seg, Slot *slot);
     void initFromSlot(Segment *seg, Slot *slot);
-    
+
     const Rect &limit() const { return _limit; }
     void setLimit(const Rect &r) { _limit = r; }
     SLOTCOLSETPOSITIONPROP(shift, setShift)
     SLOTCOLSETPOSITIONPROP(offset, setOffset)
     SLOTCOLSETPOSITIONPROP(exclOffset, setExclOffset)
     SLOTCOLSETUINTPROP(margin, setMargin)
     SLOTCOLSETUINTPROP(marginWt, setMarginWt)
     SLOTCOLSETUINTPROP(flags, setFlags)
@@ -90,17 +90,17 @@ public:
     SLOTCOLSETUINTPROP(seqAboveWt, setSeqAboveWt)
     SLOTCOLSETINTPROP(seqBelowXlim, setSeqBelowXlim)
     SLOTCOLSETUINTPROP(seqBelowWt, setSeqBelowWt)
     SLOTCOLSETUINTPROP(seqValignHt, setSeqValignHt)
     SLOTCOLSETUINTPROP(seqValignWt, setSeqValignWt)
 
     float getKern(int dir) const;
     bool ignore() const;
-    
+
 private:
     Rect        _limit;
     Position    _shift;     // adjustment within the given pass
     Position    _offset;    // total adjustment for collisions
     Position    _exclOffset;
     uint16		_margin;
     uint16		_marginWt;
     uint16		_flags;
@@ -109,17 +109,17 @@ private:
 	uint16		_seqProxClass;
     uint16		_seqOrder;
     int16		_seqAboveXoff;
     uint16		_seqAboveWt;
     int16		_seqBelowXlim;
     uint16		_seqBelowWt;
     uint16		_seqValignHt;
     uint16		_seqValignWt;
-	
+
 };  // end of class SlotColllision
 
 struct BBox;
 struct SlantBox;
 
 class ShiftCollider
 {
 public:
@@ -128,17 +128,17 @@ public:
     typedef vfpairs::iterator ivfpairs;
 
     ShiftCollider(json *dbgout);
     ~ShiftCollider() throw() { };
 
     bool initSlot(Segment *seg, Slot *aSlot, const Rect &constraint,
                 float margin, float marginMin, const Position &currShift,
                 const Position &currOffset, int dir, GR_MAYBE_UNUSED json * const dbgout);
-    bool mergeSlot(Segment *seg, Slot *slot, const SlotCollision *cinfo, const Position &currShift, bool isAfter, 
+    bool mergeSlot(Segment *seg, Slot *slot, const SlotCollision *cinfo, const Position &currShift, bool isAfter,
                 bool sameCluster, bool &hasCol, bool isExclusion, GR_MAYBE_UNUSED json * const dbgout);
     Position resolve(Segment *seg, bool &isCol, GR_MAYBE_UNUSED json * const dbgout);
     void addBox_slope(bool isx, const Rect &box, const BBox &bb, const SlantBox &sb, const Position &org, float weight, float m, bool minright, int mode);
     void removeBox(const Rect &box, const BBox &bb, const SlantBox &sb, const Position &org, int mode);
     const Position &origin() const { return _origin; }
 
 #if !defined GRAPHITE2_NTRACING
 	void outputJsonDbg(json * const dbgout, Segment *seg, int axis);
@@ -159,17 +159,17 @@ protected:
     Position _currOffset;
     Position _origin;   // Base for all relative calculations
     float   _margin;
 	float	_marginWt;
     float   _len[4];
     uint16  _seqClass;
 	uint16	_seqProxClass;
     uint16  _seqOrder;
-    
+
 	//bool _scraping[4];
 
 };	// end of class ShiftCollider
 
 inline
 ShiftCollider::ShiftCollider(GR_MAYBE_UNUSED json *dbgout)
 : _target(0),
   _margin(0.0),
@@ -207,17 +207,17 @@ private:
     float _miny;	        // y-coordinates offset by global slot position
     float _maxy;
     Vector<float> _edges;   // edges of horizontal slices
     float _sliceWidth;      // width of each slice
     float _mingap;
     float _xbound;        // max or min edge
     bool  _hit;
 
-#if !defined GRAPHITE2_NTRACING    
+#if !defined GRAPHITE2_NTRACING
     // Debugging
     Segment * _seg;
     Vector<float> _nearEdges; // closest potential collision in each slice
     Vector<Slot*> _slotNear;
 #endif
 };	// end of class KernCollider
 
 
@@ -238,9 +238,8 @@ KernCollider::KernCollider(GR_MAYBE_UNUS
   _hit(false)
 {
 #if !defined GRAPHITE2_NTRACING
     _seg = 0;
 #endif
 };
 
 };  // end of namespace graphite2
-
--- a/gfx/graphite2/src/inc/Compression.h
+++ b/gfx/graphite2/src/inc/Compression.h
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 
@@ -48,59 +48,57 @@ typedef uint64_t u64;
 #endif
 
 ptrdiff_t const     MINMATCH = 4,
                     LASTLITERALS = 5,
                     MINCODA  = LASTLITERALS+1,
                     MINSRCSIZE = 13;
 
 template<int S>
-inline 
+inline
 void unaligned_copy(void * d, void const * s) {
   ::memcpy(d, s, S);
 }
 
 inline
 size_t align(size_t p) {
     return (p + sizeof(unsigned long)-1) & ~(sizeof(unsigned long)-1);
 }
 
-inline 
+inline
 u8 * safe_copy(u8 * d, u8 const * s, size_t n) {
     while (n--) *d++ = *s++;
     return d;
 }
 
 inline
 u8 * overrun_copy(u8 * d, u8 const * s, size_t n) {
     size_t const WS = sizeof(unsigned long);
     u8 const * e = s + n;
-    do 
+    do
     {
         unaligned_copy<WS>(d, s);
         d += WS;
         s += WS;
     }
     while (s < e);
     d-=(s-e);
-    
+
     return d;
 }
 
 
 inline
 u8 * fast_copy(u8 * d, u8 const * s, size_t n) {
     size_t const WS = sizeof(unsigned long);
     size_t wn = n/WS;
-    while (wn--) 
+    while (wn--)
     {
         unaligned_copy<WS>(d, s);
         d += WS;
         s += WS;
     }
     n &= WS-1;
     return safe_copy(d, s, n);
 }
 
 
 } // end of anonymous namespace
-
-
--- a/gfx/graphite2/src/inc/Decompressor.h
+++ b/gfx/graphite2/src/inc/Decompressor.h
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 
@@ -47,10 +47,8 @@ namespace lz4
 //                      13 bytes.
 //      @out_size   -   Must always be big enough to hold the expected size.
 // Return:
 //      -1          -  Decompression failed.
 //      size        -  Actual number of bytes decompressed.
 int decompress(void const *in, size_t in_size, void *out, size_t out_size);
 
 } // end of namespace shrinker
-
-
--- a/gfx/graphite2/src/inc/Endian.h
+++ b/gfx/graphite2/src/inc/Endian.h
@@ -52,61 +52,60 @@ class be
 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)); 
+        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 
+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)); 
+        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/inc/Error.h
+++ b/gfx/graphite2/src/inc/Error.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -127,9 +127,8 @@ enum errors {
     E_CODENORETURN = 67,    // Missing return type op code at end of code
     E_CODENESTEDCTXT = 68,   // Nested context encountered in code
 // Compression errors
     E_BADSCHEME = 69,
     E_SHRINKERFAILED = 70,
 };
 
 }
-
--- a/gfx/graphite2/src/inc/Face.h
+++ b/gfx/graphite2/src/inc/Face.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -165,52 +165,52 @@ json * Face::logger() const throw()
 }
 
 
 
 class Face::Table
 {
     const Face *            _f;
     mutable const byte *    _p;
-    uint32                  _sz;
+    size_t                  _sz;
     bool                    _compressed;
 
     Error decompress();
 
-    void releaseBuffers();
+    void release();
 
 public:
     Table() throw();
     Table(const Face & face, const Tag n, uint32 version=0xffffffff) throw();
-    Table(const Table & rhs) throw();
     ~Table() throw();
+    Table(const Table && rhs) throw();
 
     operator const byte * () const throw();
 
-    Table & operator = (const Table & rhs) throw();
     size_t  size() const throw();
+    Table & operator = (const Table && rhs) throw();
 };
 
 inline
 Face::Table::Table() throw()
 : _f(0), _p(0), _sz(0), _compressed(false)
 {
 }
 
 inline
-Face::Table::Table(const Table & rhs) throw()
+Face::Table::Table(const Table && rhs) throw()
 : _f(rhs._f), _p(rhs._p), _sz(rhs._sz), _compressed(rhs._compressed)
 {
     rhs._p = 0;
 }
 
 inline
 Face::Table::~Table() throw()
 {
-    releaseBuffers();
+    release();
 }
 
 inline
 Face::Table::operator const byte * () const throw()
 {
     return _p;
 }
 
--- a/gfx/graphite2/src/inc/FeatureMap.h
+++ b/gfx/graphite2/src/inc/FeatureMap.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -36,17 +36,17 @@ class Face;
 
 
 class FeatureSetting
 {
 public:
     FeatureSetting(int16 theValue, uint16 labelId) : m_label(labelId), m_value(theValue) {};
     uint16 label() const { return m_label; }
     int16 value() const { return m_value; }
-    
+
     CLASS_NEW_DELETE;
 private:
     FeatureSetting(const FeatureSetting & fs) : m_label(fs.m_label), m_value(fs.m_value) {};
 
     uint16 m_label;
     int16 m_value;
 };
 
@@ -141,17 +141,17 @@ public:
     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
 {
@@ -159,17 +159,17 @@ private:
     class LangFeaturePair
     {
         LangFeaturePair(const LangFeaturePair &);
         LangFeaturePair & operator = (const LangFeaturePair &);
 
     public:
         LangFeaturePair() :  m_lang(0), m_pFeatures(0) {}
         ~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);
--- a/gfx/graphite2/src/inc/FeatureVal.h
+++ b/gfx/graphite2/src/inc/FeatureVal.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -43,19 +43,19 @@ public:
     FeatureVal(const FeatureVal & rhs) : Vector<uint32>(rhs), m_pMap(rhs.m_pMap) {}
 
     FeatureVal & operator = (const FeatureVal & rhs) { Vector<uint32>::operator = (rhs); m_pMap = rhs.m_pMap; return *this; }
 
     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;
 };
--- a/gfx/graphite2/src/inc/FileFace.h
+++ b/gfx/graphite2/src/inc/FileFace.h
@@ -10,18 +10,18 @@
 
     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 
+    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
--- a/gfx/graphite2/src/inc/Font.h
+++ b/gfx/graphite2/src/inc/Font.h
@@ -10,18 +10,18 @@
 
     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 
+    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
--- a/gfx/graphite2/src/inc/GlyphCache.h
+++ b/gfx/graphite2/src/inc/GlyphCache.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -66,17 +66,17 @@ struct BBox
 
 
 class GlyphBox
 {
     GlyphBox(const GlyphBox &);
     GlyphBox & operator = (const GlyphBox &);
 
 public:
-    GlyphBox(uint8 numsubs, unsigned short bitmap, Rect *slanted) : _num(numsubs), _bitmap(bitmap), _slant(*slanted) {}; 
+    GlyphBox(uint8 numsubs, unsigned short bitmap, Rect *slanted) : _num(numsubs), _bitmap(bitmap), _slant(*slanted) {};
 
     void addSubBox(int subindex, int boundary, Rect *val) { _subs[subindex * 2 + boundary] = *val; }
     Rect &subVal(int subindex, int boundary) { return _subs[subindex * 2 + boundary]; }
     const Rect &slant() const { return _slant; }
     uint8 num() const { return _num; }
     const Rect *subs() const { return _subs; }
 
 private:
@@ -110,17 +110,17 @@ public:
     const SlantBox & getBoundingSlantBox(unsigned short glyphid) const;
     const BBox &     getBoundingBBox(unsigned short glyphid) const;
     const SlantBox & getSubBoundingSlantBox(unsigned short glyphid, uint8 subindex) const;
     const BBox &     getSubBoundingBBox(unsigned short glyphid, uint8 subindex) const;
     bool             check(unsigned short glyphid) const;
     bool             hasBoxes() const { return _boxes != 0; }
 
     CLASS_NEW_DELETE;
-    
+
 private:
     const Rect            _empty_slant_box;
     const Loader        * _glyph_loader;
     const GlyphFace *   * _glyphs;
     GlyphBox        *   * _boxes;
     unsigned short        _num_glyphs,
                           _num_attrs,
                           _upem;
--- a/gfx/graphite2/src/inc/GlyphFace.h
+++ b/gfx/graphite2/src/inc/GlyphFace.h
@@ -10,18 +10,18 @@
 
     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 
+    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
--- a/gfx/graphite2/src/inc/Intervals.h
+++ b/gfx/graphite2/src/inc/Intervals.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -211,24 +211,24 @@ void Zones::removeDebug(float pos, float
 #endif
 
 template<>
 inline
 Zones::Exclusion Zones::Exclusion::weighted<XY>(float xmin, float xmax, float f, float a0,
         float m, float xi, GR_MAYBE_UNUSED float ai, float c, GR_MAYBE_UNUSED bool nega) {
     return Exclusion(xmin, xmax,
             m + f,
-            m * xi, 
+            m * xi,
             m * xi * xi + f * a0 * a0 + c);
 }
 
 template<>
 inline
 Zones::Exclusion Zones::Exclusion::weighted<SD>(float xmin, float xmax, float f, float a0,
         float m, float xi, float ai,float c, bool nega) {
     float xia = nega ? xi - ai : xi + ai;
-    return Exclusion(xmin, xmax, 
-            0.25f * (m + 2.f * f), 
-            0.25f * m * xia, 
+    return Exclusion(xmin, xmax,
+            0.25f * (m + 2.f * f),
+            0.25f * m * xia,
             0.25f * (m * xia * xia + 2.f * f * a0 * a0) + c);
 }
 
 } // end of namespace graphite2
--- a/gfx/graphite2/src/inc/List.h
+++ b/gfx/graphite2/src/inc/List.h
@@ -10,18 +10,18 @@
 
     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 
+    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.
 */
 
@@ -33,81 +33,81 @@ of the License or (at your option) any l
 #include <cstring>
 #include <cstdlib>
 #include <new>
 
 #include "Main.h"
 
 namespace graphite2 {
 
-template <typename T> 
+template <typename T>
 inline
 ptrdiff_t distance(T* first, T* last) { return last-first; }
 
 
-template <typename T> 
+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> 
+    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);
     void                resize(size_t n, const T & v = T());
-    
+
     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); new (p) T(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 
+inline
 void Vector<T>::reserve(size_t n)
 {
-    if (n > capacity()) 
+    if (n > capacity())
     {
         const ptrdiff_t sz = size();
         size_t requested;
         if (checked_mul(n,sizeof(T), requested))  std::abort();
         m_first = static_cast<T*>(realloc(m_first, requested));
         if (!m_first)   std::abort();
         m_last  = m_first + sz;
         m_end   = m_first + n;
@@ -117,41 +117,41 @@ void Vector<T>::reserve(size_t n)
 template <typename T>
 inline
 void Vector<T>::resize(size_t n, const T & v) {
     const ptrdiff_t d = n-size();
     if (d < 0)      erase(end()+d, end());
     else if (d > 0) insert(end(), d, v);
 }
 
-template<typename T> 
-inline 
+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 
+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 
+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>
--- a/gfx/graphite2/src/inc/Main.h
+++ b/gfx/graphite2/src/inc/Main.h
@@ -81,17 +81,17 @@ struct telemetry  {};
 #if defined(__has_builtin)
   #if __has_builtin(__builtin_mul_overflow)
     #define HAVE_BUILTIN_OVERFLOW
   #endif
 #elif defined(__GNUC__) && (__GNUC__ >= 5) && !defined(__INTEL_COMPILER)
   #define HAVE_BUILTIN_OVERFLOW
 #endif
 #if defined(__has_include)
-  #if __has_include(<intsafe.h>)
+  #if __has_include(<intsafe.h>) && !defined(__CYGWIN__)
     #define HAVE_INTSAFE_H
   #endif
 #elif defined(_WIN32)
   #define HAVE_INTSAFE_H
 #endif
 
 // Need to import intsafe into the top level namespace
 #if defined(HAVE_INTSAFE_H)
@@ -167,19 +167,24 @@ inline T max(const T a, const T b)
     void operator delete[] (void *, void *) throw() {}
 
 #if defined(__GNUC__)  || defined(__clang__)
 #define GR_MAYBE_UNUSED __attribute__((unused))
 #else
 #define GR_MAYBE_UNUSED
 #endif
 
-#if defined(__clang__) && __cplusplus >= 201103L
-   /* clang's fallthrough annotations are only available starting in C++11. */
-    #define GR_FALLTHROUGH [[fallthrough]]
+#ifndef __has_cpp_attribute
+#  define __has_cpp_attribute(x) 0
+#endif
+
+#if __has_cpp_attribute(clang::fallthrough)
+#  define GR_FALLTHROUGH [[clang::fallthrough]]
+#elif __has_cpp_attribute(gnu::fallthrough)
+#  define GR_FALLTHROUGH [[gnu::fallthrough]]
 #elif defined(_MSC_VER)
    /*
     * MSVC's __fallthrough annotations are checked by /analyze (Code Analysis):
     * https://msdn.microsoft.com/en-us/library/ms235402%28VS.80%29.aspx
     */
     #include <sal.h>
     #define GR_FALLTHROUGH __fallthrough
 #elif __GNUC__ >= 7
--- a/gfx/graphite2/src/inc/Pass.h
+++ b/gfx/graphite2/src/inc/Pass.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -41,37 +41,37 @@ class FiniteStateMachine;
 class Error;
 class ShiftCollider;
 class KernCollider;
 class json;
 
 enum passtype;
 
 class Pass
-{   
+{
 public:
     Pass();
     ~Pass();
-    
+
     bool readPass(const byte * pPass, size_t pass_length, size_t subtable_base, Face & face,
         enum passtype pt, uint32 version, Error &e);
     bool runGraphite(vm::Machine & m, FiniteStateMachine & fsm, bool reverse) const;
     void init(Silf *silf) { m_silf = silf; }
     byte collisionLoops() const { return m_numCollRuns; }
     bool reverseDir() const { return m_isReverseDir; }
 
     CLASS_NEW_DELETE
 private:
     void    findNDoRule(Slot* & iSlot, vm::Machine &, FiniteStateMachine& fsm) const;
     int     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    readRules(const byte * 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_constraint, const byte *constraint_data,
                      const uint16 * o_action, const byte * action_data,
                      Face &, enum passtype pt, Error &e);
     bool    readStates(const byte * starts, const byte * states, const byte * o_rule_map, Face &, Error &e);
     bool    readRanges(const byte * ranges, size_t num_ranges, Error &e);
     uint16  glyphToCol(const uint16 gid) const;
     bool    runFSM(FiniteStateMachine & fsm, Slot * slot) const;
     void    dumpRuleEventConsidered(const FiniteStateMachine & fsm, const RuleEntry & re) const;
     void    dumpRuleEventOutput(const FiniteStateMachine & fsm, const Rule & r, Slot * os) const;
@@ -104,15 +104,15 @@ private:
     uint16 m_numSuccess;
     uint16 m_successStart;
     uint16 m_numColumns;
     byte m_minPreCtxt;
     byte m_maxPreCtxt;
     byte m_colThreshold;
     bool m_isReverseDir;
     vm::Machine::Code m_cPConstraint;
-    
+
 private:        //defensive
     Pass(const Pass&);
     Pass& operator=(const Pass&);
 };
 
 } // namespace graphite2
--- a/gfx/graphite2/src/inc/Position.h
+++ b/gfx/graphite2/src/inc/Position.h
@@ -10,18 +10,18 @@
 
     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 
+    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
--- a/gfx/graphite2/src/inc/Rule.h
+++ b/gfx/graphite2/src/inc/Rule.h
@@ -10,35 +10,35 @@
 
     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 
+    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/Code.h"
 #include "inc/Slot.h"
 
 namespace graphite2 {
 
 struct Rule {
-  const vm::Machine::Code * constraint, 
+  const vm::Machine::Code * constraint,
                  * action;
   unsigned short   sort;
   byte             preContext;
 #ifndef NDEBUG
   uint16           rule_idx;
 #endif
 
   Rule();
@@ -82,39 +82,39 @@ struct RuleEntry
   }
 };
 
 
 struct State
 {
   const RuleEntry     * rules,
                       * rules_end;
-  
+
   bool   empty() const;
 };
 
 inline
 bool State::empty() const
 {
     return rules_end == rules;
 }
 
 
 class SlotMap
 {
 public:
   enum {MAX_SLOTS=64};
-  SlotMap(Segment & seg, uint8 direction, int maxSize);
-  
+  SlotMap(Segment & seg, uint8 direction, size_t maxSize);
+
   Slot       * * begin();
   Slot       * * end();
   size_t         size() const;
   unsigned short context() const;
   void           reset(Slot &, unsigned short);
-  
+
   Slot * const & operator[](int n) const;
   Slot       * & operator [] (int);
   void           pushSlot(Slot * const slot);
   void           collectGarbage(Slot *& aSlot);
 
   Slot         * highwater() { return m_highwater; }
   void           highwater(Slot *s) { m_highwater = s; m_highpassed = false; }
   bool           highpassed() const { return m_highpassed; }
@@ -144,21 +144,21 @@ 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, 
+      RuleEntry * m_begin,
                 * m_end,
                   m_rules[MAX_RULES*2];
   };
 
 public:
   FiniteStateMachine(SlotMap & map, json * logger);
   void      reset(Slot * & slot, const short unsigned int max_pre_ctxt);
 
@@ -214,44 +214,44 @@ size_t FiniteStateMachine::Rules::size()
   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.empty()) 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;    
+  RuleEntry * out = m_rules + (m_begin == m_rules)*MAX_RULES;
   const RuleEntry * const lrend = out + MAX_RULES,
                   * const rrend = state.rules_end;
-  m_begin = out; 
+  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 == rrend)
-    { 
+    {
       while (lre != end() && out != lrend) { *out++ = *lre++; }
       m_end = out;
       return;
     }
   }
   while (rre != rrend && out != lrend) { *out++ = *rre++; }
   m_end = out;
 }
 
 inline
-SlotMap::SlotMap(Segment & seg, uint8 direction, int maxSize)
+SlotMap::SlotMap(Segment & seg, uint8 direction, size_t maxSize)
 : segment(seg), m_size(0), m_precontext(0), m_highwater(0),
-    m_maxSize(maxSize), m_dir(direction), m_highpassed(false)
+    m_maxSize(int(maxSize)), m_dir(direction), m_highpassed(false)
 {
     m_slot_map[0] = 0;
 }
 
 inline
 Slot * * SlotMap::begin()
 {
   return &m_slot_map[1]; // allow map to go 1 before slot_map when inserting
deleted file mode 100644
--- a/gfx/graphite2/src/inc/SegCache.h
+++ /dev/null
@@ -1,316 +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 GRAPHITE2_NSEGCACHE
-
-#include <graphite2/Segment.h>
-#include "inc/Main.h"
-#include "inc/Slot.h"
-#include "inc/FeatureVal.h"
-#include "inc/SegCacheEntry.h"
-#include "inc/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
-{
-    SegCachePrefixEntry(const SegCachePrefixEntry &);
-    SegCachePrefixEntry & operator = (const SegCachePrefixEntry &);
-
-public:
-    SegCachePrefixEntry() : m_lastPurge(0)
-    {
-        memset(m_entryCounts, 0, sizeof m_entryCounts);
-        memset(m_entryBSIndex, 0, sizeof m_entryBSIndex);
-        memset(m_entries, 0, sizeof m_entries);
-    }
-
-    ~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].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;
-};
-
-
-#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
-
deleted file mode 100644
--- a/gfx/graphite2/src/inc/SegCacheEntry.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 GRAPHITE2_NSEGCACHE
-
-#include "inc/Main.h"
-#include "inc/Slot.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
-{
-    // Prevent any implict copying;
-    SegCacheEntry(const SegCacheEntry &);
-    SegCacheEntry & operator = (const SegCacheEntry &);
-
-    friend class SegCachePrefixEntry;
-public:
-    SegCacheEntry() :
-        m_glyphLength(0), m_unicode(NULL), m_glyph(NULL), m_attr(NULL), m_justs(0),
-        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); }
-
-    /** 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;
-    int16  * m_attr;
-    byte   * m_justs;
-    mutable unsigned long long m_accessCount;
-    mutable unsigned long long m_lastAccess;
-};
-
-} // namespace graphite2
-
-#endif
deleted file mode 100644
--- a/gfx/graphite2/src/inc/SegCacheStore.h
+++ /dev/null
@@ -1,127 +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 GRAPHITE2_NSEGCACHE
-
-#include "inc/Main.h"
-#include "inc/CmapCache.h"
-#include "inc/SegCache.h"
-
-namespace graphite2 {
-
-class SegCache;
-class Face;
-
-class SilfSegCache
-{
-    SilfSegCache(const SilfSegCache &);
-    SilfSegCache & operator = (const 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
-{
-    SegCacheStore(const SegCacheStore &);
-    SegCacheStore & operator = (const 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/inc/Segment.h
+++ b/gfx/graphite2/src/inc/Segment.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -44,19 +44,16 @@ of the License or (at your option) any l
 
 namespace graphite2 {
 
 typedef Vector<Features>        FeatureList;
 typedef Vector<Slot *>          SlotRope;
 typedef Vector<int16 *>         AttributeRope;
 typedef Vector<SlotJustify *>   JustifyRope;
 
-#ifndef GRAPHITE2_NSEGCACHE
-class SegmentScopeState;
-#endif
 class Font;
 class Segment;
 class Silf;
 
 enum SpliceParam {
 /** sub-Segments longer than this are not cached
  * (in Unicode code points) */
     eMaxSpliceSize = 96
@@ -86,66 +83,58 @@ class Segment
 
 public:
 
     enum {
         SEG_INITCOLLISIONS = 1,
         SEG_HASCOLLISIONS = 2
     };
 
-    unsigned int slotCount() const { return m_numGlyphs; }      //one slot per glyph
-    void extendLength(int num) { m_numGlyphs += num; }
+    size_t slotCount() const { return m_numGlyphs; }      //one slot per glyph
+    void extendLength(ptrdiff_t 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; }
+    size_t 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; }
 
-    Segment(unsigned int numchars, const Face* face, uint32 script, int dir);
+    Segment(size_t numchars, const Face* face, uint32 script, int dir);
     ~Segment();
-#ifndef GRAPHITE2_NSEGCACHE
-    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 * const startSlot,
-            Slot * endSlot, const Slot * srcSlot,
-            const size_t numGlyphs);
-#endif
     uint8 flags() const { return m_flags; }
     void flags(uint8 f) { m_flags = f; }
     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 *);
     SlotJustify *newJustify();
     void freeJustify(SlotJustify *aJustify);
     Position positionSlots(const Font *font=0, Slot *first=0, Slot *last=0, bool isRtl = false, bool isFinal = true);
-    void associateChars(int offset, int num);
+    void associateChars(int offset, size_t num);
     void linkClusters(Slot *first, Slot *last);
     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; }
+    int addFeatures(const Features& feats) { m_feats.push_back(feats); return int(m_feats.size()) - 1; }
     uint32 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 setFeature(int index, uint8 findex, uint32 val) {
-        const FeatureRef* pFR=m_face->theSill().theFeatureMap().featureRef(findex); 
+        const FeatureRef* pFR=m_face->theSill().theFeatureMap().featureRef(findex);
         if (pFR)
         {
             if (val > pFR->maxVal()) val = pFR->maxVal();
             pFR->applyValToFeature(val, m_feats[index]);
         } }
     int8 dir() const { return m_dir; }
     void dir(int8 val) { m_dir = val; }
     bool currdir() const { return ((m_dir >> 6) ^ m_dir) & 1; }
-    unsigned int passBits() const { return m_passBits; }
-    void mergePassBits(const unsigned int val) { m_passBits &= val; }
+    uint8 passBits() const { return m_passBits; }
+    void mergePassBits(const uint8 val) { m_passBits &= val; }
     int16 glyphAttr(uint16 gid, uint16 gattr) const { const GlyphFace * p = m_face->glyphs().glyphSafe(gid); return p ? p->attrs()[gattr] : 0; }
     int32 getGlyphMetric(Slot *iSlot, uint8 metric, uint8 attrLevel, bool rtl) const;
     float glyphAdvance(uint16 gid) const { return m_face->glyphs().glyph(gid)->theAdvance().x; }
     const Rect &theGlyphBBoxTemporary(uint16 gid) const { return m_face->glyphs().glyph(gid)->theBBox(); }   //warning value may become invalid when another glyph is accessed
     Slot *findRoot(Slot *is) const { return is->attachedTo() ? findRoot(is->attachedTo()) : is; }
     int numAttrs() const { return m_silf->numUser(); }
     int defaultOriginal() const { return m_defaultOriginal; }
     const Face * getFace() const { return m_face; }
@@ -163,38 +152,38 @@ public:
     SlotCollision *collisionInfo(const Slot *s) const { return m_collisions ? m_collisions + s->index() : 0; }
     CLASS_NEW_DELETE
 
 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);
     bool read_text(const Face *face, const Features* pFeats/*must not be NULL*/, gr_encform enc, const void*pStart, size_t nChars);
     void finalise(const Font *font, bool reverse=false);
     float justify(Slot *pSlot, const Font *font, float width, enum justFlags flags, Slot *pFirst, Slot *pLast);
     bool initCollisions();
-  
+
 private:
     Position        m_advance;          // whole segment advance
     SlotRope        m_slots;            // Vector of slot buffers
     AttributeRope   m_userAttrs;        // Vector of userAttrs buffers
     JustifyRope     m_justifies;        // Slot justification info buffers
     FeatureList     m_feats;            // feature settings referenced by charinfos in this segment
     Slot          * m_freeSlots;        // linked list of free slots
     SlotJustify   * m_freeJustifies;    // Slot justification blocks free list
     CharInfo      * m_charinfo;         // character info, one per input character
     SlotCollision * m_collisions;
     const Face    * m_face;             // GrFace
     const Silf    * m_silf;
     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
+    size_t          m_bufSize,          // how big a buffer to create when need more slots
                     m_numGlyphs,
-                    m_numCharinfo,      // size of the array and number of input characters
-                    m_passBits;         // if bit set then skip pass
+                    m_numCharinfo;      // size of the array and number of input characters
     int             m_defaultOriginal;  // number of whitespace chars in the string
     int8            m_dir;
-    uint8           m_flags;            // General purpose flags
+    uint8           m_flags,            // General purpose flags
+                    m_passBits;         // if bit set then skip pass
 };
 
 inline
 int8 Segment::getSlotBidiClass(Slot *s) const
 {
     int8 res = s->getBidiClass();
     if (res != -1) return res;
     res = int8(glyphAttr(s->gid(), m_silf->aBidi()));
@@ -240,9 +229,8 @@ bool Segment::isWhitespace(const int cid
          + (cid == 0x202F)
          + (cid == 0x205F)
          + (cid == 0x3000)) != 0;
 }
 
 } // namespace graphite2
 
 struct gr_segment : public graphite2::Segment {};
-
--- a/gfx/graphite2/src/inc/Silf.h
+++ b/gfx/graphite2/src/inc/Silf.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -68,17 +68,17 @@ class Silf
 {
     // Prevent copying
     Silf(const Silf&);
     Silf& operator=(const Silf&);
 
 public:
     Silf() throw();
     ~Silf() throw();
-    
+
     bool readGraphite(const byte * const pSilf, size_t lSilf, Face &face, uint32 version);
     bool runGraphite(Segment *seg, uint8 firstPass=0, uint8 lastPass=0, int dobidi = 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; }
@@ -116,13 +116,13 @@ private:
     uint8           m_sPass, m_pPass, m_jPass, m_bPass,
                     m_flags, m_dir;
 
     uint8       m_aPseudo, m_aBreak, m_aUser, m_aBidi, m_aMirror, m_aPassBits,
                 m_iMaxComp, m_aCollision;
     uint16      m_aLig, m_numPseudo, m_nClass, m_nLinear,
                 m_gEndLine;
     gr_faceinfo m_silfinfo;
-    
+
     void releaseBuffers() throw();
 };
 
 } // namespace graphite2
--- a/gfx/graphite2/src/inc/Slot.h
+++ b/gfx/graphite2/src/inc/Slot.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -32,17 +32,16 @@ of the License or (at your option) any l
 #include "inc/Font.h"
 #include "inc/Position.h"
 
 namespace graphite2 {
 
 typedef gr_attrCode attrCode;
 
 class GlyphFace;
-class SegCacheEntry;
 class Segment;
 
 struct SlotJustify
 {
     static const int NUMJUSTPARAMS = 5;
 
     SlotJustify(const SlotJustify &);
     SlotJustify & operator = (const SlotJustify &);
@@ -158,15 +157,14 @@ private:
     float    m_just;        // Justification inserted space
     uint8    m_flags;       // holds bit flags
     byte     m_attLevel;    // attachment level
     int8     m_bidiCls;     // bidirectional class
     byte     m_bidiLevel;   // bidirectional level
     int16   *m_userAttr;    // pointer to user attributes
     SlotJustify *m_justs;   // pointer to justification parameters
 
-    friend class SegCacheEntry;
     friend class Segment;
 };
 
 } // namespace graphite2
 
 struct gr_slot : public graphite2::Slot {};
--- a/gfx/graphite2/src/inc/Sparse.h
+++ b/gfx/graphite2/src/inc/Sparse.h
@@ -133,17 +133,17 @@ sparse::sparse(I attr, const I last)
         const typename std::iterator_traits<I>::value_type v = *attr;
         if (v.second == 0)  { --vi; continue; }
 
         chunk * const ci_ = m_array.map + v.first/SIZEOF_CHUNK;
 
         if (ci != ci_)
         {
             ci = ci_;
-            ci->offset = vi - m_array.values;
+            ci->offset = key_type(vi - m_array.values);
         }
 
         ci->mask |= 1UL << (SIZEOF_CHUNK - 1 - (v.first % SIZEOF_CHUNK));
         *vi = v.second;
     }
 }
 
 
--- a/gfx/graphite2/src/inc/TtfTypes.h
+++ b/gfx/graphite2/src/inc/TtfTypes.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -72,21 +72,21 @@ typedef uint32  long_date_time[2];
 enum
 {
     OneFix = 1<<16
 };
 
 //**********************************************************************************************
 //  Table declarations
 //**********************************************************************************************
-namespace Sfnt 
+namespace Sfnt
 {
-#pragma pack(1) // We need this or the structure members aren't alligned 
+#pragma pack(1) // We need this or the structure members aren't aligned
                         // correctly.  Fortunately this form of pragma is supposed
-                        // to be recongnised by VS C++ too (at least according to 
+                        // to be recognised by VS C++ too (at least according to
                         // MSDN).
 
     struct OffsetSubTable
     {
         uint32  scaler_type;
         uint16  num_tables,
             search_range,
             entry_selector,
@@ -94,27 +94,27 @@ namespace Sfnt
         struct Entry
         {
             uint32  tag,
                 checksum,
                 offset,
                 length;
         } table_directory[1];
 
-        enum ScalerType 
-        { 
-            TrueTypeMac = 0x74727565U, 
+        enum ScalerType
+        {
+            TrueTypeMac = 0x74727565U,
             TrueTypeWin = 0x00010000U,
             Type1   = 0x74797031U
         };
     };
 
 
 
-    
+
     struct CharacterCodeMap
     {
         uint16  version,
             num_subtables;
         struct
         {
             uint16  platform_id,
                 platform_specific_id;
@@ -132,27 +132,27 @@ namespace Sfnt
     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 
+        // start positions calculated since end_code is
         // seg_count uint16s long.
     };
 
     struct CmapSubTableFormat12
     {
         fixed   format;
         uint32  length,
             language,
             num_groups;
-        struct 
+        struct
         {
             uint32  start_char_code,
                 end_char_code,
                 start_glyph_id;
         } group[1];
     };
 
 
@@ -171,19 +171,19 @@ namespace Sfnt
             y_min,
             x_max,
             y_max;
         uint16  mac_style,
             lowest_rec_ppem;
         int16   font_direction_hint,
             index_to_loc_format,
             glyph_data_format;
-        enum 
+        enum
         {
-            MagicNumber = 0x5F0F3CF5, 
+            MagicNumber = 0x5F0F3CF5,
             GlypDataFormat = 0
         };
         enum {ShortIndexLocFormat, LongIndexLocFormat};
     };
 
 
 
 
@@ -192,47 +192,47 @@ namespace Sfnt
         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 
+            max_mem_type1;
+        enum
         {
-            Format1  = 0x10000, 
+            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,
@@ -240,17 +240,17 @@ namespace Sfnt
             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,
@@ -292,59 +292,59 @@ namespace Sfnt
         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 
+
+        enum
         {
-            Italic    =0x01, 
-            Underscore=0x02, 
-            Negative  =0x04, 
-            Outlined  =0x08, 
-            StrikeOut =0x10, 
+            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    
+        enum
         {
-            Copyright, Family, Subfamily, UniqueSubfamily, 
+            Copyright, Family, Subfamily, UniqueSubfamily,
             Fullname, Version, PostScript
         };
     };
 
     struct LangTagRecord
     {
         uint16 length,
             offset;
@@ -352,55 +352,55 @@ namespace Sfnt
 
     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 
+        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 
+        enum
         {
             Arg1Arg2Words   = 0x01,
             ArgsAreXYValues = 0x02,
             RoundXYToGrid   = 0x04,
             HaveScale       = 0x08,
             MoreComponents  = 0x20,
             HaveXAndYScale  = 0x40,
             HaveTwoByTwo    = 0x80,
--- a/gfx/graphite2/src/inc/TtfUtil.h
+++ b/gfx/graphite2/src/inc/TtfUtil.h
@@ -10,18 +10,18 @@
 
     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 
+    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
@@ -38,30 +38,32 @@ Description:
 
 #include <cstddef>
 
 namespace graphite2
 {
 namespace TtfUtil
 {
 
+#define OVERFLOW_OFFSET_CHECK(p, o) (o + reinterpret_cast<size_t>(p) < reinterpret_cast<size_t>(p))
+
 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;
+    unsigned int _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) {}
+    Tag(const unsigned int tag) throw()    : _v(tag) {}
 
-    operator unsigned long () const throw () { return _v; }
+    operator unsigned int () 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'),
@@ -95,112 +97,112 @@ public:
     ////////////////////////////////// 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); 
+    ////////////////////////////////// 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); 
+    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, 
+    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, 
+    ////////////////////////////////// cmap lookup tools
+    const void * FindCmapSubtable(const void * pCmap, int nPlatformId = 3,
         int nEncodingId = 1, size_t length = 0);
     bool CheckCmapSubtable4(const void * pCmap31, const void * pCmapEnd /*, unsigned int maxgid*/);
     gid16 CmapSubtable4Lookup(const void * pCmapSubtabel4, unsigned int nUnicodeId, int rangeKey = 0);
     unsigned int CmapSubtable4NextCodepoint(const void *pCmap31, unsigned int nUnicodeId,
         int * pRangeKey = 0);
     bool CheckCmapSubtable12(const void *pCmap310, const void * pCmapEnd /*, unsigned int maxgid*/);
     gid16 CmapSubtable12Lookup(const void * pCmap310, unsigned int uUnicodeId, int rangeKey = 0);
     unsigned int CmapSubtable12NextCodepoint(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, 
+    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); 
+    ////////////////////////////////// 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, 
+    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 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, 
+    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, 
+    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);                        
+        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, 
+    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, 
+    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, 
+    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, 
+    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, 
+    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 
+    // 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/inc/UtfCodec.h
+++ b/gfx/graphite2/src/inc/UtfCodec.h
@@ -35,17 +35,17 @@ 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();
-    static bool     validate(const codeunit_t * s, const codeunit_t * e) throw();
+    static bool     validate(const codeunit_t * s, const codeunit_t * const e) throw();
 };
 
 
 template <>
 struct _utf_codec<32>
 {
 private:
     static const uchar_t    limit = 0x110000;
@@ -61,19 +61,19 @@ public:
     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; }
     }
 
     inline
-    static bool validate(codeunit_t * s, codeunit_t * e) throw()
+    static bool validate(const codeunit_t * s, const codeunit_t * const e) throw()
     {
-        return e > s;
+        return s <= e;
     }
 };
 
 
 template <>
 struct _utf_codec<16>
 {
 private:
@@ -96,28 +96,29 @@ public:
 
     inline
     static uchar_t get(const codeunit_t * cp, int8 & l) throw()
     {
         const uint32    uh = cp[0];
         l = 1;
 
         if (uh < 0xD800|| uh > 0xDFFF) { return uh; }
+        if (uh > 0xDBFF) { l = -1; return 0xFFFD; }
         const uint32 ul = cp[1];
-        if (uh > 0xDBFF || ul < 0xDC00 || ul > 0xDFFF) { l = -1; return 0xFFFD; }
+        if (ul < 0xDC00 || ul > 0xDFFF) { l = -1; return 0xFFFD; }
         ++l;
         return (uh<<10) + ul + surrogate_offset;
     }
 
     inline
-    static bool validate(codeunit_t * s, codeunit_t * e) throw()
+    static bool validate(const codeunit_t * s, const codeunit_t * const e) throw()
     {
         const ptrdiff_t n = e-s;
         if (n <= 0) return n == 0;
-        const uint32 u = *(s+(n-1)); // Get the last codepoint
+        const uint32 u = *(e-1); // Get the last codepoint
         return (u < 0xD800 || u > 0xDBFF);
     }
 };
 
 
 template <>
 struct _utf_codec<8>
 {
@@ -161,26 +162,26 @@ public:
         {
             l = -l;
             return 0xFFFD;
         }
         return u;
     }
 
     inline
-    static bool validate(codeunit_t * s, codeunit_t * e) throw()
+    static bool validate(const codeunit_t * s, const codeunit_t * const e) throw()
     {
         const ptrdiff_t n = e-s;
         if (n <= 0) return n == 0;
         s += (n-1);
         if (*s < 0x80) return true;
         if (*s >= 0xC0) return false;
         if (n == 1) return true;
         if (*--s < 0x80) return true;
-        if (*s >= 0xe0) return false;
+        if (*s >= 0xE0) return false;
         if (n == 2 || *s >= 0xC0) return true;
         if (*--s < 0x80) return true;
         if (*s >= 0xF0) return false;
         return true;
     }
 
 };
 
@@ -220,16 +221,17 @@ public:
     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; }
+    bool validate(const _utf_iterator & e)  { return codec::validate(cp, e.cp); }
 };
 
 template <typename C>
 struct utf
 {
     typedef typename _utf_codec<sizeof(C)*8>::codeunit_t codeunit_t;
 
     typedef _utf_iterator<C>        iterator;
--- a/gfx/graphite2/src/inc/bits.h
+++ b/gfx/graphite2/src/inc/bits.h
@@ -68,51 +68,55 @@ inline unsigned int bit_set_count(unsign
     return __builtin_popcountll(v);
 }
 
 template<>
 inline unsigned int bit_set_count(signed long long v)
 {
     return __builtin_popcountll(v);
 }
+
 #else
 
 template<typename T>
 inline unsigned int bit_set_count(T v)
 {
-    v = v - ((v >> 1) & T(~(0UL)/3));                           // temp
-    v = (v & T(~(0UL)/15*3)) + ((v >> 2) & T(~(0UL)/15*3));     // temp
-    v = (v + (v >> 4)) & T(~(0UL)/255*15);                      // temp
-    return (T)(v * T(~(0UL)/255)) >> (sizeof(T)-1)*8;           // count
+	static size_t const ONES = ~0;
+
+	v = v - ((v >> 1) & T(ONES/3));                      // temp
+    v = (v & T(ONES/15*3)) + ((v >> 2) & T(ONES/15*3));  // temp
+    v = (v + (v >> 4)) & T(ONES/255*15);                 // temp
+    return (T)(v * T(ONES/255)) >> (sizeof(T)-1)*8;      // count
 }
 
 #endif
 
-
+//TODO: Changed these to uintmax_t when we go to C++11
 template<int S>
-inline unsigned long _mask_over_val(unsigned long v)
+inline size_t _mask_over_val(size_t v)
 {
     v = _mask_over_val<S/2>(v);
     v |= v >> S*4;
     return v;
 }
 
+//TODO: Changed these to uintmax_t when we go to C++11
 template<>
-inline unsigned long _mask_over_val<1>(unsigned long v)
+inline size_t _mask_over_val<1>(size_t v)
 {
     v |= v >> 1;
     v |= v >> 2;
     v |= v >> 4;
     return v;
 }
 
 template<typename T>
 inline T mask_over_val(T v)
 {
-    return _mask_over_val<sizeof(T)>(v);
+    return T(_mask_over_val<sizeof(T)>(v));
 }
 
 template<typename T>
 inline unsigned long next_highest_power2(T v)
 {
     return _mask_over_val<sizeof(T)>(v-1)+1;
 }
 
--- a/gfx/graphite2/src/inc/json.h
+++ b/gfx/graphite2/src/inc/json.h
@@ -28,49 +28,50 @@ of the License or (at your option) any l
 // Created on: 15 Dec 2011
 //     Author: Tim Eves
 
 #pragma once
 
 #include "inc/Main.h"
 #include <cassert>
 #include <cstdio>
+#include <cstdint>
 #include "inc/List.h"
 
 namespace graphite2 {
 
 class json
 {
     // Prevent copying
     json(const json &);
     json & operator = (const json &);
 
     typedef void (*_context_t)(json &);
-    class _null_t {};
 
     FILE * const    _stream;
     char            _contexts[128], // context stack
                   * _context,       // current context (top of stack)
                   * _flatten;       // if !0 points to context above which
                                     //  pretty printed output should occur.
     Vector<void *>  _env;
 
     void context(const char current) throw();
     void indent(const int d=0) throw();
     void push_context(const char, const char) throw();
     void pop_context() throw();
 
 public:
     class closer;
 
-    typedef const char *    string;
-    typedef double          number;
-    typedef long signed int integer;
-    typedef bool            boolean;
-    static const _null_t    null;
+    using string = const char *;
+    using number = double;
+    enum class integer : std::intmax_t {};
+    enum class integer_u : std::uintmax_t {};
+    using boolean = bool;
+    static const std::nullptr_t  null;
 
     void setenv(unsigned int index, void *val) { _env.reserve(index + 1); if (index >= _env.size()) _env.insert(_env.end(), _env.size() - index + 1, 0); _env[index] = val; }
     void *getenv(unsigned int index) const { return _env[index]; }
     const Vector<void *> &getenvs() const { return _env; }
 
     static void flat(json &) throw();
     static void close(json &) throw();
     static void object(json &) throw();
@@ -80,19 +81,19 @@ public:
     json(FILE * stream) throw();
     ~json() throw ();
 
     FILE * stream() const throw();
 
     json & operator << (string) throw();
     json & operator << (number) throw();
     json & operator << (integer) throw();
-    json & operator << (long unsigned int d) throw();
+    json & operator << (integer_u) throw();
     json & operator << (boolean) throw();
-    json & operator << (_null_t) throw();
+    json & operator << (std::nullptr_t) throw();
     json & operator << (_context_t) throw();
 
     operator bool() const throw();
     bool good() const throw();
     bool eof() const throw();
 
     CLASS_NEW_DELETE;
 };
@@ -131,39 +132,44 @@ FILE * json::stream() const throw()     
 inline
 json & json::operator << (json::_context_t ctxt) throw()
 {
     ctxt(*this);
     return *this;
 }
 
 inline
-json & operator << (json & j, signed char d) throw()        { return j << json::integer(d); }
+json & operator << (json & j, signed char d) throw()   { return j << json::integer(d); }
 
 inline
-json & operator << (json & j, short signed int d) throw()   { return j << json::integer(d); }
+json & operator << (json & j, unsigned char d) throw() { return j << json::integer_u(d); }
 
 inline
-json & operator << (json & j, signed int d) throw()         { return j << json::integer(d); }
+json & operator << (json & j, short int d) throw()   { return j << json::integer(d); }
 
 inline
-json & operator << (json & j, unsigned char d) throw()      { return j << json::integer(d); }
+json & operator << (json & j, unsigned short int d) throw() { return j << json::integer_u(d); }
 
 inline
-json & operator << (json & j, short unsigned int d) throw() { return j << json::integer(d); }
+json & operator << (json & j, int d) throw()         { return j << json::integer(d); }
 
 inline
-json & operator << (json & j, unsigned int d) throw()       { return j << json::integer(d); }
+json & operator << (json & j, unsigned int d) throw()       { return j << json::integer_u(d); }
 
 inline
-json & operator << (json & j, char c) throw ()
-{
-    const char str[2] = {c,0};
-    return j << str;
-}
+json & operator << (json & j, long int d) throw()         { return j << json::integer(d); }
+
+inline
+json & operator << (json & j, unsigned long int d) throw()       { return j << json::integer_u(d); }
+
+inline
+json & operator << (json & j, long long int d) throw()         { return j << json::integer(d); }
+
+inline
+json & operator << (json & j, unsigned long long int d) throw()       { return j << json::integer_u(d); }
 
 inline
 json::operator bool() const throw()     { return good(); }
 
 inline
 bool json::good() const throw()         { return _stream && ferror(_stream) == 0; }
 
 inline
--- a/gfx/graphite2/src/inc/opcode_table.h
+++ b/gfx/graphite2/src/inc/opcode_table.h
@@ -10,18 +10,18 @@
 
     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 
+    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 file will be pulled into and integrated into a machine implmentation
@@ -36,17 +36,17 @@ of the License or (at your option) any l
 //      output_class - 0 .. silf.m_nClass
 //      input_class - 0 .. silf.m_nClass
 //      sattrnum - 0 .. 29 (gr_slatJWidth) , 55 (gr_slatUserDefn)
 //      attrid - 0 .. silf.numUser() where sattrnum == 55; 0..silf.m_iMaxComp where sattrnum == 15 otherwise 0
 //      gattrnum - 0 .. face->getGlyphFaceCache->numAttrs()
 //      gmetric - 0 .. 11 (kgmetDescent)
 //      featidx - 0 .. face.numFeatures()
 //      level - any byte
-static const opcode_t opcode_table[] = 
+static const opcode_t opcode_table[] =
 {
     {{do2(nop)},                                    0, "NOP"},
 
     {{do2(push_byte)},                              1, "PUSH_BYTE"},                // number
     {{do2(push_byte_u)},                            1, "PUSH_BYTE_U"},              // number
     {{do2(push_short)},                             2, "PUSH_SHORT"},               // number number
     {{do2(push_short_u)},                           2, "PUSH_SHORT_U"},             // number number
     {{do2(push_long)},                              4, "PUSH_LONG"},                // number number number number
@@ -117,9 +117,8 @@ static const opcode_t opcode_table[] =
     {{do2(bor)},                                    0, "BITOR"},
     {{do2(band)},                                   0, "BITAND"},
     {{do2(bnot)},                                   0, "BITNOT"},   // 0x40
     {{do2(setbits)},                                4, "BITSET"},
     {{do_(set_feat), NILOP},                        2, "SET_FEAT"},                 // featidx slot
     // private opcodes for internal use only, comes after all other on disk opcodes.
     {{do_(temp_copy), NILOP},                       0, "TEMP_COPY"}
 };
-
--- a/gfx/graphite2/src/inc/opcodes.h
+++ b/gfx/graphite2/src/inc/opcodes.h
@@ -10,64 +10,64 @@
 
     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 
+    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
 // This file will be pulled into and integrated into a machine implmentation
 // DO NOT build directly and under no circumstances ever #include headers in
 // here or you will break the direct_machine.
 //
 // Implementers' notes
 // ==================
 // You have access to a few primitives and the full C++ code:
 //    declare_params(n) Tells the interpreter how many bytes of parameter
-//                      space to claim for this instruction uses and 
-//                      initialises the param pointer.  You *must* before the 
+//                      space to claim for this instruction uses and
+//                      initialises the param pointer.  You *must* before the
 //                      first use of param.
-//    use_params(n)     Claim n extra bytes of param space beyond what was 
+//    use_params(n)     Claim n extra bytes of param space beyond what was
 //                      claimed using delcare_param.
 //    param             A const byte pointer for the parameter space claimed by
 //                      this instruction.
-//    binop(op)         Implement a binary operation on the stack using the 
+//    binop(op)         Implement a binary operation on the stack using the
 //                      specified C++ operator.
-//    NOT_IMPLEMENTED   Any instruction body containing this will exit the 
+//    NOT_IMPLEMENTED   Any instruction body containing this will exit the
 //                      program with an assertion error.  Instructions that are
 //                      not implemented should also be marked NILOP in the
 //                      opcodes tables this will cause the code class to spot
-//                      them in a live code stream and throw a runtime_error 
+//                      them in a live code stream and throw a runtime_error
 //                      instead.
 //    push(n)           Push the value n onto the stack.
 //    pop()             Pop the top most value and return it.
 //
 //    You have access to the following named fast 'registers':
 //        sp        = The pointer to the current top of stack, the last value
 //                    pushed.
 //        seg       = A reference to the Segment this code is running over.
 //        is        = The current slot index
 //        isb       = The original base slot index at the start of this rule
 //        isf       = The first positioned slot
 //        isl       = The last positioned slot
 //        ip        = The current instruction pointer
 //        endPos    = Position of advance of last cluster
 //        dir       = writing system directionality of the font
-     
+
 
 // #define NOT_IMPLEMENTED     assert(false)
 // #define NOT_IMPLEMENTED
 
 #define binop(op)           const uint32 a = pop(); *sp = uint32(*sp) op a
 #define sbinop(op)          const int32 a = pop(); *sp = int32(*sp) op a
 #define use_params(n)       dp += n
 
@@ -91,17 +91,17 @@ ENDOP
 
 STARTOP(push_byte_u)
     declare_params(1);
     push(uint8(*param));
 ENDOP
 
 STARTOP(push_short)
     declare_params(2);
-    const int16 r   = int16(param[0]) << 8 
+    const int16 r   = int16(param[0]) << 8
                     | uint8(param[1]);
     push(r);
 ENDOP
 
 STARTOP(push_short_u)
     declare_params(2);
     const uint16 r  = uint16(param[0]) << 8
                     | uint8(param[1]);
@@ -317,33 +317,33 @@ STARTOP(insert)
     else
     {
         newSlot->originate(seg.defaultOriginal());
     }
     if (is == smap.highwater())
         smap.highpassed(false);
     is = newSlot;
     seg.extendLength(1);
-    if (map != &smap[-1]) 
+    if (map != &smap[-1])
         --map;
 ENDOP
 
 STARTOP(delete_)
     if (!is || is->isDeleted()) DIE
     is->markDeleted(true);
     if (is->prev())
         is->prev()->next(is->next());
     else
         seg.first(is->next());
-    
+
     if (is->next())
         is->next()->prev(is->prev());
     else
         seg.last(is->prev());
-    
+
 
     if (is == smap.highwater())
             smap.highwater(is->next());
     if (is->prev())
         is = is->prev();
     seg.extendLength(-1);
 ENDOP
 
@@ -366,75 +366,75 @@ STARTOP(assoc)
     {
         is->before(min);
         is->after(max);
     }
 ENDOP
 
 STARTOP(cntxt_item)
     // It turns out this is a cunningly disguised condition forward jump.
-    declare_params(3);    
+    declare_params(3);
     const int       is_arg = int8(param[0]);
     const size_t    iskip  = uint8(param[1]),
                     dskip  = uint8(param[2]);
 
     if (mapb + is_arg != map)
     {
         ip += iskip;
         dp += dskip;
         push(true);
     }
 ENDOP
 
 STARTOP(attr_set)
     declare_params(1);
     const attrCode      slat = attrCode(uint8(*param));
-    const          int  val  = int(pop());
+    const          int  val  = pop();
     is->setAttr(&seg, slat, 0, val, smap);
 ENDOP
 
 STARTOP(attr_add)
     declare_params(1);
     const attrCode      slat = attrCode(uint8(*param));
-    const          int  val  = int(pop());
+    const     uint32_t  val  = pop();
     if ((slat == gr_slatPosX || slat == gr_slatPosY) && (flags & POSITIONED) == 0)
     {
         seg.positionSlots(0, *smap.begin(), *(smap.end()-1), seg.currdir());
         flags |= POSITIONED;
     }
-    int res = is->getAttr(&seg, slat, 0);
-    is->setAttr(&seg, slat, 0, val + res, smap);
+    uint32_t res = uint32_t(is->getAttr(&seg, slat, 0));
+    is->setAttr(&seg, slat, 0, int32_t(val + res), smap);
 ENDOP
 
 STARTOP(attr_sub)
     declare_params(1);
     const attrCode      slat = attrCode(uint8(*param));
-    const          int  val  = int(pop());
+    const     uint32_t  val  = pop();
     if ((slat == gr_slatPosX || slat == gr_slatPosY) && (flags & POSITIONED) == 0)
     {
         seg.positionSlots(0, *smap.begin(), *(smap.end()-1), seg.currdir());
         flags |= POSITIONED;
     }
-    int res = is->getAttr(&seg, slat, 0);
-    is->setAttr(&seg, slat, 0, res - val, smap);
+    uint32_t res = uint32_t(is->getAttr(&seg, slat, 0));
+    is->setAttr(&seg, slat, 0, int32_t(res - val), smap);
 ENDOP
 
 STARTOP(attr_set_slot)
     declare_params(1);
-    const attrCode      slat = attrCode(uint8(*param));
-    const int offset = (map - smap.begin())*int(slat == gr_slatAttTo);
-    const          int  val  = int(pop())  + offset;
+    const attrCode  slat   = attrCode(uint8(*param));
+    const int       offset = int(map - smap.begin())*int(slat == gr_slatAttTo);
+    const int       val    = pop()  + offset;
     is->setAttr(&seg, slat, offset, val, smap);
 ENDOP
 
 STARTOP(iattr_set_slot)
     declare_params(2);
-    const attrCode      slat = attrCode(uint8(param[0]));
-    const size_t        idx  = uint8(param[1]);
-    const          int  val  = int(pop())  + (map - smap.begin())*int(slat == gr_slatAttTo);
+    const attrCode  slat = attrCode(uint8(param[0]));
+    const uint8     idx  = uint8(param[1]);
+    const int       val  = int(pop()  + (map - smap.begin())*int(slat == gr_slatAttTo));
     is->setAttr(&seg, slat, idx, val, smap);
 ENDOP
 
 STARTOP(push_slot_attr)
     declare_params(2);
     const attrCode      slat     = attrCode(uint8(param[0]));
     const int           slot_ref = int8(param[1]);
     if ((slat == gr_slatPosX || slat == gr_slatPosY) && (flags & POSITIONED) == 0)
@@ -526,64 +526,64 @@ STARTOP(push_islot_attr)
     }
 ENDOP
 
 #if 0
 STARTOP(push_iglyph_attr) // not implemented
     NOT_IMPLEMENTED;
 ENDOP
 #endif
-      
+
 STARTOP(pop_ret)
     const uint32 ret = pop();
     EXIT(ret);
 ENDOP
 
 STARTOP(ret_zero)
     EXIT(0);
 ENDOP
 
 STARTOP(ret_true)
     EXIT(1);
 ENDOP
 
 STARTOP(iattr_set)
     declare_params(2);
     const attrCode      slat = attrCode(uint8(param[0]));
-    const size_t        idx  = uint8(param[1]);
-    const          int  val  = int(pop());
+    const uint8         idx  = uint8(param[1]);
+    const          int  val  = pop();
     is->setAttr(&seg, slat, idx, val, smap);
 ENDOP
 
 STARTOP(iattr_add)
     declare_params(2);
     const attrCode      slat = attrCode(uint8(param[0]));
-    const size_t        idx  = uint8(param[1]);
-    const          int  val  = int(pop());
+    const uint8         idx  = uint8(param[1]);
+    const     uint32_t  val  = pop();
     if ((slat == gr_slatPosX || slat == gr_slatPosY) && (flags & POSITIONED) == 0)
     {
         seg.positionSlots(0, *smap.begin(), *(smap.end()-1), seg.currdir());
         flags |= POSITIONED;
     }
-    int res = is->getAttr(&seg, slat, idx);
-    is->setAttr(&seg, slat, idx, val + res, smap);
+    uint32_t res = uint32_t(is->getAttr(&seg, slat, idx));
+    is->setAttr(&seg, slat, idx, int32_t(val + res), smap);
 ENDOP
 
 STARTOP(iattr_sub)
     declare_params(2);
     const attrCode      slat = attrCode(uint8(param[0]));
-    const size_t        idx  = uint8(param[1]);
-    const          int  val  = int(pop());
+    const uint8         idx  = uint8(param[1]);
+    const     uint32_t  val  = pop();
     if ((slat == gr_slatPosX || slat == gr_slatPosY) && (flags & POSITIONED) == 0)
     {
         seg.positionSlots(0, *smap.begin(), *(smap.end()-1), seg.currdir());
         flags |= POSITIONED;
     }
-    int res = is->getAttr(&seg, slat, idx);
-    is->setAttr(&seg, slat, idx, res - val, smap);
+    uint32_t res = uint32_t(is->getAttr(&seg, slat, idx));
+    is->setAttr(&seg, slat, idx, int32_t(res - val), smap);
 ENDOP
 
 STARTOP(push_proc_state)
     use_params(1);
     push(1);
 ENDOP
 
 STARTOP(push_version)
@@ -684,9 +684,8 @@ STARTOP(set_feat)
     const int           slot_ref    = int8(param[1]);
     slotref slot = slotat(slot_ref);
     if (slot)
     {
         uint8 fid = seg.charinfo(slot->original())->fid();
         seg.setFeature(fid, feat, pop());
     }
 ENDOP
-
--- a/gfx/graphite2/src/json.cpp
+++ b/gfx/graphite2/src/json.cpp
@@ -28,29 +28,37 @@ of the License or (at your option) any l
 // Author: Tim Eves
 
 #if !defined GRAPHITE2_NTRACING
 
 #include <cstdio>
 #include <limits>
 #include "inc/json.h"
 
+#if defined(_MSC_VER)
+#define FORMAT_INTMAX "%lli"
+#define FORMAT_UINTMAX "%llu"
+#else
+#define FORMAT_INTMAX "%ji"
+#define FORMAT_UINTMAX "%ju"
+#endif
+
 using namespace graphite2;
 
 namespace
 {
     enum
     {
         seq = ',',
         obj='}', member=':', empty_obj='{',
         arr=']', empty_arr='['
     };
 }
 
-const json::_null_t json::null = {};
+const std::nullptr_t json::null = nullptr;
 
 inline
 void json::context(const char current) throw()
 {
     fprintf(_stream, "%c", *_context);
     indent();
     *_context = current;
 }
@@ -113,28 +121,27 @@ json & json::operator << (json::string s
     context(ctxt);
     fprintf(_stream, "\"%s\"", s);
     if (ctxt == member) fputc(' ', _stream);
 
     return *this;
 }