[USP10] Sync with Wine Staging 3.3. CORE-14434
[reactos.git] / dll / win32 / usp10 / usp10.c
index 422c229..fe83722 100644 (file)
@@ -25,6 +25,8 @@
  */
 
 #include <stdarg.h>
+#include <stdlib.h>
+#include <math.h>
 
 #include "windef.h"
 #include "winbase.h"
 #include "usp10_internal.h"
 
 #include "wine/debug.h"
+#include "wine/heap.h"
 #include "wine/unicode.h"
 
 WINE_DEFAULT_DEBUG_CHANNEL(uniscribe);
 
-typedef struct _scriptRange
+static const struct usp10_script_range
+{
+    enum usp10_script script;
+    DWORD rangeFirst;
+    DWORD rangeLast;
+    enum usp10_script numericScript;
+    enum usp10_script punctScript;
+}
+script_ranges[] =
 {
-    WORD script;
-    WORD rangeFirst;
-    WORD rangeLast;
-    WORD numericScript;
-    WORD punctScript;
-} scriptRange;
-
-static const scriptRange scriptRanges[] = {
     /* Basic Latin: U+0000–U+007A */
     { Script_Latin,      0x00,   0x07a ,  Script_Numeric, Script_Punctuation},
     /* Latin-1 Supplement: U+0080–U+00FF */
     /* Latin Extended-A: U+0100–U+017F */
     /* Latin Extended-B: U+0180–U+024F */
     /* IPA Extensions: U+0250–U+02AF */
-    { Script_Latin,      0x80,   0x2af ,  Script_Numeric2, Script_Punctuation},
+    /* Spacing Modifier Letters:U+02B0–U+02FF */
+    { Script_Latin,      0x80,   0x2ff ,  Script_Numeric2, Script_Punctuation},
     /* Combining Diacritical Marks : U+0300–U+036F */
     { Script_Diacritical,0x300,  0x36f,  0, 0},
     /* Greek: U+0370–U+03FF */
@@ -81,6 +85,8 @@ static const scriptRange scriptRanges[] = {
     { Script_Arabic,     0x750,  0x77f,  0, 0},
     /* Thaana: U+0780–U+07BF */
     { Script_Thaana,     0x780,  0x7bf,  0, 0},
+    /* N’Ko: U+07C0–U+07FF */
+    { Script_NKo,        0x7c0,  0x7ff,  0, 0},
     /* Devanagari: U+0900–U+097F */
     { Script_Devanagari, 0x900,  0x97f,  Script_Devanagari_Numeric, 0},
     /* Bengali: U+0980–U+09FF */
@@ -107,8 +113,35 @@ static const scriptRange scriptRanges[] = {
     { Script_Lao,       0xe80,  0xeff,  Script_Lao_Numeric, 0},
     /* Tibetan: U+0F00–U+0FFF */
     { Script_Tibetan,   0xf00,  0xfff,  0, 0},
+    /* Myanmar: U+1000–U+109F */
+    { Script_Myanmar,    0x1000,  0x109f, Script_Myanmar_Numeric, 0},
     /* Georgian: U+10A0–U+10FF */
     { Script_Georgian,   0x10a0,  0x10ff,  0, 0},
+    /* Hangul Jamo: U+1100–U+11FF */
+    { Script_Hangul,     0x1100,  0x11ff,  0, 0},
+    /* Ethiopic: U+1200–U+137F */
+    /* Ethiopic Extensions: U+1380–U+139F */
+    { Script_Ethiopic,   0x1200,  0x139f,  0, 0},
+    /* Cherokee: U+13A0–U+13FF */
+    { Script_Cherokee,   0x13a0,  0x13ff,  0, 0},
+    /* Canadian Aboriginal Syllabics: U+1400–U+167F */
+    { Script_Canadian,   0x1400,  0x167f,  0, 0},
+    /* Ogham: U+1680–U+169F */
+    { Script_Ogham,      0x1680,  0x169f,  0, 0},
+    /* Runic: U+16A0–U+16F0 */
+    { Script_Runic,      0x16a0,  0x16f0,  0, 0},
+    /* Khmer: U+1780–U+17FF */
+    { Script_Khmer,      0x1780,  0x17ff,  Script_Khmer_Numeric, 0},
+    /* Mongolian: U+1800–U+18AF */
+    { Script_Mongolian,  0x1800,  0x18af,  Script_Mongolian_Numeric, 0},
+    /* Canadian Aboriginal Syllabics Extended: U+18B0–U+18FF */
+    { Script_Canadian,   0x18b0,  0x18ff,  0, 0},
+    /* Tai Le: U+1950–U+197F */
+    { Script_Tai_Le,     0x1950,  0x197f,  0, 0},
+    /* New Tai Lue: U+1980–U+19DF */
+    { Script_New_Tai_Lue,0x1980,  0x19df,  Script_New_Tai_Lue_Numeric, 0},
+    /* Khmer Symbols: U+19E0–U+19FF */
+    { Script_Khmer,      0x19e0,  0x19ff,  Script_Khmer_Numeric, 0},
     /* Vedic Extensions: U+1CD0-U+1CFF */
     { Script_Devanagari, 0x1cd0, 0x1cff, Script_Devanagari_Numeric, 0},
     /* Phonetic Extensions: U+1D00–U+1DBF */
@@ -145,6 +178,8 @@ static const scriptRange scriptRanges[] = {
     /* Miscellaneous Mathematical Symbols-A : U+27c0 –U+27ef */
     /* Supplemental Arrows-A : U+27f0 –U+27ff */
     { Script_Latin,      0x2100, 0x27ff, 0, 0},
+    /* Braille Patterns: U+2800–U+28FF */
+    { Script_Braille,    0x2800, 0x28ff, 0, 0},
     /* Supplemental Arrows-B : U+2900 –U+297f */
     /* Miscellaneous Mathematical Symbols-B : U+2980 –U+29ff */
     /* Supplemental Mathematical Operators : U+2a00 –U+2aff */
@@ -154,8 +189,62 @@ static const scriptRange scriptRanges[] = {
     { Script_Latin,      0x2c60, 0x2c7f, 0, 0},
     /* Georgian: U+2D00–U+2D2F */
     { Script_Georgian,   0x2d00,  0x2d2f,  0, 0},
+    /* Tifinagh: U+2D30–U+2D7F */
+    { Script_Tifinagh,   0x2d30,  0x2d7f,  0, 0},
+    /* Ethiopic Extensions: U+2D80–U+2DDF */
+    { Script_Ethiopic,   0x2d80,  0x2ddf,  0, 0},
     /* Cyrillic Extended-A: U+2DE0–U+2DFF */
     { Script_Cyrillic,   0x2de0, 0x2dff,  0, 0},
+    /* CJK Radicals Supplement: U+2E80–U+2EFF */
+    /* Kangxi Radicals: U+2F00–U+2FDF */
+    { Script_CJK_Han,    0x2e80, 0x2fdf,  0, 0},
+    /* Ideographic Description Characters: U+2FF0–U+2FFF */
+    { Script_Ideograph  ,0x2ff0, 0x2fff,  0, 0},
+    /* CJK Symbols and Punctuation: U+3000–U+303F */
+    { Script_Ideograph  ,0x3000, 0x3004,  0, 0},
+    { Script_CJK_Han    ,0x3005, 0x3005,  0, 0},
+    { Script_Ideograph  ,0x3006, 0x3006,  0, 0},
+    { Script_CJK_Han    ,0x3007, 0x3007,  0, 0},
+    { Script_Ideograph  ,0x3008, 0x3020,  0, 0},
+    { Script_CJK_Han    ,0x3021, 0x3029,  0, 0},
+    { Script_Ideograph  ,0x302a, 0x3030,  0, 0},
+    /* Kana Marks: */
+    { Script_Kana       ,0x3031, 0x3035,  0, 0},
+    { Script_Ideograph  ,0x3036, 0x3037,  0, 0},
+    { Script_CJK_Han    ,0x3038, 0x303b,  0, 0},
+    { Script_Ideograph  ,0x303c, 0x303f,  0, 0},
+    /* Hiragana: U+3040–U+309F */
+    /* Katakana: U+30A0–U+30FF */
+    { Script_Kana       ,0x3040, 0x30ff,  0, 0},
+    /* Bopomofo: U+3100–U+312F */
+    { Script_Bopomofo   ,0x3100, 0x312f,  0, 0},
+    /* Hangul Compatibility Jamo: U+3130–U+318F */
+    { Script_Hangul     ,0x3130, 0x318f,  0, 0},
+    /* Kanbun: U+3190–U+319F */
+    { Script_Ideograph  ,0x3190, 0x319f,  0, 0},
+    /* Bopomofo Extended: U+31A0–U+31BF */
+    { Script_Bopomofo   ,0x31a0, 0x31bf,  0, 0},
+    /* CJK Strokes: U+31C0–U+31EF */
+    { Script_Ideograph  ,0x31c0, 0x31ef,  0, 0},
+    /* Katakana Phonetic Extensions: U+31F0–U+31FF */
+    { Script_Kana       ,0x31f0, 0x31ff,  0, 0},
+    /* Enclosed CJK Letters and Months: U+3200–U+32FF */
+    { Script_Hangul     ,0x3200, 0x321f,  0, 0},
+    { Script_Ideograph  ,0x3220, 0x325f,  0, 0},
+    { Script_Hangul     ,0x3260, 0x327f,  0, 0},
+    { Script_Ideograph  ,0x3280, 0x32ef,  0, 0},
+    { Script_Kana       ,0x32d0, 0x31ff,  0, 0},
+    /* CJK Compatibility: U+3300–U+33FF*/
+    { Script_Kana       ,0x3300, 0x3357,  0, 0},
+    { Script_Ideograph  ,0x3358, 0x33ff,  0, 0},
+    /* CJK Unified Ideographs Extension A: U+3400–U+4DBF */
+    { Script_CJK_Han    ,0x3400, 0x4dbf,  0, 0},
+    /* CJK Unified Ideographs: U+4E00–U+9FFF */
+    { Script_CJK_Han    ,0x4e00, 0x9fff,  0, 0},
+    /* Yi: U+A000–U+A4CF */
+    { Script_Yi         ,0xa000, 0xa4cf,  0, 0},
+    /* Vai: U+A500–U+A63F */
+    { Script_Vai        ,0xa500, 0xa63f,  Script_Vai_Numeric, 0},
     /* Cyrillic Extended-B: U+A640–U+A69F */
     { Script_Cyrillic,   0xa640, 0xa69f,  0, 0},
     /* Modifier Tone Letters: U+A700–U+A71F */
@@ -165,6 +254,22 @@ static const scriptRange scriptRanges[] = {
     { Script_Phags_pa,   0xa840, 0xa87f, 0, 0},
     /* Devanagari Extended: U+A8E0-U+A8FF */
     { Script_Devanagari, 0xa8e0, 0xa8ff, Script_Devanagari_Numeric, 0},
+    /* Myanmar Extended-A: U+AA60–U+AA7F */
+    { Script_Myanmar,    0xaa60,  0xaa7f, Script_Myanmar_Numeric, 0},
+    /* Hangul Jamo Extended-A: U+A960–U+A97F */
+    { Script_Hangul,     0xa960, 0xa97f,  0, 0},
+    /* Hangul Syllables: U+AC00–U+D7A3 */
+    { Script_Hangul,     0xac00, 0xd7a3,  0, 0},
+    /* Hangul Jamo Extended-B: U+D7B0–U+D7FF */
+    { Script_Hangul,     0xd7b0, 0xd7ff,  0, 0},
+    /* Surrogates Area: U+D800–U+DFFF */
+    { Script_Surrogates, 0xd800, 0xdbfe,  0, 0},
+    { Script_Private,    0xdbff, 0xdc00,  0, 0},
+    { Script_Surrogates, 0xdc01, 0xdfff,  0, 0},
+    /* Private Use Area: U+E000–U+F8FF */
+    { Script_Private,    0xe000, 0xf8ff,  0, 0},
+    /* CJK Compatibility Ideographs: U+F900–U+FAFF */
+    { Script_CJK_Han    ,0xf900, 0xfaff,  0, 0},
     /* Latin Ligatures: U+FB00–U+FB06 */
     { Script_Latin,      0xfb00, 0xfb06, 0, 0},
     /* Armenian ligatures U+FB13..U+FB17 */
@@ -173,22 +278,29 @@ static const scriptRange scriptRanges[] = {
     { Script_Hebrew,     0xfb1d, 0xfb4f, 0, 0},
     /* Arabic Presentation Forms-A: U+FB50–U+FDFF*/
     { Script_Arabic,     0xfb50, 0xfdff, 0, 0},
+    /* Vertical Forms: U+FE10–U+FE1F */
+    /* Combining Half Marks: U+FE20–U+FE2F */
+    /* CJK Compatibility Forms: U+FE30–U+FE4F */
+    /* Small Form Variants: U+FE50–U+FE6F */
+    { Script_Ideograph  ,0xfe10, 0xfe6f,  0, 0},
     /* Arabic Presentation Forms-B: U+FE70–U+FEFF*/
     { Script_Arabic,     0xfe70, 0xfeff, 0, 0},
-    /* END */
-    { SCRIPT_UNDEFINED,  0, 0, 0}
+    /* Halfwidth and Fullwidth Forms: U+FF00–FFEF */
+    { Script_Ideograph  ,0xff00, 0xff64,  Script_Numeric2, 0},
+    { Script_Kana       ,0xff65, 0xff9f,  0, 0},
+    { Script_Hangul     ,0xffa0, 0xffdf,  0, 0},
+    { Script_Ideograph  ,0xffe0, 0xffef,  0, 0},
+    /* Plane - 1 */
+    /* Deseret: U+10400–U+1044F */
+    { Script_Deseret,     0x10400, 0x1044F,  0, 0},
+    /* Osmanya: U+10480–U+104AF */
+    { Script_Osmanya,    0x10480, 0x104AF,  Script_Osmanya_Numeric, 0},
+    /* Mathematical Alphanumeric Symbols: U+1D400–U+1D7FF */
+    { Script_MathAlpha,  0x1D400, 0x1D7FF,  0, 0},
 };
 
-typedef struct _scriptData
-{
-    SCRIPT_ANALYSIS a;
-    SCRIPT_PROPERTIES props;
-    OPENTYPE_TAG scriptTag;
-    WCHAR fallbackFont[LF_FACESIZE];
-} scriptData;
-
-/* the must be in order so that the index matches the Script value */
-static const scriptData scriptInformation[] = {
+/* this must be in order so that the index matches the Script value */
+const scriptData scriptInformation[] = {
     {{SCRIPT_UNDEFINED, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_NEUTRAL, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      0x00000000,
@@ -196,7 +308,7 @@ static const scriptData scriptInformation[] = {
     {{Script_Latin, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ENGLISH, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
      MS_MAKE_TAG('l','a','t','n'),
-     {0}},
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
     {{Script_CR, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_NEUTRAL, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      0x00000000,
@@ -204,7 +316,7 @@ static const scriptData scriptInformation[] = {
     {{Script_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ENGLISH, 1, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      0x00000000,
-     {0}},
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
     {{Script_Control, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ENGLISH, 0, 1, 0, 0, ANSI_CHARSET, 1, 0, 0, 0, 0, 0, 1, 0, 0},
      0x00000000,
@@ -212,12 +324,12 @@ static const scriptData scriptInformation[] = {
     {{Script_Punctuation, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_NEUTRAL, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      0x00000000,
-     {0}},
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
     {{Script_Arabic, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ARABIC, 0, 1, 0, 0, ARABIC_CHARSET, 0, 0, 0, 0, 0, 0, 1, 1, 0},
      MS_MAKE_TAG('a','r','a','b'),
      {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
-    {{Script_Arabic_Numeric, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
+    {{Script_Arabic_Numeric, 0, 1, 0, 0, 0, 0, { 2,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ARABIC, 1, 1, 0, 0, ARABIC_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
      MS_MAKE_TAG('a','r','a','b'),
      {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
@@ -229,10 +341,10 @@ static const scriptData scriptInformation[] = {
      {LANG_SYRIAC, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 1, 0, 0, 1, 0},
      MS_MAKE_TAG('s','y','r','c'),
      {'E','s','t','r','a','n','g','e','l','o',' ','E','d','e','s','s','a',0}},
-    {{Script_Persian, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
+    {{Script_Persian, 0, 1, 0, 0, 0, 0, { 2,0,0,0,0,0,0,0,0,0,0}},
      {LANG_PERSIAN, 1, 1, 0, 0, ARABIC_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
-     MS_MAKE_TAG('s','y','r','c'),
-     {'E','s','t','r','a','n','g','e','l','o',' ','E','d','e','s','s','a',0}},
+     MS_MAKE_TAG('a','r','a','b'),
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
     {{Script_Thaana, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
      {LANG_DIVEHI, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      MS_MAKE_TAG('t','h','a','a'),
@@ -240,11 +352,11 @@ static const scriptData scriptInformation[] = {
     {{Script_Greek, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_GREEK, 0, 0, 0, 0, GREEK_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      MS_MAKE_TAG('g','r','e','k'),
-     {0}},
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
     {{Script_Cyrillic, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_RUSSIAN, 0, 0, 0, 0, RUSSIAN_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      MS_MAKE_TAG('c','y','r','l'),
-     {0}},
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
     {{Script_Armenian, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ARMENIAN, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
      MS_MAKE_TAG('a','r','m','n'),
@@ -372,11 +484,151 @@ static const scriptData scriptInformation[] = {
     {{Script_Punctuation2, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ENGLISH, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      MS_MAKE_TAG('l','a','t','n'),
-     {0}},
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
     {{Script_Numeric2, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
      {LANG_ENGLISH, 1, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
      0x00000000,
      {0}},
+    {{Script_Myanmar, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x55, 0, 1, 1, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 1, 0, 0, 0, 0},
+     MS_MAKE_TAG('m','y','m','r'),
+     {'M','y','a','n','m','a','r',' ','T','e','x','t',0}},
+    {{Script_Myanmar_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x55, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('m','y','m','r'),
+     {0}},
+    {{Script_Tai_Le, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('t','a','l','e'),
+     {'M','i','c','r','o','s','o','f','t',' ','T','a','i',' ','L','e',0}},
+    {{Script_New_Tai_Lue, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('t','a','l','u'),
+     {'M','i','c','r','o','s','o','f','t',' ','N','e','w',' ','T','a','i',' ','L','u','e',0}},
+    {{Script_New_Tai_Lue_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('t','a','l','u'),
+     {'M','i','c','r','o','s','o','f','t',' ','N','e','w',' ','T','a','i',' ','L','u','e',0}},
+    {{Script_Khmer, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x53, 0, 1, 1, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 1, 0, 0, 0, 0},
+     MS_MAKE_TAG('k','h','m','r'),
+     {'D','a','u','n','P','e','n','h',0}},
+    {{Script_Khmer_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x53, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('k','h','m','r'),
+     {'D','a','u','n','P','e','n','h',0}},
+    {{Script_CJK_Han, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_ENGLISH, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
+     MS_MAKE_TAG('h','a','n','i'),
+     {0}},
+    {{Script_Ideograph, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_ENGLISH, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
+     MS_MAKE_TAG('h','a','n','i'),
+     {0}},
+    {{Script_Bopomofo, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_ENGLISH, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
+     MS_MAKE_TAG('b','o','p','o'),
+     {0}},
+    {{Script_Kana, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_ENGLISH, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
+     MS_MAKE_TAG('k','a','n','a'),
+     {0}},
+    {{Script_Hangul, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_KOREAN, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
+     MS_MAKE_TAG('h','a','n','g'),
+     {0}},
+    {{Script_Yi, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_ENGLISH, 0, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
+     MS_MAKE_TAG('y','i',' ',' '),
+     {'M','i','c','r','o','s','o','f','t',' ','Y','i',' ','B','a','i','t','i',0}},
+    {{Script_Ethiopic, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x5e, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('e','t','h','i'),
+     {'N','y','a','l','a',0}},
+    {{Script_Ethiopic_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x5e, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('e','t','h','i'),
+     {'N','y','a','l','a',0}},
+    {{Script_Mongolian, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_MONGOLIAN, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('m','o','n','g'),
+     {'M','o','n','g','o','l','i','a','n',' ','B','a','i','t','i',0}},
+    {{Script_Mongolian_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_MONGOLIAN, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('m','o','n','g'),
+     {'M','o','n','g','o','l','i','a','n',' ','B','a','i','t','i',0}},
+    {{Script_Tifinagh, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('t','f','n','g'),
+     {'E','b','r','i','m','a',0}},
+    {{Script_NKo, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('n','k','o',' '),
+     {'E','b','r','i','m','a',0}},
+    {{Script_Vai, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('v','a','i',' '),
+     {'E','b','r','i','m','a',0}},
+    {{Script_Vai_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('v','a','i',' '),
+     {'E','b','r','i','m','a',0}},
+    {{Script_Cherokee, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x5c, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('c','h','e','r'),
+     {'P','l','a','n','t','a','g','e','n','e','t',' ','C','h','e','r','o','k','e','e',0}},
+    {{Script_Canadian, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0x5d, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('c','a','n','s'),
+     {'E','u','p','h','e','m','i','a',0}},
+    {{Script_Ogham, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('o','g','a','m'),
+     {'S','e','g','o','e',' ','U','I',' ','S','y','m','b','o','l',0}},
+    {{Script_Runic, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('r','u','n','r'),
+     {'S','e','g','o','e',' ','U','I',' ','S','y','m','b','o','l',0}},
+    {{Script_Braille, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_ENGLISH, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('b','r','a','i'),
+     {'S','e','g','o','e',' ','U','I',' ','S','y','m','b','o','l',0}},
+    {{Script_Surrogates, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_ENGLISH, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0},
+     0x00000000,
+     {0}},
+    {{Script_Private, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 0, 0, 0, DEFAULT_CHARSET, 0, 1, 0, 0, 0, 0, 1, 0, 0},
+     0x00000000,
+     {0}},
+    {{Script_Deseret, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('d','s','r','t'),
+     {'S','e','g','o','e',' ','U','I',' ','S','y','m','b','o','l',0}},
+    {{Script_Osmanya, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('o','s','m','a'),
+     {'E','b','r','i','m','a',0}},
+    {{Script_Osmanya_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('o','s','m','a'),
+     {'E','b','r','i','m','a',0}},
+    {{Script_MathAlpha, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {0, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('m','a','t','h'),
+     {'C','a','m','b','r','i','a',' ','M','a','t','h',0}},
+    {{Script_Hebrew_Currency, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_HEBREW, 0, 1, 0, 0, HEBREW_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('h','e','b','r'),
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
+    {{Script_Vietnamese_Currency, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_VIETNAMESE, 0, 0, 0, 0, VIETNAMESE_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('l','a','t','n'),
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
+    {{Script_Thai_Currency, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
+     {LANG_THAI, 0, 1, 0, 0, THAI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+     MS_MAKE_TAG('t','h','a','i'),
+     {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f',0}},
 };
 
 static const SCRIPT_PROPERTIES *script_props[] =
@@ -403,8 +655,36 @@ static const SCRIPT_PROPERTIES *script_props[] =
     &scriptInformation[38].props, &scriptInformation[39].props,
     &scriptInformation[40].props, &scriptInformation[41].props,
     &scriptInformation[42].props, &scriptInformation[43].props,
-    &scriptInformation[44].props, &scriptInformation[45].props
+    &scriptInformation[44].props, &scriptInformation[45].props,
+    &scriptInformation[46].props, &scriptInformation[47].props,
+    &scriptInformation[48].props, &scriptInformation[49].props,
+    &scriptInformation[50].props, &scriptInformation[51].props,
+    &scriptInformation[52].props, &scriptInformation[53].props,
+    &scriptInformation[54].props, &scriptInformation[55].props,
+    &scriptInformation[56].props, &scriptInformation[57].props,
+    &scriptInformation[58].props, &scriptInformation[59].props,
+    &scriptInformation[60].props, &scriptInformation[61].props,
+    &scriptInformation[62].props, &scriptInformation[63].props,
+    &scriptInformation[64].props, &scriptInformation[65].props,
+    &scriptInformation[66].props, &scriptInformation[67].props,
+    &scriptInformation[68].props, &scriptInformation[69].props,
+    &scriptInformation[70].props, &scriptInformation[71].props,
+    &scriptInformation[72].props, &scriptInformation[73].props,
+    &scriptInformation[74].props, &scriptInformation[75].props,
+    &scriptInformation[76].props, &scriptInformation[77].props,
+    &scriptInformation[78].props, &scriptInformation[79].props,
+    &scriptInformation[80].props, &scriptInformation[81].props
+};
+
+static CRITICAL_SECTION cs_script_cache;
+static CRITICAL_SECTION_DEBUG cs_script_cache_dbg =
+{
+    0, 0, &cs_script_cache,
+    { &cs_script_cache_dbg.ProcessLocksList, &cs_script_cache_dbg.ProcessLocksList },
+      0, 0, { (DWORD_PTR)(__FILE__ ": script_cache") }
 };
+static CRITICAL_SECTION cs_script_cache = { &cs_script_cache_dbg, -1, 0, 0, 0, 0 };
+static struct list script_cache_list = LIST_INIT(script_cache_list);
 
 typedef struct {
     ScriptCache *sc;
@@ -414,15 +694,21 @@ typedef struct {
     int* piAdvance;
     SCRIPT_VISATTR* psva;
     GOFFSET* pGoffset;
-    ABC* abc;
+    ABC abc;
     int iMaxPosX;
     HFONT fallbackFont;
 } StringGlyphs;
 
+enum stringanalysis_flags
+{
+    SCRIPT_STRING_ANALYSIS_FLAGS_SIZE    = 0x1,
+    SCRIPT_STRING_ANALYSIS_FLAGS_INVALID = 0x2,
+};
+
 typedef struct {
     HDC hdc;
-    DWORD dwFlags;
-    BOOL invalid;
+    DWORD ssa_flags;
+    DWORD flags;
     int clip_len;
     int cItems;
     int cMaxGlyphs;
@@ -430,33 +716,98 @@ typedef struct {
     int numItems;
     StringGlyphs* glyphs;
     SCRIPT_LOGATTR* logattrs;
-    SIZE* sz;
+    SIZE sz;
     int* logical2visual;
 } StringAnalysis;
 
-static inline void *heap_alloc(SIZE_T size)
-{
-    return HeapAlloc(GetProcessHeap(), 0, size);
-}
+typedef struct {
+    BOOL ascending;
+    WORD target;
+} FindGlyph_struct;
 
-static inline void *heap_alloc_zero(SIZE_T size)
+BOOL usp10_array_reserve(void **elements, SIZE_T *capacity, SIZE_T count, SIZE_T size)
 {
-    return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
-}
+    SIZE_T max_capacity, new_capacity;
+    void *new_elements;
 
-static inline void *heap_realloc_zero(LPVOID mem, SIZE_T size)
-{
-    return HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, mem, size);
+    if (count <= *capacity)
+        return TRUE;
+
+    max_capacity = ~(SIZE_T)0 / size;
+    if (count > max_capacity)
+        return FALSE;
+
+    new_capacity = max(1, *capacity);
+    while (new_capacity < count && new_capacity <= max_capacity / 2)
+        new_capacity *= 2;
+    if (new_capacity < count)
+        new_capacity = count;
+
+    if (!*elements)
+        new_elements = heap_alloc_zero(new_capacity * size);
+    else
+        new_elements = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *elements, new_capacity * size);
+    if (!new_elements)
+        return FALSE;
+
+    *elements = new_elements;
+    *capacity = new_capacity;
+    return TRUE;
 }
 
-static inline BOOL heap_free(LPVOID mem)
+/* TODO Fix font properties on Arabic locale */
+static inline BOOL set_cache_font_properties(const HDC hdc, ScriptCache *sc)
 {
-    return HeapFree(GetProcessHeap(), 0, mem);
+    sc->sfp.cBytes = sizeof(sc->sfp);
+
+    if (!sc->sfnt)
+    {
+        sc->sfp.wgBlank = sc->tm.tmBreakChar;
+        sc->sfp.wgDefault = sc->tm.tmDefaultChar;
+        sc->sfp.wgInvalid = sc->sfp.wgBlank;
+        sc->sfp.wgKashida = 0xFFFF;
+        sc->sfp.iKashidaWidth = 0;
+    }
+    else
+    {
+        static const WCHAR chars[4] = {0x0020, 0x200B, 0xF71B, 0x0640};
+        /* U+0020: numeric space
+           U+200B: zero width space
+           U+F71B: unknown char found by black box testing
+           U+0640: kashida */
+        WORD gi[4];
+
+        if (GetGlyphIndicesW(hdc, chars, 4, gi, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR)
+        {
+            if(gi[0] != 0xFFFF) /* 0xFFFF: index of default non exist char */
+                sc->sfp.wgBlank = gi[0];
+            else
+                sc->sfp.wgBlank = 0;
+
+            sc->sfp.wgDefault = 0;
+
+            if (gi[2] != 0xFFFF)
+                sc->sfp.wgInvalid = gi[2];
+            else if (gi[1] != 0xFFFF)
+                sc->sfp.wgInvalid = gi[1];
+            else if (gi[0] != 0xFFFF)
+                sc->sfp.wgInvalid = gi[0];
+            else
+                sc->sfp.wgInvalid = 0;
+
+            sc->sfp.wgKashida = gi[3];
+
+            sc->sfp.iKashidaWidth = 0; /* TODO */
+        }
+        else
+            return FALSE;
+    }
+    return TRUE;
 }
 
-static inline WCHAR get_cache_default_char(SCRIPT_CACHE *psc)
+static inline void get_cache_font_properties(SCRIPT_FONTPROPERTIES *sfp, ScriptCache *sc)
 {
-    return ((ScriptCache *)*psc)->tm.tmDefaultChar;
+    *sfp = sc->sfp;
 }
 
 static inline LONG get_cache_height(SCRIPT_CACHE *psc)
@@ -469,20 +820,26 @@ static inline BYTE get_cache_pitch_family(SCRIPT_CACHE *psc)
     return ((ScriptCache *)*psc)->tm.tmPitchAndFamily;
 }
 
-static inline WORD get_cache_glyph(SCRIPT_CACHE *psc, WCHAR c)
+static inline WORD get_cache_glyph(SCRIPT_CACHE *psc, DWORD c)
 {
-    WORD *block = ((ScriptCache *)*psc)->glyphs[c >> GLYPH_BLOCK_SHIFT];
+    CacheGlyphPage *page = ((ScriptCache *)*psc)->page[c / 0x10000];
+    WORD *block;
 
+    if (!page) return 0;
+    block = page->glyphs[(c % 0x10000) >> GLYPH_BLOCK_SHIFT];
     if (!block) return 0;
-    return block[c & GLYPH_BLOCK_MASK];
+    return block[(c % 0x10000) & GLYPH_BLOCK_MASK];
 }
 
 static inline WORD set_cache_glyph(SCRIPT_CACHE *psc, WCHAR c, WORD glyph)
 {
-    WORD **block = &((ScriptCache *)*psc)->glyphs[c >> GLYPH_BLOCK_SHIFT];
+    CacheGlyphPage **page = &((ScriptCache *)*psc)->page[c / 0x10000];
+    WORD **block;
+    if (!*page && !(*page = heap_alloc_zero(sizeof(CacheGlyphPage)))) return 0;
 
+    block = &(*page)->glyphs[(c % 0x10000) >> GLYPH_BLOCK_SHIFT];
     if (!*block && !(*block = heap_alloc_zero(sizeof(WORD) * GLYPH_BLOCK_SIZE))) return 0;
-    return ((*block)[c & GLYPH_BLOCK_MASK] = glyph);
+    return ((*block)[(c % 0x10000) & GLYPH_BLOCK_MASK] = glyph);
 }
 
 static inline BOOL get_cache_glyph_widths(SCRIPT_CACHE *psc, WORD glyph, ABC *abc)
@@ -507,52 +864,141 @@ static inline BOOL set_cache_glyph_widths(SCRIPT_CACHE *psc, WORD glyph, ABC *ab
 static HRESULT init_script_cache(const HDC hdc, SCRIPT_CACHE *psc)
 {
     ScriptCache *sc;
+    unsigned size;
+    LOGFONTW lf;
 
     if (!psc) return E_INVALIDARG;
     if (*psc) return S_OK;
     if (!hdc) return E_PENDING;
 
+    if (!GetObjectW(GetCurrentObject(hdc, OBJ_FONT), sizeof(lf), &lf))
+    {
+        return E_INVALIDARG;
+    }
+    /* Ensure canonical result by zeroing extra space in lfFaceName */
+    size = strlenW(lf.lfFaceName);
+    memset(lf.lfFaceName + size, 0, sizeof(lf.lfFaceName) - size * sizeof(WCHAR));
+
+    EnterCriticalSection(&cs_script_cache);
+    LIST_FOR_EACH_ENTRY(sc, &script_cache_list, ScriptCache, entry)
+    {
+        if (!memcmp(&sc->lf, &lf, sizeof(lf)))
+        {
+            sc->refcount++;
+            LeaveCriticalSection(&cs_script_cache);
+            *psc = sc;
+            return S_OK;
+        }
+    }
+    LeaveCriticalSection(&cs_script_cache);
+
     if (!(sc = heap_alloc_zero(sizeof(ScriptCache)))) return E_OUTOFMEMORY;
     if (!GetTextMetricsW(hdc, &sc->tm))
     {
         heap_free(sc);
         return E_INVALIDARG;
     }
-    if (!GetObjectW(GetCurrentObject(hdc, OBJ_FONT), sizeof(LOGFONTW), &sc->lf))
+    size = GetOutlineTextMetricsW(hdc, 0, NULL);
+    if (size)
+    {
+        sc->otm = heap_alloc(size);
+        sc->otm->otmSize = size;
+        GetOutlineTextMetricsW(hdc, size, sc->otm);
+    }
+    sc->sfnt = (GetFontData(hdc, MS_MAKE_TAG('h','e','a','d'), 0, NULL, 0)!=GDI_ERROR);
+    if (!set_cache_font_properties(hdc, sc))
     {
         heap_free(sc);
         return E_INVALIDARG;
     }
-    sc->sfnt = (GetFontData(hdc, MS_MAKE_TAG('h','e','a','d'), 0, NULL, 0)!=GDI_ERROR);
+    sc->lf = lf;
+    sc->refcount = 1;
     *psc = sc;
+
+    EnterCriticalSection(&cs_script_cache);
+    list_add_head(&script_cache_list, &sc->entry);
+    LIST_FOR_EACH_ENTRY(sc, &script_cache_list, ScriptCache, entry)
+    {
+        if (sc != *psc && !memcmp(&sc->lf, &lf, sizeof(lf)))
+        {
+            /* Another thread won the race. Use their cache instead of ours */
+            list_remove(&sc->entry);
+            sc->refcount++;
+            LeaveCriticalSection(&cs_script_cache);
+            heap_free(*psc);
+            *psc = sc;
+            return S_OK;
+        }
+    }
+    LeaveCriticalSection(&cs_script_cache);
     TRACE("<- %p\n", sc);
     return S_OK;
 }
 
 static WCHAR mirror_char( WCHAR ch )
 {
-    extern const WCHAR wine_mirror_map[];
+    extern const WCHAR wine_mirror_map[] DECLSPEC_HIDDEN;
     return ch + wine_mirror_map[wine_mirror_map[ch >> 8] + (ch & 0xff)];
 }
 
-static WORD get_char_script( WCHAR ch)
+static DWORD decode_surrogate_pair(const WCHAR *str, unsigned int index, unsigned int end)
+{
+    if (index < end-1 && IS_SURROGATE_PAIR(str[index],str[index+1]))
+    {
+        DWORD ch = 0x10000 + ((str[index] - 0xd800) << 10) + (str[index+1] - 0xdc00);
+        TRACE("Surrogate Pair %x %x => %x\n",str[index], str[index+1], ch);
+        return ch;
+    }
+    return 0;
+}
+
+static int usp10_compare_script_range(const void *key, const void *value)
+{
+    const struct usp10_script_range *range = value;
+    const DWORD *ch = key;
+
+    if (*ch < range->rangeFirst)
+        return -1;
+    if (*ch > range->rangeLast)
+        return 1;
+    return 0;
+}
+
+static enum usp10_script get_char_script(const WCHAR *str, unsigned int index,
+        unsigned int end, unsigned int *consumed)
 {
     static const WCHAR latin_punc[] = {'#','$','&','\'',',',';','<','>','?','@','\\','^','_','`','{','|','}','~', 0x00a0, 0};
-    WORD type = 0;
-    int i;
+    struct usp10_script_range *range;
+    WORD type = 0, type2 = 0;
+    DWORD ch;
 
-    if (ch == 0xc || ch == 0x20 || ch == 0x202f)
+    *consumed = 1;
+
+    if (str[index] == 0xc || str[index] == 0x20 || str[index] == 0x202f)
         return Script_CR;
 
-    /* These punctuation are separated out as Latin punctuation */
-    if (strchrW(latin_punc,ch))
+    /* These punctuation characters are separated out as Latin punctuation */
+    if (strchrW(latin_punc,str[index]))
         return Script_Punctuation2;
 
     /* These chars are itemized as Punctuation by Windows */
-    if (ch == 0x2212 || ch == 0x2044)
+    if (str[index] == 0x2212 || str[index] == 0x2044)
         return Script_Punctuation;
 
-    GetStringTypeW(CT_CTYPE1, &ch, 1, &type);
+    /* Currency Symbols by Unicode point */
+    switch (str[index])
+    {
+        case 0x09f2:
+        case 0x09f3: return Script_Bengali_Currency;
+        case 0x0af1: return Script_Gujarati_Currency;
+        case 0x0e3f: return Script_Thai_Currency;
+        case 0x20aa: return Script_Hebrew_Currency;
+        case 0x20ab: return Script_Vietnamese_Currency;
+        case 0xfb29: return Script_Hebrew_Currency;
+    }
+
+    GetStringTypeW(CT_CTYPE1, &str[index], 1, &type);
+    GetStringTypeW(CT_CTYPE2, &str[index], 1, &type2);
 
     if (type == 0)
         return SCRIPT_UNDEFINED;
@@ -560,41 +1006,61 @@ static WORD get_char_script( WCHAR ch)
     if (type & C1_CNTRL)
         return Script_Control;
 
-    i = 0;
-    do
-    {
-        if (ch < scriptRanges[i].rangeFirst || scriptRanges[i].script == SCRIPT_UNDEFINED)
-            break;
+    ch = decode_surrogate_pair(str, index, end);
+    if (ch)
+        *consumed = 2;
+    else
+        ch = str[index];
 
-        if (ch >= scriptRanges[i].rangeFirst && ch <= scriptRanges[i].rangeLast)
-        {
-            if (scriptRanges[i].numericScript && type & C1_DIGIT)
-                return scriptRanges[i].numericScript;
-            if (scriptRanges[i].punctScript && type & C1_PUNCT)
-                return scriptRanges[i].punctScript;
-            return scriptRanges[i].script;
-        }
-        i++;
-    } while (1);
+    if (!(range = bsearch(&ch, script_ranges, ARRAY_SIZE(script_ranges),
+            sizeof(*script_ranges), usp10_compare_script_range)))
+        return (*consumed == 2) ? Script_Surrogates : Script_Undefined;
 
-    return SCRIPT_UNDEFINED;
+    if (range->numericScript && (type & C1_DIGIT || type2 == C2_ARABICNUMBER))
+        return range->numericScript;
+    if (range->punctScript && type & C1_PUNCT)
+        return range->punctScript;
+    return range->script;
 }
 
-/***********************************************************************
- *      DllMain
- *
- */
-BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpv)
+static int compare_FindGlyph(const void *a, const void* b)
 {
-    switch(fdwReason)
-    {
-    case DLL_PROCESS_ATTACH:
-        DisableThreadLibraryCalls(hInstDLL);
-        break;
-    case DLL_PROCESS_DETACH:
-        break;
-    }
-    return TRUE;
+    const FindGlyph_struct *find = (FindGlyph_struct*)a;
+    const WORD *idx= (WORD*)b;
+    int rc = 0;
+
+    if ( find->target > *idx)
+        rc = 1;
+    else if (find->target < *idx)
+        rc = -1;
+
+    if (!find->ascending)
+        rc *= -1;
+    return rc;
+}
+
+int USP10_FindGlyphInLogClust(const WORD* pwLogClust, int cChars, WORD target)
+{
+    FindGlyph_struct fgs;
+    WORD *ptr;
+    INT k;
+
+    if (pwLogClust[0] < pwLogClust[cChars-1])
+        fgs.ascending = TRUE;
+    else
+        fgs.ascending = FALSE;
+
+    fgs.target = target;
+    ptr = bsearch(&fgs, pwLogClust, cChars, sizeof(WORD), compare_FindGlyph);
+
+    if (!ptr)
+        return -1;
+
+    for (k = (ptr - pwLogClust)-1; k >= 0 && pwLogClust[k] == target; k--)
+    ;
+    k++;
+
+    return k;
 }
 
 /***********************************************************************
@@ -616,14 +1082,51 @@ HRESULT WINAPI ScriptFreeCache(SCRIPT_CACHE *psc)
     if (psc && *psc)
     {
         unsigned int i;
+        INT n;
+
+        EnterCriticalSection(&cs_script_cache);
+        if (--((ScriptCache *)*psc)->refcount > 0)
+        {
+            LeaveCriticalSection(&cs_script_cache);
+            *psc = NULL;
+            return S_OK;
+        }
+        list_remove(&((ScriptCache *)*psc)->entry);
+        LeaveCriticalSection(&cs_script_cache);
+
         for (i = 0; i < GLYPH_MAX / GLYPH_BLOCK_SIZE; i++)
         {
-            heap_free(((ScriptCache *)*psc)->glyphs[i]);
             heap_free(((ScriptCache *)*psc)->widths[i]);
         }
+        for (i = 0; i < NUM_PAGES; i++)
+        {
+            unsigned int j;
+            if (((ScriptCache *)*psc)->page[i])
+                for (j = 0; j < GLYPH_MAX / GLYPH_BLOCK_SIZE; j++)
+                    heap_free(((ScriptCache *)*psc)->page[i]->glyphs[j]);
+            heap_free(((ScriptCache *)*psc)->page[i]);
+        }
         heap_free(((ScriptCache *)*psc)->GSUB_Table);
         heap_free(((ScriptCache *)*psc)->GDEF_Table);
-        heap_free(((ScriptCache *)*psc)->features);
+        heap_free(((ScriptCache *)*psc)->CMAP_Table);
+        heap_free(((ScriptCache *)*psc)->GPOS_Table);
+        for (n = 0; n < ((ScriptCache *)*psc)->script_count; n++)
+        {
+            int j;
+            for (j = 0; j < ((ScriptCache *)*psc)->scripts[n].language_count; j++)
+            {
+                int k;
+                for (k = 0; k < ((ScriptCache *)*psc)->scripts[n].languages[j].feature_count; k++)
+                    heap_free(((ScriptCache *)*psc)->scripts[n].languages[j].features[k].lookups);
+                heap_free(((ScriptCache *)*psc)->scripts[n].languages[j].features);
+            }
+            for (j = 0; j < ((ScriptCache *)*psc)->scripts[n].default_language.feature_count; j++)
+                heap_free(((ScriptCache *)*psc)->scripts[n].default_language.features[j].lookups);
+            heap_free(((ScriptCache *)*psc)->scripts[n].default_language.features);
+            heap_free(((ScriptCache *)*psc)->scripts[n].languages);
+        }
+        heap_free(((ScriptCache *)*psc)->scripts);
+        heap_free(((ScriptCache *)*psc)->otm);
         heap_free(*psc);
         *psc = NULL;
     }
@@ -652,7 +1155,7 @@ HRESULT WINAPI ScriptGetProperties(const SCRIPT_PROPERTIES ***props, int *num)
 
     if (!props && !num) return E_INVALIDARG;
 
-    if (num) *num = sizeof(script_props)/sizeof(script_props[0]);
+    if (num) *num = ARRAY_SIZE(script_props);
     if (props) *props = script_props;
 
     return S_OK;
@@ -680,12 +1183,7 @@ HRESULT WINAPI ScriptGetFontProperties(HDC hdc, SCRIPT_CACHE *psc, SCRIPT_FONTPR
     if (sfp->cBytes != sizeof(SCRIPT_FONTPROPERTIES))
         return E_INVALIDARG;
 
-    /* return something sensible? */
-    sfp->wgBlank = 0;
-    sfp->wgDefault = get_cache_default_char(psc);
-    sfp->wgInvalid = 0;
-    sfp->wgKashida = 0xffff;
-    sfp->iKashidaWidth = 0;
+    get_cache_font_properties(sfp, *psc);
 
     return S_OK;
 }
@@ -732,7 +1230,8 @@ HRESULT WINAPI ScriptRecordDigitSubstitution(LCID locale, SCRIPT_DIGITSUBSTITUTE
         sds->NationalDigitLanguage = LANG_ENGLISH;
 
     if (!GetLocaleInfoW(locale, LOCALE_IDIGITSUBSTITUTION | LOCALE_RETURN_NUMBER,
-                        (LPWSTR)&sub, sizeof(sub)/sizeof(WCHAR))) return E_INVALIDARG;
+            (WCHAR *)&sub, sizeof(sub) / sizeof(WCHAR)))
+        return E_INVALIDARG;
 
     switch (sub)
     {
@@ -801,12 +1300,12 @@ HRESULT WINAPI ScriptApplyDigitSubstitution(const SCRIPT_DIGITSUBSTITUTE *sds,
     }
 }
 
-static inline BOOL is_indic(WORD script)
+static inline BOOL is_indic(enum usp10_script script)
 {
     return (script >= Script_Devanagari && script <= Script_Malayalam_Numeric);
 }
 
-static inline WORD base_indic(WORD script)
+static inline enum usp10_script base_indic(enum usp10_script script)
 {
     switch (script)
     {
@@ -831,49 +1330,42 @@ static inline WORD base_indic(WORD script)
         case Script_Malayalam:
         case Script_Malayalam_Numeric: return Script_Malayalam;
         default:
-            return -1;
+            return Script_Undefined;
     };
 }
 
-/***********************************************************************
- *      ScriptItemizeOpenType (USP10.@)
- *
- * Split a Unicode string into shapeable parts.
- *
- * PARAMS
- *  pwcInChars  [I] String to split.
- *  cInChars    [I] Number of characters in pwcInChars.
- *  cMaxItems   [I] Maximum number of items to return.
- *  psControl   [I] Pointer to a SCRIPT_CONTROL structure.
- *  psState     [I] Pointer to a SCRIPT_STATE structure.
- *  pItems      [O] Buffer to receive SCRIPT_ITEM structures.
- *  pScriptTags [O] Buffer to receive OPENTYPE_TAGs.
- *  pcItems     [O] Number of script items returned.
- *
- * RETURNS
- *  Success: S_OK
- *  Failure: Non-zero HRESULT value.
- */
-HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int cMaxItems,
-                             const SCRIPT_CONTROL *psControl, const SCRIPT_STATE *psState,
-                             SCRIPT_ITEM *pItems, OPENTYPE_TAG *pScriptTags, int *pcItems)
+static BOOL script_is_numeric(enum usp10_script script)
+{
+    return scriptInformation[script].props.fNumeric;
+}
+
+static HRESULT _ItemizeInternal(const WCHAR *pwcInChars, int cInChars,
+                int cMaxItems, const SCRIPT_CONTROL *psControl,
+                const SCRIPT_STATE *psState, SCRIPT_ITEM *pItems,
+                OPENTYPE_TAG *pScriptTags, int *pcItems)
 {
 
 #define Numeric_space 0x0020
+#define ZWSP 0x200B
 #define ZWNJ 0x200C
 #define ZWJ  0x200D
 
+    enum usp10_script last_indic = Script_Undefined;
     int   cnt = 0, index = 0, str = 0;
-    int   New_Script = -1;
+    enum usp10_script New_Script = -1;
     int   i;
     WORD  *levels = NULL;
+    WORD  *layout_levels = NULL;
+    WORD  *overrides = NULL;
     WORD  *strength = NULL;
-    WORD  *scripts = NULL;
+    enum usp10_script *scripts;
     WORD  baselevel = 0;
+    WORD  baselayout = 0;
     BOOL  new_run;
-    WORD  last_indic = -1;
     WORD layoutRTL = 0;
     BOOL forceLevels = FALSE;
+    unsigned int consumed = 0;
+    HRESULT res = E_OUTOFMEMORY;
 
     TRACE("%s,%d,%d,%p,%p,%p,%p\n", debugstr_wn(pwcInChars, cInChars), cInChars, cMaxItems, 
           psControl, psState, pItems, pcItems);
@@ -881,34 +1373,76 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
     if (!pwcInChars || !cInChars || !pItems || cMaxItems < 2)
         return E_INVALIDARG;
 
-    scripts = heap_alloc(cInChars * sizeof(WORD));
-    if (!scripts)
+    if (!(scripts = heap_alloc(cInChars * sizeof(*scripts))))
         return E_OUTOFMEMORY;
 
     for (i = 0; i < cInChars; i++)
     {
-        scripts[i] = get_char_script(pwcInChars[i]);
+        if (!consumed)
+        {
+            scripts[i] = get_char_script(pwcInChars,i,cInChars,&consumed);
+            consumed --;
+        }
+        else
+        {
+            scripts[i] = scripts[i-1];
+            consumed --;
+        }
         /* Devanagari danda (U+0964) and double danda (U+0965) are used for
            all Indic scripts */
-        if ((pwcInChars[i] == 0x964 || pwcInChars[i] ==0x965) && last_indic > 0)
+        if ((pwcInChars[i] == 0x964 || pwcInChars[i] ==0x965) && last_indic != Script_Undefined)
             scripts[i] = last_indic;
         else if (is_indic(scripts[i]))
             last_indic = base_indic(scripts[i]);
 
-        /* Some unicode points (Zero Width Space U+200B -
-           Right-to-Left Mark U+200F) will force us into bidi mode */
-        if (!forceLevels && pwcInChars[i] >= 0x200B && pwcInChars[i] <= 0x200F)
+        /* Some unicode points :
+           (Zero Width Space U+200B - Right-to-Left Mark U+200F)
+           (Left Right Embed U+202A - Left Right Override U+202D)
+           (Left Right Isolate U+2066 - Pop Directional Isolate U+2069)
+           will force us into bidi mode */
+        if (!forceLevels && ((pwcInChars[i] >= 0x200B && pwcInChars[i] <= 0x200F) ||
+            (pwcInChars[i] >= 0x202A && pwcInChars[i] <= 0x202E) ||
+            (pwcInChars[i] >= 0x2066 && pwcInChars[i] <= 0x2069)))
+
             forceLevels = TRUE;
 
         /* Diacritical marks merge with other scripts */
-        if (scripts[i] == Script_Diacritical && i > 0)
-                scripts[i] = scripts[i-1];
+        if (scripts[i] == Script_Diacritical)
+        {
+            if (i > 0)
+            {
+                if (pScriptTags)
+                    scripts[i] = scripts[i-1];
+                else
+                {
+                    int j;
+                    BOOL asian = FALSE;
+                    enum usp10_script first_script = scripts[i-1];
+                    for (j = i-1; j >= 0 &&  scripts[j] == first_script && pwcInChars[j] != Numeric_space; j--)
+                    {
+                        enum usp10_script original = scripts[j];
+                        if (original == Script_Ideograph || original == Script_Kana || original == Script_Yi || original == Script_CJK_Han || original == Script_Bopomofo)
+                        {
+                            asian = TRUE;
+                            break;
+                        }
+                        if (original != Script_MathAlpha && scriptInformation[scripts[j]].props.fComplex)
+                            break;
+                        scripts[j] = scripts[i];
+                        if (original == Script_Punctuation2)
+                            break;
+                    }
+                    if (j >= 0 && (scriptInformation[scripts[j]].props.fComplex || asian))
+                        scripts[i] = scripts[j];
+                }
+            }
+        }
     }
 
     for (i = 0; i < cInChars; i++)
     {
         /* Joiners get merged preferencially right */
-        if (i > 0 && (pwcInChars[i] == ZWJ || pwcInChars[i] == ZWNJ))
+        if (i > 0 && (pwcInChars[i] == ZWJ || pwcInChars[i] == ZWNJ || pwcInChars[i] == ZWSP))
         {
             int j;
             if (i+1 == cInChars)
@@ -917,7 +1451,8 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
             {
                 for (j = i+1; j < cInChars; j++)
                 {
-                    if (pwcInChars[j] != ZWJ && pwcInChars[j] != ZWNJ && pwcInChars[j] != Numeric_space)
+                    if (pwcInChars[j] != ZWJ && pwcInChars[j] != ZWNJ
+                            && pwcInChars[j] != ZWSP && pwcInChars[j] != Numeric_space)
                     {
                         scripts[i] = scripts[j];
                         break;
@@ -931,33 +1466,62 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
     {
         levels = heap_alloc_zero(cInChars * sizeof(WORD));
         if (!levels)
+            goto nomemory;
+
+        overrides = heap_alloc_zero(cInChars * sizeof(WORD));
+        if (!overrides)
+            goto nomemory;
+
+        layout_levels = heap_alloc_zero(cInChars * sizeof(WORD));
+        if (!layout_levels)
+            goto nomemory;
+
+        if (psState->fOverrideDirection)
         {
-            heap_free(scripts);
-            return E_OUTOFMEMORY;
-        }
+            if (!forceLevels)
+            {
+                SCRIPT_STATE s = *psState;
+                s.fOverrideDirection = FALSE;
+                BIDI_DetermineLevels(pwcInChars, cInChars, &s, psControl, layout_levels, overrides);
+                if (odd(layout_levels[0]))
+                    forceLevels = TRUE;
+                else for (i = 0; i < cInChars; i++)
+                    if (layout_levels[i]!=layout_levels[0])
+                    {
+                        forceLevels = TRUE;
+                        break;
+                    }
+            }
 
-        BIDI_DetermineLevels(pwcInChars, cInChars, psState, psControl, levels);
+            BIDI_DetermineLevels(pwcInChars, cInChars, psState, psControl, levels, overrides);
+        }
+        else
+        {
+            BIDI_DetermineLevels(pwcInChars, cInChars, psState, psControl, levels, overrides);
+            memcpy(layout_levels, levels, cInChars * sizeof(WORD));
+        }
         baselevel = levels[0];
+        baselayout = layout_levels[0];
         for (i = 0; i < cInChars; i++)
             if (levels[i]!=levels[0])
                 break;
         if (i >= cInChars && !odd(baselevel) && !odd(psState->uBidiLevel) && !forceLevels)
         {
             heap_free(levels);
+            heap_free(overrides);
+            heap_free(layout_levels);
+            overrides = NULL;
             levels = NULL;
+            layout_levels = NULL;
         }
         else
         {
-            BOOL inNumber = FALSE;
-            static WCHAR math_punc[] = {'#','$','%','+',',','-','.','/',':',0x2212, 0x2044, 0x00a0,0};
+            static const WCHAR math_punc[] = {'#','$','%','+',',','-','.','/',':',0x2212, 0x2044, 0x00a0,0};
+            static const WCHAR repeatable_math_punc[] = {'#','$','%','+','-','/',0x2212, 0x2044,0};
 
             strength = heap_alloc_zero(cInChars * sizeof(WORD));
             if (!strength)
-            {
-                heap_free(scripts);
-                heap_free(levels);
-                return E_OUTOFMEMORY;
-            }
+                goto nomemory;
             BIDI_GetStrengths(pwcInChars, cInChars, psControl, strength);
 
             /* We currently mis-level leading Diacriticals */
@@ -968,31 +1532,60 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
                     strength[i] = BIDI_STRONG;
                 }
 
+            /* Math punctuation bordered on both sides by numbers can be
+               merged into the number */
             for (i = 0; i < cInChars; i++)
             {
-                /* Script_Numeric and select puncuation at level 0 get bumped to level 2 */
-                if ((levels[i] == 0 || (odd(psState->uBidiLevel) && levels[i] == psState->uBidiLevel+1)) && inNumber && strchrW(math_punc,pwcInChars[i]))
+                if (i > 0 && i < cInChars-1 &&
+                    script_is_numeric(scripts[i-1]) &&
+                    strchrW(math_punc, pwcInChars[i]))
                 {
-                    scripts[i] = Script_Numeric;
-                    levels[i] = 2;
+                    if (script_is_numeric(scripts[i+1]))
+                    {
+                        scripts[i] = scripts[i+1];
+                        levels[i] = levels[i-1];
+                        strength[i] = strength[i-1];
+                        i++;
+                    }
+                    else if (strchrW(repeatable_math_punc, pwcInChars[i]))
+                    {
+                        int j;
+                        for (j = i+1; j < cInChars; j++)
+                        {
+                            if (script_is_numeric(scripts[j]))
+                            {
+                                for(;i<j; i++)
+                                {
+                                    scripts[i] = scripts[j];
+                                    levels[i] = levels[i-1];
+                                    strength[i] = strength[i-1];
+                                }
+                            }
+                            else if (pwcInChars[i] != pwcInChars[j]) break;
+                        }
+                    }
                 }
-                else if ((levels[i] == 0 || (odd(psState->uBidiLevel) && levels[i] == psState->uBidiLevel+1)) && scripts[i] == Script_Numeric)
+            }
+
+            for (i = 0; i < cInChars; i++)
+            {
+                /* Numerics at level 0 get bumped to level 2 */
+                if (!overrides[i] && (levels[i] == 0 || (odd(psState->uBidiLevel)
+                        && levels[i] == psState->uBidiLevel + 1)) && script_is_numeric(scripts[i]))
                 {
                     levels[i] = 2;
-                    inNumber = TRUE;
                 }
-                else
-                    inNumber = FALSE;
 
                 /* Joiners get merged preferencially right */
-                if (i > 0 && (pwcInChars[i] == ZWJ || pwcInChars[i] == ZWNJ))
+                if (i > 0 && (pwcInChars[i] == ZWJ || pwcInChars[i] == ZWNJ || pwcInChars[i] == ZWSP))
                 {
                     int j;
                     if (i+1 == cInChars && levels[i-1] == levels[i])
                         strength[i] = strength[i-1];
                     else
                         for (j = i+1; j < cInChars && levels[i] == levels[j]; j++)
-                            if (pwcInChars[j] != ZWJ && pwcInChars[j] != ZWNJ && pwcInChars[j] != Numeric_space)
+                            if (pwcInChars[j] != ZWJ && pwcInChars[j] != ZWNJ
+                                    && pwcInChars[j] != ZWSP && pwcInChars[j] != Numeric_space)
                             {
                                 strength[i] = strength[j];
                                 break;
@@ -1040,7 +1633,8 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
         }
     }
 
-    while ((!levels || (levels && levels[cnt+1] == levels[0])) && (pwcInChars[cnt] == Numeric_space) && cnt < cInChars)
+    while ((!levels || (levels && cnt+1 < cInChars && levels[cnt+1] == levels[0]))
+            && (cnt < cInChars && pwcInChars[cnt] == Numeric_space))
         cnt++;
 
     if (cnt == cInChars) /* All Spaces */
@@ -1051,7 +1645,8 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
 
     pItems[index].iCharPos = 0;
     pItems[index].a = scriptInformation[scripts[cnt]].a;
-    pScriptTags[index] = scriptInformation[scripts[cnt]].scriptTag;
+    if (pScriptTags)
+        pScriptTags[index] = scriptInformation[scripts[cnt]].scriptTag;
 
     if (strength && strength[cnt] == BIDI_STRONG)
         str = strength[cnt];
@@ -1063,19 +1658,29 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
     if (levels)
     {
         if (strength[cnt] == BIDI_STRONG)
-            layoutRTL = (odd(levels[cnt]))?1:0;
+            layoutRTL = odd(layout_levels[cnt]);
         else
-            layoutRTL = (psState->uBidiLevel || odd(levels[cnt]))?1:0;
+            layoutRTL = (psState->uBidiLevel || odd(layout_levels[cnt]));
+        if (overrides)
+            pItems[index].a.s.fOverrideDirection = (overrides[cnt] != 0);
         pItems[index].a.fRTL = odd(levels[cnt]);
-        pItems[index].a.fLayoutRTL = layoutRTL;
+        if (script_is_numeric(pItems[index].a.eScript))
+            pItems[index].a.fLayoutRTL = layoutRTL;
+        else
+            pItems[index].a.fLayoutRTL = pItems[index].a.fRTL;
         pItems[index].a.s.uBidiLevel = levels[cnt];
     }
-    else if (!pItems[index].a.s.uBidiLevel)
+    else if (!pItems[index].a.s.uBidiLevel || (overrides && overrides[cnt]))
     {
-        layoutRTL = (odd(baselevel))?1:0;
+        if (pItems[index].a.s.uBidiLevel != baselevel)
+            pItems[index].a.s.fOverrideDirection = TRUE;
+        layoutRTL = odd(baselayout);
         pItems[index].a.s.uBidiLevel = baselevel;
-        pItems[index].a.fLayoutRTL = odd(baselevel);
         pItems[index].a.fRTL = odd(baselevel);
+        if (script_is_numeric(pItems[index].a.eScript))
+            pItems[index].a.fLayoutRTL = odd(baselayout);
+        else
+            pItems[index].a.fLayoutRTL = pItems[index].a.fRTL;
     }
 
     TRACE("New_Level=%i New_Strength=%i New_Script=%d, eScript=%d index=%d cnt=%d iCharPos=%d\n",
@@ -1126,8 +1731,9 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
 
         if (!new_run && strength && str == BIDI_STRONG)
         {
-            layoutRTL = odd(levels[cnt])?1:0;
-            pItems[index].a.fLayoutRTL = layoutRTL;
+            layoutRTL = odd(layout_levels[cnt]);
+            if (script_is_numeric(pItems[index].a.eScript))
+                pItems[index].a.fLayoutRTL = layoutRTL;
         }
 
         if (new_run)
@@ -1136,7 +1742,7 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
 
             index++;
             if  (index+1 > cMaxItems)
-                return E_OUTOFMEMORY;
+                goto nomemory;
 
             if (strength)
                 str = strength[cnt];
@@ -1145,22 +1751,33 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
             memset(&pItems[index].a, 0, sizeof(SCRIPT_ANALYSIS));
 
             pItems[index].a = scriptInformation[New_Script].a;
-            pScriptTags[index] = scriptInformation[New_Script].scriptTag;
+            if (pScriptTags)
+                pScriptTags[index] = scriptInformation[New_Script].scriptTag;
             if (levels)
             {
-                if (levels[cnt] == 0)
+                if (overrides)
+                    pItems[index].a.s.fOverrideDirection = (overrides[cnt] != 0);
+                if (layout_levels[cnt] == 0)
                     layoutRTL = 0;
                 else
-                    layoutRTL = (layoutRTL || odd(levels[cnt]))?1:0;
+                    layoutRTL = (layoutRTL || odd(layout_levels[cnt]));
                 pItems[index].a.fRTL = odd(levels[cnt]);
-                pItems[index].a.fLayoutRTL = layoutRTL;
+                if (script_is_numeric(pItems[index].a.eScript))
+                    pItems[index].a.fLayoutRTL = layoutRTL;
+                else
+                    pItems[index].a.fLayoutRTL = pItems[index].a.fRTL;
                 pItems[index].a.s.uBidiLevel = levels[cnt];
             }
-            else if (!pItems[index].a.s.uBidiLevel)
+            else if (!pItems[index].a.s.uBidiLevel || (overrides && overrides[cnt]))
             {
+                if (pItems[index].a.s.uBidiLevel != baselevel)
+                    pItems[index].a.s.fOverrideDirection = TRUE;
                 pItems[index].a.s.uBidiLevel = baselevel;
-                pItems[index].a.fLayoutRTL = layoutRTL;
                 pItems[index].a.fRTL = odd(baselevel);
+                if (script_is_numeric(pItems[index].a.eScript))
+                    pItems[index].a.fLayoutRTL = layoutRTL;
+                else
+                    pItems[index].a.fLayoutRTL = pItems[index].a.fRTL;
             }
 
             TRACE("index=%d cnt=%d iCharPos=%d\n", index, cnt, pItems[index].iCharPos);
@@ -1171,20 +1788,50 @@ HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int
      * item is set up to prevent random behaviour if the caller erroneously
      * checks the n+1 structure                                              */
     index++;
+    if (index + 1 > cMaxItems) goto nomemory;
     memset(&pItems[index].a, 0, sizeof(SCRIPT_ANALYSIS));
 
     TRACE("index=%d cnt=%d iCharPos=%d\n", index, cnt, pItems[index].iCharPos);
 
     /*  Set one SCRIPT_STATE item being returned  */
-    if  (index + 1 > cMaxItems) return E_OUTOFMEMORY;
     if (pcItems) *pcItems = index;
 
     /*  Set SCRIPT_ITEM                                     */
     pItems[index].iCharPos = cnt;         /* the last item contains the ptr to the lastchar */
+    res = S_OK;
+nomemory:
     heap_free(levels);
+    heap_free(overrides);
+    heap_free(layout_levels);
     heap_free(strength);
     heap_free(scripts);
-    return S_OK;
+    return res;
+}
+
+/***********************************************************************
+ *      ScriptItemizeOpenType (USP10.@)
+ *
+ * Split a Unicode string into shapeable parts.
+ *
+ * PARAMS
+ *  pwcInChars  [I] String to split.
+ *  cInChars    [I] Number of characters in pwcInChars.
+ *  cMaxItems   [I] Maximum number of items to return.
+ *  psControl   [I] Pointer to a SCRIPT_CONTROL structure.
+ *  psState     [I] Pointer to a SCRIPT_STATE structure.
+ *  pItems      [O] Buffer to receive SCRIPT_ITEM structures.
+ *  pScriptTags [O] Buffer to receive OPENTYPE_TAGs.
+ *  pcItems     [O] Number of script items returned.
+ *
+ * RETURNS
+ *  Success: S_OK
+ *  Failure: Non-zero HRESULT value.
+ */
+HRESULT WINAPI ScriptItemizeOpenType(const WCHAR *pwcInChars, int cInChars, int cMaxItems,
+                             const SCRIPT_CONTROL *psControl, const SCRIPT_STATE *psState,
+                             SCRIPT_ITEM *pItems, OPENTYPE_TAG *pScriptTags, int *pcItems)
+{
+    return _ItemizeInternal(pwcInChars, cInChars, cMaxItems, psControl, psState, pItems, pScriptTags, pcItems);
 }
 
 /***********************************************************************
@@ -1209,15 +1856,7 @@ HRESULT WINAPI ScriptItemize(const WCHAR *pwcInChars, int cInChars, int cMaxItem
                              const SCRIPT_CONTROL *psControl, const SCRIPT_STATE *psState,
                              SCRIPT_ITEM *pItems, int *pcItems)
 {
-    OPENTYPE_TAG *discarded_tags;
-    HRESULT res;
-
-    discarded_tags = heap_alloc(cMaxItems * sizeof(OPENTYPE_TAG));
-    if (!discarded_tags)
-        return E_OUTOFMEMORY;
-    res = ScriptItemizeOpenType(pwcInChars, cInChars, cMaxItems, psControl, psState, pItems, discarded_tags, pcItems);
-    heap_free(discarded_tags);
-    return res;
+    return _ItemizeInternal(pwcInChars, cInChars, cMaxItems, psControl, psState, pItems, NULL, pcItems);
 }
 
 static inline int getGivenTabWidth(ScriptCache *psc, SCRIPT_TABDEF *pTabdef, int charPos, int current_x)
@@ -1251,7 +1890,12 @@ static inline int getGivenTabWidth(ScriptCache *psc, SCRIPT_TABDEF *pTabdef, int
         cTabStops = 0;
     }
     else
-        defWidth = 8 * psc->tm.tmAveCharWidth;
+    {
+        if (pTabdef->iScale)
+            defWidth = (32 * pTabdef->iScale) / 4;
+        else
+            defWidth = 8 * psc->tm.tmAveCharWidth;
+    }
 
     for (; cTabStops>0 ; lpTabPos++, cTabStops--)
     {
@@ -1265,10 +1909,10 @@ static inline int getGivenTabWidth(ScriptCache *psc, SCRIPT_TABDEF *pTabdef, int
 
         if( nTabOrg + position > current_x)
         {
-            if( *lpTabPos >= 0)
+            if( position >= 0)
             {
                 /* a left aligned tab */
-                x = (nTabOrg + *lpTabPos) - current_x;
+                x = (nTabOrg + position) - current_x;
                 break;
             }
             else
@@ -1317,7 +1961,7 @@ static BOOL requires_fallback(HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS *psa,
     return FALSE;
 }
 
-static void find_fallback_font(DWORD scriptid, LPWSTR FaceName)
+static void find_fallback_font(enum usp10_script scriptid, WCHAR *FaceName)
 {
     HKEY hkey;
 
@@ -1329,7 +1973,7 @@ static void find_fallback_font(DWORD scriptid, LPWSTR FaceName)
         DWORD type;
 
         sprintfW(value, szFmt, scriptInformation[scriptid].scriptTag);
-        if (RegQueryValueExW(hkey, value, 0, &type, (LPBYTE)FaceName, &count))
+        if (RegQueryValueExW(hkey, value, 0, &type, (BYTE *)FaceName, &count))
             lstrcpyW(FaceName,scriptInformation[scriptid].fallbackFont);
         RegCloseKey(hkey);
     }
@@ -1374,7 +2018,7 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
     /* FIXME: handle clipping */
     analysis->clip_len = cString;
     analysis->hdc = hdc;
-    analysis->dwFlags = dwFlags;
+    analysis->ssa_flags = dwFlags;
 
     if (psState)
         sState = *psState;
@@ -1402,19 +2046,12 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
     hr = ScriptItemize(pString, cString, num_items, &sControl, &sState, analysis->pItem,
                        &analysis->numItems);
 
-    while (hr == E_OUTOFMEMORY)
+    if (FAILED(hr))
     {
-        SCRIPT_ITEM *tmp;
-
-        num_items *= 2;
-        if (!(tmp = heap_realloc_zero(analysis->pItem, num_items * sizeof(SCRIPT_ITEM) + 1)))
-            goto error;
-
-        analysis->pItem = tmp;
-        hr = ScriptItemize(pString, cString, num_items, psControl, psState, analysis->pItem,
-                           &analysis->numItems);
+        if (hr == E_OUTOFMEMORY)
+            hr = E_INVALIDARG;
+        goto error;
     }
-    if (hr != S_OK) goto error;
 
     /* set back to out of memory for default goto error behaviour */
     hr = E_OUTOFMEMORY;
@@ -1424,7 +2061,9 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
         if ((analysis->logattrs = heap_alloc(sizeof(SCRIPT_LOGATTR) * cString)))
         {
             for (i = 0; i < analysis->numItems; i++)
-                ScriptBreak(&((LPWSTR)pString)[analysis->pItem[i].iCharPos], analysis->pItem[i+1].iCharPos - analysis->pItem[i].iCharPos, &analysis->pItem[i].a, &analysis->logattrs[analysis->pItem[i].iCharPos]);
+                ScriptBreak(&((WCHAR *)pString)[analysis->pItem[i].iCharPos],
+                        analysis->pItem[i + 1].iCharPos - analysis->pItem[i].iCharPos,
+                        &analysis->pItem[i].a, &analysis->logattrs[analysis->pItem[i].iCharPos]);
         }
         else
             goto error;
@@ -1454,7 +2093,6 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
             int *piAdvance = heap_alloc_zero(sizeof(int) * numGlyphs);
             SCRIPT_VISATTR *psva = heap_alloc_zero(sizeof(SCRIPT_VISATTR) * numGlyphs);
             GOFFSET *pGoffset = heap_alloc_zero(sizeof(GOFFSET) * numGlyphs);
-            ABC *abc = heap_alloc_zero(sizeof(ABC));
             int numGlyphsReturned;
             HFONT originalFont = 0x0;
 
@@ -1462,7 +2100,7 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
             const WCHAR* pStr = (const WCHAR*)pString;
             analysis->glyphs[i].fallbackFont = NULL;
 
-            if (!glyphs || !pwLogClust || !piAdvance || !psva || !pGoffset || !abc)
+            if (!glyphs || !pwLogClust || !piAdvance || !psva || !pGoffset)
             {
                 heap_free (BidiLevel);
                 heap_free (glyphs);
@@ -1470,7 +2108,6 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
                 heap_free (piAdvance);
                 heap_free (psva);
                 heap_free (pGoffset);
-                heap_free (abc);
                 hr = E_OUTOFMEMORY;
                 goto error;
             }
@@ -1480,20 +2117,30 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
                 LOGFONTW lf;
                 GetObjectW(GetCurrentObject(hdc, OBJ_FONT), sizeof(lf), & lf);
                 lf.lfCharSet = scriptInformation[analysis->pItem[i].a.eScript].props.bCharSet;
+                lf.lfFaceName[0] = 0;
                 find_fallback_font(analysis->pItem[i].a.eScript, lf.lfFaceName);
-                analysis->glyphs[i].fallbackFont = CreateFontIndirectW(&lf);
-                if (analysis->glyphs[i].fallbackFont)
+                if (lf.lfFaceName[0])
                 {
-                    ScriptFreeCache(sc);
-                    originalFont = SelectObject(hdc, analysis->glyphs[i].fallbackFont);
+                    analysis->glyphs[i].fallbackFont = CreateFontIndirectW(&lf);
+                    if (analysis->glyphs[i].fallbackFont)
+                    {
+                        ScriptFreeCache(sc);
+                        originalFont = SelectObject(hdc, analysis->glyphs[i].fallbackFont);
+                    }
                 }
             }
 
-            hr = ScriptShape(hdc, sc, &pStr[analysis->pItem[i].iCharPos],
-                             cChar, numGlyphs, &analysis->pItem[i].a,
-                             glyphs, pwLogClust, psva, &numGlyphsReturned);
+            /* FIXME: When we properly shape Hangul remove this check */
+            if ((dwFlags & SSA_LINK) && !analysis->glyphs[i].fallbackFont && analysis->pItem[i].a.eScript == Script_Hangul)
+                analysis->pItem[i].a.fNoGlyphIndex = TRUE;
+
+            if ((dwFlags & SSA_LINK) && !analysis->glyphs[i].fallbackFont && !scriptInformation[analysis->pItem[i].a.eScript].props.fComplex && !analysis->pItem[i].a.fRTL)
+                analysis->pItem[i].a.fNoGlyphIndex = TRUE;
+
+            ScriptShape(hdc, sc, &pStr[analysis->pItem[i].iCharPos], cChar, numGlyphs,
+                        &analysis->pItem[i].a, glyphs, pwLogClust, psva, &numGlyphsReturned);
             hr = ScriptPlace(hdc, sc, glyphs, numGlyphsReturned, psva, &analysis->pItem[i].a,
-                             piAdvance, pGoffset, abc);
+                        piAdvance, pGoffset, &analysis->glyphs[i].abc);
             if (originalFont)
                 SelectObject(hdc,originalFont);
 
@@ -1514,7 +2161,6 @@ HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
             analysis->glyphs[i].piAdvance = piAdvance;
             analysis->glyphs[i].psva = psva;
             analysis->glyphs[i].pGoffset = pGoffset;
-            analysis->glyphs[i].abc = abc;
             analysis->glyphs[i].iMaxPosX= -1;
 
             BidiLevel[i] = analysis->pItem[i].a.s.uBidiLevel;
@@ -1545,13 +2191,9 @@ error:
 
 static inline BOOL does_glyph_start_cluster(const SCRIPT_VISATTR *pva, const WORD *pwLogClust, int cChars, int glyph, int direction)
 {
-    int i;
-
     if (pva[glyph].fClusterStart)
         return TRUE;
-    for (i = 0; i < cChars; i++)
-        if (pwLogClust[i] == glyph) break;
-    if (i != cChars)
+    if (USP10_FindGlyphInLogClust(pwLogClust, cChars, glyph) >= 0)
         return TRUE;
 
     return FALSE;
@@ -1578,6 +2220,8 @@ static HRESULT SS_ItemOut( SCRIPT_STRING_ANALYSIS ssa,
     INT runStart, runEnd;
     INT iGlyph, cGlyphs;
     HFONT oldFont = 0x0;
+    RECT  crc;
+    int i;
 
     TRACE("(%p,%d,%d,%d,%d,%d, 0x%1x, %d, %d)\n",
          ssa, iX, iY, iItem, cStart, cEnd, uOptions, fSelected, fDisabled);
@@ -1588,6 +2232,7 @@ static HRESULT SS_ItemOut( SCRIPT_STRING_ANALYSIS ssa,
          (cEnd >= 0 && analysis->pItem[iItem].iCharPos >= cEnd))
             return S_OK;
 
+    CopyRect(&crc,prc);
     if (fSelected)
     {
         BkMode = GetBkMode(analysis->hdc);
@@ -1618,6 +2263,7 @@ static HRESULT SS_ItemOut( SCRIPT_STRING_ANALYSIS ssa,
             ScriptStringCPtoX(ssa, cEnd, FALSE, &off_x);
         else
             ScriptStringCPtoX(ssa, analysis->pItem[iItem+1].iCharPos-1, TRUE, &off_x);
+        crc.left = iX + off_x;
     }
     else
     {
@@ -1625,6 +2271,7 @@ static HRESULT SS_ItemOut( SCRIPT_STRING_ANALYSIS ssa,
             ScriptStringCPtoX(ssa, cStart, FALSE, &off_x);
         else
             ScriptStringCPtoX(ssa, analysis->pItem[iItem].iCharPos, FALSE, &off_x);
+        crc.left = iX + off_x;
     }
 
     if (analysis->pItem[iItem].a.fRTL)
@@ -1639,6 +2286,24 @@ static HRESULT SS_ItemOut( SCRIPT_STRING_ANALYSIS ssa,
 
     cGlyphs++;
 
+    /* adjust for cluster glyphs when starting */
+    if (analysis->pItem[iItem].a.fRTL)
+        i = analysis->pItem[iItem+1].iCharPos - 1;
+    else
+        i = analysis->pItem[iItem].iCharPos;
+
+    for (; i >=analysis->pItem[iItem].iCharPos && i < analysis->pItem[iItem+1].iCharPos; (analysis->pItem[iItem].a.fRTL)?i--:i++)
+    {
+        if (analysis->glyphs[iItem].pwLogClust[i - analysis->pItem[iItem].iCharPos] == iGlyph)
+        {
+            if (analysis->pItem[iItem].a.fRTL)
+                ScriptStringCPtoX(ssa, i, TRUE, &off_x);
+            else
+                ScriptStringCPtoX(ssa, i, FALSE, &off_x);
+            break;
+        }
+    }
+
     if (cEnd < 0 || scriptInformation[analysis->pItem[iItem].a.eScript].props.fNeedsCaretInfo)
     {
         INT direction;
@@ -1660,7 +2325,7 @@ static HRESULT SS_ItemOut( SCRIPT_STRING_ANALYSIS ssa,
 
     hr = ScriptTextOut(analysis->hdc,
                        (SCRIPT_CACHE *)&analysis->glyphs[iItem].sc, iX + off_x,
-                       iY, uOptions, prc, &analysis->pItem[iItem].a, NULL, 0,
+                       iY, uOptions, &crc, &analysis->pItem[iItem].a, NULL, 0,
                        &analysis->glyphs[iItem].glyphs[iGlyph], cGlyphs,
                        &analysis->glyphs[iItem].piAdvance[iGlyph], NULL,
                        &analysis->glyphs[iItem].pGoffset[iGlyph]);
@@ -1691,7 +2356,7 @@ static HRESULT SS_ItemOut( SCRIPT_STRING_ANALYSIS ssa,
  *  ssa       [I] buffer to hold the analysed string components
  *  iX        [I] X axis displacement for output
  *  iY        [I] Y axis displacement for output
- *  uOptions  [I] flags controling output processing
+ *  uOptions  [I] flags controlling output processing
  *  prc       [I] rectangle coordinates
  *  iMinSel   [I] starting pos for substringing output string
  *  iMaxSel   [I] ending pos for substringing output string
@@ -1714,11 +2379,11 @@ HRESULT WINAPI ScriptStringOut(SCRIPT_STRING_ANALYSIS ssa,
     int   item;
     HRESULT hr;
 
-    TRACE("(%p,%d,%d,0x%1x,%p,%d,%d,%d)\n",
-         ssa, iX, iY, uOptions, prc, iMinSel, iMaxSel, fDisabled);
+    TRACE("(%p,%d,%d,0x%08x,%s,%d,%d,%d)\n",
+         ssa, iX, iY, uOptions, wine_dbgstr_rect(prc), iMinSel, iMaxSel, fDisabled);
 
     if (!(analysis = ssa)) return E_INVALIDARG;
-    if (!(analysis->dwFlags & SSA_GLYPHS)) return E_INVALIDARG;
+    if (!(analysis->ssa_flags & SSA_GLYPHS)) return E_INVALIDARG;
 
     for (item = 0; item < analysis->numItems; item++)
     {
@@ -1755,12 +2420,12 @@ HRESULT WINAPI ScriptStringCPtoX(SCRIPT_STRING_ANALYSIS ssa, int icp, BOOL fTrai
     TRACE("(%p), %d, %d, (%p)\n", ssa, icp, fTrailing, pX);
 
     if (!ssa || !pX) return S_FALSE;
-    if (!(analysis->dwFlags & SSA_GLYPHS)) return S_FALSE;
+    if (!(analysis->ssa_flags & SSA_GLYPHS)) return S_FALSE;
 
     /* icp out of range */
     if(icp < 0)
     {
-        analysis->invalid = TRUE;
+        analysis->flags |= SCRIPT_STRING_ANALYSIS_FLAGS_INVALID;
         return E_INVALIDARG;
     }
 
@@ -1801,7 +2466,7 @@ HRESULT WINAPI ScriptStringCPtoX(SCRIPT_STRING_ANALYSIS ssa, int icp, BOOL fTrai
     }
 
     /* icp out of range */
-    analysis->invalid = TRUE;
+    analysis->flags |= SCRIPT_STRING_ANALYSIS_FLAGS_INVALID;
     return E_INVALIDARG;
 }
 
@@ -1817,7 +2482,7 @@ HRESULT WINAPI ScriptStringXtoCP(SCRIPT_STRING_ANALYSIS ssa, int iX, int* piCh,
     TRACE("(%p), %d, (%p), (%p)\n", ssa, iX, piCh, piTrailing);
 
     if (!ssa || !piCh || !piTrailing) return S_FALSE;
-    if (!(analysis->dwFlags & SSA_GLYPHS)) return S_FALSE;
+    if (!(analysis->ssa_flags & SSA_GLYPHS)) return S_FALSE;
 
     /* out of range */
     if(iX < 0)
@@ -1901,7 +2566,7 @@ HRESULT WINAPI ScriptStringFree(SCRIPT_STRING_ANALYSIS *pssa)
 
     if (!pssa || !(analysis = *pssa)) return E_INVALIDARG;
 
-    invalid = analysis->invalid;
+    invalid = analysis->flags & SCRIPT_STRING_ANALYSIS_FLAGS_INVALID;
 
     if (analysis->glyphs)
     {
@@ -1912,7 +2577,6 @@ HRESULT WINAPI ScriptStringFree(SCRIPT_STRING_ANALYSIS *pssa)
             heap_free(analysis->glyphs[i].piAdvance);
             heap_free(analysis->glyphs[i].psva);
             heap_free(analysis->glyphs[i].pGoffset);
-            heap_free(analysis->glyphs[i].abc);
             if (analysis->glyphs[i].fallbackFont)
                 DeleteObject(analysis->glyphs[i].fallbackFont);
             ScriptFreeCache((SCRIPT_CACHE *)&analysis->glyphs[i].sc);
@@ -1923,7 +2587,6 @@ HRESULT WINAPI ScriptStringFree(SCRIPT_STRING_ANALYSIS *pssa)
 
     heap_free(analysis->pItem);
     heap_free(analysis->logattrs);
-    heap_free(analysis->sz);
     heap_free(analysis->logical2visual);
     heap_free(analysis);
 
@@ -1958,16 +2621,14 @@ static inline int get_cluster_size(const WORD *pwLogClust, int cChars, int item,
 static inline int get_glyph_cluster_advance(const int* piAdvance, const SCRIPT_VISATTR *pva, const WORD *pwLogClust, int cGlyphs, int cChars, int glyph, int direction)
 {
     int advance;
-    int log_clust_max = 0;
-    int i;
+    int log_clust_max;
 
     advance = piAdvance[glyph];
 
-    for (i = 0; i < cChars; i++)
-    {
-        if (pwLogClust[i] > log_clust_max)
-            log_clust_max = pwLogClust[i];
-    }
+    if (pwLogClust[0] > pwLogClust[cChars-1])
+        log_clust_max = pwLogClust[0];
+    else
+        log_clust_max = pwLogClust[cChars-1];
 
     if (glyph > log_clust_max)
         return advance;
@@ -2038,7 +2699,7 @@ HRESULT WINAPI ScriptCPtoX(int iCP,
     iPosX = 0.0;
     for (item=0; item < iCP && item < cChars; item++)
     {
-        if (iSpecial == -1 && (iCluster == -1 || (iCluster != -1 && iCluster+clust_size <= item)))
+        if (iSpecial == -1 && (iCluster == -1 || iCluster+clust_size <= item))
         {
             int check;
             int clust = pwLogClust[item];
@@ -2051,8 +2712,9 @@ HRESULT WINAPI ScriptCPtoX(int iCP,
 
             if (check >= cChars && !iMaxPos)
             {
-                for (check = clust; check < cChars; check++)
-                    special_size += get_glyph_cluster_advance(piAdvance, psva, pwLogClust, cGlyphs, cChars, check, 1);
+                int glyph;
+                for (glyph = clust; glyph < cGlyphs; glyph++)
+                    special_size += get_glyph_cluster_advance(piAdvance, psva, pwLogClust, cGlyphs, cChars, glyph, 1);
                 iSpecial = item;
                 special_size /= (cChars - item);
                 iPosX += special_size;
@@ -2097,9 +2759,100 @@ HRESULT WINAPI ScriptCPtoX(int iCP,
     return S_OK;
 }
 
+/* Count the number of characters in a cluster and its starting index*/
+static inline BOOL get_cluster_data(const WORD *pwLogClust, int cChars, int cluster_index, int *cluster_size, int *start_index)
+{
+    int size = 0;
+    int i;
+
+    for (i = 0; i < cChars; i++)
+    {
+        if (pwLogClust[i] == cluster_index)
+        {
+            if (!size && start_index)
+            {
+                *start_index = i;
+                if (!cluster_size)
+                    return TRUE;
+            }
+            size++;
+        }
+        else if (size) break;
+    }
+    if (cluster_size)
+        *cluster_size = size;
+
+    return (size > 0);
+}
+
+/*
+    To handle multi-glyph clusters we need to find all the glyphs that are
+    represented in the cluster. This involves finding the glyph whose
+    index is the cluster index as well as whose glyph indices are greater than
+    our cluster index but not part of a new cluster.
+
+    Then we sum all those glyphs' advances.
+*/
+static inline int get_cluster_advance(const int* piAdvance,
+                                      const SCRIPT_VISATTR *psva,
+                                      const WORD *pwLogClust, int cGlyphs,
+                                      int cChars, int cluster, int direction)
+{
+    int glyph_start;
+    int glyph_end;
+    int i, advance;
+
+    if (direction > 0)
+        i = 0;
+    else
+        i = (cChars - 1);
+
+    for (glyph_start = -1, glyph_end = -1; i < cChars && i >= 0 && (glyph_start < 0 || glyph_end < 0); i+=direction)
+    {
+        if (glyph_start < 0 && pwLogClust[i] != cluster) continue;
+        if (pwLogClust[i] == cluster && glyph_start < 0) glyph_start = pwLogClust[i];
+        if (glyph_start >= 0 && glyph_end < 0 && pwLogClust[i] != cluster) glyph_end = pwLogClust[i];
+    }
+    if (glyph_end < 0)
+    {
+        if (direction > 0)
+            glyph_end = cGlyphs;
+        else
+        {
+            /* Don't fully understand multi-glyph reversed clusters yet,
+             * do they occur for real or just in our test? */
+            FIXME("multi-glyph reversed clusters found\n");
+            glyph_end = glyph_start + 1;
+        }
+    }
+
+    /* Check for fClusterStart, finding this generally would mean a malformed set of data */
+    for (i = glyph_start+1; i< glyph_end; i++)
+    {
+        if (psva[i].fClusterStart)
+        {
+            glyph_end = i;
+            break;
+        }
+    }
+
+    for (advance = 0, i = glyph_start; i < glyph_end; i++)
+        advance += piAdvance[i];
+
+    return advance;
+}
+
+
 /***********************************************************************
  *      ScriptXtoCP (USP10.@)
  *
+ * Basic algorithm :
+ *  Use piAdvance to find the cluster we are looking at.
+ *  Find the character that is the first character of the cluster.
+ *  That is our base piCP.
+ *  If the script snaps to cluster boundaries (Hebrew, Indic, Thai) then we
+ *  are good. Otherwise if the cluster is larger than 1 glyph we need to
+ *  determine how far through the cluster to advance the cursor.
  */
 HRESULT WINAPI ScriptXtoCP(int iX,
                            int cChars,
@@ -2111,16 +2864,11 @@ HRESULT WINAPI ScriptXtoCP(int iX,
                            int *piCP,
                            int *piTrailing)
 {
-    int item;
-    float iPosX;
-    float iLastPosX;
-    int iSpecial = -1;
-    int iCluster = -1;
-    int clust_size = 1;
-    int cjump = 0;
-    int advance;
-    float special_size = 0.0;
     int direction = 1;
+    int iPosX;
+    int i;
+    int glyph_index, cluster_index;
+    int cluster_size;
 
     TRACE("(%d,%d,%d,%p,%p,%p,%p,%p,%p)\n",
           iX, cChars, cGlyphs, pwLogClust, psva, piAdvance,
@@ -2129,127 +2877,156 @@ HRESULT WINAPI ScriptXtoCP(int iX,
     if (psa->fRTL && ! psa->fLogicalOrder)
         direction = -1;
 
-    if (direction<0)
+    /* Handle an iX < 0 */
+    if (iX < 0)
     {
-        int max_clust = pwLogClust[0];
-
-        if (iX < 0)
+        if (direction < 0)
         {
             *piCP = cChars;
             *piTrailing = 0;
-            return S_OK;
         }
+        else
+        {
+            *piCP = -1;
+            *piTrailing = 1;
+        }
+        return S_OK;
+    }
 
-        for (item=0; item < cChars; item++)
-            if (pwLogClust[item] > max_clust)
+    /* Looking for non-reversed clusters in a reversed string */
+    if (direction < 0)
+    {
+        int max_clust = pwLogClust[0];
+        for (i=0; i< cChars; i++)
+            if (pwLogClust[i] > max_clust)
             {
-                ERR("We do not handle non reversed clusters properly\n");
+                FIXME("We do not handle non reversed clusters properly\n");
                 break;
             }
     }
 
-    if (iX < 0)
+    /* find the glyph_index based in iX */
+    if (direction > 0)
     {
-        *piCP = -1;
-        *piTrailing = 1;
-        return S_OK;
+        for (glyph_index = -1, iPosX = iX; iPosX >=0 && glyph_index < cGlyphs; iPosX -= piAdvance[glyph_index+1], glyph_index++)
+            ;
     }
-
-    iPosX = iLastPosX = 0;
-    if (direction > 0)
-        item = 0;
     else
-        item = cChars - 1;
-    for (; iPosX <= iX && item < cChars && item >= 0; item+=direction)
-    {
-        iLastPosX = iPosX;
-        if (iSpecial == -1 &&
-             (iCluster == -1 ||
-              (iCluster != -1 &&
-                 ((direction > 0 && iCluster+clust_size <= item) ||
-                  (direction < 0 && iCluster-clust_size >= item))
-              )
-             )
-            )
+    {
+        for (glyph_index = -1, iPosX = iX; iPosX > 0 && glyph_index < cGlyphs; iPosX -= piAdvance[glyph_index+1], glyph_index++)
+            ;
+    }
+
+    TRACE("iPosX %i ->  glyph_index %i (%i)\n", iPosX, glyph_index, cGlyphs);
+
+    *piTrailing = 0;
+    if (glyph_index >= 0 && glyph_index < cGlyphs)
+    {
+        /* find the cluster */
+        if (direction > 0 )
+            for (i = 0, cluster_index = pwLogClust[0]; i < cChars && pwLogClust[i] <= glyph_index; cluster_index=pwLogClust[i++])
+                ;
+        else
+            for (i = 0, cluster_index = pwLogClust[0]; i < cChars && pwLogClust[i] >= glyph_index; cluster_index=pwLogClust[i++])
+                ;
+
+        TRACE("cluster_index %i\n", cluster_index);
+
+        if (direction < 0 && iPosX >= 0 && glyph_index != cluster_index)
         {
-            int check;
-            int clust = pwLogClust[item];
+            /* We are off the end of the string */
+            *piCP = -1;
+            *piTrailing = 1;
+            return S_OK;
+        }
 
-            iCluster = -1;
-            cjump = 0;
-            clust_size = get_cluster_size(pwLogClust, cChars, item, direction,
-                                          &iCluster, &check);
-            advance = get_glyph_cluster_advance(piAdvance, psva, pwLogClust, cGlyphs, cChars, clust, direction);
+        get_cluster_data(pwLogClust, cChars, cluster_index, &cluster_size, &i);
 
-            if (check >= cChars && direction > 0)
-            {
-                for (check = clust; check < cChars; check++)
-                    special_size += get_glyph_cluster_advance(piAdvance, psva, pwLogClust, cGlyphs, cChars, check, direction);
-                iSpecial = item;
-                special_size /= (cChars - item);
-                iPosX += special_size;
-            }
-            else
+        TRACE("first char index %i\n",i);
+        if (scriptInformation[psa->eScript].props.fNeedsCaretInfo)
+        {
+            /* Check trailing */
+            if (glyph_index != cluster_index ||
+                (direction > 0 && abs(iPosX) <= (piAdvance[glyph_index] / 2)) ||
+                (direction < 0 && abs(iPosX) >= (piAdvance[glyph_index] / 2)))
+                *piTrailing = cluster_size;
+        }
+        else
+        {
+            if (cluster_size > 1)
             {
-                if (scriptInformation[psa->eScript].props.fNeedsCaretInfo)
+                /* Be part way through the glyph cluster based on size and position */
+                int cluster_advance = get_cluster_advance(piAdvance, psva, pwLogClust, cGlyphs, cChars, cluster_index, direction);
+                double cluster_part_width = cluster_advance / (float)cluster_size;
+                double adv;
+                int part_index;
+
+                /* back up to the beginning of the cluster */
+                for (adv = iPosX, part_index = cluster_index; part_index <= glyph_index; part_index++)
+                    adv += piAdvance[part_index];
+                if (adv > iX) adv = iX;
+
+                TRACE("Multi-char cluster, no snap\n");
+                TRACE("cluster size %i, pre-cluster iPosX %f\n",cluster_size, adv);
+                TRACE("advance %i divides into %f per char\n", cluster_advance, cluster_part_width);
+                if (direction > 0)
                 {
-                    if (!cjump)
-                        iPosX += advance;
-                    cjump++;
+                    for (part_index = 0; adv >= 0; adv-=cluster_part_width, part_index++)
+                        ;
+                    if (part_index) part_index--;
                 }
                 else
-                    iPosX += advance / (float)clust_size;
+                {
+                    for (part_index = 0; adv > 0; adv-=cluster_part_width, part_index++)
+                        ;
+                    if (part_index > cluster_size)
+                    {
+                        adv += cluster_part_width;
+                        part_index=cluster_size;
+                    }
+                }
+
+                TRACE("base_char %i part_index %i, leftover advance %f\n",i, part_index, adv);
+
+                if (direction > 0)
+                    i += part_index;
+                else
+                    i += (cluster_size - part_index);
+
+                /* Check trailing */
+                if ((direction > 0 && fabs(adv) <= (cluster_part_width / 2.0)) ||
+                    (direction < 0 && adv && fabs(adv) >= (cluster_part_width / 2.0)))
+                    *piTrailing = 1;
             }
-        }
-        else if (iSpecial != -1)
-            iPosX += special_size;
-        else /* (iCluster != -1) */
-        {
-            int adv = get_glyph_cluster_advance(piAdvance, psva, pwLogClust, cGlyphs, cChars, pwLogClust[iCluster], direction);
-            if (scriptInformation[psa->eScript].props.fNeedsCaretInfo)
+            else
             {
-                if (!cjump)
-                    iPosX += adv;
-                cjump++;
+                /* Check trailing */
+                if ((direction > 0 && abs(iPosX) <= (piAdvance[glyph_index] / 2)) ||
+                    (direction < 0 && abs(iPosX) >= (piAdvance[glyph_index] / 2)))
+                    *piTrailing = 1;
             }
-            else
-                iPosX += adv / (float)clust_size;
-        }
-    }
-
-    if (direction > 0)
-    {
-        if (iPosX > iX)
-            item--;
-        if (item < cChars && ((iPosX - iLastPosX) / 2.0) + iX >= iPosX)
-        {
-            if (scriptInformation[psa->eScript].props.fNeedsCaretInfo && clust_size > 1)
-                item+=(clust_size-1);
-            *piTrailing = 1;
         }
-        else
-            *piTrailing = 0;
     }
     else
     {
-        if (iX == iLastPosX)
-            item++;
-        if (iX >= iLastPosX && iX <= iPosX)
-            item++;
-
-        if (iLastPosX == iX)
-            *piTrailing = 0;
-        else if (item < 0 || ((iLastPosX - iPosX) / 2.0) + iX <= iLastPosX)
+        TRACE("Point falls outside of string\n");
+        if (glyph_index < 0)
+            i = cChars-1;
+        else /* (glyph_index >= cGlyphs) */
+            i = cChars;
+
+        /* If not snaping in the reverse direction (such as Hebrew) Then 0
+           point flow to the next character */
+        if (direction < 0)
         {
-            if (scriptInformation[psa->eScript].props.fNeedsCaretInfo && clust_size > 1)
-                item-=(clust_size-1);
-            *piTrailing = 1;
+            if (!scriptInformation[psa->eScript].props.fNeedsCaretInfo && abs(iPosX) == piAdvance[glyph_index])
+                i++;
+            else
+                *piTrailing = 1;
         }
-        else
-            *piTrailing = 0;
     }
 
-    *piCP = item;
+    *piCP = i;
 
     TRACE("*piCP=%d\n", *piCP);
     TRACE("*piTrailing=%d\n", *piTrailing);
@@ -2263,7 +3040,7 @@ HRESULT WINAPI ScriptXtoCP(int iX,
  *
  *  PARAMS
  *   chars [I] Array of characters.
- *   sa    [I] String analysis.
+ *   sa    [I] Script analysis.
  *   la    [I] Array of logical attribute structures.
  *
  *  RETURNS
@@ -2274,7 +3051,8 @@ HRESULT WINAPI ScriptBreak(const WCHAR *chars, int count, const SCRIPT_ANALYSIS
 {
     TRACE("(%s, %d, %p, %p)\n", debugstr_wn(chars, count), count, sa, la);
 
-    if (!la) return S_FALSE;
+    if (count < 0 || !la) return E_INVALIDARG;
+    if (count == 0) return E_FAIL;
 
     BREAK_line(chars, count, sa, la);
 
@@ -2298,18 +3076,20 @@ HRESULT WINAPI ScriptBreak(const WCHAR *chars, int count, const SCRIPT_ANALYSIS
  */
 HRESULT WINAPI ScriptIsComplex(const WCHAR *chars, int len, DWORD flag)
 {
-    int i;
+    enum usp10_script script;
+    unsigned int i, consumed;
 
     TRACE("(%s,%d,0x%x)\n", debugstr_wn(chars, len), len, flag);
 
-    for (i = 0; i < len; i++)
-    {
-        int script;
+    if (!chars || len < 0)
+        return E_INVALIDARG;
 
+    for (i = 0; i < len; i+=consumed)
+    {
         if ((flag & SIC_ASCIIDIGIT) && chars[i] >= 0x30 && chars[i] <= 0x39)
             return S_OK;
 
-        script = get_char_script(chars[i]);
+        script = get_char_script(chars,i,len, &consumed);
         if ((scriptInformation[script].props.fComplex && (flag & SIC_COMPLEX))||
             (!scriptInformation[script].props.fComplex && (flag & SIC_NEUTRAL)))
             return S_OK;
@@ -2354,8 +3134,11 @@ HRESULT WINAPI ScriptShapeOpenType( HDC hdc, SCRIPT_CACHE *psc,
                                     SCRIPT_GLYPHPROP *pOutGlyphProps, int *pcGlyphs)
 {
     HRESULT hr;
-    unsigned int i;
+    int i;
+    unsigned int g;
     BOOL rtl;
+    int cluster;
+    static int once = 0;
 
     TRACE("(%p, %p, %p, %s, %s, %p, %p, %d, %s, %d, %d, %p, %p, %p, %p, %p )\n",
      hdc, psc, psa,
@@ -2370,7 +3153,7 @@ HRESULT WINAPI ScriptShapeOpenType( HDC hdc, SCRIPT_CACHE *psc,
     if (cChars > cMaxGlyphs) return E_OUTOFMEMORY;
 
     if (cRanges)
-        FIXME("Ranges not supported yet\n");
+        if(!once++) FIXME("Ranges not supported yet\n");
 
     rtl = (psa && !psa->fLogicalOrder && psa->fRTL);
 
@@ -2381,10 +3164,6 @@ HRESULT WINAPI ScriptShapeOpenType( HDC hdc, SCRIPT_CACHE *psc,
     ((ScriptCache *)*psc)->userScript = tagScript;
     ((ScriptCache *)*psc)->userLang = tagLangSys;
 
-    /* set fNoGlyphIndex non truetype/opentype fonts */
-    if (!psa->fNoGlyphIndex && !((ScriptCache *)*psc)->sfnt)
-        psa->fNoGlyphIndex = TRUE;
-
     /* Initialize a SCRIPT_VISATTR and LogClust for each char in this run */
     for (i = 0; i < cChars; i++)
     {
@@ -2404,46 +3183,81 @@ HRESULT WINAPI ScriptShapeOpenType( HDC hdc, SCRIPT_CACHE *psc,
         pwLogClust[i] = idx;
     }
 
-    if (psa && !psa->fNoGlyphIndex)
+    if (psa && !psa->fNoGlyphIndex && ((ScriptCache *)*psc)->sfnt)
     {
         WCHAR *rChars;
         if ((hr = SHAPE_CheckFontForRequiredFeatures(hdc, (ScriptCache *)*psc, psa)) != S_OK) return hr;
 
         rChars = heap_alloc(sizeof(WCHAR) * cChars);
         if (!rChars) return E_OUTOFMEMORY;
-        for (i = 0; i < cChars; i++)
+        for (i = 0, g = 0, cluster = 0; i < cChars; i++)
         {
             int idx = i;
-            WCHAR chInput;
+            DWORD chInput;
+
             if (rtl) idx = cChars - 1 - i;
-            if (psa->fRTL)
-                chInput = mirror_char(pwcChars[idx]);
-            else
-                chInput = pwcChars[idx];
-            /* special case for tabs */
-            if (chInput == 0x0009)
-                chInput = 0x0020;
-            if (!(pwOutGlyphs[i] = get_cache_glyph(psc, chInput)))
+            if (!cluster)
             {
-                WORD glyph;
-                if (!hdc)
+                chInput = decode_surrogate_pair(pwcChars, idx, cChars);
+                if (!chInput)
+                {
+                    if (psa->fRTL)
+                        chInput = mirror_char(pwcChars[idx]);
+                    else
+                        chInput = pwcChars[idx];
+                    rChars[i] = chInput;
+                }
+                else
                 {
-                    heap_free(rChars);
-                    return E_PENDING;
+                    rChars[i] = pwcChars[idx];
+                    rChars[i+1] = pwcChars[(rtl)?idx-1:idx+1];
+                    cluster = 1;
                 }
-                if (GetGlyphIndicesW(hdc, &chInput, 1, &glyph, 0) == GDI_ERROR)
+                if (!(pwOutGlyphs[g] = get_cache_glyph(psc, chInput)))
                 {
-                    heap_free(rChars);
-                    return S_FALSE;
+                    WORD glyph;
+                    if (!hdc)
+                    {
+                        heap_free(rChars);
+                        return E_PENDING;
+                    }
+                    if (OpenType_CMAP_GetGlyphIndex(hdc, (ScriptCache *)*psc, chInput, &glyph, 0) == GDI_ERROR)
+                    {
+                        heap_free(rChars);
+                        return S_FALSE;
+                    }
+                    pwOutGlyphs[g] = set_cache_glyph(psc, chInput, glyph);
                 }
-                pwOutGlyphs[i] = set_cache_glyph(psc, chInput, glyph);
+                g++;
+            }
+            else
+            {
+                int k;
+                cluster--;
+                pwLogClust[idx] = (rtl)?pwLogClust[idx+1]:pwLogClust[idx-1];
+                for (k = (rtl)?idx-1:idx+1; k >= 0 && k < cChars; (rtl)?k--:k++)
+                    pwLogClust[k]--;
             }
-            rChars[i] = chInput;
         }
+        *pcGlyphs = g;
 
         SHAPE_ContextualShaping(hdc, (ScriptCache *)*psc, psa, rChars, cChars, pwOutGlyphs, pcGlyphs, cMaxGlyphs, pwLogClust);
         SHAPE_ApplyDefaultOpentypeFeatures(hdc, (ScriptCache *)*psc, psa, pwOutGlyphs, pcGlyphs, cMaxGlyphs, cChars, pwLogClust);
         SHAPE_CharGlyphProp(hdc, (ScriptCache *)*psc, psa, pwcChars, cChars, pwOutGlyphs, *pcGlyphs, pwLogClust, pCharProps, pOutGlyphProps);
+
+        for (i = 0; i < cChars; ++i)
+        {
+            /* Special case for tabs and joiners. As control characters, ZWNJ
+             * and ZWJ would in principle get handled by the corresponding
+             * shaping functions. However, since ZWNJ and ZWJ can get merged
+             * into adjoining runs during itemisation, these don't generally
+             * get classified as Script_Control. */
+            if (pwcChars[i] == 0x0009 || pwcChars[i] == ZWSP || pwcChars[i] == ZWNJ || pwcChars[i] == ZWJ)
+            {
+                pwOutGlyphs[pwLogClust[i]] = ((ScriptCache *)*psc)->sfp.wgBlank;
+                pOutGlyphProps[pwLogClust[i]].sva.fZeroWidth = 1;
+            }
+        }
         heap_free(rChars);
     }
     else
@@ -2455,6 +3269,29 @@ HRESULT WINAPI ScriptShapeOpenType( HDC hdc, SCRIPT_CACHE *psc,
             /* No mirroring done here */
             if (rtl) idx = cChars - 1 - i;
             pwOutGlyphs[i] = pwcChars[idx];
+
+            if (!psa)
+                continue;
+
+            /* overwrite some basic control glyphs to blank */
+            if (psa->fNoGlyphIndex)
+            {
+                if (pwcChars[idx] == ZWSP || pwcChars[idx] == ZWNJ || pwcChars[idx] == ZWJ)
+                {
+                    pwOutGlyphs[i] = 0x20;
+                    pOutGlyphProps[i].sva.fZeroWidth = 1;
+                }
+            }
+            else if (psa->eScript == Script_Control || pwcChars[idx] == ZWSP
+                    || pwcChars[idx] == ZWNJ || pwcChars[idx] == ZWJ)
+            {
+                if (pwcChars[idx] == 0x0009 || pwcChars[idx] == 0x000A ||
+                    pwcChars[idx] == 0x000D || pwcChars[idx] >= 0x001C)
+                {
+                    pwOutGlyphs[i] = ((ScriptCache *)*psc)->sfp.wgBlank;
+                    pOutGlyphProps[i].sva.fZeroWidth = 1;
+                }
+            }
         }
     }
 
@@ -2527,7 +3364,7 @@ HRESULT WINAPI ScriptShape(HDC hdc, SCRIPT_CACHE *psc, const WCHAR *pwcChars,
  * PARAMS
  *  hdc       [I]   Device context.
  *  psc       [I/O] Opaque pointer to a script cache.
- *  psa       [I/O] String analysis.
+ *  psa       [I/O] Script analysis.
  *  tagScript   [I]   The OpenType tag for the Script
  *  tagLangSys  [I]   The OpenType tag for the Language
  *  rcRangeChars[I]   Array of Character counts in each range
@@ -2561,6 +3398,7 @@ HRESULT WINAPI ScriptPlaceOpenType( HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS
 {
     HRESULT hr;
     int i;
+    static int once = 0;
 
     TRACE("(%p, %p, %p, %s, %s, %p, %p, %d, %s, %p, %p, %d, %p, %p, %d, %p %p %p)\n",
      hdc, psc, psa,
@@ -2574,7 +3412,7 @@ HRESULT WINAPI ScriptPlaceOpenType( HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS
     if (!pGoffset) return E_FAIL;
 
     if (cRanges)
-        FIXME("Ranges not supported yet\n");
+        if (!once++) FIXME("Ranges not supported yet\n");
 
     ((ScriptCache *)*psc)->userScript = tagScript;
     ((ScriptCache *)*psc)->userLang = tagLangSys;
@@ -2583,17 +3421,30 @@ HRESULT WINAPI ScriptPlaceOpenType( HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS
     for (i = 0; i < cGlyphs; i++)
     {
         ABC abc;
-        if (!get_cache_glyph_widths(psc, pwGlyphs[i], &abc))
+        if (pGlyphProps[i].sva.fZeroWidth)
         {
+            abc.abcA = abc.abcB = abc.abcC = 0;
+        }
+        else if (!get_cache_glyph_widths(psc, pwGlyphs[i], &abc))
+        {
+            BOOL ret;
             if (!hdc) return E_PENDING;
-            if ((get_cache_pitch_family(psc) & TMPF_TRUETYPE) && !psa->fNoGlyphIndex)
+            if (get_cache_pitch_family(psc) & TMPF_TRUETYPE)
             {
-                if (!GetCharABCWidthsI(hdc, 0, 1, (WORD *)&pwGlyphs[i], &abc)) return S_FALSE;
+                if (psa->fNoGlyphIndex)
+                    ret = GetCharABCWidthsW(hdc, pwGlyphs[i], pwGlyphs[i], &abc);
+                else
+                    ret = GetCharABCWidthsI(hdc, 0, 1, (WORD *)&pwGlyphs[i], &abc);
+                if (!ret) return S_FALSE;
             }
             else
             {
                 INT width;
-                if (!GetCharWidth32W(hdc, pwGlyphs[i], pwGlyphs[i], &width)) return S_FALSE;
+                if (psa->fNoGlyphIndex)
+                    ret = GetCharWidth32W(hdc, pwGlyphs[i], pwGlyphs[i], &width);
+                else
+                    ret = GetCharWidthI(hdc, 0, 1, (WORD *)&pwGlyphs[i], &width);
+                if (!ret) return S_FALSE;
                 abc.abcB = width;
                 abc.abcA = abc.abcC = 0;
             }
@@ -2610,6 +3461,8 @@ HRESULT WINAPI ScriptPlaceOpenType( HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS
         if (piAdvance) piAdvance[i] = abc.abcA + abc.abcB + abc.abcC;
     }
 
+    SHAPE_ApplyOpenTypePositions(hdc, (ScriptCache *)*psc, psa, pwGlyphs, cGlyphs, piAdvance, pGoffset);
+
     if (pABC) TRACE("Total for run: abcA=%d, abcB=%d, abcC=%d\n", pABC->abcA, pABC->abcB, pABC->abcC);
     return S_OK;
 }
@@ -2740,9 +3593,12 @@ HRESULT WINAPI ScriptTextOut(const HDC hdc, SCRIPT_CACHE *psc, int x, int y, UIN
                              const int *piJustify, const GOFFSET *pGoffset)
 {
     HRESULT hr = S_OK;
+    INT i, dir = 1;
+    INT *lpDx;
+    WORD *reordered_glyphs = (WORD *)pwGlyphs;
 
-    TRACE("(%p, %p, %d, %d, %04x, %p, %p, %p, %d, %p, %d, %p, %p, %p)\n",
-         hdc, psc, x, y, fuOptions, lprc, psa, pwcReserved, iReserved, pwGlyphs, cGlyphs,
+    TRACE("(%p, %p, %d, %d, %08x, %s, %p, %p, %d, %p, %d, %p, %p, %p)\n",
+         hdc, psc, x, y, fuOptions, wine_dbgstr_rect(lprc), psa, pwcReserved, iReserved, pwGlyphs, cGlyphs,
          piAdvance, piJustify, pGoffset);
 
     if (!hdc || !psc) return E_INVALIDARG;
@@ -2753,25 +3609,51 @@ HRESULT WINAPI ScriptTextOut(const HDC hdc, SCRIPT_CACHE *psc, int x, int y, UIN
     if  (!psa->fNoGlyphIndex)                                     /* Have Glyphs?                      */
         fuOptions |= ETO_GLYPH_INDEX;                             /* Say don't do translation to glyph */
 
+    if (!(lpDx = heap_calloc(cGlyphs, 2 * sizeof(*lpDx))))
+        return E_OUTOFMEMORY;
+    fuOptions |= ETO_PDY;
+
     if (psa->fRTL && psa->fLogicalOrder)
     {
-        int i;
-        WORD *rtlGlyphs;
-
-        rtlGlyphs = heap_alloc(cGlyphs * sizeof(WORD));
-        if (!rtlGlyphs)
+        if (!(reordered_glyphs = heap_calloc(cGlyphs, sizeof(*reordered_glyphs))))
+        {
+            heap_free( lpDx );
             return E_OUTOFMEMORY;
+        }
 
         for (i = 0; i < cGlyphs; i++)
-            rtlGlyphs[i] = pwGlyphs[cGlyphs-1-i];
+            reordered_glyphs[i] = pwGlyphs[cGlyphs - 1 - i];
+        dir = -1;
+    }
 
-        if (!ExtTextOutW(hdc, x, y, fuOptions, lprc, rtlGlyphs, cGlyphs, NULL))
-            hr = S_FALSE;
-        heap_free(rtlGlyphs);
+    for (i = 0; i < cGlyphs; i++)
+    {
+        int orig_index = (dir > 0) ? i : cGlyphs - 1 - i;
+        lpDx[i * 2] = piAdvance[orig_index];
+        lpDx[i * 2 + 1] = 0;
+
+        if (pGoffset)
+        {
+            if (i == 0)
+            {
+                x += pGoffset[orig_index].du * dir;
+                y += pGoffset[orig_index].dv;
+            }
+            else
+            {
+                lpDx[(i - 1) * 2]     += pGoffset[orig_index].du * dir;
+                lpDx[(i - 1) * 2 + 1] += pGoffset[orig_index].dv;
+            }
+            lpDx[i * 2]     -= pGoffset[orig_index].du * dir;
+            lpDx[i * 2 + 1] -= pGoffset[orig_index].dv;
+        }
     }
-    else
-        if (!ExtTextOutW(hdc, x, y, fuOptions, lprc, pwGlyphs, cGlyphs, NULL))
-            hr = S_FALSE;
+
+    if (!ExtTextOutW(hdc, x, y, fuOptions, lprc, reordered_glyphs, cGlyphs, lpDx))
+        hr = S_FALSE;
+
+    if (reordered_glyphs != pwGlyphs) heap_free( reordered_glyphs );
+    heap_free(lpDx);
 
     return hr;
 }
@@ -2861,10 +3743,6 @@ HRESULT WINAPI ScriptGetGlyphABCWidth(HDC hdc, SCRIPT_CACHE *psc, WORD glyph, AB
  *  Success: S_OK
  *  Failure: Non-zero HRESULT value.
  *
- * BUGS
- *  This stub works correctly for any sequence of a single
- *  embedding level but not for sequences of different
- *  embedding levels, i.e. mixtures of RTL and LTR scripts.
  */
 HRESULT WINAPI ScriptLayout(int runs, const BYTE *level, int *vistolog, int *logtovis)
 {
@@ -2876,11 +3754,9 @@ HRESULT WINAPI ScriptLayout(int runs, const BYTE *level, int *vistolog, int *log
     if (!level || (!vistolog && !logtovis))
         return E_INVALIDARG;
 
-    indexs = heap_alloc(sizeof(int) * runs);
-    if (!indexs)
+    if (!(indexs = heap_calloc(runs, sizeof(*indexs))))
         return E_OUTOFMEMORY;
 
-
     if (vistolog)
     {
         for( ich = 0; ich < runs; ich++)
@@ -2889,11 +3765,9 @@ HRESULT WINAPI ScriptLayout(int runs, const BYTE *level, int *vistolog, int *log
         ich = 0;
         while (ich < runs)
             ich += BIDI_ReorderV2lLevel(0, indexs+ich, level+ich, runs - ich, FALSE);
-        for (ich = 0; ich < runs; ich++)
-            vistolog[ich] = indexs[ich];
+        memcpy(vistolog, indexs, runs * sizeof(*vistolog));
     }
 
-
     if (logtovis)
     {
         for( ich = 0; ich < runs; ich++)
@@ -2902,8 +3776,7 @@ HRESULT WINAPI ScriptLayout(int runs, const BYTE *level, int *vistolog, int *log
         ich = 0;
         while (ich < runs)
             ich += BIDI_ReorderL2vLevel(0, indexs+ich, level+ich, runs - ich, FALSE);
-        for (ich = 0; ich < runs; ich++)
-            logtovis[ich] = indexs[ich];
+        memcpy(logtovis, indexs, runs * sizeof(*logtovis));
     }
     heap_free(indexs);
 
@@ -2931,7 +3804,7 @@ HRESULT WINAPI ScriptStringGetLogicalWidths(SCRIPT_STRING_ANALYSIS ssa, int *piD
     TRACE("%p, %p\n", ssa, piDx);
 
     if (!analysis) return S_FALSE;
-    if (!(analysis->dwFlags & SSA_GLYPHS)) return S_FALSE;
+    if (!(analysis->ssa_flags & SSA_GLYPHS)) return S_FALSE;
 
     for (i = 0; i < analysis->numItems; i++)
     {
@@ -2980,7 +3853,7 @@ HRESULT WINAPI ScriptStringValidate(SCRIPT_STRING_ANALYSIS ssa)
     TRACE("(%p)\n", ssa);
 
     if (!analysis) return E_INVALIDARG;
-    return (analysis->invalid) ? S_FALSE : S_OK;
+    return analysis->flags & SCRIPT_STRING_ANALYSIS_FLAGS_INVALID ? S_FALSE : S_OK;
 }
 
 /***********************************************************************
@@ -3003,23 +3876,22 @@ const SIZE * WINAPI ScriptString_pSize(SCRIPT_STRING_ANALYSIS ssa)
     TRACE("(%p)\n", ssa);
 
     if (!analysis) return NULL;
-    if (!(analysis->dwFlags & SSA_GLYPHS)) return NULL;
+    if (!(analysis->ssa_flags & SSA_GLYPHS)) return NULL;
 
-    if (!analysis->sz)
+    if (!(analysis->flags & SCRIPT_STRING_ANALYSIS_FLAGS_SIZE))
     {
-        if (!(analysis->sz = heap_alloc(sizeof(SIZE)))) return NULL;
-        analysis->sz->cy = analysis->glyphs[0].sc->tm.tmHeight;
+        analysis->sz.cy = analysis->glyphs[0].sc->tm.tmHeight;
 
-        analysis->sz->cx = 0;
+        analysis->sz.cx = 0;
         for (i = 0; i < analysis->numItems; i++)
         {
-            if (analysis->glyphs[i].sc->tm.tmHeight > analysis->sz->cy)
-                analysis->sz->cy = analysis->glyphs[i].sc->tm.tmHeight;
+            if (analysis->glyphs[i].sc->tm.tmHeight > analysis->sz.cy)
+                analysis->sz.cy = analysis->glyphs[i].sc->tm.tmHeight;
             for (j = 0; j < analysis->glyphs[i].numGlyphs; j++)
-                analysis->sz->cx += analysis->glyphs[i].piAdvance[j];
+                analysis->sz.cx += analysis->glyphs[i].piAdvance[j];
         }
     }
-    return analysis->sz;
+    return &analysis->sz;
 }
 
 /***********************************************************************
@@ -3041,7 +3913,7 @@ const SCRIPT_LOGATTR * WINAPI ScriptString_pLogAttr(SCRIPT_STRING_ANALYSIS ssa)
     TRACE("(%p)\n", ssa);
 
     if (!analysis) return NULL;
-    if (!(analysis->dwFlags & SSA_BREAK)) return NULL;
+    if (!(analysis->ssa_flags & SSA_BREAK)) return NULL;
     return analysis->logattrs;
 }
 
@@ -3089,7 +3961,7 @@ HRESULT WINAPI ScriptStringGetOrder(SCRIPT_STRING_ANALYSIS ssa, UINT *order)
     TRACE("(%p)\n", ssa);
 
     if (!analysis) return S_FALSE;
-    if (!(analysis->dwFlags & SSA_GLYPHS)) return S_FALSE;
+    if (!(analysis->ssa_flags & SSA_GLYPHS)) return S_FALSE;
 
     /* FIXME: handle RTL scripts */
     for (i = 0, k = 0; i < analysis->numItems; i++)
@@ -3118,16 +3990,33 @@ HRESULT WINAPI ScriptStringGetOrder(SCRIPT_STRING_ANALYSIS ssa, UINT *order)
  *  Failure: a non-zero HRESULT.
  */
 HRESULT WINAPI ScriptGetLogicalWidths(const SCRIPT_ANALYSIS *sa, int nbchars, int nbglyphs,
-                                      const int *glyph_width, const WORD *log_clust,
+                                      const int *advances, const WORD *log_clust,
                                       const SCRIPT_VISATTR *sva, int *widths)
 {
-    int i;
+    int i, next = 0, direction;
 
     TRACE("(%p, %d, %d, %p, %p, %p, %p)\n",
-          sa, nbchars, nbglyphs, glyph_width, log_clust, sva, widths);
+          sa, nbchars, nbglyphs, advances, log_clust, sva, widths);
+
+    if (sa->fRTL && !sa->fLogicalOrder)
+        direction = -1;
+    else
+        direction = 1;
+
+    for (i = 0; i < nbchars; i++)
+    {
+        int clust_size = get_cluster_size(log_clust, nbchars, i, direction, NULL, NULL);
+        int advance = get_glyph_cluster_advance(advances, sva, log_clust, nbglyphs, nbchars, log_clust[i], direction);
+        int j;
+
+        for (j = 0; j < clust_size; j++)
+        {
+            widths[next] = advance / clust_size;
+            next++;
+            if (j) i++;
+        }
+    }
 
-    /* FIXME */
-    for (i = 0; i < nbchars; i++) widths[i] = glyph_width[i];
     return S_OK;
 }
 
@@ -3176,8 +4065,37 @@ HRESULT WINAPI ScriptJustify(const SCRIPT_VISATTR *sva, const int *advance,
     return S_OK;
 }
 
+HRESULT WINAPI ScriptGetFontScriptTags( HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS *psa, int cMaxTags, OPENTYPE_TAG *pScriptTags, int *pcTags)
+{
+    HRESULT hr;
+    if (!pScriptTags || !pcTags || cMaxTags == 0) return E_INVALIDARG;
+    if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
+
+    return SHAPE_GetFontScriptTags(hdc, (ScriptCache *)*psc, psa, cMaxTags, pScriptTags, pcTags);
+}
+
+HRESULT WINAPI ScriptGetFontLanguageTags( HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS *psa, OPENTYPE_TAG tagScript, int cMaxTags, OPENTYPE_TAG *pLangSysTags, int *pcTags)
+{
+    HRESULT hr;
+    if (!pLangSysTags || !pcTags || cMaxTags == 0) return E_INVALIDARG;
+    if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
+
+    return SHAPE_GetFontLanguageTags(hdc, (ScriptCache *)*psc, psa, tagScript, cMaxTags, pLangSysTags, pcTags);
+}
+
+HRESULT WINAPI ScriptGetFontFeatureTags( HDC hdc, SCRIPT_CACHE *psc, SCRIPT_ANALYSIS *psa, OPENTYPE_TAG tagScript, OPENTYPE_TAG tagLangSys, int cMaxTags, OPENTYPE_TAG *pFeatureTags, int *pcTags)
+{
+    HRESULT hr;
+    if (!pFeatureTags || !pcTags || cMaxTags == 0) return E_INVALIDARG;
+    if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
+
+    return SHAPE_GetFontFeatureTags(hdc, (ScriptCache *)*psc, psa, tagScript, tagLangSys, cMaxTags, pFeatureTags, pcTags);
+}
+
+#ifdef __REACTOS__
 BOOL gbLpkPresent = FALSE;
 VOID WINAPI LpkPresent()
 {
     gbLpkPresent = TRUE; /* Turn it on this way! Wine is out of control! */
 }
+#endif