Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/im.c
blob: 4c869f9b35d329182e05cbbdeebea5c7d6f4bbc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
/*
  im.c

  Input method handling
  Copyright (c)2007 by Mark K. Kim and others

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  (See COPYING.txt)

  $Id: im.c,v 1.13 2009/11/22 23:17:35 albert Exp $
*/

/*
* See the LANGUAGE-SPECIFIC IM FUNCTIONS section for instructions on adding
* support for new languages.
*
* This file is called IM (Input Method), but it's actually an Input Translator.
* This implementation was sort of necessary in order to work without having to
* modify SDL.
*
* Basically, to read in text in foreign language, read Keysym off of SDL and
* pass to im_read.  im_read will translate the text and pass the unicode string
* back to you.  But before all this is done, be sure to create the IM_DATA
* structure and initialize it with the proper language translator you want to use.
*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>

#include "im.h"
#include "tuxpaint.h"



/* ***************************************************************************
* I18N GETTEXT
*/

#ifndef gettext_noop
#define gettext_noop(s) (s)
#endif


enum {
  IM_TIP_NONE,
  IM_TIP_ENGLISH,
  IM_TIP_HIRAGANA,
  IM_TIP_KATAKANA,
  IM_TIP_HANGUL,
  IM_TIP_THAI,
  IM_TIP_ZH_TW,
  NUM_IM_TIPS
};


static const char* const im_tip_text[NUM_IM_TIPS] =
{
  NULL,

  // Input Method: English mode
  gettext_noop("English"),

  // Input Method: Japanese Romanized Hiragana mode
  gettext_noop("Hiragana"),

  // Input Method: Japanese Romanized Katakana mode
  gettext_noop("Katakana"),

  // Input Method: Korean Hangul 2-Bul mode
  gettext_noop("Hangul"),

  // Input Method: Thai mode
  gettext_noop("Thai"),

  // Input Method: Traditional Chinese mode
  gettext_noop("ZH_TW")
};


/* ***************************************************************************
* CONSTANTS
*/

/* #define IM_DEBUG       1 */

#define MAX_SECTIONS     8    /* Maximum numbers of sections in *.im file */
#define MAX_UNICODE_SEQ 16    /* Output of state machine, including NUL */
#define INITIAL_SMSIZE   8    /* Initial num of transitions in STATE_MACHINE */

#ifndef LANG_DEFAULT
#define LANG_DEFAULT   (LANG_EN)
#endif


/**
* Event types that im_event_*() functions need to handle.
*/
enum {
  IM_REQ_TRANSLATE,    /* The ever-more important IM translation request */
  IM_REQ_INIT,         /* Initialization request */
  IM_REQ_RESET_SOFT,   /* Soft reset request */
  IM_REQ_RESET_FULL,   /* Full reset request */
  IM_REQ_FREE,         /* Free resources */
  NUM_IM_REQUESTS
};


/**
* Match statuses.
*/
enum {
  MATCH_STAT_NONE       = 0x00,
  MATCH_STAT_NOMOSTATES = 0x01,
  MATCH_STAT_NOMOBUF    = 0x02,
};


/* ***************************************************************************
* TYPES
*/

/**
* All im_event_*() functions have this type.
*/
typedef int (*IM_EVENT_FN)(IM_DATA*, SDL_keysym);   /* IM_EVENT_FN type */


/**
* State Machine key-value pair for transition control.  When the "key"
* is pressed, transition is made to "state".
*
* @see STATE_MACHINE
*/
typedef struct SM_WITH_KEY {
  char key;
  struct STATE_MACHINE* state;
} SM_WITH_KEY;


/**
* A State Machine is used to map key strokes to the unicode output.
* A single State Machine has a possible output (the unicode) and pointers
* to next states.  The "next state" is determined by the key stroke
* pressed by the user - this key is looked up in SM_WITH_KEY and
* its next state determined by the STATE_MACHINE pointer in SM_WITH_KEY.
*
* The number of possible transitions to the next state is dynamically
* adjustable using the parameter next_maxsize.  The actual storage in
* use can be determined via next_size.
*
* @see SM_WITH_KEY
*/
typedef struct STATE_MACHINE {
  wchar_t output[MAX_UNICODE_SEQ];
  char flag;

  SM_WITH_KEY* next;      /* Possible transitions */
  size_t next_maxsize;    /* Potential size of the next pointer */
  size_t next_size;       /* Used size of the next pointer */
} STATE_MACHINE;


/**
* A Character Map loads the *.im file, which may have several "sections".
* Each section has its own state machine, and the C code determines which
* section is used in determining which STATE_MACHINE to use for the
* key mapping.
*/
typedef struct {
  STATE_MACHINE sections[MAX_SECTIONS];
  int section;

  /* These variables get populated when a search is performed */
  int match_count;              /* How many char seq was used for output */
  int match_is_final;           /* T/F - tells if match is final */
  int match_stats;              /* Statistics gathering */
  STATE_MACHINE* match_state;
  STATE_MACHINE* match_state_prev;
} CHARMAP;


/* ***************************************************************************
* STATIC GLOBALS
*/

/**
* Global initialization flag.
*/
static int im_initialized = 0;


/**
* Language-specific IM event-handler function pointers.  This lookup table
* is initialized in im_init().  Every support language should have a pointer
* mapped here.
*
* @see im_init()
* @see im_read()
*/
static IM_EVENT_FN im_event_fns[NUM_LANGS];


/* ***************************************************************************
* UTILITY FUNCTIONS
*/

#define MIN(a,b)              ((a)<=(b) ? (a) : (b))
#define IN_RANGE(a,v,b)       ( (a)<=(v) && (v)<(b) )
#define ARRAYLEN(a)           ( sizeof(a)/sizeof(*(a)) )


static void wcs_lshift(wchar_t* s, size_t count)
{
  wchar_t* dest = s;
  wchar_t* src = s+count;
  size_t len = wcslen(src)+1;   /* Copy over all src string + NUL */

  memmove(dest, src, len * sizeof(wchar_t));
}


/**
* Pull out "count" characters from the back.
*/
static void wcs_pull(wchar_t* s, size_t count)
{
  int peg = (int)wcslen(s) - (int)count;
  if(peg < 0) peg = 0;

  s[peg] = L'\0';
}


