summaryrefslogtreecommitdiff
path: root/src-worddic/record.c
blob: 66e85f316e453c3f5b4b64cc36c14eb234979c7d (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
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
/*
 * 学習の履歴などを管理するためのデータベース
 * 文字列(xstr)をキーにして高速に行(row)を検索することができる.
 * 複数のセクションをもつことができ,学習の違うフェーズなどに対応する
 *  (セクション * 文字列 -> 行)
 * 各行は文字列か数を持つ配列になっている
 *
 * 「パトリシア・トライ」というデータ構造を使用している。
 * 自然言語の検索などを扱っている教科書を参照のこと
 */
/*
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

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

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 */
/*
 * Funded by IPA未踏ソフトウェア創造事業 2002 1/18
 * Funded by IPA未踏ソフトウェア創造事業 2005
 * Copyright (C) 2005 YOSHIDA Yuichi
 * Copyright (C) 2000-2006 TABATA Yusuke
 * Copyright (C) 2000-2003 UGAWA Tomoharu
 * Copyright (C) 2001-2002 TAKAI Kosuke
 */
/*
 * パーソナリティ""は匿名パーソナリティであり,
 * ファイルへの読み書きは行わない.
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "config.h"
#include <anthy/anthy.h>
#include <anthy/dic.h>
#include <anthy/alloc.h>
#include <anthy/conf.h>
#include <anthy/ruleparser.h>
#include <anthy/record.h>
#include <anthy/logger.h>
#include <anthy/prediction.h>

#include "dic_main.h"
#include "dic_personality.h"

/* 個人辞書をセーブするファイル名のsuffix */
#define ENCODING_SUFFIX ".utf8"


enum val_type {
  RT_EMPTY, RT_VAL, RT_XSTR, RT_XSTRP
};

/* 値 */
struct record_val {
  enum val_type type;
  union {
    xstr str;
    int val;
    xstr* strp;
  } u;
};

/* 行 */
struct record_row {
  xstr key;
  int nr_vals;
  struct record_val *vals;
};

/* trie node管理用 */
struct trie_node {
  struct trie_node *l;
  struct trie_node *r;
  int bit;
  struct record_row row;
  struct trie_node *lru_prev, *lru_next; /* 両端ループ */
  int dirty; /* LRU のための used, sused ビット */
};

/* trie treeのroot */
struct trie_root {
  struct trie_node root;
  allocator node_ator;
};

#define LRU_USED  0x01
#define LRU_SUSED 0x02
#define PROTECT   0x04 /* 差分書き出し時に使う(LRUとは関係ない)
			*   差分書き出しでは、ファイルに書き出す前に
			*   ファイル上に他のプロセスが記録した更新を
			*   読み込む。それによって、これから追加しよ
			*   うとするノードが消されるのを防ぐ
			*/
/*
 * LRU:
 *   USED:  メモリ上で使われた
 *   SUSED: 保存された used ビット
 *
 * LRUリスト上では、 USED は必ずリスト先頭に並んでいるが、 SUSED は
 * フラグなしのノードと混在している可能性がある。
 *
 * n個を残すように指定された時の動作
 *    1. used > n
 *        LRU リストの先頭から n 番目以降を消す
 *    2. used + sused > n
 *        used -> 残す
 *        sused -> sused フラグを落す
 *        それ以外 -> 消す
 *    3. それ以外
 *        全て残す
 * ファイルに書き出す時に、 used || sused -> sused として書き出す
 */

/** セクション */
struct record_section {
  const char *name;
  struct trie_root cols;
  struct record_section *next;
  int lru_nr_used, lru_nr_sused; /* LRU 用 */
};

/** データベース */
struct record_stat {
  struct record_section section_list; /* sectionのリスト*/
  struct record_section *cur_section;
  struct trie_root xstrs; /* xstr を intern するための trie */
  struct trie_node *cur_row;
  int row_dirty; /* cur_row が保存の必要があるか */
  int encoding;
  /**/
  int is_anon;
  const char *id;         /* パーソナリティのid */
  char *base_fn; /* 基本ファイル 絶対パス */
  char *journal_fn; /* 差分ファイル 絶対パス */
  /**/
  time_t base_timestamp; /* 基本ファイルのタイムスタンプ */
  int last_update;  /* 差分ファイルの最後に読んだ位置 */
  time_t journal_timestamp; /* 差分ファイルのタイムスタンプ */
};

/* 差分が100KB越えたら基本ファイルへマージ */
#define FILE2_LIMIT 102400


/*
 * xstr の intern:
 *  個人ごと( record_stat ごと)に文字列を intern する。これは、
 *  メモリの節約の他に、データベースの flush 時にデータベースに
 *  由来する xstr が無効になるのを防ぐ目的がある。
 *  したがって、データベースの flush 時でも xstr の intern 用
 *  のデータベース xstrs はそのまま保存する。
 *  
 *  xstrs: xstr の intern 用のデータベース
 *         row の key を intern された xstr として使う。
 *         row に value は持たない。
 *                    (将来的には参照カウンタをつけてもいいかも)
 *  参照: intern_xstr()
 */

/*
 * 差分書き出し:
 *  データベースの保存、複数の anthy ライブラリをリンクした
 *  プロセスの学習履歴の同期のために、学習履歴の更新情報を
 *  逐一ファイルに書き出す。
 *
 * ・基本ファイル  古い anthy の学習履歴と同じ形式。
 *                 差分情報を適用する元となるファイル。
 *                 基本的には起動時だけに読み込む。
 *                 このプログラム中でファイル1,baseと呼ぶことがある。
 * ・差分ファイル  基本ファイルに対する更新情報。
 *                 データベースに対する更新がコミットされるたびに
 *                 読み書きされる。
 *                 このプログラム中でファイル2,journalと呼ぶことがある。
 *  基本方針:
 *     データベースに対する更新がコミットされると、まず差分ファイル
 *     に他のプロセスが追加した更新情報を読み込み、その後に自分の
 *     コミットした更新を差分ファイルに書き出す。
 *     これらはロックファイルを用いてアトミックに行われる。また、
 *     基本ファイル、差分ファイルとも、ロックを取っている間しか
 *     オープンしていてはいけない。
 *  追加と削除:
 *     追加はすでにメモリ上で更新された row をコミットによって
 *     メモリに書き出すため、
 *       1. コミット対象 row 以外を差分ファイルの情報で
 *       2. コミット対象 row を差分ファイルに書き出し
 *     とする。削除はまだメモリ上に row が残っている状態でコミット
 *     が行われる(削除要求をコミットとして扱う)ため、
 *       1. 削除の情報を差分ファイルに書き出し
 *       2. 差分ファイルの読み込みにより削除要求も実行する
 *     とする。
 *  基本ファイルの更新:
 *     差分ファイルがある程度肥大化すると、差分ファイルの情報を
 *     基本ファイルに反映して差分ファイルを空にする。
 *     更新するプロセス:
 *       差分ファイルに書き出しを行った後、差分ファイルの大きさを調べ、
 *       肥大化していれば、そのときのメモリ上のデータベース(これには
 *       全ての差分ファイルの更新が適用されている)を基本ファイルに
 *       書き出す。
 *     それ以外のプロセス:
 *       差分ファイルを読む前に、基本ファイルが更新されているかを
 *       ファイルのタイムスタンプで調べ、更新されていれば、コミット
 *       された更新情報を直ちに更新ファイルに追加し、メモリ上の
 *       データベースを flush した後基本ファイル、差分ファイルを
 *       読み込み直す。
 *       データベースの flush により、 
 *           ・cur_row が無効になる (NULL になる)
 *           ・cur_section の有効性は保存される(sectionは解放しない)
 *           ・xstr は intern していれば保存される
 *                              (すべての xstr は intern されているはず)
 *   結局、次の様になる:
 *     if (基本ファイルが更新されている) {
 *             差分ファイルへコミットされた更新を書き出す;
 *             データベースのフラッシュ;
 *             基本ファイルの読込と差分ファイルの最終読込位置クリア;
 *             差分ファイルの読込と差分ファイルの最終読込位置更新;
 *     } else {
 *             if (追加) {
 *                     差分ファイルの読込と差分ファイルの最終読込位置更新;
 *                     差分ファイルへの書き出し;
 *             } else {
 *                     差分ファイルへの書き出し;
 *                     差分ファイルの読込と差分ファイルの最終読込位置更新;
 *             }
 *     }
 *     if (差分ファイルが大きい) {
 *             基本ファイルへの書き出し;
 *             差分ファイルのクリア;
 *     }
 */

static allocator record_ator;

/* trie操作用 */
static void init_trie_root(struct trie_root *n);
static int trie_key_nth_bit(xstr* key, int n);
static int trie_key_first_diff_bit_1byte(xchar c1, xchar c2);
static int trie_key_first_diff_bit(xstr *k1, xstr *k2);
static int trie_key_cmp(xstr *k1, xstr *k2);
static void trie_key_dup(xstr *dst, xstr *src);
static void trie_row_init(struct record_row *rc);
static void trie_row_free(struct record_row *rc);
static struct trie_node *trie_find(struct trie_root *root, xstr *key);
static struct trie_node *trie_insert(struct trie_root *root, xstr *key,
				     int dirty, int *nr_used, int *nr_sused);
static void trie_remove(struct trie_root *root, xstr *key,
			int *nr_used, int *nr_sused);
static struct trie_node *trie_first(struct trie_root *root);
static struct trie_node *trie_next(struct trie_root *root,
				   struct trie_node *cur);
static void trie_remove_all(struct trie_root *root,
			    int *nr_used, int *nr_sused);
static void trie_remove_old(struct trie_root *root, int count,
			    int* nr_used, int* nr_sused);
static void trie_mark_used(struct trie_root *root, struct trie_node *n,
			   int *nr_used, int *nr_sused);


/* 
 * トライの実装
 * struct trie_nodeのうちrow以外の部分とrow.keyを使用
 * 削除の時はtrie_row_freeを使ってrowの内容を解放
 */

#define PUTNODE(x) ((x) == &root->root ? printf("root\n") : anthy_putxstrln(&(x)->row.key))
static int
debug_trie_dump(FILE* fp, struct trie_node* n, int encoding)
{
  int cnt = 0;
  char buf[1024];

  if (n->l->bit > n->bit) {
    cnt = debug_trie_dump(fp, n->l, encoding);
  } else {
    if (n->l->row.key.len == -1) {
      if (fp) {
	fprintf(fp, "root\n");
      }
    } else {
      if (fp) {
	anthy_sputxstr(buf, &n->l->row.key, encoding);
	fprintf(fp, "%s\n", buf);
      }
      cnt = 1;
    }
  }

  if (n->r->bit > n->bit) {
    return cnt + debug_trie_dump(fp, n->r, encoding);
  } else {
    if (n->r->row.key.len == -1) {
      if(fp) {
	fprintf(fp, "root\n");
      }
    } else {
      if(fp) {
	anthy_sputxstr(buf, &n->r->row.key, encoding);
	fprintf(fp, "%s\n", buf);
      }
      return cnt + 1;
    }
  }

  return cnt;
}

static void
init_trie_root(struct trie_root *root)
{
  struct trie_node* n;
  root->node_ator = anthy_create_allocator(sizeof(struct trie_node), NULL);
  n = &root->root;
  n->l = n;
  n->r = n;
  n->bit = 0;
  n->lru_next = n;
  n->lru_prev = n;
  n->dirty = 0;
  trie_row_init(&n->row);
  n->row.key.len = -1;
}

/*
 * bit0: 0
 * bit1: headのキーだけ0
 * bit2: 文字列のビット0
 * bit3: 文字列のビット1
 *   ...
 * 文字列長を越えると0
 */
static int
trie_key_nth_bit(xstr* key, int n)
{
  switch (n) {
  case 0:
    return 0;
  case 1:
    return key->len + 1; /* key->len == -1 ? 0 : non-zero */
  default:
    {
      int pos;
      n -= 2;
      pos = n / (sizeof(xchar) << 3);
      if (pos >= key->len) {
	return 0;
      }
      return key->str[pos] & (1 << (n % (sizeof(xchar) << 3)));
    }
  }
}

/* c1 == c2 では呼んではいけない */
static int
trie_key_first_diff_bit_1byte(xchar c1, xchar c2)
{
  int i;
  int ptn;
  for (i = 0, ptn = c1 ^ c2; !(ptn & 1); i++, ptn >>= 1 )
    ;
  return i;
}

/*
 * k1 == k2 では呼んではいけない
 * ki->str[0 .. (ki->len - 1)]に0はないと仮定
 */
#define MIN(a,b) ((a)<(b)?(a):(b))
static int
trie_key_first_diff_bit(xstr *k1, xstr *k2)
{
  int len;
  int i;

  len = MIN(k1->len, k2->len);
  if (len == -1) {
    return 1;
  }
  for ( i = 0 ; i < len ; i++ ){
    if (k1->str[i] != k2->str[i]) {
      return (2 + (i * (sizeof(xchar) << 3)) + 
	      trie_key_first_diff_bit_1byte(k1->str[i], k2->str[i]));
    }
  }
  if (k1->len < k2->len) {
    return (2 + (i * (sizeof(xchar) << 3)) +
	    trie_key_first_diff_bit_1byte(0, k2->str[i]));
  } else {
    return (2 + (i * (sizeof(xchar) << 3)) +
	    trie_key_first_diff_bit_1byte(k1->str[i], 0));
  }
}
#undef MIN

static int
trie_key_cmp(xstr *k1, xstr *k2)
{
  if (k1->len == -1 || k2->len == -1) {
    return k1->len - k2->len;
  }
  return anthy_xstrcmp(k1, k2);
}

static void
trie_key_dup(xstr *dst, xstr *src)
{
  dst->str = anthy_xstr_dup_str(src);
  dst->len = src->len;
}

/*
 * 見つからなければ 0 
 */
static struct trie_node *
trie_find(struct trie_root *root, xstr *key)
{
  struct trie_node *p;
  struct trie_node *q;

  p = &root->root;
  q = p->l;
  while (p->bit < q->bit) {
    p = q;
    q = trie_key_nth_bit(key, p->bit) ? p->r : p->l;
  }
  return trie_key_cmp(&q->row.key,key) ? NULL : q; 
}

/*
 * 最長マッチのための補助関数
 *  key で探索して、始めて一致しなくなったノードを返す。
 */
static struct trie_node *
trie_find_longest (struct trie_root* root, xstr *key)
{
  struct trie_node *p;
  struct trie_node *q;

  p = &root->root;
  q = p->l;
  while (p->bit < q->bit) {
    p = q;
    q = trie_key_nth_bit(key, p->bit) ? p->r : p->l;
  }

  return q;
}

/* 
 * 追加したノードを返す
 * すでに同じキーをもつノードがあるときは、追加せずに0を返す
 */
static struct trie_node *
trie_insert(struct trie_root *root, xstr *key,
	    int dirty, int *nr_used, int *nr_sused)
{
  struct trie_node *n;
  struct trie_node *p;
  struct trie_node *q;
  int i;

  p = &root->root;
  q = p->l;
  while (p->bit < q->bit) {
    p = q;
    q = trie_key_nth_bit(key, p->bit) ? p->r : p->l;
  }
  if (trie_key_cmp(&q->row.key,key) == 0) {
    /* USED > SUSED > 0 で強い方を残す */
    if (dirty == LRU_USED) {
      trie_mark_used(root, q, nr_used, nr_sused);
    } else if (q->dirty == 0) {
      q->dirty = dirty;
    }
    return 0;
  }
  i = trie_key_first_diff_bit(&q->row.key, key);
  p = &root->root;
  q = p->l;
  while (p->bit < q->bit && i > q->bit) {
    p = q;
    q = trie_key_nth_bit(key, p->bit) ? p->r : p->l;
  }
  n = anthy_smalloc(root->node_ator);
  trie_row_init(&n->row);
  trie_key_dup(&n->row.key, key);
  n->bit = i;
  if (trie_key_nth_bit(key, i)) {
    n->l = q;
    n->r = n;
  } else {
    n->l = n;
    n->r = q;
  }
  if (p->l == q) {
    p->l = n;
  } else {
    p->r = n;
  }

  /* LRU の処理 */
  if (dirty == LRU_USED) {
    root->root.lru_next->lru_prev = n;
    n->lru_prev = &root->root;
    n->lru_next = root->root.lru_next;
    root->root.lru_next = n;
    (*nr_used)++;
  } else {
    root->root.lru_prev->lru_next = n;
    n->lru_next = &root->root;
    n->lru_prev = root->root.lru_prev;
    root->root.lru_prev = n;
    if (dirty == LRU_SUSED) {
      (*nr_sused)++;
    }
  }
  n->dirty = dirty;
  return n;
}

/* 
 * ノードを見つけると削除する
 * 内部でtrie_row_freeを呼び、キーを含むデータ部分をfreeする
 *
 * データとノードを削除する。
 * 削除対象のデータは削除対象のノードに格納されているとは
 * 限らないことに注意。
 * 1. 削除対象の葉を持つノードに削除対象の葉が含まれているとき
 *  削除対象のノードは、子への枝のうち、生きのこる枝を親に渡して死ぬ
 * 2. 削除対象の葉を持つノードの祖先に削除対象の葉が含まれているとき
 *  1. に加えて、削除対象の葉をもつノードを殺して、代わりに削除
 *  対象のノードを削除対象の葉をもつノードの位置に移動させ生かす
 */
static void
trie_remove(struct trie_root *root, xstr *key, 
	    int *nr_used, int *nr_sused)
{
  struct trie_node *p;
  struct trie_node *q;
  struct trie_node **pp = NULL; /* gcc の warning 回避 */
  struct trie_node **qq;
  p = &root->root;
  qq = &p->l;
  q = *qq;
  while (p->bit < q->bit) {
    pp = qq;
    p = q;
    qq = trie_key_nth_bit(key,p->bit) ? &p->r : &p->l;
    q = *qq;
  }
  if (trie_key_cmp(&q->row.key, key) != 0) {
    return ;
  }
  if (p != q) {
    /* case 2. */
    struct trie_node *r;
    struct trie_node *s;
    r = &root->root;
    s = r->l;
    while (s != q) {
      r = s;
      s = trie_key_nth_bit(key, r->bit) ? r->r : r->l;
    }
    *pp = (p->r == q) ? p->l : p->r;
    p->l = q->l;
    p->r = q->r;
    p->bit = q->bit;
    if (trie_key_nth_bit(key, r->bit)) {
      r->r = p;
    } else {
      r->l = p;
    }
    p = q;
  } else {
    *pp = (p->r == q) ? p->l : p->r;
  }
  p->lru_prev->lru_next = p->lru_next;
  p->lru_next->lru_prev = p->lru_prev;
  if (p->dirty == LRU_USED) {
    (*nr_used)--;
  } else if (p->dirty == LRU_SUSED) {
    (*nr_sused)--;
  }
  trie_row_free(&p->row);
  anthy_sfree(root->node_ator, p);
}

/* head以外のノードがなければ 0 を返す */
static struct trie_node *
trie_first (struct trie_root *root)
{
  return root->root.lru_next == &root->root ?
    NULL : root->root.lru_next;
}

/* 次のノードがなければ 0 を返す */
static struct trie_node *
trie_next (struct trie_root *root,
	   struct trie_node *cur)
{
  return cur->lru_next == &root->root ? 0 : cur->lru_next;
}

/*
 * head以外全てのノードを削除する
 * 内部でtrie_row_freeを呼び、キーを含むデータ部分をfreeする
 */
static void 
trie_remove_all (struct trie_root *root,
		 int *nr_used, int *nr_sused)
{
  struct trie_node* p;
  for (p = root->root.lru_next; p != &root->root; p = p->lru_next) {
    trie_row_free(&p->row);
  }
  anthy_free_allocator(root->node_ator);
  init_trie_root(root);
  *nr_used = 0;
  *nr_sused = 0;
}

/*
 * LRU リストの先頭から count 番目までを残して残りを解放する
 */
static void
trie_remove_old (struct trie_root *root, int count, 
		 int *nr_used, int *nr_sused)
{
  struct trie_node *p;
  struct trie_node *q;

  if (*nr_used > count) {
    for (p = root->root.lru_next; count; count--, p = p->lru_next)
      ;
    /* p から head までを消す */
    for ( ; p != &root->root; p = q) {
      q = p->lru_next;
      trie_remove(root, &p->row.key, nr_used, nr_sused);
    }
  } else if (*nr_used + *nr_sused > count) {
    for (p = root->root.lru_next; p->dirty == LRU_USED; p = p->lru_next)
      ; 
    /*
     * p から root まで  sused    -> dirty := 0
     *                   それ以外 -> 消す
     */
    for ( ; p != &root->root; p = q) {
      q = p->lru_next;
      if (p->dirty == LRU_SUSED) {
	p->dirty = 0;
      } else {
	trie_remove(root, &p->row.key, nr_used, nr_sused);
      }
    }
    *nr_sused = 0;
  }
}      

static void
trie_mark_used (struct trie_root *root, struct trie_node *n,
		int *nr_used, int *nr_sused)
{
  switch(n->dirty) {
  case LRU_USED:
    break;
  case LRU_SUSED:
    (*nr_sused)--;
    /* fall through */
  default:
    n->dirty = LRU_USED;
    (*nr_used)++;
    break;
  }
  n->lru_prev->lru_next = n->lru_next;
  n->lru_next->lru_prev = n->lru_prev;
  root->root.lru_next->lru_prev = n;
  n->lru_next = root->root.lru_next;
  root->root.lru_next = n;
  n->lru_prev = &root->root;
}

/*
 * トライの実装はここまで
 */

static xstr *
do_get_index_xstr(struct record_stat *rec)
{
  if (!rec->cur_row) {
    return 0;
  }
  return &rec->cur_row->row.key;
}

static struct record_section*
do_select_section(struct record_stat *rst, const char *name, int flag)
{
  struct record_section *rsc;

  for (rsc = rst->section_list.next; rsc; rsc = rsc->next) {
    if (!strcmp(name, rsc->name)) {
      return rsc;
    }
  }

  if (flag) {
    rsc = malloc(sizeof(struct record_section));
    rsc->name = strdup(name);
    rsc->next = rst->section_list.next;
    rst->section_list.next = rsc;
    rsc->lru_nr_used = 0;
    rsc->lru_nr_sused = 0;
    init_trie_root(&rsc->cols);
    return rsc;
  }

  return NULL;
}

static struct trie_node* 
do_select_longest_row(struct record_section *rsc, xstr *name)
{
  struct trie_node *mark, *found;
  xstr xs;
  int i;

  if ((NULL == name) || (NULL == name->str) || (name->len < 1) || (0 == name->str[0])) {
    /* 辞書もしくは学習データが壊れていた時の対策 */
    return NULL;
  }

  mark = trie_find_longest(&rsc->cols, name);
  xs.str = name->str;
  for (i = (mark->row.key.len <= name->len) ? mark->row.key.len : name->len; i > 1; i--) {  /* 不正なメモリアクセスの修正 */
    /* ルートノードは i == 1 でマッチするので除外
     * trie_key_nth_bit 参照
     */
    xs.len = i;
    found = trie_find(&rsc->cols, &xs);
    if (found) {
      return found;
    }
  }
  return NULL;
}

static struct trie_node* 
do_select_row(struct record_section* rsc, xstr *name,
		 int flag, int dirty)
{
  struct trie_node *node;

  if (flag) {
    node = trie_insert(&rsc->cols, name, dirty,
		       &rsc->lru_nr_used, &rsc->lru_nr_sused);
    if (node) {
      node->row.nr_vals = 0;
      node->row.vals = 0;
    } else {
      node = trie_find(&rsc->cols, name);
    }
  } else {
    node = trie_find(&rsc->cols, name);
  }
  return node;
}

static void 
do_mark_row_used(struct record_section* rsc, struct trie_node* node)
{
  trie_mark_used(&rsc->cols, node, &rsc->lru_nr_used, &rsc->lru_nr_sused);
}

static void
do_truncate_section(struct record_stat *s, int count)
{
  if (!s->cur_section) {
    return;
  }

  trie_remove_old(&s->cur_section->cols, count,
		  &s->cur_section->lru_nr_used,
		  &s->cur_section->lru_nr_sused);
}


static struct trie_node*
do_select_first_row(struct record_section *rsc)
{
  return trie_first(&rsc->cols);
}

static struct trie_node*
do_select_next_row(struct record_section *rsc, 
  struct trie_node* node)
{
  return trie_next(&rsc->cols, node);
}


static int
do_get_nr_values(struct trie_node *node)
{
  if (!node)
    return 0;
  return node->row.nr_vals;
}

static struct record_val *
get_nth_val_ent(struct trie_node *node, int n, int f)
{
  struct record_row *col;
  col = &node->row;
  if (n < 0) {
    return NULL;
  }
  if (n < do_get_nr_values(node)) {
    return &col->vals[n];
  }
  if (f) {
    int i;
    col->vals = realloc(col->vals, sizeof(struct record_val)*(n + 1));
    for (i = col->nr_vals; i < n+1; i++) {
      col->vals[i].type = RT_EMPTY;
    }
    col->nr_vals = n + 1;
    return &col->vals[n];
  }
  return NULL;
}

static void
free_val_contents(struct record_val* v)
{
  switch (v->type) {
  case RT_XSTR:
    anthy_free_xstr_str(&v->u.str);
    break;
  case RT_XSTRP:
  case RT_VAL:
  case RT_EMPTY:
  default:
    break;
  }
}

static void
do_set_nth_value(struct trie_node *node, int nth, int val)
{
  struct record_val *v = get_nth_val_ent(node, nth, 1);
  if (!v) {
    return ;
  }
  free_val_contents(v);
  v->type = RT_VAL;
  v->u.val = val;
}

static int
do_get_nth_value(struct trie_node *node, int n)
{
  struct record_val *v = get_nth_val_ent(node, n, 0);
  if (v && v->type == RT_VAL) {
    return v->u.val;
  }
  return 0;
}

static xstr*
intern_xstr (struct trie_root* xstrs, xstr* xs)
{
  struct trie_node* node;
  int dummy;

  if ((NULL == xs) || (NULL == xs->str) || (xs->len < 1) || (0 == xs->str[0])) {
    /* 辞書もしくは学習データが壊れていた時の対策 */
    return NULL;
  }
  node = trie_find(xstrs, xs);
  if (!node) 
    node = trie_insert(xstrs, xs, 0, &dummy, &dummy);
  return &node->row.key;
}

static void
do_set_nth_xstr (struct trie_node *node, int nth, xstr *xs,
		 struct trie_root* xstrs)
{
  struct record_val *v = get_nth_val_ent(node, nth, 1);
  if (!v){
    return ;
  }
  free_val_contents(v);
  v->type = RT_XSTRP;
  v->u.strp = intern_xstr(xstrs, xs);
}

static void
do_truncate_row (struct trie_node* node, int n)
{
  int i;
  if (n < node->row.nr_vals) {
    for (i = n; i < node->row.nr_vals; i++) {
      free_val_contents(node->row.vals + i);
    }
    node->row.vals = realloc(node->row.vals, 
				sizeof(struct record_val)* n);
    node->row.nr_vals = n;
  }
}

static void
do_remove_row (struct record_section* rsc,
		  struct trie_node* node)
{
  xstr* xs;
  xs = anthy_xstr_dup(&node->row.key);
  trie_remove(&rsc->cols, &node->row.key, 
	      &rsc->lru_nr_used, &rsc->lru_nr_sused);

  anthy_free_xstr(xs);
}

static xstr *
do_get_nth_xstr(struct trie_node *node, int n)
{
  struct record_val *v = get_nth_val_ent(node, n, 0);
  if (v) {
    if (v->type == RT_XSTR) {
      return &v->u.str;
    } else if (v->type == RT_XSTRP) {
      return v->u.strp;
    }
  }
  return 0;
}

static void
lock_record (struct record_stat* rs)
{
  if (rs->is_anon) {
    return ;
  }
  anthy_priv_dic_lock();
}

static void
unlock_record (struct record_stat* rs)
{
  if (rs->is_anon) {
    return ;
  }
  anthy_priv_dic_unlock();
}

/* 再読み込みの必要があるかをチェックする
 * 必要があれば返り値が1になる */
static int
check_base_record_uptodate(struct record_stat *rst)
{
  struct stat st;
  if (rst->is_anon) {
    return 1;
  }
  anthy_check_user_dir();
  if (stat(rst->base_fn, &st) < 0) {
    return 0;
  } else if (st.st_mtime != rst->base_timestamp) {
    return 0;
  }
  return 1;
}


/*
 * row format:
 *  ROW := OPERATION SECTION KEY VALUE*
 *  OPERATION := "ADD"    (追加またはLRU更新)
 *               "DEL"    (削除)
 *  SECTION := (文字列)
 *  KEY     := TD
 *  VALUE   := TD
 *  TD      := TYPE DATA  (空白をあけずに書く)
 *  TYPE    := "S"        (xstr)
 *             "N"        (number)
 *  DATA    := (型ごとにシリアライズしたもの)
 */

static char*
read_1_token (FILE* fp, int* eol)
{
  int c;
  char* s;
  int in_quote;
  int len;

  in_quote = 0;
  s = NULL;
  len = 0;
  while (1) {
    c = fgetc(fp);
    switch (c) {
    case EOF: case '\n':
      goto out;
    case '\\':
      c = fgetc(fp);
      if (c == EOF || c == '\n') {
	goto out;
      }
      break;
    case '\"':
      in_quote = !in_quote;
      continue;
    case ' ': case '\t': case '\r':
      if (in_quote) {
	break;
      }
      if (s != NULL) {
	goto out;
      }
      break;
    default:
      break;
    }

    s = (char*) realloc(s, len + 2);
    s[len] = c;
    len ++;
  }
out:
  if (s) {
    s[len] = '\0';
  }
  *eol = (c == '\n');
  return s;
}

/* journalからADDの行を読む */
static void
read_add_row(FILE *fp, struct record_stat* rst,
	     struct record_section* rsc)
{
  int n;
  xstr* xs;
  char *token;
  int eol;
  struct trie_node* node;

  token = read_1_token(fp, &eol);
  if (!token) {
    return ;
  }

  xs = anthy_cstr_to_xstr(/* xstr 型を表す S を読み捨てる */
			  token + 1,
			  rst->encoding);
  node = do_select_row(rsc, xs, 1, LRU_USED);
  anthy_free_xstr(xs);
  free(token);

  if (node->dirty & PROTECT) {
    /* 保存すべき row なので、差分ファイルを読み捨てる */
    while (!eol) {
      free(read_1_token(fp, &eol));
    }
    return ;
  }

  n = 0;
  while (!eol) {
    token = read_1_token(fp, &eol);
    if (token) {
      switch(*token) {
	/* String 文字列 */
      case 'S':
	{
	  xstr* xs;
	  xs = anthy_cstr_to_xstr(token + 1, rst->encoding);
	  do_set_nth_xstr(node, n, xs, &rst->xstrs);
	  anthy_free_xstr(xs);
	}
	break;
	/* Number 数値 */
      case 'N':
	do_set_nth_value(node, n, atoi(token + 1));
	break;
      }
      free(token);
      n++;
    }
  }
  do_truncate_row(node, n);
}

/* journalからDELの行を読む */
static void
read_del_row(FILE *fp, struct record_stat* rst,
	     struct record_section* rsc)
{
  struct trie_node* node;
  char* token;
  xstr* xs;
  int eol;

  token = read_1_token(fp, &eol);
  if (!token) {
    return ;
  }

  xs = anthy_cstr_to_xstr(/* xstr 型を表す S を読み飛ばす */
			  token + 1,
			  rst->encoding);
  if ((node = do_select_row(rsc, xs, 0, 0)) != NULL) {
    do_remove_row(rsc, node);
  }
  anthy_free_xstr(xs);
  free(token);
}

/** 差分ファイルから1行読み込む */
static void
read_1_row(struct record_stat* rst, FILE* fp, char *op)
{
  char* sec_name;
  struct record_section* rsc;
  int eol;

  sec_name = read_1_token(fp, &eol);
  if (!sec_name || eol) {
    free(sec_name);
    return ;
  }
  rsc = do_select_section(rst, sec_name, 1);
  free(sec_name);
  if (!rsc) {
    return ;
  }

  if (strcmp(op, "ADD") == 0) {
    read_add_row(fp, rst, rsc);
  } else if (strcmp(op, "DEL") == 0) {
    read_del_row(fp, rst, rsc);
  }
}

/*
 * journal(差分)ファイルを読む
 */
static void
read_journal_record(struct record_stat* rs)
{
  FILE* fp;
  struct stat st;

  if (rs->is_anon) {
    return ;
  }
  fp = fopen(rs->journal_fn, "r");
  if (fp == NULL) {
    return;
  }
  if (fstat(fileno(fp), &st) == -1) {
    fclose(fp);
    return ;
  }
  if (st.st_size < rs->last_update) {
    /* ファイルサイズが小さくなっているので、
     * 最初から読み込む */
    fseek(fp, 0, SEEK_SET);
  } else {
    fseek(fp, rs->last_update, SEEK_SET);
  }
  rs->journal_timestamp = st.st_mtime;
  while (!feof(fp)) {
    char *op;
    int eol;
    op = read_1_token(fp, &eol);
    if (op && !eol) {
      read_1_row(rs, fp, op);
    }
    free(op);
  }
  rs->last_update = ftell(fp);
  fclose(fp);
}

static void
write_string(FILE* fp, const char* str)
{
  fprintf(fp, "%s", str);
}

/* ダブルクオートもしくはバックスラッシュにバックスラッシュを付ける */
static void
write_quote_string(FILE* fp, const char* str)
{
  const char* p;

  for (p = str; *p; p++) {
    if (*p == '\"' || *p == '\\') {
      fputc('\\', fp);
    }
    fputc(*p, fp);
  }
}

static void
write_quote_xstr(FILE* fp, xstr* xs, int encoding)
{
  char* buf;

  if ((NULL == xs) || (NULL == xs->str) || (xs->len < 1) || (0 == xs->str[0])) {
    /* 辞書もしくは学習データが壊れていた時の対策 */
    return;
  }

  buf = (char*) alloca(xs->len * 6 + 2); /* EUC またはUTF8を仮定 */
  anthy_sputxstr(buf, xs, encoding);
  write_quote_string(fp, buf);
}

static void
write_number(FILE* fp, int x)
{
  fprintf(fp, "%d", x);
}

/* journalに1行追記する */
static void
commit_add_row(struct record_stat* rst,
	       const char* sname, struct trie_node* node)
{
  FILE* fp;
  int i;

  fp = fopen(rst->journal_fn, "a");
  if (fp == NULL) {
    return;
  }

  write_string(fp, "ADD \"");
  write_quote_string(fp, sname);
  write_string(fp, "\" S\"");
  write_quote_xstr(fp, &node->row.key, rst->encoding);
  write_string(fp, "\"");

  for (i = 0; i < node->row.nr_vals; i++) {
    switch (node->row.vals[i].type) {
    case RT_EMPTY:
      write_string(fp, " E");
      break;
    case RT_VAL:
      write_string(fp, " N");
      write_number(fp, node->row.vals[i].u.val);
      break;
    case RT_XSTR:
      write_string(fp, " S\"");
      write_quote_xstr(fp, &node->row.vals[i].u.str, rst->encoding);
      write_string(fp, "\"");
      break;
    case RT_XSTRP:
      write_string(fp, " S\"");
      write_quote_xstr(fp, node->row.vals[i].u.strp, rst->encoding);
      write_string(fp, "\"");
      break;
    }
  }
  write_string(fp, "\n");
  rst->last_update = ftell(fp);
  fclose(fp);
}

/* 全ての row を解放する */
static void
clear_record(struct record_stat* rst)
{
  struct record_section *rsc;
  for (rsc = rst->section_list.next; rsc; rsc = rsc->next) {
    trie_remove_all(&rsc->cols, &rsc->lru_nr_used, &rsc->lru_nr_sused); 
  }
  rst->cur_row = NULL;
}

/* 基本ファイルを読む */
static void
read_session(struct record_stat *rst)
{
  char **tokens;
  int nr;
  int in_section = 0;
  while (!anthy_read_line(&tokens, &nr)) {
    xstr *xs;
    int i;
    int dirty = 0;
    struct trie_node* node;

    if (!strcmp(tokens[0], "---") && nr > 1) {
      /* セクションの切れ目 */
      in_section = 1;
      rst->cur_section = do_select_section(rst, tokens[1], 1);
      goto end;
    }
    if (!in_section || nr < 2) {
      /* セクションが始まってない or 行が不完全 */
      goto end;
    }
    /* 行頭のLRUのマークを読む */
    if (tokens[0][0] == '-') {
      dirty = 0;
    } else if (tokens[0][0] == '+') {
      dirty = LRU_SUSED;
    }
    /* 次にindex */
    xs = anthy_cstr_to_xstr(&tokens[0][1], rst->encoding);
    node = do_select_row(rst->cur_section, xs, 1, dirty);
    anthy_free_xstr(xs);
    if (!node) {
      goto end;
    }
    rst->cur_row = node;
    /**/
    for (i = 1; i < nr; i++) {
      if (tokens[i][0] == '"') {
	char *str;
	str = strdup(&tokens[i][1]);
	str[strlen(str) - 1] = 0;
	xs = anthy_cstr_to_xstr(str, rst->encoding);
	free(str);
	do_set_nth_xstr(rst->cur_row, i-1, xs, &rst->xstrs);
	anthy_free_xstr(xs);
      }else if (tokens[i][0] == '*') {
	/* EMPTY entry */
	get_nth_val_ent(rst->cur_row, i-1, 1);
      } else {
	do_set_nth_value(rst->cur_row, i-1, atoi(tokens[i]));
      }
    }
  end:
    anthy_free_line();
  }
}

/* いまのデータベースを解放した後にファイルから読み込む */
static void
read_base_record(struct record_stat *rst)
{
  struct stat st;
  if (rst->is_anon) {
    clear_record(rst);
    return ;
  }
  anthy_check_user_dir();

  if (anthy_open_file(rst->base_fn) == -1) {
    return ;
  }

  clear_record(rst);
  read_session(rst);
  anthy_close_file();
  if (stat(rst->base_fn, &st) == 0) {
    rst->base_timestamp = st.st_mtime;
  }
  rst->last_update = 0;
}

static FILE *
open_tmp_in_recorddir(void)
{
  char *pn;
  const char *hd;
  const char *sid;
  sid = anthy_conf_get_str("SESSION-ID");
  hd = anthy_conf_get_str("HOME");
  pn = alloca(strlen(hd)+strlen(sid) + 10);
  sprintf(pn, "%s/.anthy/%s", hd, sid);
  return fopen(pn, "w");
}

/*
 * 一時ファイルからbaseファイルへrenameする 
 */
static void
update_file(const char *fn)
{
  const char *hd;
  char *tmp_fn;
  const char *sid;
  hd = anthy_conf_get_str("HOME");
  sid = anthy_conf_get_str("SESSION-ID");
  tmp_fn = alloca(strlen(hd)+strlen(sid) + 10);

  sprintf(tmp_fn, "%s/.anthy/%s", hd, sid);
  if (rename(tmp_fn, fn)){
    anthy_log(0, "Failed to update record file %s -> %s.\n", tmp_fn, fn);
  }
}

/* カラムを保存する */
static void
save_a_row(FILE *fp, struct record_stat* rst,
	   struct record_row *c, int dirty)
{
  int i;
  char *buf = alloca(c->key.len * 6 + 2);
  /* LRUのマークを出力 */
  if (dirty == 0) {
    fputc('-', fp);
  } else {
    fputc('+', fp);
  }
  anthy_sputxstr(buf, &c->key, rst->encoding);
  /* index を出力 */
  fprintf(fp, "%s ", buf);
  /**/
  for (i = 0; i < c->nr_vals; i++) {
    struct record_val *val = &c->vals[i];
    switch (val->type) {
    case RT_EMPTY:
      fprintf(fp, "* ");
      break;
    case RT_XSTR:
      /* should not happen */
      fprintf(fp, "\"");
      write_quote_xstr(fp, &val->u.str, rst->encoding);
      fprintf(fp, "\" ");
      abort();
      break;
    case RT_XSTRP:
      fprintf(fp, "\"");
      write_quote_xstr(fp, val->u.strp, rst->encoding);
      fprintf(fp, "\" ");
      break;
    case RT_VAL:
      fprintf(fp, "%d ", val->u.val);
      break;
    default:
      anthy_log(0, "Faild to save an unkonwn record. (in record.c)\n");
      break;
    }
  }
  fprintf(fp, "\n");
}

static void
update_base_record(struct record_stat* rst)
{
  struct record_section *sec;
  struct trie_node *col;
  FILE *fp;
  struct stat st;

  /* 一時ファイルを作ってrecordを書き出す */
  anthy_check_user_dir();
  fp = open_tmp_in_recorddir();
  if (!fp) {
    anthy_log(0, "Failed to open temporaly session file.\n");
    return ;
  }
  /* 各セクションに対して */
  for (sec = rst->section_list.next;
       sec; sec = sec->next) {
    if (!trie_first(&sec->cols)) {
      /*このセクションは空*/
      continue;
    }
    /* セクション境界の文字列 */
    fprintf(fp, "--- %s\n", sec->name);
    /* 各カラムを保存する */
    for (col = trie_first(&sec->cols); col; 
	 col = trie_next(&sec->cols, col)) {
      save_a_row(fp, rst, &col->row, col->dirty);
    }
  }
  fclose(fp);

  /* 本来の名前にrenameする */
  update_file(rst->base_fn);

  if (stat(rst->base_fn, &st) == 0) {
    rst->base_timestamp = st.st_mtime;
  }
  /* journalファイルを消す */
  unlink(rst->journal_fn);
  rst->last_update = 0;
}

static void
commit_del_row(struct record_stat* rst,
	       const char* sname, struct trie_node* node)
{
  FILE* fp;

  fp = fopen(rst->journal_fn, "a");
  if (fp == NULL) {
    return;
  }
  write_string(fp, "DEL \"");
  write_quote_string(fp, sname);
  write_string(fp, "\" S\"");
  write_quote_xstr(fp, &node->row.key, rst->encoding);
  write_string(fp, "\"");
  write_string(fp, "\n");
  fclose(fp);
}

/*
 * sync_add: ADD の書き込み
 * sync_del_and_del: DEL の書き込みと削除
 *   どちらも書き込みの前に、他のプロセスによってディスク上に保存された
 *   更新をメモリ上に読み込む。
 *   このとき、データベースをフラッシュする可能性もある。データベースの
 *   フラッシュがあると、 cur_row と全ての xstr は無効になる。
 *   ただし、 cur_section の有効性は保存される。
 */
static void
sync_add(struct record_stat* rst, struct record_section* rsc, 
	 struct trie_node* node)
{
  lock_record(rst);
  if (check_base_record_uptodate(rst)) {
    node->dirty |= PROTECT;
    /* 差分ファイルだけ読む */
    read_journal_record(rst);
    node->dirty &= ~PROTECT;
    commit_add_row(rst, rsc->name, node);
  } else {
    /* 再読み込み */
    commit_add_row(rst, rsc->name, node);
    read_base_record(rst);
    read_journal_record(rst);
  }
  if (rst->last_update > FILE2_LIMIT) {
    update_base_record(rst);
  }
  unlock_record(rst);
}

static void
sync_del_and_del(struct record_stat* rst, struct record_section* rsc, 
		 struct trie_node* node)
{
  lock_record(rst);
  commit_del_row(rst, rsc->name, node);
  if (!check_base_record_uptodate(rst)) {
    read_base_record(rst);
  }
  read_journal_record(rst);
  if (rst->last_update > FILE2_LIMIT) {
    update_base_record(rst);
  }
  unlock_record(rst);
}


/*
 * prediction関係
 */

static int
read_prediction_node(struct trie_node *n, struct prediction_t* predictions, int index)
{
  int i;
  int nr_predictions = do_get_nr_values(n);
  for (i = 0; i < nr_predictions; i += 2) {
    time_t t = do_get_nth_value(n, i);
    xstr* xs = do_get_nth_xstr(n, i + 1);
    if (t && xs) {
      if (predictions) {
	predictions[index].timestamp = t;
	predictions[index].src_str = anthy_xstr_dup(&n->row.key);
	predictions[index].str = anthy_xstr_dup(xs);
      }
      ++index;
    }
  }
  return index;
}


/*
 * trie中をたどり、prefixがマッチしたらread_prediction_nodeを
 * 呼んでpredictionsの配列に結果を追加する。
 */
static int
traverse_record_for_prediction(xstr* key, struct trie_node *n,
			       struct prediction_t* predictions, int index)
{
  if (n->l->bit > n->bit) {
    index = traverse_record_for_prediction(key, n->l, predictions, index);
  } else {
    if (n->l->row.key.len != -1) {
      if (anthy_xstrncmp(&n->l->row.key, key, key->len) == 0) {
	index = read_prediction_node(n->l, predictions, index);
      }
    }
  }
  if (n->r->bit > n->bit) {
    index = traverse_record_for_prediction(key, n->r, predictions, index);
  } else {
    if (n->r->row.key.len != -1) {
      if (anthy_xstrncmp(&n->r->row.key, key, key->len) == 0) {
	index = read_prediction_node(n->r, predictions, index);
      }
    }
  }
  return index;
}

/*
 * key で探索
 * key の文字列長を越えるか、ノードが無くなったら探索打ち切り
 * trieのkeyが格納されているところでななくて葉を返す
 */
static struct trie_node *
trie_find_for_prediction (struct trie_root* root, xstr *key)
{
  struct trie_node *p;
  struct trie_node *q;

  p = &root->root;
  q = p->l;

  while (p->bit < q->bit) {
    if (q->bit >= 2) {
      if ((q->bit - 2) / (int)(sizeof(xchar) << 3) >= key->len) {
	break;
      }
    }
    p = q;
    q = trie_key_nth_bit(key, p->bit) ? p->r : p->l;
  }
  return p;
}

static int
prediction_cmp(const void* lhs, const void* rhs)
{
  struct prediction_t *lpre = (struct prediction_t*)lhs;
  struct prediction_t *rpre = (struct prediction_t*)rhs;
  return rpre->timestamp - lpre->timestamp;
}

int
anthy_traverse_record_for_prediction(xstr* key, struct prediction_t* predictions)
{
  struct trie_node* mark;
  int nr_predictions;
  if (anthy_select_section("PREDICTION", 0)) {
    return 0;
  }

  /* 指定された文字列をprefixに持つnodeを探す */
  mark = trie_find_for_prediction(&anthy_current_record->cur_section->cols, key);
  if (!mark) {
    return 0;
  }
  nr_predictions = traverse_record_for_prediction(key, mark, predictions, 0);
  if (predictions) {
    /* タイムスタンプで予測候補をソートする */
    qsort(predictions, nr_predictions, sizeof(struct prediction_t), prediction_cmp);
  }
  return nr_predictions;
}

/* Wrappers begin.. */
int 
anthy_select_section(const char *name, int flag)
{
  struct record_stat* rst;
  struct record_section* rsc;

  rst = anthy_current_record;
  if (rst->row_dirty && rst->cur_section && rst->cur_row) {
    sync_add(rst, rst->cur_section, rst->cur_row);
  }
  rst->cur_row = NULL;
  rst->row_dirty = 0;
  rsc = do_select_section(rst, name, flag);
  if (!rsc) {
    return -1;
  }
  rst->cur_section = rsc;
  return 0;
}

int
anthy_select_row(xstr *name, int flag)
{
  struct record_stat* rst;
  struct trie_node* node;

  rst = anthy_current_record;
  if (!rst->cur_section) {
    return -1;
  }
  if (rst->row_dirty && rst->cur_row) {
    sync_add(rst, rst->cur_section, rst->cur_row);
    rst->row_dirty = 0;
  }
  node = do_select_row(rst->cur_section, name, flag, LRU_USED);
  if (!node) {
    return -1;
  }
  rst->cur_row = node;
  rst->row_dirty = flag;
  return 0;
}

int
anthy_select_longest_row(xstr *name)
{
  struct record_stat* rst;
  struct trie_node* node;

  rst = anthy_current_record;
  if (!rst->cur_section)
    return -1;

  if (rst->row_dirty && rst->cur_row) {
    sync_add(rst, rst->cur_section, rst->cur_row);
    rst->row_dirty = 0;
  }
  node = do_select_longest_row(rst->cur_section, name);
  if (!node) {
    return -1;
  }

  rst->cur_row = node;
  rst->row_dirty = 0;
  return 0;
}

void
anthy_truncate_section(int count)
{
  do_truncate_section(anthy_current_record, count);
}

void
anthy_truncate_row(int nth)
{
  struct trie_node *cur_row = anthy_current_record->cur_row;  
  if (!cur_row) {
    return ;
  }
  do_truncate_row(cur_row, nth);

}

int
anthy_mark_row_used(void)
{
  struct record_stat* rst = anthy_current_record;
  if (!rst->cur_row) {
    return -1;
  }

  do_mark_row_used(rst->cur_section, rst->cur_row);
  sync_add(rst, rst->cur_section, rst->cur_row);
  rst->row_dirty = 0;
  return 0;
}

void
anthy_set_nth_value(int nth, int val)
{
  struct record_stat* rst;

  rst = anthy_current_record;
  if (!rst->cur_row) {
    return;
  }
  do_set_nth_value(rst->cur_row, nth, val);
  rst->row_dirty = 1;
}

void
anthy_set_nth_xstr(int nth, xstr *xs)
{
  struct record_stat* rst = anthy_current_record;
  if (!rst->cur_row) {
    return;
  }
  do_set_nth_xstr(rst->cur_row, nth, xs, &rst->xstrs);
  rst->row_dirty = 1;
}

int
anthy_get_nr_values(void)
{
  return do_get_nr_values(anthy_current_record->cur_row);
}

int
anthy_get_nth_value(int n)
{
  return do_get_nth_value(anthy_current_record->cur_row, n);
}

xstr *
anthy_get_nth_xstr(int n)
{
  return do_get_nth_xstr(anthy_current_record->cur_row, n);
}

int
anthy_select_first_row(void)
{
  struct record_stat* rst;
  struct trie_node* node;

  rst = anthy_current_record;
  if (!rst->cur_section)
    return -1;
  
  if (rst->row_dirty && rst->cur_row) {
    sync_add(rst, rst->cur_section, rst->cur_row);
    rst->row_dirty = 0;
  }
  node = do_select_first_row(rst->cur_section);
  if (!node) {
    return -1;
  }
  rst->cur_row = node;
  rst->row_dirty = 0;
  return 0;
}

int
anthy_select_next_row(void)
{
  struct record_stat* rst;
  struct trie_node* node;

  rst = anthy_current_record;
  if (!rst->cur_section || !rst->cur_row)
    return -1;
  
  /* sync_add() で cur_row が無効になることがあるので、
   * たとえ row_dirty でも sync_add() しない
   */
  rst->row_dirty = 0;
  node = do_select_next_row(rst->cur_section, rst->cur_row);
  if (!node)
    return -1;
  rst->cur_row = node;
  rst->row_dirty = 0;
  return 0;
}

xstr *
anthy_get_index_xstr(void)
{
  return do_get_index_xstr(anthy_current_record);
}
/*..Wrappers end*/

/*
 * trie_row_init は何回よんでもいい
 */
static void
trie_row_init(struct record_row* rc)
{
  rc->nr_vals = 0;
  rc->vals = NULL;
}

static void
trie_row_free(struct record_row *rc)
{
  int i;
  for (i = 0; i < rc->nr_vals; i++)
    free_val_contents(rc->vals + i);
  free(rc->vals);
  free(rc->key.str);
}  

/* あるセクションのデータを全て解放する */
static void
free_section(struct record_stat *r, struct record_section *rs)
{
  struct record_section *s;
  trie_remove_all(&rs->cols, &rs->lru_nr_used, &rs->lru_nr_sused);
  if (r->cur_section == rs) {
    r->cur_row = 0;
    r->cur_section = 0;
  }
  for (s = &r->section_list; s && s->next; s = s->next) {
    if (s->next == rs) {
      s->next = s->next->next;
    }
  }
  if (rs->name){
    free((void *)rs->name);
  }
  free(rs);
}

/* すべてのデータを解放する */
static void
free_record(struct record_stat *rst)
{
  struct record_section *rsc;
  for (rsc = rst->section_list.next; rsc; ){
    struct record_section *tmp;
    tmp = rsc;
    rsc = rsc->next;
    free_section(rst, tmp);
  }
  rst->section_list.next = NULL;
}

void
anthy_release_section(void)
{
  struct record_stat* rst;

  rst = anthy_current_record;
  if (!rst->cur_section) {
    return ;
  }
  free_section(rst, rst->cur_section);
  rst->cur_section = 0;
}

void
anthy_release_row(void)
{
  struct record_stat* rst;

  rst = anthy_current_record;
  if (!rst->cur_section || !rst->cur_row) {
    return;
  }

  rst->row_dirty = 0;
  /* sync_del_and_del で削除もする */
  sync_del_and_del(rst, rst->cur_section, rst->cur_row);
  rst->cur_row = NULL;
}

static void
check_record_encoding(struct record_stat *rst)
{
  FILE *fp;
  if (anthy_open_file(rst->base_fn) == 0) {
    /* EUCの履歴ファイルがあった */
    anthy_close_file();
    return ;
  }
  fp = fopen(rst->journal_fn, "r");
  if (fp) {
    /* EUCの差分ファイルがあった */
    fclose(fp);
    return ;
  }
  rst->encoding = ANTHY_UTF8_ENCODING;
  strcat(rst->base_fn, ENCODING_SUFFIX);
  strcat(rst->journal_fn, ENCODING_SUFFIX);
}

static void
record_dtor(void *p)
{
  int dummy;
  struct record_stat *rst = (struct record_stat*) p;
  free_record(rst);
  if (rst->id) {
    free(rst->base_fn);
    free(rst->journal_fn);
  }
  trie_remove_all(&rst->xstrs, &dummy, &dummy);
}

void
anthy_reload_record(void)
{
  struct stat st;
  struct record_stat *rst = anthy_current_record;
  
  if (stat(rst->journal_fn, &st) == 0 &&
      rst->journal_timestamp == st.st_mtime) {
    return ;
  }

  lock_record(rst);
  read_base_record(rst);
  read_journal_record(rst);
  unlock_record(rst);
}

void
anthy_init_record(void)
{
  record_ator = anthy_create_allocator(sizeof(struct record_stat),
				       record_dtor);
}

static void
setup_filenames(const char *id, struct record_stat *rst)
{
  const char *home = anthy_conf_get_str("HOME");
  int base_len = strlen(home) + strlen(id) + 10;

  /* 基本ファイル */
  rst->base_fn = (char*) malloc(base_len +
				strlen("/.anthy/last-record1_"));
  sprintf(rst->base_fn, "%s/.anthy/last-record1_%s",
	  home, id);
  /* 差分ファイル */
  rst->journal_fn = (char*) malloc(base_len +
				   strlen("/.anthy/last-record2_"));
  sprintf(rst->journal_fn, "%s/.anthy/last-record2_%s",
	  home, id);
}

struct record_stat *
anthy_create_record(const char *id)
{
  struct record_stat *rst;

  if (!id) {
    return NULL;
  }

  rst = anthy_smalloc(record_ator);
  rst->id = id;
  rst->section_list.next = 0;
  init_trie_root(&rst->xstrs);
  rst->cur_section = 0;
  rst->cur_row = 0;
  rst->row_dirty = 0;
  rst->encoding = 0;

  /* ファイル名の文字列を作る */
  setup_filenames(id, rst);

  rst->last_update = 0;

  if (!strcmp(id, ANON_ID)) {
    rst->is_anon = 1;
  } else {
    rst->is_anon = 0;
    anthy_check_user_dir();
  }

  /* ファイルから読み込む */
  lock_record(rst);
  check_record_encoding(rst);
  read_base_record(rst);
  read_journal_record(rst);
  unlock_record(rst);

  return rst;
}

void
anthy_release_record(struct record_stat *rs)
{
  anthy_sfree(record_ator, rs);
}