summaryrefslogtreecommitdiff
path: root/modules/im/ximcp/imThaiFlt.c
blob: 5168de2b1f7e8b488afaa44dbbe64e8e77ffe42e (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
/* $Xorg: imThaiFlt.c,v 1.5 2001/02/09 02:03:39 xorgcvs Exp $ */
/***********************************************************

Copyright 1993, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.


Copyright 1993 by Digital Equipment Corporation, Maynard, Massachusetts.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

******************************************************************/
/* $XFree86: xc/lib/X11/imThaiFlt.c,v 3.18 2003/02/21 03:13:30 dawes Exp $ */

/*
**++ 
**  FACILITY: 
** 
**      Xlib 
** 
**  ABSTRACT: 
** 
**	Thai specific functions.
**	Handles character classifications, composibility checking,
**	Input sequence check and other Thai specific requirements
**	according to WTT specification and DEC extensions.
** 
**  MODIFICATION HISTORY: 
** 
**/

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xmd.h>
#include <X11/keysym.h>
#include <X11/Xutil.h>
#include "Xlibint.h"
#include "Xlcint.h"
#include "Ximint.h"
#include "XimThai.h"

/* EXTERNS */
/* KeyBind.c */
extern int _XKeyInitialize();

/* lcStd.c */
extern int _Xlcmbstowcs(
    XLCd	lcd,
    wchar_t	*wstr,
    char	*str,
    int		len
);
extern int _Xlcwcstombs(
    XLCd	lcd,
    char	*str,
    wchar_t	*wstr,
    int		len
);
extern int _Xlcmbstoutf8(
    XLCd	lcd,
    char	*ustr,
    const char	*str,
    int		len
);

#define SPACE   32

/* character classification table */
#define TACTIS_CHARS 256
Private
char const tactis_chtype[TACTIS_CHARS] = {
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /*  0 -  7 */
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /*  8 - 15 */
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /* 16 - 23 */
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /* 24 - 31 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 32 - 39 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 40 - 47 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 48 - 55 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 56 - 63 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 64 - 71 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 72 - 79 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 80 - 87 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 88 - 95 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 96 - 103 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 104 - 111 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 112 - 119 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  CTRL,  /* 120 - 127 */
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /* 128 - 135 */
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /* 136 - 143 */
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /* 144 - 151 */
    CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL, CTRL,  /* 152 - 159 */
    NON,  CONS, CONS, CONS, CONS, CONS, CONS, CONS,  /* 160 - 167 */
    CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS,  /* 168 - 175 */
    CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS,  /* 176 - 183 */
    CONS, CONS, CONS, CONS, CONS, CONS, CONS, CONS,  /* 184 - 191 */
    CONS, CONS, CONS, CONS,  FV3, CONS,  FV3, CONS,  /* 192 - 199 */
    CONS, CONS, CONS, CONS, CONS, CONS, CONS, NON,   /* 200 - 207 */
    FV1,  AV2,  FV1,  FV1,  AV1,  AV3,  AV2,  AV3,   /* 208 - 215 */
    BV1,  BV2,  BD,   NON,  NON,  NON,  NON,  NON,   /* 216 - 223 */
    LV,   LV,   LV,   LV,   LV,   FV2,  NON,  AD2,   /* 224 - 231 */
    TONE, TONE, TONE, TONE, AD1,  AD1,  AD3,  NON,   /* 232 - 239 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  NON,   /* 240 - 247 */
    NON,  NON,  NON,  NON,  NON,  NON,  NON,  CTRL   /* 248 - 255 */
};

/* Composibility checking tables */
#define NC  0   /* NOT COMPOSIBLE - following char displays in next cell */
#define CP  1   /* COMPOSIBLE - following char is displayed in the same cell
                                as leading char, also implies ACCEPT */
#define XC  3   /* Non-display */
#define AC  4   /* ACCEPT - display the following char in the next cell */
#define RJ  5   /* REJECT - discard that following char, ignore it */

#define CH_CLASSES      17  /* 17 classes of chars */

Private
char const write_rules_lookup[CH_CLASSES][CH_CLASSES] = {
        /* Table 0: writing/outputing rules */
        /* row: leading char,  column: following char */
/* CTRL NON CONS LV FV1 FV2 FV3 BV1 BV2 BD TONE AD1 AD2 AD3 AV1 AV2 AV3 */
   {XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*CTRL*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*NON*/
  ,{XC, NC, NC, NC, NC, NC, NC, CP, CP, CP, CP, CP, CP, CP, CP, CP, CP}/*CONS*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*LV*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*FV1*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*FV2*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*FV3*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, CP, CP, NC, NC, NC, NC, NC}/*BV1*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, CP, NC, NC, NC, NC, NC, NC}/*BV2*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*BD*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*TONE*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*AD1*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*AD2*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC, NC}/*AD3*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, CP, CP, NC, NC, NC, NC, NC}/*AV1*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, CP, NC, NC, NC, NC, NC, NC}/*AV2*/
  ,{XC, NC, NC, NC, NC, NC, NC, NC, NC, NC, CP, NC, CP, NC, NC, NC, NC}/*AV3*/
};

Private
char const wtt_isc1_lookup[CH_CLASSES][CH_CLASSES] = {
      /* Table 1: WTT default input sequence check rules */
      /* row: leading char,  column: following char */
/* CTRL NON CONS LV FV1 FV2 FV3 BV1 BV2 BD TONE AD1 AD2 AD3 AV1 AV2 AV3 */
   {XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*CTRL*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*NON*/
  ,{XC, AC, AC, AC, AC, AC, AC, CP, CP, CP, CP, CP, CP, CP, CP, CP, CP}/*CONS*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*LV*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV3*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, CP, RJ, RJ, RJ, RJ, RJ}/*BV1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, RJ, RJ, RJ, RJ, RJ, RJ}/*BV2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*BD*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*TONE*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*AD1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*AD2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*AD3*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, CP, RJ, RJ, RJ, RJ, RJ}/*AV1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, RJ, RJ, RJ, RJ, RJ, RJ}/*AV2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, RJ, CP, RJ, RJ, RJ, RJ}/*AV3*/
};

Private
char const wtt_isc2_lookup[CH_CLASSES][CH_CLASSES] = {
      /* Table 2: WTT strict input sequence check rules */
      /* row: leading char,  column: following char */
/* CTRL NON CONS LV FV1 FV2 FV3 BV1 BV2 BD TONE AD1 AD2 AD3 AV1 AV2 AV3 */
   {XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*CTRL*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*NON*/
  ,{XC, AC, AC, AC, AC, RJ, AC, CP, CP, CP, CP, CP, CP, CP, CP, CP, CP}/*CONS*/
  ,{XC, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*LV*/
  ,{XC, AC, AC, AC, AC, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV1*/
  ,{XC, AC, AC, AC, AC, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV2*/
  ,{XC, AC, AC, AC, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV3*/
  ,{XC, AC, AC, AC, AC, RJ, AC, RJ, RJ, RJ, CP, CP, RJ, RJ, RJ, RJ, RJ}/*BV1*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, CP, RJ, RJ, RJ, RJ, RJ, RJ}/*BV2*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*BD*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*TONE*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*AD1*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*AD2*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*AD3*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, CP, CP, RJ, RJ, RJ, RJ, RJ}/*AV1*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, CP, RJ, RJ, RJ, RJ, RJ, RJ}/*AV2*/
  ,{XC, AC, AC, AC, RJ, RJ, AC, RJ, RJ, RJ, CP, RJ, CP, RJ, RJ, RJ, RJ}/*AV3*/
};

Private
char const thaicat_isc_lookup[CH_CLASSES][CH_CLASSES] = {
      /* Table 3: Thaicat input sequence check rules */
      /* row: leading char,  column: following char */
/* CTRL NON CONS LV FV1 FV2 FV3 BV1 BV2 BD TONE AD1 AD2 AD3 AV1 AV2 AV3 */
   {XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*CTRL*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*NON*/
  ,{XC, AC, AC, AC, AC, AC, AC, CP, CP, CP, CP, CP, CP, CP, CP, CP, CP}/*CONS*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*LV*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*FV2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ} /*FV3*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, CP, RJ, RJ, RJ, RJ, RJ}/*BV1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, RJ, RJ, RJ, RJ, RJ, RJ}/*BV2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*BD*/
  ,{XC, AC, AC, AC, AC, AC, AC, CP, CP, RJ, RJ, RJ, RJ, RJ, CP, CP, CP}/*TONE*/
  ,{XC, AC, AC, AC, AC, AC, AC, CP, RJ, RJ, RJ, RJ, RJ, RJ, CP, RJ, RJ}/*AD1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, CP}/*AD2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ, RJ}/*AD3*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, CP, RJ, RJ, RJ, RJ, RJ}/*AV1*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, RJ, RJ, RJ, RJ, RJ, RJ}/*AV2*/
  ,{XC, AC, AC, AC, AC, AC, AC, RJ, RJ, RJ, CP, RJ, CP, RJ, RJ, RJ, RJ}/*AV3*/
};


/* returns classification of a char */
Private int
#if NeedFunctionPrototypes
THAI_chtype (unsigned char	ch)
#else
THAI_chtype (ch)
    unsigned char	ch;
#endif
{
    return tactis_chtype[ch];
}


/* returns the display level */
Private int
#if NeedFunctionPrototypes
THAI_chlevel (unsigned char	ch)
#else
THAI_chlevel (ch)
    unsigned char	ch;
#endif
{
    int     chlevel;

    switch (tactis_chtype[ch])
    {
        case CTRL:
            chlevel = NON;
            break;
        case BV1:
        case BV2:
        case BD:
            chlevel = BELOW;
            break;
        case TONE:
        case AD1:
        case AD2:
            chlevel = TOP;
            break;
        case AV1:
        case AV2:
        case AV3:
        case AD3:
            chlevel = ABOVE;
            break;
        case NON:
        case CONS:
        case LV:
        case FV1:
        case FV2:
        case FV3:
        default: /* if tactis_chtype is invalid */
            chlevel = BASE;
            break;
    }
    return chlevel;
}


/* return True if char is non-spacing */
Private Bool
#if NeedFunctionPrototypes
THAI_isdead (unsigned char	ch)
#else
THAI_isdead (ch)
    unsigned char	ch;
#endif
{
    return ((tactis_chtype[ch] == CTRL) || (tactis_chtype[ch] == BV1) ||
            (tactis_chtype[ch] == BV2)  || (tactis_chtype[ch] == BD)  ||
            (tactis_chtype[ch] == TONE) || (tactis_chtype[ch] == AD1) ||
            (tactis_chtype[ch] == AD2)  || (tactis_chtype[ch] == AD3) ||
            (tactis_chtype[ch] == AV1)  || (tactis_chtype[ch] == AV2) ||
            (tactis_chtype[ch] == AV3));
}


/* return True if char is consonant */
Private Bool
#if NeedFunctionPrototypes
THAI_iscons (unsigned char	ch)
#else
THAI_iscons (ch)
    unsigned char	ch;
#endif
{
    return (tactis_chtype[ch] == CONS);
}


/* return True if char is vowel */
Private Bool
#if NeedFunctionPrototypes
THAI_isvowel (unsigned char	ch)
#else
THAI_isvowel (ch)
    unsigned char	ch;
#endif
{
    return ((tactis_chtype[ch] == LV)  || (tactis_chtype[ch] == FV1) ||
            (tactis_chtype[ch] == FV2) || (tactis_chtype[ch] == FV3) ||
            (tactis_chtype[ch] == BV1) || (tactis_chtype[ch] == BV2) ||
            (tactis_chtype[ch] == AV1) || (tactis_chtype[ch] == AV2) ||
            (tactis_chtype[ch] == AV3));
}


/* return True if char is tonemark */
Private Bool
#if NeedFunctionPrototypes
THAI_istone (unsigned char	ch)
#else
THAI_istone (ch)
    unsigned char	ch;
#endif
{
    return (tactis_chtype[ch] == TONE);
}


Private Bool
#if NeedFunctionPrototypes
THAI_iscomposible (
    unsigned char	follow_ch, 
    unsigned char	lead_ch)
#else
THAI_iscomposible (follow_ch, lead_ch)
    unsigned char	follow_ch;
    unsigned char	lead_ch;
#endif
{/* "Can follow_ch be put in the same display cell as lead_ch?" */

    return (write_rules_lookup[THAI_chtype(lead_ch)][THAI_chtype(follow_ch)] 
            == CP);
}

Private Bool
#if NeedFunctionPrototypes
THAI_isaccepted (
    unsigned char	follow_ch, 
    unsigned char	lead_ch,
    unsigned char	mode)
#else
THAI_isaccepted (follow_ch, lead_ch, mode)
    unsigned char	follow_ch;
    unsigned char	lead_ch;
    unsigned char	mode;
#endif
{
    Bool iskeyvalid; /*  means "Can follow_ch be keyed in after lead_ch?" */

    switch (mode)
    {
        case WTT_ISC1:
            iskeyvalid = 
          (wtt_isc1_lookup[THAI_chtype(lead_ch)][THAI_chtype(follow_ch)] != RJ);
            break;
        case WTT_ISC2:
            iskeyvalid = 
          (wtt_isc2_lookup[THAI_chtype(lead_ch)][THAI_chtype(follow_ch)] != RJ);
            break;
        case THAICAT_ISC:
            iskeyvalid =
       (thaicat_isc_lookup[THAI_chtype(lead_ch)][THAI_chtype(follow_ch)] != RJ);
            break;
        default:
            iskeyvalid = True;
            break;
    }

    return iskeyvalid;
}

#if 0
Private void 
#if NeedFunctionPrototypes
THAI_apply_write_rules(
    unsigned char	*instr, 
    unsigned char	*outstr, 
    unsigned char	insert_ch, 
    int 		*num_insert_ch)
#else
THAI_apply_write_rules(instr, outstr, insert_ch, num_insert_ch)
    unsigned char	*instr;
    unsigned char	*outstr;
    unsigned char	insert_ch;
    int 		*num_insert_ch;
#endif
{
/*
Input parameters: 
    instr - input string
    insert_ch specify what char to be added when invalid composition is found
Output parameters:
    outstr - output string after input string has been applied the rules
    num_insert_ch - number of insert_ch added to outstr.
*/
    unsigned char   *lead_ch = NULL, *follow_ch = NULL, *out_ch = NULL;

    *num_insert_ch = 0;
    lead_ch = follow_ch = instr;
    out_ch = outstr;
    if ((*lead_ch == '\0') || !(THAI_find_chtype(instr,DEAD)))
    {   /* Empty string or can't find any non-spacing char*/
        strcpy((char *)outstr, (char *)instr);
    } else { /* String of length >= 1, keep looking */
        follow_ch++;
        if (THAI_isdead(*lead_ch)) { /* is first char non-spacing? */
            *out_ch++ = SPACE;
            (*num_insert_ch)++;
        }
        *out_ch++ = *lead_ch;
        while (*follow_ch != '\0')  /* more char in string to check */
        {
            if (THAI_isdead(*follow_ch) && 
                 !THAI_iscomposible(*follow_ch,*lead_ch)) 
            {
                *out_ch++ = SPACE;
                (*num_insert_ch)++;
            }
            *out_ch++ = *follow_ch;
            lead_ch = follow_ch;
            follow_ch++;
        }
        *out_ch = '\0';
    }
}

Private int 
#if NeedFunctionPrototypes
THAI_find_chtype (
    unsigned char	*instr, 
    int		chtype)
#else
THAI_find_chtype (instr, chtype)
    unsigned char	*instr;
    int		chtype;
#endif
{
/*
Input parameters:
    instr - input string
    chtype - type of character to look for
Output parameters:
    function returns first position of character with matched chtype
    function returns -1 if it does not find.
*/
    int i = 0, position = -1;

    switch (chtype)
    {
        case DEAD:
            for (i = 0; *instr != '\0' && THAI_isdead(*instr); i++, instr++)
		;
            if (*instr != '\0') position = i; 
            break;
        default:
            break;
    }
    return position;
}
#endif

Private int 
#if NeedFunctionPrototypes
THAI_apply_scm(
    unsigned char	*instr, 
    unsigned char	*outstr, 
    unsigned char	spec_ch, 
    int		num_sp, 
    unsigned char	insert_ch)
#else
THAI_apply_scm(instr, outstr, spec_ch, num_sp, insert_ch)
    unsigned char	*instr;
    unsigned char	*outstr;
    unsigned char	spec_ch;
    int		num_sp;
    unsigned char	insert_ch;
#endif
{
    unsigned char   *scan, *outch;
    int             i, dead_count, found_count;
    Bool            isconsecutive;

    scan = instr;
    outch = outstr;
    dead_count = found_count = 0;
    isconsecutive = False;
    while (*scan != '\0') {
        if (THAI_isdead(*scan))
            dead_count++;       /* count number of non-spacing char */
        if (*scan == spec_ch)
            if (!isconsecutive) 
                found_count++;      /* count number consecutive spec char found */
        *outch++ = *scan++;
        if (found_count == num_sp) {
            for (i = 0; i < dead_count; i++)
                *outch++ = insert_ch;
            dead_count = found_count = 0;
        }
    }
    /* what to return? */
    return 0; /* probably not right but better than returning garbage */
}

/* The following functions are copied from XKeyBind.c */

#if 0
Private void ComputeMaskFromKeytrans();
#endif
Private int IsCancelComposeKey();
Private void SetLed();
Private CARD8 FindKeyCode();

/* The following functions are specific to this module */ 

#if 0
Private int XThaiTranslateKey();
Private int XThaiTranslateKeySym();
#endif

Private KeySym HexIMNormalKey();
Private KeySym HexIMFirstComposeKey();
Private KeySym HexIMSecondComposeKey();
Private KeySym HexIMComposeSequence();
Private void InitIscMode();
Private Bool ThaiComposeConvert();

/*
 * Definitions
 */

#define BellVolume 		0

#define ucs2tis(wc)  \
 (unsigned char) ( \
   (0<=(wc)&&(wc)<=0x7F) ? \
     (wc) : \
     ((0x0E01<=(wc)&&(wc)<=0x0E5F) ? ((wc)-0x0E00+0xA0) : 0))
#define tis2ucs(c)  \
  ( \
   ((c)<=0x7F) ? \
     (wchar_t)(c) : \
     ((0x0A1<=(c)&&(c)<=0x0FF) ? ((wchar_t)(c)-0xA0+0x0E00) : 0))

/*
 * Macros to save and recall last input character in XIC
 */
#define IC_SavePreviousChar(ic,ch) \
		(*((ic)->private.local.context->mb) = (char) (ch))
#define IC_ClearPreviousChar(ic) \
		(*((ic)->private.local.context->mb) = 0)
#define IC_GetPreviousChar(ic) \
		(IC_RealGetPreviousChar(ic,1))
#define IC_GetContextChar(ic) \
		(IC_RealGetPreviousChar(ic,2))
#define IC_DeletePreviousChar(ic) \
		(IC_RealDeletePreviousChar(ic))

Private unsigned char
#if NeedFunctionPrototypes
IC_RealGetPreviousChar(Xic ic, unsigned short pos)
#else
IC_RealGetPreviousChar(ic, pos)
  Xic ic;
  XIMStringConversionPosition pos;
#endif
{
    XICCallback* cb = &ic->core.string_conversion_callback;

    if (cb && cb->callback) {
        XIMStringConversionCallbackStruct screc;
        unsigned char c;

        /* Use a safe value of position = 0 and stretch the range to desired
         * place, as XIM protocol is unclear here whether it could be negative
         */
        screc.position = 0;
        screc.direction = XIMBackwardChar;
        screc.operation = XIMStringConversionRetrieval;
        screc.factor = pos;
        screc.text = 0;

        (cb->callback)((XIC)ic, cb->client_data, (XPointer)&screc);
        if (!screc.text)
            return (unsigned char) *((ic)->private.local.context->mb);
        if ((screc.text->feedback &&
             *screc.text->feedback == XIMStringConversionLeftEdge) ||
            screc.text->length < 1)
        {
            c = 0;
        } else {
            if (screc.text->encoding_is_wchar) {
                c = ucs2tis(screc.text->string.wcs[0]);
                XFree(screc.text->string.wcs);
            } else {
                c = screc.text->string.mbs[0];
                XFree(screc.text->string.mbs);
            }
        }
        XFree(screc.text);
        return c;
    } else {
        return (unsigned char) *((ic)->private.local.context->mb);
    }
}

Private unsigned char
#if NeedFunctionPrototypes
IC_RealDeletePreviousChar(Xic ic)
#else
IC_RealDeletePreviousChar(ic)
  Xic ic;
#endif
{
    XICCallback* cb = &ic->core.string_conversion_callback;

    if (cb && cb->callback) {
        XIMStringConversionCallbackStruct screc;
        unsigned char c;

        screc.position = 0;
        screc.direction = XIMBackwardChar;
        screc.operation = XIMStringConversionSubstitution;
        screc.factor = 1;
        screc.text = 0;

        (cb->callback)((XIC)ic, cb->client_data, (XPointer)&screc);
        if (!screc.text) { return 0; }
        if ((screc.text->feedback &&
             *screc.text->feedback == XIMStringConversionLeftEdge) ||
            screc.text->length < 1)
        {
            c = 0;
        } else {
            if (screc.text->encoding_is_wchar) {
                c = ucs2tis(screc.text->string.wcs[0]);
                XFree(screc.text->string.wcs);
            } else {
                c = screc.text->string.mbs[0];
                XFree(screc.text->string.mbs);
            }
        }
        XFree(screc.text);
        return c;
    } else {
        return 0;
    }
}
/*
 * Input sequence check mode in XIC
 */
#define IC_IscMode(ic)		((ic)->private.local.thai.input_mode)

/*
 * Max. size of string handled by the two String Lookup functions.
 */
#define STR_LKUP_BUF_SIZE	256

/*
 * Size of buffer to contain previous locale name.
 */
#define SAV_LOCALE_NAME_SIZE	256

/*
 * Size of buffer to contain the IM modifier.
 */
#define MAXTHAIIMMODLEN 20

#define AllMods (ShiftMask|LockMask|ControlMask| \
		 Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask)


#define IsISOControlKey(ks) ((ks) >= XK_2 && (ks) <= XK_8)

#define IsValidControlKey(ks)   (((((ks)>=XK_A && (ks)<=XK_asciitilde) || \
                (ks)==XK_space || (ks)==XK_Delete) && \
                ((ks)!=0)))

#define COMPOSE_LED 2

typedef KeySym (*StateProc)();

/*
 * macros to classify XKeyEvent state field
 */

#define IsShift(state) (((state) & ShiftMask) != 0)
#define IsLock(state) (((state) & LockMask) != 0)
#define IsControl(state) (((state) & ControlMask) != 0)
#define IsMod1(state) (((state) & Mod1Mask) != 0)
#define IsMod2(state) (((state) & Mod2Mask) != 0)
#define IsMod3(state) (((state) & Mod3Mask) != 0)
#define IsMod4(state) (((state) & Mod4Mask) != 0)
#define IsMod5(state) (((state) & Mod5Mask) != 0)

/*
 * key starts Thai compose sequence (Hex input method) if :
 */

#define IsComposeKey(ks, event)  \
	(( ks==XK_Alt_L && 	\
	   IsControl((event)->state) &&	\
	   !IsShift((event)->state))	\
	 ? True : False)

#if 0
/*
 *  State handler to implement the Thai hex input method.
 */

Private int const nstate_handlers = 3;
Private StateProc state_handler[] = {
	HexIMNormalKey,
	HexIMFirstComposeKey,
	HexIMSecondComposeKey
};
#endif

/*
 *  Table for 'Thai Compose' character input.
 *  The current implementation uses latin-1 keysyms.
 */
struct _XMapThaiKey {
	KeySym from;
	KeySym to;
};

Private struct _XMapThaiKey const ThaiComposeTable[] = {
	{ /* 0xa4 */ XK_currency,	/* 0xa5 */ XK_yen },
	{ /* 0xa2 */ XK_cent,		/* 0xa3 */ XK_sterling },
	{ /* 0xe6 */ XK_ae,		/* 0xef */ XK_idiaeresis },
	{ /* 0xd3 */ XK_Oacute,		/* 0xee */ XK_icircumflex },
	{ /* 0xb9 */ XK_onesuperior,	/* 0xfa */ XK_uacute },
	{ /* 0xd2 */ XK_Ograve,		/* 0xe5 */ XK_aring },
	{ /* 0xbc */ XK_onequarter,	/* 0xfb */ XK_ucircumflex },
	{	     XK_VoidSymbol,		   XK_VoidSymbol }
};

struct _XKeytrans {
	struct _XKeytrans *next;/* next on list */
	char *string;		/* string to return when the time comes */
	int len;		/* length of string (since NULL is legit)*/
	KeySym key;		/* keysym rebound */
	unsigned int state;	/* modifier state */
	KeySym *modifiers;	/* modifier keysyms you want */
	int mlen;		/* length of modifier list */
};

/* Convert keysym to 'Thai Compose' keysym */
/* The current implementation use latin-1 keysyms */
Private Bool
ThaiComposeConvert(dpy, insym, outsym ,lower, upper)
    Display *dpy;
    KeySym insym;
    KeySym *outsym,*lower,*upper;
{
    struct _XMapThaiKey const *table_entry = ThaiComposeTable;

    while (table_entry->from != XK_VoidSymbol) {
	if (table_entry->from == insym) {
	    *outsym = table_entry->to;
	    *lower = *outsym;
	    *upper = *outsym;
	    return True;
	}
	table_entry++;
    }
    return False;
}

#if 0
Private int
XThaiTranslateKey(dpy, keycode, modifiers, modifiers_return, keysym_return,
	      lsym_return, usym_return)
    register Display *dpy;
    KeyCode keycode;
    register unsigned int modifiers;
    unsigned int *modifiers_return;
    KeySym *keysym_return,*lsym_return,*usym_return;
{
    int per;
    register KeySym *syms;
    KeySym sym = 0, lsym = 0, usym = 0;

    if ((! dpy->keysyms) && (! _XKeyInitialize(dpy)))
	return 0;
    *modifiers_return = (ShiftMask|LockMask) | dpy->mode_switch;
    if (((int)keycode < dpy->min_keycode) || ((int)keycode > dpy->max_keycode))
    {
	*keysym_return = NoSymbol;
	return 1;
    }
    per = dpy->keysyms_per_keycode;
    syms = &dpy->keysyms[(keycode - dpy->min_keycode) * per];
    while ((per > 2) && (syms[per - 1] == NoSymbol))
	per--;
    if ((per > 2) && (modifiers & dpy->mode_switch)) {
	syms += 2;
	per -= 2;
    }
    if (!(modifiers & ShiftMask) &&
	(!(modifiers & LockMask) || (dpy->lock_meaning == NoSymbol))) {
	if ((per == 1) || (syms[1] == NoSymbol))
	    XConvertCase(syms[0], keysym_return, &usym);
	else {
	    XConvertCase(syms[0], &lsym, &usym);
	    *keysym_return = syms[0];
	}
    } else if (!(modifiers & LockMask) ||
	       (dpy->lock_meaning != XK_Caps_Lock)) {
	if ((per == 1) || ((usym = syms[1]) == NoSymbol))
	    XConvertCase(syms[0], &lsym, &usym);
	*keysym_return = usym;
    } else {
	if ((per == 1) || ((sym = syms[1]) == NoSymbol))
	    sym = syms[0];
	XConvertCase(sym, &lsym, &usym);
	if (!(modifiers & ShiftMask) && (sym != syms[0]) &&
	    ((sym != usym) || (lsym == usym)))
	    XConvertCase(syms[0], &lsym, &usym);
	*keysym_return = usym;
    }
    /*
     * ThaiCat keyboard support :
     * When the Shift and Thai keys are hold for some keys a 'Thai Compose'  
     * character code is generated which is different from column 3 and
     * 4 of the keymap. 
     * Since we don't know whether ThaiCat keyboard or WTT keyboard is
     * in use, the same mapping is done for all Thai input.
     * We just arbitary choose to use column 3 keysyms as the indices of 
     * this mapping.
     * When the control key is also hold, this mapping has no effect.
     */
    if ((modifiers & Mod1Mask) &&
	(modifiers & ShiftMask) &&
	!(modifiers & ControlMask)) {
	if (ThaiComposeConvert(dpy, syms[0], &sym, &lsym, &usym))
	    *keysym_return = sym;
    }

    if (*keysym_return == XK_VoidSymbol)
	*keysym_return = NoSymbol;
    *lsym_return = lsym;
    *usym_return = usym;
    return 1;
}

/* 
 * XThaiTranslateKeySym
 *
 * Translate KeySym to TACTIS code output.
 * The current implementation uses ISO latin-1 keysym.
 * Should be changed to TACTIS keysyms when they are defined by the
 * standard.
 */
Private int
XThaiTranslateKeySym(dpy, symbol, lsym, usym, modifiers, buffer, nbytes)
    Display *dpy;
    register KeySym symbol, lsym, usym;
    unsigned int modifiers;
    unsigned char *buffer;
    int nbytes;
{
    KeySym ckey = 0;
    register struct _XKeytrans *p; 
    int length;
    unsigned long hiBytes;
    register unsigned char c;

    /*
     * initialize length = 1 ;
     */
    length = 1;

    if (!symbol)
	return 0;
    /* see if symbol rebound, if so, return that string. */
    for (p = dpy->key_bindings; p; p = p->next) {
	if (((modifiers & AllMods) == p->state) && (symbol == p->key)) {
	    length = p->len;
	    if (length > nbytes) length = nbytes;
	    memcpy (buffer, p->string, length);
	    return length;
	}
    }
    /* try to convert to TACTIS, handling control */
    hiBytes = symbol >> 8;
    if (!(nbytes &&
	  ((hiBytes == 0) ||
	   ((hiBytes == 0xFF) &&
	    (((symbol >= XK_BackSpace) && (symbol <= XK_Clear)) ||
	     (symbol == XK_Return) ||
	     (symbol == XK_Escape) ||
	     (symbol == XK_KP_Space) ||
	     (symbol == XK_KP_Tab) ||
	     (symbol == XK_KP_Enter) ||
	     ((symbol >= XK_KP_Multiply) && (symbol <= XK_KP_9)) ||
	     (symbol == XK_KP_Equal) ||
             (symbol == XK_Scroll_Lock) ||
#ifdef DXK_PRIVATE /* DEC private keysyms */
             (symbol == DXK_Remove) ||
#endif
             (symbol == NoSymbol) ||
	     (symbol == XK_Delete))))))
	return 0;

    /* if X keysym, convert to ascii by grabbing low 7 bits */
    if (symbol == XK_KP_Space)
	c = XK_space & 0x7F; /* patch encoding botch */
/* not for Thai
    else if (symbol == XK_hyphen)
	c = XK_minus & 0xFF; */ /* map to equiv character */
    else if (hiBytes == 0xFF)
	c = symbol & 0x7F;
    else
	c = symbol & 0xFF;
    /* only apply Control key if it makes sense, else ignore it */
    if (modifiers & ControlMask) {
    if (!(IsKeypadKey(lsym) || lsym==XK_Return || lsym==XK_Tab)) {
        if (IsISOControlKey(lsym)) ckey = lsym;
        else if (IsISOControlKey(usym)) ckey = usym;
        else if (lsym == XK_question) ckey = lsym;
        else if (usym == XK_question) ckey = usym;
        else if (IsValidControlKey(lsym)) ckey = lsym;
        else if (IsValidControlKey(usym)) ckey = usym;
        else length = 0;

        if (length != 0) {
        if (ckey == XK_2) c = '\000';
        else if (ckey >= XK_3 && ckey <= XK_7)
            c = (char)(ckey-('3'-'\033'));
        else if (ckey == XK_8) c = '\177';
        else if (ckey == XK_Delete) c = '\030';
        else if (ckey == XK_question) c = '\037';
        else if (ckey == XK_quoteleft) c = '\036';  /* KLee 1/24/91 */
        else c = (char)(ckey & 0x1f);
        }
    }
    }
    /*
     *  ThaiCat has a key that generates two TACTIS codes D1 & E9.
     *  It is represented by the latin-1 keysym XK_thorn (0xfe). 
     *  If c is XK_thorn, this key is pressed and it is converted to  
     *  0xd1 0xe9.
     */
    if (c == XK_thorn) {
	buffer[0] = 0xd1;
	buffer[1] = 0xe9;
	buffer[2] = '\0';
	return 2;
    }
    else {
	/* Normal case */
        buffer[0] = c;
	buffer[1] = '\0';
        return 1;
    }
}
#endif

/*
 * given a KeySym, returns the first keycode containing it, if any.
 */
Private CARD8
FindKeyCode(dpy, code)
    register Display *dpy;
    register KeySym code;
{

    register KeySym *kmax = dpy->keysyms + 
	(dpy->max_keycode - dpy->min_keycode + 1) * dpy->keysyms_per_keycode;
    register KeySym *k = dpy->keysyms;
    while (k < kmax) {
	if (*k == code)
	    return (((k - dpy->keysyms) / dpy->keysyms_per_keycode) +
		    dpy->min_keycode);
	k += 1;
	}
    return 0;
}

#if 0
/*
 * given a list of modifiers, computes the mask necessary for later matching.
 * This routine must lookup the key in the Keymap and then search to see
 * what modifier it is bound to, if any.  Sets the AnyModifier bit if it
 * can't map some keysym to a modifier.
 */
Private void
ComputeMaskFromKeytrans(dpy, p)
    Display *dpy;
    register struct _XKeytrans *p;
{
    register int i;
    register CARD8 code;
    register XModifierKeymap *m = dpy->modifiermap;

    p->state = AnyModifier;
    for (i = 0; i < p->mlen; i++) {
	/* if not found, then not on current keyboard */
	if ((code = FindKeyCode(dpy, p->modifiers[i])) == 0)
		return;
	/* code is now the keycode for the modifier you want */
	{
	    register int j = m->max_keypermod<<3;

	    while ((--j >= 0) && (code != m->modifiermap[j]))
		;
	    if (j < 0)
		return;
	    p->state |= (1<<(j/m->max_keypermod));
	}
    }
    p->state &= AllMods;
}
#endif

/************************************************************************
 *
 *
 * Compose handling routines - compose handlers 0,1,2
 * 
 * 
 ************************************************************************/

#define NORMAL_KEY_STATE 0
#define FIRST_COMPOSE_KEY_STATE 1
#define SECOND_COMPOSE_KEY_STATE 2

Private
KeySym HexIMNormalKey (thai_part, symbol, event)
    XicThaiPart *thai_part;
    KeySym symbol;
    XKeyEvent *event;

{
    if (IsComposeKey (symbol, event))	/* start compose sequence	*/
	{
	SetLed (event->display,COMPOSE_LED, LedModeOn);
	thai_part->comp_state = FIRST_COMPOSE_KEY_STATE;
	return NoSymbol;
	}
    return symbol;
}


Private
KeySym HexIMFirstComposeKey (thai_part, symbol, event)	
    XicThaiPart *thai_part;
    KeySym symbol;
    XKeyEvent *event;

{
    if (IsModifierKey (symbol)) return symbol; /* ignore shift etc. */
    if (IsCancelComposeKey (&symbol, event))	/* cancel sequence */
	{
	SetLed (event->display,COMPOSE_LED, LedModeOff);
	thai_part->comp_state = NORMAL_KEY_STATE;
	return symbol;
	}
    if (IsComposeKey (symbol, event))		/* restart sequence ?? */
	{
	return NoSymbol;			/* no state change necessary */
	}

    thai_part->keysym = symbol;		/* save key pressed */
    thai_part->comp_state = SECOND_COMPOSE_KEY_STATE;
    return NoSymbol;
}

Private
KeySym HexIMSecondComposeKey (thai_part, symbol, event)
    XicThaiPart *thai_part;
    KeySym symbol;
    XKeyEvent *event;

{
    if (IsModifierKey (symbol)) return symbol;	/* ignore shift etc. */
    if (IsComposeKey (symbol, event))		/* restart sequence ? */
	{
	thai_part->comp_state =FIRST_COMPOSE_KEY_STATE;
	return NoSymbol;
	}
    SetLed (event->display,COMPOSE_LED, LedModeOff);
    if (IsCancelComposeKey (&symbol, event))	/* cancel sequence ? */
	{
	thai_part->comp_state = NORMAL_KEY_STATE;
	return symbol;
	}

    if ((symbol = HexIMComposeSequence (thai_part->keysym, symbol))
								==NoSymbol)
	{ /* invalid compose sequence */
	XBell(event->display, BellVolume);
	}
    thai_part->comp_state = NORMAL_KEY_STATE; /* reset to normal state */
    return symbol;
}


/*
 * Interprets two keysyms entered as hex digits and return the Thai keysym
 * correspond to the TACTIS code formed.
 * The current implementation of this routine returns ISO Latin Keysyms.
 */

Private
KeySym HexIMComposeSequence (ks1, ks2)

KeySym ks1, ks2;
{
int	hi_digit;
int	lo_digit;
int	tactis_code;

    if ((ks1 >= XK_0) && (ks1 <= XK_9))
	hi_digit = ks1 - XK_0;
    else if ((ks1 >= XK_A) && (ks1 <= XK_F))
	hi_digit = ks1 - XK_A + 10;
    else if ((ks1 >= XK_a) && (ks1 <= XK_f))
	hi_digit = ks1 - XK_a + 10;
    else	/* out of range */
	return NoSymbol;
	    
    if ((ks2 >= XK_0) && (ks2 <= XK_9))
	lo_digit = ks2 - XK_0;
    else if ((ks2 >= XK_A) && (ks2 <= XK_F))
	lo_digit = ks2 - XK_A + 10;
    else if ((ks2 >= XK_a) && (ks2 <= XK_f))
	lo_digit = ks2 - XK_a + 10;
    else	/* out of range */
	return NoSymbol;

    tactis_code = hi_digit * 0x10 + lo_digit ;

    return (KeySym)tactis_code;

}

/*
 * routine determines
 *	1) whether key event should cancel a compose sequence
 *	2) whether cancelling key event should be processed or ignored
 */

Private
int IsCancelComposeKey(symbol, event)
    KeySym *symbol;
    XKeyEvent *event;
{
    if (*symbol==XK_Delete && !IsControl(event->state) &&
						!IsMod1(event->state)) {
	*symbol=NoSymbol;  /* cancel compose sequence, and ignore key */
	return True;
    }
    if (IsComposeKey(*symbol, event)) return False;
    return (
	IsControl (event->state) ||
	IsMod1(event->state) ||
	IsKeypadKey (*symbol) ||
	IsFunctionKey (*symbol) ||
	IsMiscFunctionKey (*symbol) ||
#ifdef DXK_PRIVATE /* DEC private keysyms */
	*symbol == DXK_Remove ||
#endif
	IsPFKey (*symbol) ||
	IsCursorKey (*symbol) ||
	(*symbol >= XK_Tab && *symbol < XK_Multi_key)
		? True : False);	/* cancel compose sequence and pass */
					/* cancelling key through	    */
}


/*
 *	set specified keyboard LED on or off
 */

Private
void SetLed (dpy, num, state)
    Display *dpy;
    int num;
    int state;
{
    XKeyboardControl led_control;

    led_control.led_mode = state;
    led_control.led = num;
    XChangeKeyboardControl (dpy, KBLed | KBLedMode,	&led_control);
}


/*
 * Initialize ISC mode from im modifier 
 */
Private void InitIscMode(ic)
Xic ic;
{
    Xim im;
    char *im_modifier_name;

    /* If already defined, just return */

    if (IC_IscMode(ic)) return;

    /* Get IM modifier */

    im = (Xim) XIMOfIC((XIC)ic);
    im_modifier_name = im->core.im_name;

    /* Match with predefined value, default is Basic Check */

    if (!strncmp(im_modifier_name,"BasicCheck",MAXTHAIIMMODLEN+1))
	IC_IscMode(ic) = WTT_ISC1;
    else if (!strncmp(im_modifier_name,"Strict",MAXTHAIIMMODLEN+1))
	IC_IscMode(ic) = WTT_ISC2;
    else if (!strncmp(im_modifier_name,"Thaicat",MAXTHAIIMMODLEN+1))
	IC_IscMode(ic) = THAICAT_ISC;
    else if (!strncmp(im_modifier_name,"Passthrough",MAXTHAIIMMODLEN+1))
	IC_IscMode(ic) = NOISC;
    else
	IC_IscMode(ic) = WTT_ISC1;

    return;
}
    
/*
 * Helper functions for _XimThaiFilter()
 */
Private Bool
#if NeedFunctionPrototypes
ThaiFltAcceptInput(Xic ic, unsigned char new_char, KeySym symbol)
#else
ThaiFltAcceptInput(ic, new_char, symbol)
    Xic           ic;
    unsigned char new_char;
    KeySym        symbol;
#endif
{
    ic->private.local.composed->wc[0] = tis2ucs(new_char);
    ic->private.local.composed->wc[1] = '\0';

    if ((new_char <= 0x1f) || (new_char == 0x7f))
        ic->private.local.composed->keysym = symbol;
    else
        ic->private.local.composed->keysym = NoSymbol;

    return True;
}

Private Bool
#if NeedFunctionPrototypes
ThaiFltReorderInput(Xic ic, unsigned char previous_char, unsigned char new_char)
#else
ThaiFltReorderInput(ic, previous_char, new_char)
    Xic           ic;
    unsigned char previous_char, new_char;
#endif
{
    if (!IC_DeletePreviousChar(ic)) return False;
    ic->private.local.composed->wc[0] = tis2ucs(new_char);
    ic->private.local.composed->wc[1] = tis2ucs(previous_char);
    ic->private.local.composed->wc[2] = '\0';

    ic->private.local.composed->keysym = NoSymbol;

    return True;
}

Private Bool
#if NeedFunctionPrototypes
ThaiFltReplaceInput(Xic ic, unsigned char new_char, KeySym symbol)
#else
ThaiFltReplaceInput(ic, new_char, symbol)
    Xic           ic;
    unsigned char new_char;
    KeySym        symbol;
#endif
{
    if (!IC_DeletePreviousChar(ic)) return False;
    ic->private.local.composed->wc[0] = tis2ucs(new_char);
    ic->private.local.composed->wc[1] = '\0';

    if ((new_char <= 0x1f) || (new_char == 0x7f))
        ic->private.local.composed->keysym = symbol;
    else
        ic->private.local.composed->keysym = NoSymbol;

    return True;
}

/*
 * Filter function for TACTIS
 */
Bool
_XimThaiFilter(d, w, ev, client_data)
Display		*d;
Window		w;
XEvent		*ev;
XPointer	client_data;
{
    Xic		    ic = (Xic)client_data;
    KeySym 	    symbol;
    int 	    wcount;
    int 	    isc_mode; /* Thai Input Sequence Check mode */
    unsigned char   previous_char; /* Last inputted Thai char */
    unsigned char   new_char;
#if 0
    unsigned int    modifiers;
    KeySym	    lsym,usym;
    int		    state;
    XicThaiPart     *thai_part;
    char	    buf[10];
#endif
    wchar_t	    wbuf[10];
    Bool            isReject;

    if ((ev->type != KeyPress)
        || (ev->xkey.keycode == 0))
        return False;

    if (!IC_IscMode(ic)) InitIscMode(ic);

    wcount = XwcLookupString((XIC)ic, &ev->xkey,
                            wbuf, sizeof(wbuf)/sizeof(wbuf[0]), &symbol, NULL);

    if ((ev->xkey.state & (AllMods & ~ShiftMask)) ||
         ((symbol >> 8 == 0xFF) &&
         ((XK_BackSpace <= symbol && symbol <= XK_Clear) ||
           (symbol == XK_Return) ||
           (symbol == XK_Pause) ||
           (symbol == XK_Scroll_Lock) ||
           (symbol == XK_Sys_Req) ||
           (symbol == XK_Escape) ||
           (symbol == XK_Delete) ||
           IsCursorKey(symbol) ||
           IsKeypadKey(symbol) ||
           IsMiscFunctionKey(symbol) ||
           IsFunctionKey(symbol))))
        {
            IC_ClearPreviousChar(ic); 
            return False;
        }
    if (((symbol >> 8 == 0xFF) &&
         IsModifierKey(symbol)) ||
#ifdef XK_XKB_KEYS
        ((symbol >> 8 == 0xFE) &&
         (XK_ISO_Lock <= symbol && symbol <= XK_ISO_Last_Group_Lock)) ||
#endif
        (symbol == NoSymbol))
    {
        return False;
    }
#if 0
    if (! XThaiTranslateKey(ev->xkey.display, ev->xkey.keycode, ev->xkey.state,
	 		&modifiers, &symbol, &lsym, &usym))
	return False;

    /*
     *  Hex input method processing 
     */

    thai_part = &ic->private.local.thai;
    state = thai_part->comp_state;
    if (state >= 0 && state < nstate_handlers) /* call handler for state */
    {
        symbol = (* state_handler[state])(thai_part, symbol, (XKeyEvent *)ev);
    }

    /*
     *  Translate KeySym into mb.
     */
    count = XThaiTranslateKeySym(ev->xkey.display, symbol, lsym,
				usym, ev->xkey.state, buf, 10);

    if (!symbol && !count)
	return True;

    /* Return symbol if cannot convert to character */
    if (!count)
	return False;
#endif

    /*
     *  Thai Input sequence check
     */
    isc_mode = IC_IscMode(ic);
    if (!(previous_char = IC_GetPreviousChar(ic))) previous_char = ' ';
    new_char = ucs2tis(wbuf[0]);
    isReject = True;
    if (THAI_isaccepted(new_char, previous_char, isc_mode)) {
        ThaiFltAcceptInput(ic, new_char, symbol);
        isReject = False;
    } else {
        unsigned char context_char;

        context_char = IC_GetContextChar(ic);
        if (context_char) {
            if (THAI_iscomposible(new_char, context_char)) {
                if (THAI_iscomposible(previous_char, new_char)) {
                    isReject = !ThaiFltReorderInput(ic, previous_char, new_char);
                } else if (THAI_iscomposible(previous_char, context_char)) {
                    isReject = !ThaiFltReplaceInput(ic, new_char, symbol);
                } else if (THAI_chtype(previous_char) == FV1
                           && THAI_chtype(new_char) == TONE) {
                    isReject = !ThaiFltReorderInput(ic, previous_char, new_char);
                }
            } else if (THAI_isaccepted(new_char, context_char, isc_mode)) {
                isReject = !ThaiFltReplaceInput(ic, new_char, symbol);
            }
        }
    }
    if (isReject) {
        /* reject character */
        XBell(ev->xkey.display, BellVolume);
        return True;
    }

    _Xlcwcstombs(ic->core.im->core.lcd, ic->private.local.composed->mb,
		 ic->private.local.composed->wc, 10);

    _Xlcmbstoutf8(ic->core.im->core.lcd, ic->private.local.composed->utf8,
		  ic->private.local.composed->mb, 10);

    /* Remember the last character inputted
     * (as fallback in case StringConversionCallback is not provided)
     */
    IC_SavePreviousChar(ic, new_char);

    ev->xkey.keycode = 0;
    XPutBackEvent(d, ev);
    return True;
}