/* ***************************************************************************
* STATE_MACHINE FUNCTIONS
*/

/**
* Compare two SM_WITH_KEY, return appropriate result.
*/
static int swk_compare(const void* swk1, const void* swk2)
{
  SM_WITH_KEY* sk1 = (SM_WITH_KEY*)swk1;
  SM_WITH_KEY* sk2 = (SM_WITH_KEY*)swk2;

  return (sk1->key) - (sk2->key);
}


/**
* Initialize the State Machine.
*/
static int sm_init(STATE_MACHINE* sm)
{
  memset(sm, 0, sizeof(STATE_MACHINE));

  sm->next = calloc(INITIAL_SMSIZE, sizeof(SM_WITH_KEY));
  if(!sm->next) {
    perror("sm_init");
    return 1;
  }

  sm->next_maxsize = INITIAL_SMSIZE;
  return 0;
}


/**
* Free the State Machine resources.
*/
static void sm_free(STATE_MACHINE* sm)
{
  if(sm->next) {
    int i = 0;

    for(i = 0; i < (int)sm->next_maxsize; i++) {
      STATE_MACHINE* next_state = sm->next[i].state;
      if(next_state) sm_free(next_state);
      sm->next[i].state = NULL;
    }

    free(sm->next);
    sm->next = NULL;
  }

  memset(sm, 0, sizeof(STATE_MACHINE));
}


/**
* Double the storage space of the possible transition states.
*/
static int sm_dblspace(STATE_MACHINE* sm)
{
  size_t newsize = sm->next_maxsize * 2;
  SM_WITH_KEY* next = realloc(sm->next, sizeof(SM_WITH_KEY) * newsize);

  if(next == NULL) {
    perror("sm_dblspace");
    return 1;
  }

  sm->next = next;
  sm->next_maxsize = newsize;
  return 0;
}


/**
* Search the state machine's transition keys, return pointer to the next state.
* Return NULL if none is found.  The search is done only at 1 level, and does
* not recurse deep.
*/
static STATE_MACHINE* sm_search_shallow(STATE_MACHINE* sm, char key)
{
  SM_WITH_KEY smk = { key, NULL };
  SM_WITH_KEY* smk_found;

  smk_found = bsearch(
      &smk, sm->next, sm->next_size, sizeof(SM_WITH_KEY), swk_compare);

  if(!smk_found) return NULL;
  return smk_found->state;
}


/**
* Search the state machine's transition keys, return the unicode output of the
* last state found.  The search is done deep, recursing until no more match
* can be found.
*
* @param start    Starting point of the state transition.  Constant.
* @param key      The key string to look for.  Constant.
* @param matched  The number of character strings matched.  Return on output.
* @param end      The last state found.  Return on output.
* @param penult   The penultimate state found.
*
* @return         Found unicode character sequence output of the last state.
*/
static const wchar_t* sm_search(STATE_MACHINE* start, wchar_t* key, int* matched, STATE_MACHINE** penult, STATE_MACHINE** end)
{
  STATE_MACHINE* sm = sm_search_shallow(start, (char)*key);
  const wchar_t* unicode;

  /* No match - stop recursion */
  if(!sm) {
    *matched = 0;
    *end = start;

    return start->output;
  }

  /* Match - recurse */
  *penult = start;
  unicode = sm_search(sm, key+1, matched, penult, end);
  (*matched)++;

  return unicode;
}


/**
* Sort the state machine's transition keys so it can be binary-searched.
* The sort is done only at 1 level, and does not recurse deep.
*/
static void sm_sort_shallow(STATE_MACHINE* sm)
{
  qsort(sm->next, sm->next_size, sizeof(SM_WITH_KEY), swk_compare);
}


/**
* Add a single sequence-to-unicode path to the state machine.
*/
static int sm_add(STATE_MACHINE* sm, char* seq, const wchar_t* unicode, char flag)
{
  STATE_MACHINE* sm_found = sm_search_shallow(sm, seq[0]);

  /* Empty sequence */
  if(seq[0] == '\0') {
    if(wcslen(sm->output)) {
      size_t i;

      fprintf(stderr, "Unicode sequence ");
      for(i = 0; i < wcslen(sm->output); i++) fprintf(stderr, "%04X ", (int)sm->output[i]);
      fprintf(stderr, " already defined, overriding with ");
      for(i = 0; i < wcslen(unicode); i++) fprintf(stderr, "%04X ", (int)unicode[i]);
      fprintf(stderr, "\n");
    }
    wcscpy(sm->output, unicode);
    sm->flag = flag;
    return 0;
  }

  /* The key doesn't exist yet */
  if(!sm_found) {
    int index = (int)sm->next_size;
    SM_WITH_KEY* next = &sm->next[index];

    /* Add the key */
    next->key = seq[0];
    next->state = malloc(sizeof(STATE_MACHINE));
    if(!next->state) {
      perror("sm_add");
      return 1;
    }
    sm_init(next->state);

    /* Increase store for next time, if necessary */
    if(++(sm->next_size) >= sm->next_maxsize) {
      if(sm_dblspace(sm)) {
        fprintf(stderr, "Memory expansion failure\n");
        return 1;
      }
    }

    sm_found = next->state;
  }

  /* Recurse */
  sm_add(sm_found, seq+1, unicode, flag);

  /* Sort the states */
  sm_sort_shallow(sm);

  return 0;
}



/* ***************************************************************************
* CHARMAP FUNCTIONS
*/

/**
* Initialize the character map table.
*/
static int charmap_init(CHARMAP* cm)
{
  int error_code = 0;
  int i = 0;

  memset(cm, 0, sizeof(CHARMAP));

  for(i = 0; i < MAX_SECTIONS; i++) {
    error_code += sm_init(&cm->sections[i]);
  }

  return error_code;
}


/**
* Add a character-sequence-to-unicode mapping to the character map.
*
* @param cm      Character map to which to add the mapping.
* @param section The section of the character map to add the mapping.
* @param seq     The character sequence to which to add the mapping.
* @param unicode The unicode of the character sequence.
* @param flag    The flag associated with this state, if any.
*
* @return        0 if no error, 1 if error.
*/
static int charmap_add(CHARMAP* cm, int section, char* seq, const wchar_t* unicode, char* flag)
{
  if(section >= MAX_SECTIONS) {
    fprintf(stderr, "Section count exceeded\n");
    return 1;
  }

  /* For now, we only utilize one-character flags */
  if(strlen(flag) > 1) {
    fprintf(stderr, "%04X: Multi-character flag, truncated.\n", (int)unicode);
  }

  return sm_add(&cm->sections[section], seq, unicode, flag[0]);
}


/**
* Load the character map table from a file.
*
* @param cm     Character Map to load the table into.
* @param path   The path of the file to load.
* @return       Zero if the file is loaded fine, nonzero otherwise.
*/
static int charmap_load(CHARMAP* cm, const char* path)
{
  FILE* is = NULL;
  int section = 0;
  int error_code = 0;

  /* Open */
  is = fopen(path, "rt");
  if(!is) {
    perror("path");
    return 1;
  }

  /* Load */
  while(!feof(is)) {
    wchar_t unicode[MAX_UNICODE_SEQ];
    int ulen = 0;

    char buf[256];
    char flag[256];

    int scanned = 0;

    /* Scan a single token first */
    scanned = fscanf(is, "%255s", buf);
    if(scanned < 0) break;
    if(scanned == 0) {
      fprintf(stderr, "%s: Character map syntax error\n", path);
      return 1;
    }

    /* Handle the first argument */
    if(strcmp(buf, "section") == 0) {    /* Section division */
      section++;
      continue;
    }
    else if(buf[0] == '#') {             /* Comment */
      fscanf(is, "%*[^\n]");
      continue;
    }
    else {
      char* bp = buf;
      int u;

      do {
        if(sscanf(bp, "%x", &u) == 1) {   /* Unicode */
          unicode[ulen++] = u;
        }
        else {
          fprintf(stderr, "%s: Syntax error at '%s'\n", path, buf);
          return 1;
        }

        bp = strchr(bp, ':');
        if(bp) bp++;
      } while(bp && ulen < MAX_UNICODE_SEQ-1);
      unicode[ulen] = L'\0';
    }

    /* Scan some more */
    scanned = fscanf(is, "%255s\t%255s", buf, flag);
    if(scanned < 0) break;

    /* Input count checking */
    switch(scanned) {
      case 0: case 1:
        fprintf(stderr, "%s: Character map syntax error\n", path);
        return 1;

      default:
        if(charmap_add(cm, section, buf, unicode, flag)) {
          size_t i = 0;

#ifndef __BEOS__
#if defined __GLIBC__ && __GLIBC__ == 2 && __GLIBC_MINOR__ >=2 || __GLIBC__ > 2 || __APPLE__
          fwprintf(stderr, L"Unable to add sequence '%ls', unicode ", buf);
          for(i = 0; i < wcslen(unicode); i++) fwprintf(stderr, L"%04X ", (int)unicode[i]);
          fwprintf(stderr, L"in section %d\n", section);
#endif
#endif

          error_code = 1;
        }
    }
  }

  /* Close */
  fclose(is);

  return error_code;
}


/**
* Free the resources used by a character map.
*/
static void charmap_free(CHARMAP* cm)
{
  int i;

  for(i = 0; i < MAX_SECTIONS; i++) {
    sm_free(&cm->sections[i]);
  }

  memset(cm, 0, sizeof(CHARMAP));
}


/**
* Search for a matching character string in the character map.
*/
static const wchar_t* charmap_search(CHARMAP* cm, wchar_t* s)
{
  STATE_MACHINE* start;
  const wchar_t* unicode;
  int section;

  /* Determine the starting state based on the charmap's active section */
  section = cm->section;
  if(!IN_RANGE(0, section, (int)ARRAYLEN(cm->sections))) section = 0;
  start = &cm->sections[section];

  cm->match_state = NULL;
  cm->match_state_prev = NULL;
  unicode = sm_search(start, s, &cm->match_count, &cm->match_state_prev, &cm->match_state);

  /**
  * Determine whether the match is final.  A match is considered to be final
  * in two cases: (1)if the last state mached has no exit paths, or (2)if we
  * did not consume all of the search string.  (1) is obvious - if there are
  * no more states to transition to, then the unicode we find is the final
  * code.  (2) means we reached the final state that can be the only
  * interpretation of the input string, so it must be the final state.
  * If neither of these is true, that means further input from the user
  * may allow us to get to a different state, so we have not reached the
  * final state we possibly can.
  */
  cm->match_is_final = 0;
  if(cm->match_count < (int)wcslen(s)) {
    cm->match_is_final = 1;
  }

  /* Statistics */
  cm->match_stats = MATCH_STAT_NONE;
  if(cm->match_state->next_size == 0) {
    cm->match_is_final = 1;
    cm->match_stats |= MATCH_STAT_NOMOSTATES;
  }
  if(cm->match_count == (int)wcslen(s)) {
    cm->match_stats |= MATCH_STAT_NOMOBUF;
  }

  return unicode;
}


/* ***************************************************************************
* GENERIC IM FUNCTIONS
*/

/**
* Default C IM event handler.
*
* @see im_read
*/
static int im_event_c(IM_DATA* im, SDL_keysym ks)
{
  /* Handle event requests */
  im->s[0] = L'\0';
  if(im->request != IM_REQ_TRANSLATE) return 0;

  /* Handle key stroke */
  switch(ks.sym) {
    case SDLK_BACKSPACE: im->s[0] = L'\b'; break;
    case SDLK_TAB:       im->s[0] = L'\t'; break;
    case SDLK_RETURN:    im->s[0] = L'\r'; break;
    default:             im->s[0] = ks.unicode;
  }
  im->s[1] = L'\0';
  im->buf[0] = L'\0';

  return 0;
}

/* ***************************************************************************
* PUBLIC IM FUNCTIONS
*/

/**
* IM-process a character.  This function simply looks up the language from
* IM and calls the appropriate im_event_<lang>() language-specific IM event
* handler.  im_event_c() is called by default if no language-specific
* function is specified for the specified language.
*
* @param im  IM-processed data to return to the caller function.
* @param ks  SDL_keysym typed on the keyboard.
*
* @return    The number of characters in im->s that should not be committed.
*            In other words, the returned number of characters at the end of
*            im->s should be overwritten the next time im_read is called.
*
* @see im_event_c()
* @see im_event_fns
*/
int im_read(IM_DATA* im, SDL_keysym ks)
{
  IM_EVENT_FN im_event_fp = NULL;
  int redraw = 0;

  /* Sanity check */
  if(im->lang < 0 || im->lang >= NUM_LANGS) {
    fprintf(stderr, "im->lang out of range (%d), using default\n", im->lang);
    im->lang = LANG_DEFAULT;
  }

  /* Function pointer to the language-specific im_event_* function */
  im_event_fp = im_event_fns[im->lang];

  /* Run the language-specific IM or run the default C IM */
  if(im_event_fp) redraw = (*im_event_fp)(im, ks);
  else redraw = im_event_c(im, ks);

  #ifdef IM_DEBUG
  wprintf(L"* [%8ls] [%8ls] %2d %2d (%2d)\n", im->s, im->buf, wcslen(im->s), wcslen(im->buf), im->redraw);
  #endif

  return redraw;
}

/* ***************************************************************************
* OTHER STATIC IM FUNCTIONS
*/

/**
* Generic event handler that calls the appropriate language handler.
* im->request should have the event ID.
*/
static void im_event(IM_DATA* im)
{
  SDL_keysym ks;

  ks.sym = 0;
  ks.unicode = 0;

  im_read(im, ks);
}


/**
* Make an event request and call the event handler.
*/
static void im_request(IM_DATA* im, int request)
{
  im->request = request;
  im_event(im);
  im->request = IM_REQ_TRANSLATE;
}

/* ***************************************************************************
* PUBLIC IM FUNCTIONS
*/

/**
* Free any allocated resources.
*/
static void im_free(IM_DATA* im)
{
  im_request(im, IM_REQ_FREE);
}


void im_softreset(IM_DATA* im)
{
  im->s[0] = L'\0';
  im->buf[0] = L'\0';

  im_request(im, IM_REQ_RESET_SOFT);
}


static void im_fullreset(IM_DATA* im)
{
  im->s[0] = L'\0';
  im->buf[0] = L'\0';

  im_request(im, IM_REQ_RESET_FULL);
}


/* ***************************************************************************
* LANGUAGE-SPECIFIC IM FUNCTIONS
*
* If you want to add a new language support, add the main code to this
* section.  More specifically, do the following:
*
*   1) Add im_event_<lang>() function to this section.  Use the existing
*      im_event_* functions as models, and feel free to use the state-machine
*      character map engine (CHARMAP struct) but do not feel obligated to
*      do so.  The CHARMAP engine exists for the programmer's benefit, to
*      make it easier to support complex languages.
*
*   2) Update the im_init() functions so that it initializes im_event_fns[]
*      with a pointer to your im_event_<lang>() function.
*
*   3) Create <lang>.im in the "im" directory, if you use the CHARMAP engine.
*      Your code is what loads this file so you should already know to do this
*      step if you have already written a working im_event_<lang>() function
*      that uses CHARMAP, but I explicitly write out this instruction for
*      those trying to figure out the relationship of <lang>.im to this IM
*      framework.
*
*   4) Increase MAX_SECTION if your language needs more sections in <lang>.im
*
*   5) Increase INITIAL_SMSIZE if your <lang>.im is huginormous and takes too
*      long to load.  I can't think of any reason why this would happen unless
*      you're writing a Chinese IM with a significant characters of the
*      language represented, but the code as-is is somewhat lacking when it
*      comes to writing a Chinese IM (need some way to show a dropdown box
*      from the main app - same problem with Korean Hanja and Japanese Kanji
*      inputs, but this isn't meant to be a complex IM framework so I think
*      we're safe for Hanja and Kanji.)  Do this with caution because
*      changing INITIAL_SMSIZE will affect the memory consumption of all IM
*      functions.
*/

/**
* Chinese Traditional IM.
*
* @see im_read
*/
static int im_event_zh_tw(IM_DATA* im, SDL_keysym ks)
{
  enum { SEC_ENGLISH, SEC_ZH_TW, SEC_TOTAL };

  static CHARMAP cm;


  /* Handle event requests */
  switch(im->request) {
    case 0: break;

    case IM_REQ_FREE:        /* Free allocated resources */
      charmap_free(&cm);
      /* go onto full reset */

    case IM_REQ_RESET_FULL:  /* Full reset */
      cm.section = SEC_ENGLISH;
      im->tip_text = im_tip_text[IM_TIP_ENGLISH];
      /* go onto soft reset */

    case IM_REQ_RESET_SOFT:  /* Soft reset */
      im->s[0] = L'\0';
      im->buf[0] = L'\0';
      im->redraw = 0;
      cm.match_count = 0;
      cm.match_is_final = 0;
      cm.match_state = &cm.sections[cm.section];
      cm.match_state_prev = &cm.sections[cm.section];
      break;

    case IM_REQ_INIT:        /* Initialization */
      {
        char lang_file[MAX_PATH];
        snprintf(lang_file, sizeof(lang_file), "%s/im/zh_tw.im", DATA_PREFIX);

        charmap_init(&cm);

        if(charmap_load(&cm, lang_file)) {
          fprintf(stderr, "Unable to load %s, defaulting to im_event_c\n", lang_file);
          im->lang = LANG_DEFAULT;
          return im_event_c(im, ks);
        }

        im_fullreset(im);

        #ifdef DEBUG
        printf("IM: Loaded '%s'\n", lang_file);
        #endif
        break;
      }
  }
  if(im->request != IM_REQ_TRANSLATE) return 0;


  /* Discard redraw characters, so they can be redrawn */
  if((int)wcslen(im->s) < im->redraw) im->redraw = wcslen(im->s);
  wcs_lshift(im->s, (wcslen(im->s) - im->redraw) );


  /* Handle keys */
  switch(ks.sym) {
    /* Keys to ignore */
    case SDLK_NUMLOCK: case SDLK_CAPSLOCK: case SDLK_SCROLLOCK:
    case SDLK_LSHIFT:  case SDLK_RSHIFT:
    case SDLK_LCTRL:   case SDLK_RCTRL:
    case SDLK_LMETA:   case SDLK_RMETA:
    case SDLK_LSUPER:  case SDLK_RSUPER:
    case SDLK_MODE:    case SDLK_COMPOSE:
      break;

    /* Left-Alt & Right-Alt mapped to mode-switch */
    case SDLK_RALT:    case SDLK_LALT:
      cm.section = (++cm.section % SEC_TOTAL);   /* Change section */
      im_softreset(im);                          /* Soft reset */

      /* Set tip text */
      switch(cm.section) {
        case SEC_ENGLISH:  im->tip_text = im_tip_text[IM_TIP_ENGLISH]; break;
        case SEC_ZH_TW: im->tip_text = im_tip_text[IM_TIP_ZH_TW]; break;
      }
      break;

    /* Enter finalizes previous redraw */
    case SDLK_RETURN:
      if(im->redraw <= 0) {
        im->s[0] = L'\r';
        im->s[1] = L'\0';
      }
      im->buf[0] = L'\0';
      im->redraw = 0;
      break;

    /* Actual character processing */
    default:
      /* English mode */
      if(cm.section == SEC_ENGLISH) {
        im->s[0] = ks.unicode;
        im->s[1] = L'\0';
        im->buf[0] = L'\0';
      }
      /* Thai mode */
      else {
        wchar_t u = ks.unicode;

        im->s[0] = L'\0';                     /* Zero-out output string */
        wcsncat(im->buf, &u, 1);              /* Copy new character */

        /* Translate the characters */
        im->redraw = 0;
        while(1) {
          const wchar_t* us = charmap_search(&cm, im->buf);
          #ifdef IM_DEBUG
          wprintf(L"  [%8ls] [%8ls] %2d %2d\n", im->s, im->buf, wcslen(im->s), wcslen(im->buf));
          #endif

          /* Match was found? */
          if(us && wcslen(us)) {
            #ifdef IM_DEBUG
            wprintf(L"    1\n");
            #endif

            wcscat(im->s, us);

            /* Final match */
            if(cm.match_is_final) {
              wcs_lshift(im->buf, cm.match_count);
              cm.match_count = 0;
              cm.match_is_final = 0;
            }
            /* May need to be overwritten next time */
            else {
              im->redraw += wcslen(us);
              break;
            }
          }
          /* No match, but more data is in the buffer */
          else if(wcslen(im->buf) > 0) {
            /* If the input character has no state, it's its own state */
            if(cm.match_count == 0) {
              #ifdef IM_DEBUG
              wprintf(L"    2a\n");
              #endif
              wcsncat(im->s, im->buf, 1);
              wcs_lshift(im->buf, 1);
              cm.match_is_final = 0;
            }
            /* If the matched characters didn't consume all, it's own state */
            else if((size_t)cm.match_count != wcslen(im->buf)) {
              #ifdef IM_DEBUG
              wprintf(L"    2b (%2d)\n", cm.match_count);
              #endif
              wcsncat(im->s, im->buf, 1);
              wcs_lshift(im->buf, 1);
              cm.match_is_final = 0;
            }
            /* Otherwise it's just a part of a future input */
            else {
              #ifdef IM_DEBUG
              wprintf(L"    2c (%2d)\n", cm.match_count);
              #endif
              wcscat(im->s, im->buf);
              cm.match_is_final = 0;
              im->redraw += wcslen(im->buf);
              break;
            }
          }
          /* No match and no more data in the buffer */
          else {
            #ifdef IM_DEBUG
            wprintf(L"    3\n");
            #endif
            break;
          }

          /* Is this the end? */
          if(cm.match_is_final) break;
        }
      }
  }

  return im->redraw;
}


/**
* Thai IM.
*
* @see im_read
*/
static int im_event_th(IM_DATA* im, SDL_keysym ks)
{
  enum { SEC_ENGLISH, SEC_THAI, SEC_TOTAL };

  static CHARMAP cm;


  /* Handle event requests */
  switch(im->request) {
    case 0: break;

    case IM_REQ_FREE:        /* Free allocated resources */
      charmap_free(&cm);
      /* go onto full reset */

    case IM_REQ_RESET_FULL:  /* Full reset */
      cm.section = SEC_ENGLISH;
      im->tip_text = im_tip_text[IM_TIP_ENGLISH];
      /* go onto soft reset */

    case IM_REQ_RESET_SOFT:  /* Soft reset */
      im->s[0] = L'\0';
      im->buf[0] = L'\0';
      im->redraw = 0;
      cm.match_count = 0;
      cm.match_is_final = 0;
      cm.match_state = &cm.sections[cm.section];
      cm.match_state_prev = &cm.sections[cm.section];
      break;

    case IM_REQ_INIT:        /* Initialization */
      {
        char lang_file[MAX_PATH];
        snprintf(lang_file, sizeof(lang_file), "%s/im/th.im", DATA_PREFIX);

        charmap_init(&cm);

        if(charmap_load(&cm, lang_file)) {
          fprintf(stderr, "Unable to load %s, defaulting to im_event_c\n", lang_file);
          im->lang = LANG_DEFAULT;
          return im_event_c(im, ks);
        }

        im_fullreset(im);

        #ifdef DEBUG
        printf("IM: Loaded '%s'\n", lang_file);
        #endif
        break;
      }
  }
  if(im->request != IM_REQ_TRANSLATE) return 0;


  /* Discard redraw characters, so they can be redrawn */
  if((int)wcslen(im->s) < im->redraw) im->redraw = wcslen(im->s);
  wcs_lshift(im->s, (wcslen(im->s) - im->redraw) );


  /* Handle keys */
  switch(ks.sym) {
    /* Keys to ignore */
    case SDLK_NUMLOCK: case SDLK_CAPSLOCK: case SDLK_SCROLLOCK:
    case SDLK_LSHIFT:  case SDLK_RSHIFT:
    case SDLK_LCTRL:   case SDLK_RCTRL:
    case SDLK_LALT:
    case SDLK_LMETA:   case SDLK_RMETA:
    case SDLK_LSUPER:  case SDLK_RSUPER:
    case SDLK_MODE:    case SDLK_COMPOSE:
      break;

    /* Right-Alt mapped to mode-switch */
    case SDLK_RALT:
      cm.section = (++cm.section % SEC_TOTAL);   /* Change section */
      im_softreset(im);                          /* Soft reset */

      /* Set tip text */
      switch(cm.section) {
        case SEC_ENGLISH:  im->tip_text = im_tip_text[IM_TIP_ENGLISH]; break;
        case SEC_THAI: im->tip_text = im_tip_text[IM_TIP_THAI]; break;
      }
      break;

    /* Enter finalizes previous redraw */
    case SDLK_RETURN:
      if(im->redraw <= 0) {
        im->s[0] = L'\r';
        im->s[1] = L'\0';
      }
      im->buf[0] = L'\0';
      im->redraw = 0;
      break;

    /* Actual character processing */
    default:
      /* English mode */
      if(cm.section == SEC_ENGLISH) {
        im->s[0] = ks.unicode;
        im->s[1] = L'\0';
        im->buf[0] = L'\0';
      }
      /* Thai mode */
      else {
        wchar_t u = ks.unicode;

        im->s[0] = L'\0';                     /* Zero-out output string */
        wcsncat(im->buf, &u, 1);              /* Copy new character */

        /* Translate the characters */
        im->redraw = 0;
        while(1) {
          const wchar_t* us = charmap_search(&cm, im->buf);
          #ifdef IM_DEBUG
          wprintf(L"  [%8ls] [%8ls] %2d %2d\n", im->s, im->buf, wcslen(im->s), wcslen(im->buf));
          #endif

          /* Match was found? */
          if(us && wcslen(us)) {
            #ifdef IM_DEBUG
            wprintf(L"    1\n");
            #endif

            wcscat(im->s, us);

            /* Final match */
            if(cm.match_is_final) {
              wcs_lshift(im->buf, cm.match_count);
              cm.match_count = 0;
              cm.match_is_final = 0;
            }
            /* May need to be overwritten next time */
            else {
              im->redraw += wcslen(us);
              break;
            }
          }
          /* No match, but more data is in the buffer */
          else if(wcslen(im->buf) > 0) {
            /* If the input character has no state, it's its own state */
            if(cm.match_count == 0) {
              #ifdef IM_DEBUG
              wprintf(L"    2a\n");
              #endif
              wcsncat(im->s, im->buf, 1);
              wcs_lshift(im->buf, 1);
              cm.match_is_final = 0;
            }
            /* If the matched characters didn't consume all, it's own state */
            else if((size_t)cm.match_count != wcslen(im->buf)) {
              #ifdef IM_DEBUG
              wprintf(L"    2b (%2d)\n", cm.match_count);
              #endif
              wcsncat(im->s, im->buf, 1);
              wcs_lshift(im->buf, 1);
              cm.match_is_final = 0;
            }
            /* Otherwise it's just a part of a future input */
            else {
              #ifdef IM_DEBUG
              wprintf(L"    2c (%2d)\n", cm.match_count);
              #endif
              wcscat(im->s, im->buf);
              cm.match_is_final = 0;
              im->redraw += wcslen(im->buf);
              break;
            }
          }
          /* No match and no more data in the buffer */
          else {
            #ifdef IM_DEBUG
            wprintf(L"    3\n");
            #endif
            break;
          }

          /* Is this the end? */
          if(cm.match_is_final) break;
        }
      }
  }

  return im->redraw;
}


/**
* Japanese IM.
*
* @see im_read
*/
static int im_event_ja(IM_DATA* im, SDL_keysym ks)
{
  enum { SEC_ENGLISH, SEC_HIRAGANA, SEC_KATAKANA, SEC_TOTAL };

  static CHARMAP cm;


  /* Handle event requests */
  switch(im->request) {
    case 0: break;

    case IM_REQ_FREE:        /* Free allocated resources */
      charmap_free(&cm);
      /* go onto full reset */

    case IM_REQ_RESET_FULL:  /* Full reset */
      cm.section = SEC_ENGLISH;
      im->tip_text = im_tip_text[IM_TIP_ENGLISH];
      /* go onto soft reset */

    case IM_REQ_RESET_SOFT:  /* Soft reset */
      im->s[0] = L'\0';
      im->buf[0] = L'\0';
      im->redraw = 0;
      cm.match_count = 0;
      cm.match_is_final = 0;
      cm.match_state = &cm.sections[cm.section];
      cm.match_state_prev = &cm.sections[cm.section];
      break;

    case IM_REQ_INIT:        /* Initialization */
      {
        char lang_file[MAX_PATH];
        snprintf(lang_file, sizeof(lang_file), "%s/im/ja.im", DATA_PREFIX);

        charmap_init(&cm);

        if(charmap_load(&cm, lang_file)) {
          fprintf(stderr, "Unable to load %s, defaulting to im_event_c\n", lang_file);
          im->lang = LANG_DEFAULT;
          return im_event_c(im, ks);
        }

        im_fullreset(im);

        #ifdef DEBUG
        printf("IM: Loaded '%s'\n", lang_file);
        #endif
        break;
      }
  }
  if(im->request != IM_REQ_TRANSLATE) return 0;


  /* Discard redraw characters, so they can be redrawn */
  if((int)wcslen(im->s) < im->redraw) im->redraw = wcslen(im->s);
  wcs_lshift(im->s, (wcslen(im->s) - im->redraw) );


  /* Handle keys */
  switch(ks.sym) {
    /* Keys to ignore */
    case SDLK_NUMLOCK: case SDLK_CAPSLOCK: case SDLK_SCROLLOCK:
    case SDLK_LSHIFT:  case SDLK_RSHIFT:
    case SDLK_LCTRL:   case SDLK_RCTRL:
    case SDLK_LALT:
    case SDLK_LMETA:   case SDLK_RMETA:
    case SDLK_LSUPER:  case SDLK_RSUPER:
    case SDLK_MODE:    case SDLK_COMPOSE:
      break;

    /* Right-Alt mapped to mode-switch */
    case SDLK_RALT:
      cm.section = (++cm.section % SEC_TOTAL);   /* Change section */
      im_softreset(im);                          /* Soft reset */

      /* Set tip text */
      switch(cm.section) {
        case SEC_ENGLISH:  im->tip_text = im_tip_text[IM_TIP_ENGLISH]; break;
        case SEC_HIRAGANA: im->tip_text = im_tip_text[IM_TIP_HIRAGANA]; break;
        case SEC_KATAKANA: im->tip_text = im_tip_text[IM_TIP_KATAKANA]; break;
      }
      break;

    /* Enter finalizes previous redraw */
    case SDLK_RETURN:
      if(im->redraw <= 0) {
        im->s[0] = L'\r';
        im->s[1] = L'\0';
      }
      im->buf[0] = L'\0';
      im->redraw = 0;
      break;

    /* Actual character processing */
    default:
      /* English mode */
      if(cm.section == SEC_ENGLISH) {
        im->s[0] = ks.unicode;
        im->s[1] = L'\0';
        im->buf[0] = L'\0';
      }
      /* Hiragana and Katakana modes */
      else {
        wchar_t u = ks.unicode;

        im->s[0] = L'\0';                     /* Zero-out output string */
        wcsncat(im->buf, &u, 1);              /* Copy new character */

        /* Translate the characters */
        im->redraw = 0;
        while(1) {
          const wchar_t* us = charmap_search(&cm, im->buf);
          #ifdef IM_DEBUG
          wprintf(L"  [%8ls] [%8ls] %2d %2d\n", im->s, im->buf, wcslen(im->s), wcslen(im->buf));
          #endif

          /* Match was found? */
          if(us && wcslen(us)) {
            #ifdef IM_DEBUG
            wprintf(L"    1\n");
            #endif

            wcscat(im->s, us);

            /* Final match */
            if(cm.match_is_final) {
              wcs_lshift(im->buf, cm.match_count);
              cm.match_count = 0;
              cm.match_is_final = 0;
            }
            /* May need to be overwritten next time */
            else {
              im->redraw += wcslen(us);
              break;
            }
          }
          /* No match, but more data is in the buffer */
          else if(wcslen(im->buf) > 0) {
            /* If the input character has no state, it's its own state */
            if(cm.match_count == 0) {
              #ifdef IM_DEBUG
              wprintf(L"    2a\n");
              #endif
              wcsncat(im->s, im->buf, 1);
              wcs_lshift(im->buf, 1);
              cm.match_is_final = 0;
            }
            /* If the matched characters didn't consume all, it's own state */
            else if((size_t)cm.match_count != wcslen(im->buf)) {
              #ifdef IM_DEBUG
              wprintf(L"    2b (%2d)\n", cm.match_count);
              #endif
              wcsncat(im->s, im->buf, 1);
              wcs_lshift(im->buf, 1);
              cm.match_is_final = 0;
            }
            /* Otherwise it's just a part of a future input */
            else {
              #ifdef IM_DEBUG
              wprintf(L"    2c (%2d)\n", cm.match_count);
              #endif
              wcscat(im->s, im->buf);
              cm.match_is_final = 0;
              im->redraw += wcslen(im->buf);
              break;
            }
          }
          /* No match and no more data in the buffer */
          else {
            #ifdef IM_DEBUG
            wprintf(L"    3\n");
            #endif
            break;
          }

          /* Is this the end? */
          if(cm.match_is_final) break;
        }
      }
  }

  return im->redraw;
}


/**
* Korean IM helper function to tell whether a character typed will produce
* a vowel.
*
* @see im_event_ko
*/
static int im_event_ko_isvowel(CHARMAP* cm, wchar_t c)
{
  STATE_MACHINE *start, *next;
  const wchar_t* unicode;
  int section;

  /* Determine the starting state based on the charmap's active section */
  section = cm->section;
  if(!IN_RANGE(0, section, (int)ARRAYLEN(cm->sections))) section = 0;
  start = &cm->sections[section];

  next = sm_search_shallow(start, (char)c);
  unicode = next ? next->output : NULL;

  return (unicode && wcslen(unicode) == 1 && 0x314F <= unicode[0] && unicode[0] <= 0x3163);
}


/**
* Korean IM.
*
* @see im_read
*/
static int im_event_ko(IM_DATA* im, SDL_keysym ks)
{
  enum { SEC_ENGLISH, SEC_HANGUL, SEC_TOTAL };

  static CHARMAP cm;


  /* Handle event requests */
  switch(im->request) {
    case 0: break;

    case IM_REQ_FREE:        /* Free allocated resources */
      charmap_free(&cm);
      /* go onto full reset */

    case IM_REQ_RESET_FULL:  /* Full reset */
      cm.section = SEC_ENGLISH;
      im->tip_text = im_tip_text[IM_TIP_ENGLISH];
      /* go onto soft reset */

    case IM_REQ_RESET_SOFT:  /* Soft reset */
      im->s[0] = L'\0';
      im->buf[0] = L'\0';
      im->redraw = 0;
      cm.match_count = 0;
      cm.match_is_final = 0;
      cm.match_state = &cm.sections[cm.section];
      cm.match_state_prev = &cm.sections[cm.section];
      break;

    case IM_REQ_INIT:        /* Initialization */
      {
        char lang_file[MAX_PATH];
        snprintf(lang_file, sizeof(lang_file), "%s/im/ko.im", DATA_PREFIX);

        charmap_init(&cm);

        if(charmap_load(&cm, lang_file)) {
          fprintf(stderr, "Unable to load %s, defaulting to im_event_c\n", lang_file);
          im->lang = LANG_DEFAULT;
          return im_event_c(im, ks);
        }

        im_fullreset(im);

        #ifdef DEBUG
        printf("IM: Loaded '%s'\n", lang_file);
        #endif
        break;
      }
  }
  if(im->request != IM_REQ_TRANSLATE) return 0;


  /* Discard redraw characters, so they can be redrawn */
  if((int)wcslen(im->s) < im->redraw) im->redraw = wcslen(im->s);
  wcs_lshift(im->s, (wcslen(im->s) - im->redraw) );


  /* Handle keys */
  switch(ks.sym) {
    /* Keys to ignore */
    case SDLK_NUMLOCK: case SDLK_CAPSLOCK: case SDLK_SCROLLOCK:
    case SDLK_LSHIFT:  case SDLK_RSHIFT:
    case SDLK_LCTRL:   case SDLK_RCTRL:
    case SDLK_LMETA:   case SDLK_RMETA:
    case SDLK_LSUPER:  case SDLK_RSUPER:
    case SDLK_MODE:    case SDLK_COMPOSE:
      break;

    /* Right-Alt mapped to mode-switch */
    case SDLK_LALT: case SDLK_RALT:
      cm.section = (++cm.section % SEC_TOTAL);   /* Change section */
      im_softreset(im);                          /* Soft reset */

      /* Set tip text */
      switch(cm.section) {
        case SEC_ENGLISH: im->tip_text = im_tip_text[IM_TIP_ENGLISH]; break;
        case SEC_HANGUL:  im->tip_text = im_tip_text[IM_TIP_HANGUL]; break;
      }
      break;

    /* Backspace removes only a single buffered character */
    case SDLK_BACKSPACE:
      /* Delete one buffered character */
      if(wcslen(im->buf) > 0) {
        wcs_pull(im->buf, 1);
        if(im->redraw > 0) im->redraw--;
        ks.unicode = L'\0';
      }
      /* continue processing: */

    /* Actual character processing */
    default:
      /* English mode */
      if(cm.section == SEC_ENGLISH) {
        im->s[0] = ks.unicode;
        im->s[1] = L'\0';
        im->buf[0] = L'\0';
      }
      /* Hangul mode */
      else {
        wchar_t u = ks.unicode;
        wchar_t* bp = im->buf;

        im->s[0] = L'\0';                     /* Zero-out output string */
        wcsncat(bp, &u, 1);                   /* Copy new character */

        /* Translate the characters */
        im->redraw = 0;
        while(1) {
          const wchar_t* us = charmap_search(&cm, bp);
          #ifdef IM_DEBUG
          wprintf(L"  [%8ls] [%8ls] %2d %2d\n", im->s, im->buf, wcslen(im->s), wcslen(im->buf));
          #endif

          /* Match was found? */
          if(us && wcslen(us)) {
            /* Final match */
            if(cm.match_is_final) {
              /* Batchim may carry over to the next character */
              if(cm.match_state->flag == 'b') {
                wchar_t next_char = bp[cm.match_count];

                /* If there is no more buffer, output it */
                if(cm.match_stats & MATCH_STAT_NOMOBUF) {
                  #ifdef IM_DEBUG
                  wprintf(L"    1a\n");
                  #endif

                  wcscat(im->s, us);          /* Output */
                  im->redraw += wcslen(us);  /* May need to re-eval next time */
                  bp += cm.match_count;       /* Keep buffer data for re-eval*/
                  cm.match_count = 0;
                  cm.match_is_final = 0;
                }
                /* If there is buffer data but it's not vowel, finalize it */
                else if(!im_event_ko_isvowel(&cm, next_char)) {
                  #ifdef IM_DEBUG
                  wprintf(L"    1b\n");
                  #endif

                  wcscat(im->s, us);     /* Output */
                  wcs_lshift(bp, cm.match_count);
                  cm.match_count = 0;
                  cm.match_is_final = 0;
                }
                /* If there is buffer and it's vowel, re-eval */
                else {
                  #ifdef IM_DEBUG
                  wprintf(L"    1c\n");
                  #endif

                  us = cm.match_state_prev->output;
                  wcscat(im->s, us);      /* Output */
                  cm.match_count--;       /* Matched all but one */
                  cm.match_is_final = 0;
                  wcs_lshift(bp, cm.match_count);
                }
              }
              /* No batchim - this is final */
              else {
                #ifdef IM_DEBUG
                wprintf(L"    1d\n");
                #endif

                wcscat(im->s, us);
                wcs_lshift(bp, cm.match_count);
                cm.match_count = 0;
                cm.match_is_final = 0;
              }
            }
            /* May need to be overwritten next time */
            else {
              #ifdef IM_DEBUG
              wprintf(L"    1e\n");
              #endif

              wcscat(im->s, us);
              im->redraw += wcslen(us);
              break;
            }
          }
          /* No match, but more data is in the buffer */
          else if(wcslen(bp) > 0) {
            /* If the input character has no state, it's its own state */
            if(cm.match_count == 0) {
              #ifdef IM_DEBUG
              wprintf(L"    2a\n");
              #endif
              wcsncat(im->s, bp, 1);
              wcs_lshift(bp, 1);
              cm.match_is_final = 0;
            }
            /* If the matched characters didn't consume all, it's own state */
            else if((size_t)cm.match_count != wcslen(bp)) {
              #ifdef IM_DEBUG
              wprintf(L"    2b (%2d)\n", cm.match_count);
              #endif
              wcsncat(im->s, bp, 1);
              wcs_lshift(bp, 1);
              cm.match_is_final = 0;
            }
            /* Otherwise it's just a part of a future input */
            else {
              #ifdef IM_DEBUG
              wprintf(L"    2c (%2d)\n", cm.match_count);
              #endif
              wcscat(im->s, bp);
              cm.match_is_final = 0;
              im->redraw += wcslen(bp);
              break;
            }
          }
          /* No match and no more data in the buffer */
          else {
            #ifdef IM_DEBUG
            wprintf(L"    3\n");
            #endif
            break;
          }

          /* Is this the end? */
          if(cm.match_is_final) break;
        }
      }
  }

  return im->redraw;
}


/* ***************************************************************************
* PUBLIC IM FUNCTIONS
*/

/**
* Initialize the IM_DATA structure.
*
* @param im    IM_DATA structure to initialize.
* @param lang  LANG_* defined constant to initialize the structure with.
*/
void im_init(IM_DATA* im, int lang)
{
  /* Free already allocated resources if initialized before */
  if(im_initialized) {
    im_free(im);
  }

  /* Initialize */
  memset(im, 0, sizeof(IM_DATA));
  im->lang = lang;

  /* Setup static globals */
  if(!im_initialized) {
    /* ADD NEW LANGUAGE SUPPORT HERE */
    im_event_fns[LANG_JA] = &im_event_ja;
    im_event_fns[LANG_KO] = &im_event_ko;
    im_event_fns[LANG_TH] = &im_event_th;
    im_event_fns[LANG_ZH_TW] = &im_event_zh_tw;

    im_initialized = 1;
  }

  #ifdef DEBUG
  assert(0 <= im->lang && im->lang < NUM_LANGS);
  if(im_event_fp) printf("Initializing IM for %s...\n", lang_prefixes[im->lang]);
  #endif

  /* Initialize the individual IM */
  im_request(im, IM_REQ_INIT);
}




/* vim:ts=2:et
*/