aboutsummaryrefslogtreecommitdiffstats
path: root/src/io.c
blob: 2bd0ce49e17cb804419c2a0a10b8d2b603545508 (plain) (blame)
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
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
/*
 * Calcurse - text-based organizer
 *
 * Copyright (c) 2004-2011 calcurse Development Team <misc@calcurse.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *      - Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the
 *        following disclaimer.
 *
 *      - Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the
 *        following disclaimer in the documentation and/or other
 *        materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Send your feedback or comments to : misc@calcurse.org
 * Calcurse home page : http://calcurse.org
 *
 */

#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <errno.h>

#include "calcurse.h"
#include "sha1.h"

#define ICALDATEFMT      "%Y%m%d"
#define ICALDATETIMEFMT  "%Y%m%dT%H%M%S"

typedef enum {
  PROGRESS_BAR_SAVE,
  PROGRESS_BAR_LOAD,
  PROGRESS_BAR_EXPORT
} progress_bar_t;

enum {
  PROGRESS_BAR_CONF,
  PROGRESS_BAR_TODO,
  PROGRESS_BAR_APTS,
  PROGRESS_BAR_KEYS
};

enum {
  PROGRESS_BAR_EXPORT_EVENTS,
  PROGRESS_BAR_EXPORT_APOINTS,
  PROGRESS_BAR_EXPORT_TODO
};

typedef enum {
  ICAL_VEVENT,
  ICAL_VTODO,
  ICAL_TYPES
} ical_types_e;

typedef enum {
  UNDEFINED,
  APPOINTMENT,
  EVENT
} ical_vevent_e;

typedef struct {
  enum recur_type type;
  int             freq;
  long            until;
  unsigned        count;
} ical_rpt_t;

struct ht_keybindings_s {
  char     *label;
  enum key  key;
  HTABLE_ENTRY (ht_keybindings_s);
};

/* Type definition for callbacks to multiple-mode export functions. */
typedef void (*cb_export_t)(FILE *);
typedef void (*cb_dump_t)(FILE *, long, long, char *);

/* Static functions used to add export functionalities. */
static void ical_export_header (FILE *);
static void ical_export_recur_events (FILE *);
static void ical_export_events (FILE *);
static void ical_export_recur_apoints (FILE *);
static void ical_export_apoints (FILE *);
static void ical_export_todo (FILE *);
static void ical_export_footer (FILE *);

static void pcal_export_header (FILE *);
static void pcal_export_recur_events (FILE *);
static void pcal_export_events (FILE *);
static void pcal_export_recur_apoints (FILE *);
static void pcal_export_apoints (FILE *);
static void pcal_export_todo (FILE *);
static void pcal_export_footer (FILE *);

cb_export_t cb_export_header[IO_EXPORT_NBTYPES] =
  {ical_export_header, pcal_export_header};
cb_export_t cb_export_recur_events[IO_EXPORT_NBTYPES] =
  {ical_export_recur_events, pcal_export_recur_events};
cb_export_t cb_export_events[IO_EXPORT_NBTYPES] =
  {ical_export_events, pcal_export_events};
cb_export_t cb_export_recur_apoints[IO_EXPORT_NBTYPES] =
  {ical_export_recur_apoints, pcal_export_recur_apoints};
cb_export_t cb_export_apoints[IO_EXPORT_NBTYPES] =
  {ical_export_apoints, pcal_export_apoints};
cb_export_t cb_export_todo[IO_EXPORT_NBTYPES] =
  {ical_export_todo, pcal_export_todo};
cb_export_t cb_export_footer[IO_EXPORT_NBTYPES] =
  {ical_export_footer, pcal_export_footer};

static char *ical_recur_type[RECUR_TYPES] =
  { "", "DAILY", "WEEKLY", "MONTHLY", "YEARLY" };

/* Draw a progress bar while saving, loading or exporting data. */
static void
progress_bar (progress_bar_t type, int progress)
{
#define NBFILES		4
#define NBEXPORTED      3
#define LABELENGTH      15
  int i, step, steps;
  char *mesg_sav = _("Saving...");
  char *mesg_load = _("Loading...");
  char *mesg_export = _("Exporting...");
  char *error_msg = _("Internal error while displaying progress bar");
  char *barchar = "|";
  char *file[NBFILES] = {
    "[    conf    ]",
    "[    todo    ]",
    "[    apts    ]",
    "[    keys    ]"
  };
  char *data[NBEXPORTED] = {
    "[   events   ]",
    "[appointments]",
    "[    todo    ]"
  };
  int ipos =  LABELENGTH + 2;
  int epos[NBFILES];

  /* progress bar length init. */
  ipos = LABELENGTH + 2;
  steps = (type == PROGRESS_BAR_EXPORT) ? NBEXPORTED : NBFILES;
  step = floor (col / (steps + 1));
  for (i = 0; i < steps - 1; i++)
    epos[i] = (i + 2) * step;
  epos[steps - 1] = col - 2;

  switch (type)
    {
    case PROGRESS_BAR_SAVE:
      EXIT_IF (progress < 0 || progress > PROGRESS_BAR_KEYS, "%s", error_msg);
      status_mesg (mesg_sav, file[progress]);
      break;
    case PROGRESS_BAR_LOAD:
      EXIT_IF (progress < 0 || progress > PROGRESS_BAR_KEYS, "%s", error_msg);
      status_mesg (mesg_load, file[progress]);
      break;
    case PROGRESS_BAR_EXPORT:
      EXIT_IF (progress < 0
               || progress > PROGRESS_BAR_EXPORT_TODO, "%s", error_msg);
      status_mesg (mesg_export, data[progress]);
      break;
    }

  /* Draw the progress bar. */
  mvwprintw (win[STA].p, 1, ipos, barchar);
  mvwprintw (win[STA].p, 1, epos[steps - 1], barchar);
  custom_apply_attr (win[STA].p, ATTR_HIGHEST);
  for (i = ipos + 1; i < epos[progress]; i++)
    mvwaddch (win[STA].p, 1, i, ' ' | A_REVERSE);
  custom_remove_attr (win[STA].p, ATTR_HIGHEST);
  wmove (win[STA].p, 0, 0);
  wins_wrefresh (win[STA].p);
#undef NBFILES
#undef NBEXPORTED
#undef LABELENGTH
}

/* Ask user for a file name to export data to. */
static FILE *
get_export_stream (enum export_type type)
{
  FILE *stream;
  int cancel;
  char *home, *stream_name;
  char *question = _("Choose the file used to export calcurse data:");
  char *wrong_name =
    _("The file cannot be accessed, please enter another file name.");
  char *press_enter = _("Press [ENTER] to continue.");
  const char *file_ext[IO_EXPORT_NBTYPES] = {"ical", "txt"};

  stream = NULL;
  stream_name = (char *) mem_malloc (BUFSIZ);
  if ((home = getenv ("HOME")) != NULL)
    snprintf (stream_name, BUFSIZ, "%s/calcurse.%s", home, file_ext[type]);
  else
    snprintf (stream_name, BUFSIZ, "%s/calcurse.%s", get_tempdir (),
              file_ext[type]);

  while (stream == NULL)
    {
      status_mesg (question, "");
      cancel = updatestring (win[STA].p, &stream_name, 0, 1);
      if (cancel)
        {
          mem_free (stream_name);
          return NULL;
        }
      stream = fopen (stream_name, "w");
      if (stream == NULL)
        {
          status_mesg (wrong_name, press_enter);
          wgetch (win[STA].p);
        }
    }
  mem_free (stream_name);

  return stream;
}

/*
 * Travel through each occurence of an item, and execute the given callback
 * (mainly used to export data).
 */
static void
foreach_date_dump (const long date_end, struct rpt *rpt, llist_t *exc,
                   long item_first_date, long item_dur, char *item_mesg,
                   cb_dump_t cb_dump, FILE *stream)
{
  long date, item_time;
  struct tm lt;
  time_t t;

  t = item_first_date;
  lt = *localtime (&t);
  lt.tm_hour = lt.tm_min = lt.tm_sec = 0;
  lt.tm_isdst = -1;
  date = mktime (&lt);
  item_time = item_first_date - date;

  while (date <= date_end && date <= rpt->until)
    {
      if (recur_item_inday (item_first_date, item_dur, exc, rpt->type,
                            rpt->freq, rpt->until, date))
        {
          (*cb_dump)(stream, date + item_time, item_dur, item_mesg);
        }
      switch (rpt->type)
        {
        case RECUR_DAILY:
          date = date_sec_change (date, 0, rpt->freq);
          break;
        case RECUR_WEEKLY:
          date = date_sec_change (date, 0, rpt->freq * WEEKINDAYS);
          break;
        case RECUR_MONTHLY:
          date = date_sec_change (date, rpt->freq, 0);
          break;
        case RECUR_YEARLY:
          date = date_sec_change (date, rpt->freq * 12, 0);
          break;
        default:
          EXIT (_("incoherent repetition type"));
          /* NOTREACHED */
          break;
        }
    }
}

/* iCal alarm notification. */
static void
ical_export_valarm (FILE *stream)
{
  fputs ("BEGIN:VALARM\n", stream);
  pthread_mutex_lock (&nbar.mutex);
  fprintf (stream, "TRIGGER:-P%dS\n", nbar.cntdwn);
  pthread_mutex_unlock (&nbar.mutex);
  fputs ("ACTION:DISPLAY\n", stream);
  fputs ("END:VALARM\n", stream);
}

/* Export header. */
static void
ical_export_header (FILE *stream)
{
  fputs ("BEGIN:VCALENDAR\n", stream);
  fprintf (stream, "PRODID:-//calcurse//NONSGML v%s//EN\n", VERSION);
  fputs ("VERSION:2.0\n", stream);
}

static void
pcal_export_header (FILE *stream)
{
  fputs ("# calcurse pcal export\n", stream);
  fputs ("\n# =======\n# options\n# =======\n", stream);
  fprintf (stream, "opt -A -K -l -m -F %s\n",
           calendar_week_begins_on_monday () ?  "Monday" : "Sunday");
  fputs ("# Display week number (i.e. 1-52) on every Monday\n", stream);
  fprintf (stream, "all monday in all  %s %%w\n", _("Week"));
  fputc ('\n', stream);
}

/* Export footer. */
static void
ical_export_footer (FILE *stream)
{
  fputs ("END:VCALENDAR\n", stream);
}

static void
pcal_export_footer (FILE *stream)
{
}

/* Export recurrent events. */
static void
ical_export_recur_events (FILE *stream)
{
  llist_item_t *i, *j;
  char ical_date[BUFSIZ];

  LLIST_FOREACH (&recur_elist, i)
    {
      struct recur_event *rev = LLIST_GET_DATA (i);
      date_sec2date_fmt (rev->day, ICALDATEFMT, ical_date);
      fputs ("BEGIN:VEVENT\n", stream);
      fprintf (stream, "DTSTART:%s\n", ical_date);
      fprintf (stream, "RRULE:FREQ=%s;INTERVAL=%d",
               ical_recur_type[rev->rpt->type], rev->rpt->freq);

      if (rev->rpt->until != 0)
        {
          date_sec2date_fmt (rev->rpt->until, ICALDATEFMT, ical_date);
          fprintf (stream, ";UNTIL=%s\n", ical_date);
        }
      else
        fputc ('\n', stream);

      if (LLIST_FIRST (&rev->exc))
        {
          fputs ("EXDATE:", stream);
          LLIST_FOREACH (&rev->exc, j)
            {
              struct excp *exc = LLIST_GET_DATA (j);
              date_sec2date_fmt (exc->st, ICALDATEFMT, ical_date);
              fprintf (stream, "%s", ical_date);
              if (LLIST_NEXT (j))
                fputc (',', stream);
              else
                fputc ('\n', stream);
            }
        }

      fprintf (stream, "SUMMARY:%s\n", rev->mesg);
      fputs ("END:VEVENT\n", stream);
    }
}

/* Format and dump event data to a pcal formatted file. */
static void
pcal_dump_event (FILE *stream, long event_date, long event_dur,
                 char *event_mesg)
{
  char pcal_date[BUFSIZ];

  date_sec2date_fmt (event_date, "%b %d", pcal_date);
  fprintf (stream, "%s  %s\n", pcal_date, event_mesg);
}

/* Format and dump appointment data to a pcal formatted file. */
static void
pcal_dump_apoint (FILE *stream, long apoint_date, long apoint_dur,
                  char *apoint_mesg)
{
  char pcal_date[BUFSIZ], pcal_beg[BUFSIZ], pcal_end[BUFSIZ];

  date_sec2date_fmt (apoint_date, "%b %d", pcal_date);
  date_sec2date_fmt (apoint_date, "%R", pcal_beg);
  date_sec2date_fmt (apoint_date + apoint_dur, "%R", pcal_end);
  fprintf (stream, "%s  ", pcal_date);
  fprintf (stream, "(%s -> %s) %s\n", pcal_beg, pcal_end, apoint_mesg);
}

static void
pcal_export_recur_events (FILE *stream)
{
  llist_item_t *i;
  char pcal_date[BUFSIZ];

  fputs ("\n# =============", stream);
  fputs ("\n# Recur. Events", stream);
  fputs ("\n# =============\n", stream);
  fputs ("# (pcal does not support from..until dates specification\n", stream);

  LLIST_FOREACH (&recur_elist, i)
    {
      struct recur_event *rev = LLIST_GET_DATA (i);
      if (rev->rpt->until == 0 && rev->rpt->freq == 1)
        {
          switch (rev->rpt->type)
            {
            case RECUR_DAILY:
              date_sec2date_fmt (rev->day, "%b %d", pcal_date);
              fprintf (stream, "all day on_or_after %s  %s\n", pcal_date,
                       rev->mesg);
              break;
            case RECUR_WEEKLY:
              date_sec2date_fmt (rev->day, "%a", pcal_date);
              fprintf (stream, "all %s on_or_after ", pcal_date);
              date_sec2date_fmt (rev->day, "%b %d", pcal_date);
              fprintf (stream, "%s  %s\n", pcal_date, rev->mesg);
              break;
            case RECUR_MONTHLY:
              date_sec2date_fmt (rev->day, "%d", pcal_date);
              fprintf (stream, "day on all %s  %s\n", pcal_date, rev->mesg);
              break;
            case RECUR_YEARLY:
              date_sec2date_fmt (rev->day, "%b %d", pcal_date);
              fprintf (stream, "%s  %s\n", pcal_date, rev->mesg);
              break;
            default:
              EXIT (_("incoherent repetition type"));
            }
        }
      else
        {
          const long YEAR_START = calendar_start_of_year ();
          const long YEAR_END = calendar_end_of_year ();

          if (rev->day < YEAR_END && rev->day > YEAR_START)
            foreach_date_dump (YEAR_END, rev->rpt, &rev->exc, rev->day, 0,
                               rev->mesg, (cb_dump_t) pcal_dump_event, stream);
        }
    }
}

/* Export events. */
static void
ical_export_events (FILE *stream)
{
  llist_item_t *i;
  char ical_date[BUFSIZ];

  LLIST_FOREACH (&eventlist, i)
    {
      struct event *ev = LLIST_TS_GET_DATA (i);
      date_sec2date_fmt (ev->day, ICALDATEFMT, ical_date);
      fputs ("BEGIN:VEVENT\n", stream);
      fprintf (stream, "DTSTART:%s\n", ical_date);
      fprintf (stream, "SUMMARY:%s\n", ev->mesg);
      fputs ("END:VEVENT\n", stream);
    }
}

static void
pcal_export_events (FILE *stream)
{
  llist_item_t *i;

  fputs ("\n# ======\n# Events\n# ======\n", stream);
  LLIST_FOREACH (&eventlist, i)
    {
      struct event *ev = LLIST_TS_GET_DATA (i);
      pcal_dump_event (stream, ev->day, 0, ev->mesg);
    }
  fputc ('\n', stream);
}

/* Export recurrent appointments. */
static void
ical_export_recur_apoints (FILE *stream)
{
  llist_item_t *i, *j;
  char ical_datetime[BUFSIZ];
  char ical_date[BUFSIZ];

  LLIST_TS_LOCK (&recur_alist_p);
  LLIST_TS_FOREACH (&recur_alist_p, i)
    {
      struct recur_apoint *rapt = LLIST_TS_GET_DATA (i);

      date_sec2date_fmt (rapt->start, ICALDATETIMEFMT, ical_datetime);
      fputs ("BEGIN:VEVENT\n", stream);
      fprintf (stream, "DTSTART:%s\n", ical_datetime);
      fprintf (stream, "DURATION:PT0H0M%ldS\n", rapt->dur);
      fprintf (stream, "RRULE:FREQ=%s;INTERVAL=%d",
               ical_recur_type[rapt->rpt->type], rapt->rpt->freq);

      if (rapt->rpt->until != 0)
        {
          date_sec2date_fmt (rapt->rpt->until + HOURINSEC, ICALDATEFMT,
                             ical_date);
          fprintf (stream, ";UNTIL=%s\n", ical_date);
        }
      else
        fputc ('\n', stream);

      if (LLIST_FIRST (&rapt->exc))
        {
          fputs ("EXDATE:", stream);
          LLIST_FOREACH (&rapt->exc, j)
            {
              struct excp *exc = LLIST_GET_DATA (j);
              date_sec2date_fmt (exc->st, ICALDATEFMT, ical_date);
              fprintf (stream, "%s", ical_date);
              if (LLIST_NEXT (j))
                fputc (',', stream);
              else
                fputc ('\n', stream);
            }
        }

      fprintf (stream, "SUMMARY:%s\n", rapt->mesg);
      if (rapt->state & APOINT_NOTIFY)
        ical_export_valarm (stream);
      fputs ("END:VEVENT\n", stream);
    }
  LLIST_TS_UNLOCK (&recur_alist_p);
}

static void
pcal_export_recur_apoints (FILE *stream)
{
  llist_item_t *i;
  char pcal_date[BUFSIZ], pcal_beg[BUFSIZ], pcal_end[BUFSIZ];

  fputs ("\n# ==============", stream);
  fputs ("\n# Recur. Apoints", stream);
  fputs ("\n# ==============\n", stream);
  fputs ("# (pcal does not support from..until dates specification\n", stream);

  LLIST_TS_FOREACH (&recur_alist_p, i)
    {
      struct recur_apoint *rapt = LLIST_TS_GET_DATA (i);

      if (rapt->rpt->until == 0 && rapt->rpt->freq == 1)
        {
          date_sec2date_fmt (rapt->start, "%R", pcal_beg);
          date_sec2date_fmt (rapt->start + rapt->dur, "%R", pcal_end);
          switch (rapt->rpt->type)
            {
            case RECUR_DAILY:
              date_sec2date_fmt (rapt->start, "%b %d", pcal_date);
              fprintf (stream, "all day on_or_after %s  (%s -> %s) %s\n",
                       pcal_date, pcal_beg, pcal_end, rapt->mesg);
              break;
            case RECUR_WEEKLY:
              date_sec2date_fmt (rapt->start, "%a", pcal_date);
              fprintf (stream, "all %s on_or_after ", pcal_date);
              date_sec2date_fmt (rapt->start, "%b %d", pcal_date);
              fprintf (stream, "%s  (%s -> %s) %s\n", pcal_date, pcal_beg,
                       pcal_end, rapt->mesg);
              break;
            case RECUR_MONTHLY:
              date_sec2date_fmt (rapt->start, "%d", pcal_date);
              fprintf (stream, "day on all %s  (%s -> %s) %s\n", pcal_date,
                       pcal_beg, pcal_end, rapt->mesg);
              break;
            case RECUR_YEARLY:
              date_sec2date_fmt (rapt->start, "%b %d", pcal_date);
              fprintf (stream, "%s  (%s -> %s) %s\n", pcal_date, pcal_beg,
                       pcal_end, rapt->mesg);
              break;
            default:
              EXIT (_("incoherent repetition type"));
            }
        }
      else
        {
          const long YEAR_START = calendar_start_of_year ();
          const long YEAR_END = calendar_end_of_year ();

          if (rapt->start < YEAR_END && rapt->start > YEAR_START)
            foreach_date_dump (YEAR_END, rapt->rpt, &rapt->exc, rapt->start,
                               rapt->dur, rapt->mesg,
                               (cb_dump_t)pcal_dump_apoint, stream);
        }
    }
}

/* Export appointments. */
static void
ical_export_apoints (FILE *stream)
{
  llist_item_t *i;
  char ical_datetime[BUFSIZ];

  LLIST_TS_LOCK (&alist_p);
  LLIST_TS_FOREACH (&alist_p, i)
    {
      struct apoint *apt = LLIST_TS_GET_DATA (i);
      date_sec2date_fmt (apt->start, ICALDATETIMEFMT, ical_datetime);
      fputs ("BEGIN:VEVENT\n", stream);
      fprintf (stream, "DTSTART:%s\n", ical_datetime);
      fprintf (stream, "DURATION:PT0H0M%ldS\n", apt->dur);
      fprintf (stream, "SUMMARY:%s\n", apt->mesg);
      if (apt->state & APOINT_NOTIFY)
        ical_export_valarm (stream);
      fputs ("END:VEVENT\n", stream);
    }
  LLIST_TS_UNLOCK (&alist_p);
}

static void
pcal_export_apoints (FILE *stream)
{
  llist_item_t *i;

  fputs ("\n# ============\n# Appointments\n# ============\n", stream);
  LLIST_TS_LOCK (&alist_p);
  LLIST_TS_FOREACH (&alist_p, i)
    {
      struct apoint *apt = LLIST_TS_GET_DATA (i);
      pcal_dump_apoint (stream, apt->start, apt->dur, apt->mesg);
    }
  LLIST_TS_UNLOCK (&alist_p);
  fputc ('\n', stream);
}

/* Export todo items. */
static void
ical_export_todo (FILE *stream)
{
  llist_item_t *i;

  LLIST_FOREACH (&todolist, i)
    {
      struct todo *todo = LLIST_TS_GET_DATA (i);
      if (todo->id < 0)  /* completed items */
        continue;

      fputs ("BEGIN:VTODO\n", stream);
      fprintf (stream, "PRIORITY:%d\n", todo->id);
      fprintf (stream, "SUMMARY:%s\n", todo->mesg);
      fputs ("END:VTODO\n", stream);
    }
}

static void
pcal_export_todo (FILE *stream)
{
  llist_item_t *i;

  fputs ("#\n# Todos\n#\n", stream);
  LLIST_FOREACH (&todolist, i)
    {
      struct todo *todo = LLIST_TS_GET_DATA (i);
      if (todo->id < 0)  /* completed items */
        continue;

      fputs ("note all  ", stream);
      fprintf (stream, "%d. %s\n", todo->id, todo->mesg);
    }
  fputc ('\n', stream);
}

/* Append a line to a file. */
unsigned
io_fprintln (const char *fname, const char *fmt, ...)
{
  FILE *fp;
  va_list ap;
  char buf[BUFSIZ];
  int ret;

  fp = fopen (fname, "a");
  RETVAL_IF (!fp, 0, _("Failed to open \"%s\", - %s\n"),
             fname, strerror (errno));

  va_start (ap, fmt);
  ret = vsnprintf (buf, sizeof buf, fmt, ap);
  RETVAL_IF (ret < 0, 0, _("Failed to build message\n"));
  va_end (ap);

  ret = fprintf (fp, "%s", buf);
  RETVAL_IF (ret < 0, 0, _("Failed to print message \"%s\"\n"), buf);

  ret = fclose (fp);
  RETVAL_IF (ret != 0, 0, _("Failed to close \"%s\" - %s\n"),
             fname, strerror (errno));

  return 1;
}

/*
 * Initialization of data paths. The cfile argument is the variable
 * which contains the calendar file. If none is given, then the default
 * one (~/.calcurse/apts) is taken. If the one given does not exist, it
 * is created.
 * The datadir argument can be use to specify an alternative data root dir.
 */
void
io_init (char *cfile, char *datadir)
{
  FILE *data_file;
  char *home;
  char apts_file[BUFSIZ] = "";
  int ch;

  if (datadir != NULL)
    {
      home = datadir;
      snprintf (path_dir, BUFSIZ, "%s", home);
      snprintf (path_todo, BUFSIZ, "%s/" TODO_PATH_NAME, home);
      snprintf (path_conf, BUFSIZ, "%s/" CONF_PATH_NAME, home);
      snprintf (path_notes, BUFSIZ, "%s/" NOTES_DIR_NAME, home);
      snprintf (path_apts, BUFSIZ, "%s/" APTS_PATH_NAME, home);
      snprintf (path_keys, BUFSIZ, "%s/" KEYS_PATH_NAME, home);
      snprintf (path_cpid, BUFSIZ, "%s/" CPID_PATH_NAME, home);
      snprintf (path_dpid, BUFSIZ, "%s/" DPID_PATH_NAME, home);
      snprintf (path_dmon_log, BUFSIZ, "%s/" DLOG_PATH_NAME, home);
    }
  else
    {
      home = getenv ("HOME");
      if (home == NULL)
        {
          home = ".";
        }
      snprintf (path_dir, BUFSIZ, "%s/" DIR_NAME, home);
      snprintf (path_todo, BUFSIZ, "%s/" TODO_PATH, home);
      snprintf (path_conf, BUFSIZ, "%s/" CONF_PATH, home);
      snprintf (path_keys, BUFSIZ, "%s/" KEYS_PATH, home);
      snprintf (path_cpid, BUFSIZ, "%s/" CPID_PATH, home);
      snprintf (path_dpid, BUFSIZ, "%s/" DPID_PATH, home);
      snprintf (path_dmon_log, BUFSIZ, "%s/" DLOG_PATH, home);
      snprintf (path_notes, BUFSIZ, "%s/" NOTES_DIR, home);
      if (cfile == NULL)
        {
          snprintf (path_apts, BUFSIZ, "%s/" APTS_PATH, home);
        }
      else
        {
          snprintf (apts_file, BUFSIZ, "%s", cfile);
          strncpy (path_apts, apts_file, BUFSIZ);
          /* check if the file exists, otherwise create it */
          data_file = fopen (path_apts, "r");
          if (data_file == NULL)
            {
              printf (_("%s does not exist, create it now [y or n] ? "),
                      path_apts);
              ch = getchar ();
              switch (ch)
                {
                case 'N':
                case 'n':
                  puts (_("aborting...\n"));
                  exit_calcurse (EXIT_FAILURE);
                  break;

                case 'Y':
                case 'y':
                  data_file = fopen (path_apts, "w");
                  if (data_file == NULL)
                    {
                      perror (path_apts);
                      exit_calcurse (EXIT_FAILURE);
                    }
                  else
                    {
                      printf (_("%s successfully created\n"), path_apts);
                      puts (_("starting interactive mode...\n"));
                    }
                  break;

                default:
                  puts (_("aborting...\n"));
                  exit_calcurse (EXIT_FAILURE);
                  break;
                }
            }
          file_close (data_file, __FILE_POS__);
        }
    }
}

void
io_extract_data (char *dst_data, const char *org, int len)
{
  int i;

  for (; *org == ' ' || *org == '\t'; org++);
  for (i = 0; i < len - 1; i++)
    {
      if (*org == '\n' || *org == '\0' || *org == '#')
        break;
      *dst_data++ = *org++;
    }
  *dst_data = '\0';
}

void
display_mark (void)
{
  const int DISPLAY_TIME = 1;
  WINDOW *mwin;

  mwin = newwin (1, 2, 1, col - 3);

  custom_apply_attr (mwin, ATTR_HIGHEST);
  mvwprintw (mwin, 0, 0, "**");
  wins_wrefresh (mwin);
  sleep (DISPLAY_TIME);
  mvwprintw (mwin, 0, 0, "  ");
  wins_wrefresh (mwin);
  delwin (mwin);
  wins_doupdate ();
}

static pthread_mutex_t io_save_mutex = PTHREAD_MUTEX_INITIALIZER;

/* Save the user configuration. */
unsigned
io_save_conf (void)
{
  char *config_txt =
    "#\n"
    "# Calcurse configuration file\n#\n"
    "# This file sets the configuration options used by Calcurse. These\n"
    "# options are usually set from within Calcurse. A line beginning with \n"
    "# a space or tab is considered to be a continuation of the previous "
    "line.\n"
    "# For a variable to be unset its value must be blank, followed by an\n"
    "# empty line. To set a variable to the empty string its value should be "
    "\"\".\n"
    "# Lines beginning with \"#\" are comments, and ignored by Calcurse.\n";
  char theme_name[BUFSIZ];
  FILE *fp;

  if ((fp = fopen (path_conf, "w")) == NULL)
    return 0;

  custom_color_theme_name (theme_name);

  fprintf (fp, "%s\n", config_txt);

  fputs ("# If this option is set to yes, "
         "automatic save is done when quitting\n", fp);
  fputs ("auto_save=", fp);
  fprintf (fp, "%s\n", (conf.auto_save) ? "yes" : "no");

  fputs ("\n# If this option is set to yes, "
         "the GC is run automatically when quitting\n", fp);
  fputs ("auto_gc=", fp);
  fprintf (fp, "%s\n", (conf.auto_gc) ? "yes" : "no");

  fputs ("\n# If not null, perform automatic saves every "
         "'periodic_save' minutes\n", fp);
  fputs ("periodic_save=", fp);
  fprintf (fp, "%d\n", conf.periodic_save);

  fputs ("\n# If this option is set to yes, "
         "confirmation is required before quitting\n", fp);
  fputs ("confirm_quit=", fp);
  fprintf (fp, "%s\n", (conf.confirm_quit) ? "yes" : "no");

  fputs ("\n# If this option is set to yes, "
         "confirmation is required before deleting an event\n", fp);
  fputs ("confirm_delete=", fp);
  fprintf (fp, "%s\n", (conf.confirm_delete) ? "yes" : "no");

  fputs ("\n# If this option is set to yes, messages about loaded and "
         "saved data will not be displayed\n", fp);
  fputs ("skip_system_dialogs=", fp);
  fprintf (fp, "%s\n", (conf.skip_system_dialogs) ? "yes" : "no");

  fputs ("\n# If this option is set to yes, progress bar appearing "
         "when saving data will not be displayed\n", fp);
  fputs ("skip_progress_bar=", fp);
  fprintf (fp, "%s\n", (conf.skip_progress_bar) ? "yes" : "no");

  fputs ("\n# Default calendar view (0)monthly (1)weekly:\n", fp);
  fputs ("calendar_default_view=", fp);
  fprintf (fp, "%d\n", calendar_get_view ());

  fputs ("\n# If this option is set to yes, "
         "monday is the first day of the week, else it is sunday\n", fp);
  fputs ("week_begins_on_monday=", fp);
  fprintf (fp, "%s\n", (calendar_week_begins_on_monday ())? "yes" : "no");

  fputs ("\n# This is the color theme used for menus :\n", fp);
  fputs ("color-theme=", fp);
  fprintf (fp, "%s\n", theme_name);

  fputs ("\n# This is the layout of the calendar :\n", fp);
  fputs ("layout=", fp);
  fprintf (fp, "%d\n", wins_layout ());

  fputs ("\n# Width ( percentage, 0 being minimun width, fp) "
         "of the side bar :\n", fp);
  fputs ("side-bar_width=", fp);
  fprintf (fp, "%d\n", wins_sbar_wperc ());

  if (ui_mode == UI_CURSES)
    pthread_mutex_lock (&nbar.mutex);
  fputs ("\n# If this option is set to yes, "
         "notify-bar will be displayed :\n", fp);
  fputs ("notify-bar_show=", fp);
  fprintf (fp, "%s\n", (nbar.show) ? "yes" : "no");

  fputs ("\n# Format of the date to be displayed inside notify-bar :\n", fp);
  fputs ("notify-bar_date=", fp);
  fprintf (fp, "%s\n", nbar.datefmt);

  fputs ("\n# Format of the time to be displayed inside notify-bar :\n", fp);
  fputs ("notify-bar_clock=", fp);
  fprintf (fp, "%s\n", nbar.timefmt);

  fputs ("\n# Warn user if he has an appointment within next "
         "'notify-bar_warning' seconds :\n", fp);
  fputs ("notify-bar_warning=", fp);
  fprintf (fp, "%d\n", nbar.cntdwn);

  fputs ("\n# Command used to notify user of "
         "an upcoming appointment :\n", fp);
  fputs ("notify-bar_command=", fp);
  fprintf (fp, "%s\n", nbar.cmd);

  fputs ("\n# Notify all appointments instead of flagged ones only\n", fp);
  fputs ("notify-all=", fp);
  fprintf (fp, "%s\n", (nbar.notify_all) ? "yes" : "no");

  fputs ("\n# Format of the date to be displayed "
         "in non-interactive mode :\n", fp);
  fputs ("output_datefmt=", fp);
  fprintf (fp, "%s\n", conf.output_datefmt);

  fputs ("\n# Format to be used when entering a date "
         "(1)mm/dd/yyyy (2)dd/mm/yyyy (3)yyyy/mm/dd) "
         "(4)yyyy-mm-dd:\n", fp);
  fputs ("input_datefmt=", fp);
  fprintf (fp, "%d\n", conf.input_datefmt);

  if (ui_mode == UI_CURSES)
    pthread_mutex_unlock (&nbar.mutex);

  fputs ("\n# If this option is set to yes, "
         "calcurse will run in background to get notifications "
         "after exiting\n", fp);
  fputs ("notify-daemon_enable=", fp);
  fprintf (fp, "%s\n", dmon.enable ? "yes" : "no");

  fputs ("\n# If this option is set to yes, "
         "activity will be logged when running in background\n", fp);
  fputs ("notify-daemon_log=", fp);
  fprintf (fp, "%s\n", dmon.log ? "yes" : "no");

  file_close (fp, __FILE_POS__);

  return 1;
}

/*
 * Save the apts data file, which contains the
 * appointments first, and then the events.
 * Recursive items are written first.
 */
unsigned
io_save_apts (void)
{
  llist_item_t *i;
  FILE *fp;

  if ((fp = fopen (path_apts, "w")) == NULL)
    return 0;

  recur_save_data (fp);

  if (ui_mode == UI_CURSES)
    LLIST_TS_LOCK (&alist_p);
  LLIST_TS_FOREACH (&alist_p, i)
    {
      struct apoint *apt = LLIST_TS_GET_DATA (i);
      apoint_write (apt, fp);
    }
  if (ui_mode == UI_CURSES)
    LLIST_TS_UNLOCK (&alist_p);

  LLIST_FOREACH (&eventlist, i)
    {
      struct event *ev = LLIST_TS_GET_DATA (i);
      event_write (ev, fp);
    }
  file_close (fp, __FILE_POS__);

  return 1;
}

/* Save the todo data file. */
unsigned
io_save_todo (void)
{
  llist_item_t *i;
  FILE *fp;

  if ((fp = fopen (path_todo, "w")) == NULL)
    return 0;

  LLIST_FOREACH (&todolist, i)
    {
      struct todo *todo = LLIST_TS_GET_DATA (i);
      todo_write (todo, fp);
    }
  file_close (fp, __FILE_POS__);

  return 1;
}

/* Save user-defined keys */
unsigned
io_save_keys (void)
{
  FILE *fp;

  if ((fp = fopen (path_keys, "w")) == NULL)
    return 0;

  keys_save_bindings (fp);
  file_close (fp, __FILE_POS__);

  return 1;
}

/* Save the calendar data */
void
io_save_cal (enum save_display display)
{
  char *access_pb = _("Problems accessing data file ...");
  char *save_success = _("The data files were successfully saved");
  char *enter = _("Press [ENTER] to continue");
  int show_bar;

  pthread_mutex_lock (&io_save_mutex);

  show_bar = 0;
  if (ui_mode == UI_CURSES && display == IO_SAVE_DISPLAY_BAR
      && !conf.skip_progress_bar)
    show_bar = 1;
  else if (ui_mode == UI_CURSES && display == IO_SAVE_DISPLAY_MARK)
    display_mark ();

  if (show_bar)
    progress_bar (PROGRESS_BAR_SAVE, PROGRESS_BAR_CONF);
  if (!io_save_conf ())
    ERROR_MSG ("%s", access_pb);

  if (show_bar)
    progress_bar (PROGRESS_BAR_SAVE, PROGRESS_BAR_TODO);
  if (!io_save_todo ())
    ERROR_MSG ("%s", access_pb);

  if (show_bar)
    progress_bar (PROGRESS_BAR_SAVE, PROGRESS_BAR_APTS);
  if (!io_save_apts ())
    ERROR_MSG ("%s", access_pb);

  if (show_bar)
    progress_bar (PROGRESS_BAR_SAVE, PROGRESS_BAR_KEYS);
  if (!io_save_keys ())
    ERROR_MSG ("%s", access_pb);

  /* Print a message telling data were saved */
  if (ui_mode == UI_CURSES && !conf.skip_system_dialogs
      && display != IO_SAVE_DISPLAY_MARK)
    {
      status_mesg (save_success, enter);
      wgetch (win[STA].p);
    }

  pthread_mutex_unlock (&io_save_mutex);
}

/*
 * Check what type of data is written in the appointment file,
 * and then load either: a new appointment, a new event, or a new
 * recursive item (which can also be either an event or an appointment).
 */
void
io_load_app (void)
{
  FILE *data_file;
  int c, is_appointment, is_event, is_recursive;
  struct tm start, end, until, *lt;
  llist_t exc;
  time_t t;
  int id = 0;
  int freq;
  char type, state = 0L;
  char note[MAX_NOTESIZ + 1], *notep;

  t = time (NULL);
  lt = localtime (&t);
  start = end = until = *lt;

  data_file = fopen (path_apts, "r");
  for (;;)
    {
      LLIST_INIT (&exc);
      is_appointment = is_event = is_recursive = 0;
      c = getc (data_file);
      if (c == EOF)
        break;
      ungetc (c, data_file);

      /* Read the date first: it is common to both events
       * and appointments.
       */
      if (fscanf (data_file, "%u / %u / %u ",
                  &start.tm_mon, &start.tm_mday, &start.tm_year) != 3)
        {
          EXIT (_("syntax error in the item date"));
        }

      /* Read the next character : if it is an '@' then we have
       * an appointment, else if it is an '[' we have en event.
       */
      c = getc (data_file);

      if (c == '@')
        is_appointment = 1;
      else if (c == '[')
        is_event = 1;
      else
        {
          EXIT (_("no event nor appointment found"));
        }
      ungetc (c, data_file);

      /* Read the remaining informations. */
      if (is_appointment)
        {
          fscanf (data_file, "@ %u : %u -> %u / %u / %u @ %u : %u ",
                  &start.tm_hour, &start.tm_min,
                  &end.tm_mon, &end.tm_mday, &end.tm_year,
                  &end.tm_hour, &end.tm_min);
        }
      else if (is_event)
        {
          fscanf (data_file, "[%d] ", &id);
        }
      else
        {
          EXIT (_("wrong format in the appointment or event"));
          /* NOTREACHED */
        }

      /* Check if we have a recursive item. */
      c = getc (data_file);

      if (c == '{')
        {
          ungetc (c, data_file);
          is_recursive = 1;
          fscanf (data_file, "{ %d%c ", &freq, &type);

          c = getc (data_file);
          if (c == '}')
            {			/* endless recurrent item */
              ungetc (c, data_file);
              fscanf (data_file, "} ");
              until.tm_year = 0;
            }
          else if (c == '-')
            {
              ungetc (c, data_file);
              fscanf (data_file, " -> %u / %u / %u ",
                      &until.tm_mon, &until.tm_mday, &until.tm_year);
              c = getc (data_file);
              if (c == '!')
                {
                  ungetc (c, data_file);
                  recur_exc_scan (&exc, data_file);
                  c = getc (data_file);
                }
              else
                {
                  ungetc (c, data_file);
                  fscanf (data_file, "} ");
                }
            }
          else if (c == '!')
            {			// endless item with exceptions
              ungetc (c, data_file);
              recur_exc_scan (&exc, data_file);
              c = getc (data_file);
              until.tm_year = 0;
            }
          else
            {
              EXIT (_("wrong format in the appointment or event"));
              /* NOTREACHED */
            }
        }
      else
        ungetc (c, data_file);

      /* Check if a note is attached to the item. */
      c = getc (data_file);
      if (c == '>')
        {
          note_read (note, data_file);
          notep = note;
        }
      else
        {
          notep = NULL;
          ungetc (c, data_file);
        }

      /*
       * Last: read the item description and load it into its
       * corresponding linked list, depending on the item type.
       */
      if (is_appointment)
        {
          c = getc (data_file);
          if (c == '!')
            {
              ungetc (c, data_file);
              fscanf (data_file, " ! ");
              state |= APOINT_NOTIFY;
            }
          else
            {
              ungetc (c, data_file);
              fscanf (data_file, " | ");
              state = 0L;
            }
          if (is_recursive)
            {
              recur_apoint_scan (data_file, start, end,
                                 type, freq, until, notep, &exc, state);
            }
          else
            {
              apoint_scan (data_file, start, end, state, notep);
            }
        }
      else if (is_event)
        {
          if (is_recursive)
            {
              recur_event_scan (data_file, start, id, type,
                                freq, until, notep, &exc);
            }
          else
            {
              event_scan (data_file, start, id, notep);
            }
        }
      else
        {
          EXIT (_("wrong format in the appointment or event"));
          /* NOTREACHED */
        }
    }
  file_close (data_file, __FILE_POS__);
}

/* Load the todo data */
void
io_load_todo (void)
{
  FILE *data_file;
  char *mesg_line1 = _("Failed to open todo file");
  char *mesg_line2 = _("Press [ENTER] to continue");
  char *newline;
  int nb_tod = 0;
  int c, id;
  char buf[BUFSIZ], e_todo[BUFSIZ], note[MAX_NOTESIZ + 1];

  data_file = fopen (path_todo, "r");
  if (data_file == NULL)
    {
      status_mesg (mesg_line1, mesg_line2);
      wgetch (win[STA].p);
    }
  for (;;)
    {
      c = getc (data_file);
      if (c == EOF)
        {
          break;
        }
      else if (c == '[')
        {			/* new style with id */
          fscanf (data_file, "%d]", &id);
        }
      else
        {
          id = 9;
          ungetc (c, data_file);
        }
      /* Now read the attached note, if any. */
      c = getc (data_file);
      if (c == '>')
        note_read (note, data_file);
      else
        note[0] = '\0';
      /* Then read todo description. */
      fgets (buf, sizeof buf, data_file);
      newline = strchr (buf, '\n');
      if (newline)
        *newline = '\0';
      io_extract_data (e_todo, buf, sizeof buf);
      todo_add (e_todo, id, note);
      ++nb_tod;
    }
  file_close (data_file, __FILE_POS__);
  todo_set_nb (nb_tod);
}

static void
load_keys_ht_getkey (struct ht_keybindings_s *data, char **key, int *len)
{
  *key = data->label;
  *len = strlen (data->label);
}

static int
load_keys_ht_compare (struct ht_keybindings_s *data1,
                      struct ht_keybindings_s *data2)
{
  const int KEYLEN = strlen (data1->label);

  if (strlen (data2->label) == KEYLEN
      && !memcmp (data1->label, data2->label, KEYLEN))
    return 0;
  else
    return 1;
}

/*
 * isblank(3) is protected by the __BSD_VISIBLE macro and this fails to be
 * visible in some specific cases. Thus replace it by the following is_blank()
 * function.
 */
static int is_blank (int c)
{
  return c == ' ' || c == '\t';
}

/*
 * Load user-definable keys from file.
 * A hash table is used to speed up loading process in avoiding string
 * comparisons.
 * A log file is also built in case some errors were found in the key
 * configuration file.
 */
void
io_load_keys (char *pager)
{
  struct ht_keybindings_s keys[NBKEYS];
  FILE *keyfp;
  char buf[BUFSIZ];
  struct io_file *log;
  int i, skipped, loaded, line;
  const int MAX_ERRORS = 5;

  keys_init ();

#define HSIZE 256
  HTABLE_HEAD (ht_keybindings, HSIZE, ht_keybindings_s) ht_keys =
    HTABLE_INITIALIZER (&ht_keys);

  HTABLE_GENERATE (ht_keybindings, ht_keybindings_s, load_keys_ht_getkey,
                   load_keys_ht_compare);

  for (i = 0; i < NBKEYS; i++)
    {
      keys[i].key = (enum key)i;
      keys[i].label = keys_get_label ((enum key)i);
      HTABLE_INSERT (ht_keybindings, &ht_keys, &keys[i]);
    }

  keyfp = fopen (path_keys, "r");
  EXIT_IF (keyfp == NULL, _("could not find any key file."));
  log = io_log_init ();
  skipped = loaded = line = 0;
  while (fgets (buf, BUFSIZ, keyfp) != NULL)
    {
      char key_label[BUFSIZ], *p;
      struct ht_keybindings_s *ht_elm, ht_entry;
      const int AWAITED = 1;
      int assigned;

      line++;
      if (skipped > MAX_ERRORS)
        {
          char *too_many =
            _("\nToo many errors while reading configuration file!\n"
              "Please backup your keys file, remove it from directory, "
              "and launch calcurse again.\n");

          io_log_print (log, line, too_many);
          break;
        }
      for (p = buf; is_blank ((int)*p); p++)
        ;
      if (p != buf)
        memmove (buf, p, strlen (p));
      if (buf[0] == '#' || buf[0] == '\n')
        continue;

      if (sscanf (buf, "%s", key_label) != AWAITED)
        {
          skipped++;
          io_log_print (log, line, _("Could not read key label"));
          continue;
        }
      ht_entry.label = key_label;
      p = buf + strlen (key_label) + 1;
      ht_elm = HTABLE_LOOKUP (ht_keybindings, &ht_keys, &ht_entry);
      if (!ht_elm)
        {
          skipped++;
          io_log_print (log, line, _("Key label not recognized"));
          continue;
        }
      assigned = 0;
      for (;;)
        {
          char key_ch[BUFSIZ], tmpbuf[BUFSIZ];

          while (*p == ' ')
            p++;
          (void)strncpy (tmpbuf, p, BUFSIZ);
          if (sscanf (tmpbuf, "%s", key_ch) == AWAITED)
            {
              int ch;

              if ((ch = keys_str2int (key_ch)) < 0)
                {
                  char unknown_key[BUFSIZ];

                  skipped++;
                  (void)snprintf (unknown_key, BUFSIZ,
                                  _("Error reading key: \"%s\""), key_ch);
                  io_log_print (log, line, unknown_key);
                }
              else
                {
                  int used;

                  used = keys_assign_binding (ch, ht_elm->key);
                  if (used)
                    {
                      char already_assigned[BUFSIZ];

                      skipped++;
                      (void)snprintf (already_assigned, BUFSIZ,
                                _("\"%s\" assigned multiple times!"), key_ch);
                      io_log_print (log, line, already_assigned);
                    }
                  else
                    assigned++;
                }
              p += strlen (key_ch) + 1;
            }
          else
            {
              if (assigned)
                loaded++;
              break;
            }
        }
    }
  file_close (keyfp, __FILE_POS__);
  file_close (log->fd, __FILE_POS__);
  if (skipped > 0)
    {
      char *view_log =
        _("There were some errors when loading keys file, see log file ?");

      io_log_display (log, view_log, pager);
    }
  io_log_free (log);
  EXIT_IF (skipped > MAX_ERRORS,
           _("Too many errors while reading keys file, aborting..."));
  if (loaded < NBKEYS)
    keys_fill_missing ();
  if (keys_check_missing_bindings ())
    WARN_MSG (_("Some actions do not have any associated key bindings!"));
#undef HSIZE
}

void
io_check_dir (char *dir, int *missing)
{
  errno = 0;
  if (mkdir (dir, 0700) != 0)
    {
      if (errno != EEXIST)
        {
          fprintf (stderr, _("FATAL ERROR: could not create %s: %s\n"), dir,
                   strerror (errno));
          exit_calcurse (EXIT_FAILURE);
        }
    }
  else
    {
      if (missing)
        (*missing)++;
    }
}

unsigned
io_file_exist (char *file)
{
  FILE *fd;

  if (!file)
    return 0;

  if ((fd = fopen (file, "r")) == NULL)
    return 0;

  fclose (fd);

  return 1;
}

void
io_check_file (char *file, int *missing)
{
  errno = 0;
  if (!io_file_exist (file))
    {
      FILE *fd;

      if (missing)
        (*missing)++;
      if ((fd = fopen (file, "w")) == NULL)
        {
          fprintf (stderr, _("FATAL ERROR: could not create %s: %s\n"), file,
                   strerror (errno));
          exit_calcurse (EXIT_FAILURE);
        }
      file_close (fd, __FILE_POS__);
    }
}

/*
 * Checks if data files exist. If not, create them.
 * The following structure has to be created:
 *
 *	$HOME/.calcurse/
 *                 |
 *                 +--- notes/
 *                 |___ conf
 *                 |___ keys
 *                 |___ apts
 *                 |___ todo
 */
int
io_check_data_files (void)
{
  int missing, missing_keys;

  missing = missing_keys = 0;
  errno = 0;
  io_check_dir (path_dir, &missing);
  io_check_dir (path_notes, &missing);
  io_check_file (path_todo, &missing);
  io_check_file (path_apts, &missing);
  io_check_file (path_conf, &missing);
  io_check_file (path_keys, &missing_keys);
  if (missing_keys)
    {
      missing++;
      keys_dump_defaults (path_keys);
    }

  return missing;
}

/* Draw the startup screen */
void
io_startup_screen (unsigned skip_dialogs, int no_data_file)
{
  char *welcome_mesg =
    _("Welcome to Calcurse. Missing data files were created.");
  char *data_mesg = _("Data files found. Data will be loaded now.");
  char *enter = _("Press [ENTER] to continue");

  if (no_data_file != 0)
    {
      status_mesg (welcome_mesg, enter);
      wgetch (win[STA].p);
    }
  else if (!skip_dialogs)
    {
      status_mesg (data_mesg, enter);
      wgetch (win[STA].p);
    }
}

/* Export calcurse data. */
void
io_export_data (enum export_type type)
{
  FILE *stream;
  char *success = _("The data were successfully exported");
  char *enter = _("Press [ENTER] to continue");

  if (type < IO_EXPORT_ICAL || type >= IO_EXPORT_NBTYPES)
    EXIT (_("unknown export type"));

  stream = 0;
  switch (ui_mode)
    {
    case UI_CMDLINE:
      stream = stdout;
      break;
    case UI_CURSES:
      stream = get_export_stream (type);
      break;
    default:
      EXIT (_("wrong export mode"));
      /* NOTREACHED */
    }

  if (stream == NULL)
    return;

  cb_export_header[type] (stream);

  if (!conf.skip_progress_bar && ui_mode == UI_CURSES)
    progress_bar (PROGRESS_BAR_EXPORT, PROGRESS_BAR_EXPORT_EVENTS);
  cb_export_recur_events[type] (stream);
  cb_export_events[type] (stream);

  if (!conf.skip_progress_bar && ui_mode == UI_CURSES)
    progress_bar (PROGRESS_BAR_EXPORT, PROGRESS_BAR_EXPORT_APOINTS);
  cb_export_recur_apoints[type] (stream);
  cb_export_apoints[type] (stream);

  if (!conf.skip_progress_bar && ui_mode == UI_CURSES)
    progress_bar (PROGRESS_BAR_EXPORT, PROGRESS_BAR_EXPORT_TODO);
  cb_export_todo[type] (stream);

  cb_export_footer[type] (stream);

  if (stream != stdout)
    file_close (stream, __FILE_POS__);

  if (!conf.skip_system_dialogs && ui_mode == UI_CURSES)
    {
      status_mesg (success, enter);
      wgetch (win[STA].p);
    }
}

/* Draws the export format selection bar */
void
io_export_bar (void)
{
  int smlspc, spc;

  smlspc = 2;
  spc = 15;

  custom_apply_attr (win[STA].p, ATTR_HIGHEST);
  mvwprintw (win[STA].p, 0, 2, "Q");
  mvwprintw (win[STA].p, 1, 2, "I");
  mvwprintw (win[STA].p, 0, 2 + spc, "P");
  custom_remove_attr (win[STA].p, ATTR_HIGHEST);

  mvwprintw (win[STA].p, 0, 2 + smlspc, _("Exit"));
  mvwprintw (win[STA].p, 1, 2 + smlspc, _("Ical"));
  mvwprintw (win[STA].p, 0, 2 + spc + smlspc, _("Pcal"));

  wnoutrefresh (win[STA].p);
  wmove (win[STA].p, 0, 0);
  wins_doupdate ();
}

/* Print a header to describe import log report format. */
static void
ical_log_init (FILE *log, float version)
{
  const char *header =
    "+-------------------------------------------------------------------+\n"
    "| Calcurse icalendar import log.                                    |\n"
    "|                                                                   |\n"
    "| Items imported from icalendar file, version %1.1f                   |\n"
    "| Some items could not be imported, they are described hereafter.   |\n"
    "| The log line format is as follows:                                |\n"
    "|                                                                   |\n"
    "|       TYPE [LINE]: DESCRIPTION                                    |\n"
    "|                                                                   |\n"
    "| where:                                                            |\n"
    "|  * TYPE represents the item type ('VEVENT' or 'VTODO')            |\n"
    "|  * LINE is the line in the input stream at which this item begins |\n"
    "|  * DESCRIPTION indicates why the item could not be imported       |\n"
    "+-------------------------------------------------------------------+\n\n";

  if (log)
    fprintf (log, header, version);
}

/*
 * Used to build a report of the import process.
 * The icalendar item for which a problem occurs is mentioned (by giving its
 * first line inside the icalendar file), together with a message describing the
 * problem.
 */
static void
ical_log (FILE *log, ical_types_e type, unsigned lineno, char *msg)
{
  const char *typestr[ICAL_TYPES] = {"VEVENT", "VTODO"};

  RETURN_IF (type < 0 || type >= ICAL_TYPES, _("unknown ical type"));
  if (log)
    fprintf (log, "%s [%d]: %s\n", typestr[type], lineno, msg);
}

static void
ical_store_todo (int priority, char *mesg, char *note)
{
  todo_add (mesg, priority, note);
  mem_free (mesg);
  erase_note (&note);
}

static void
ical_store_event (char *mesg, char *note, long day, long end, ical_rpt_t *rpt,
                  llist_t *exc)
{
  const int EVENTID = 1;

  if (rpt)
    {
      recur_event_new (mesg, note, day, EVENTID, rpt->type, rpt->freq,
                       rpt->until, exc);
      mem_free (rpt);
    }
  else if (end && end != day)
    {
      /* Here we have an event that spans over several days. */
      rpt = mem_malloc (sizeof (ical_rpt_t));
      rpt->type = RECUR_DAILY;
      rpt->freq = 1;
      rpt->count = 0;
      rpt->until = end;
      recur_event_new (mesg, note, day, EVENTID, rpt->type, rpt->freq,
                       rpt->until, exc);
      mem_free (rpt);
    }
  else
    {
      event_new (mesg, note, day, EVENTID);
    }
  mem_free (mesg);
  erase_note (&note);
}

static void
ical_store_apoint (char *mesg, char *note, long start, long dur,
                   ical_rpt_t *rpt, llist_t *exc, int has_alarm)
{
  char state = 0L;

  if (has_alarm)
    state |= APOINT_NOTIFY;
  if (rpt)
    {
      recur_apoint_new (mesg, note, start, dur, state, rpt->type, rpt->freq,
                        rpt->until, exc);
      mem_free (rpt);
    }
  else
    {
      apoint_new (mesg, note, start, dur, state);
    }
  mem_free (mesg);
  erase_note (&note);
}

/*
 * Returns an allocated string representing the string given in argument once
 * unformatted.
 *
 * Note:
 * Even if the RFC2445 recommends not to have more than 75 octets on one line of
 * text, I prefer not to restrict the parsing to this size, thus I use a buffer
 * of size BUFSIZ.
 *
 * Extract from RFC2445:
 * Lines of text SHOULD NOT be longer than 75 octets, excluding the line
 * break.
 */
static char *
ical_unformat_line (char *line)
{
  char *p, uline[BUFSIZ];
  int len;

  if (strlen (line) >= BUFSIZ)
    return NULL;

  bzero (uline, BUFSIZ);
  for (len = 0, p = line; *p; p++)
    {
      switch (*p)
        {
        case '\\':
          switch (*(p + 1))
            {
            case 'n':
              uline[len++] = '\n';
              p++;
              break;
            case 't':
              uline[len++] = '\t';
              p++;
              break;
            case ';':
            case ':':
            case ',':
              uline[len++] = *(p + 1);
              p++;
              break;
            default:
              uline[len++] = *p;
              break;
            }
          break;
        default:
          uline[len++] = *p;
          break;
        }
    }

  return mem_strdup (uline);
}

static void
ical_readline_init (FILE *fdi, char *buf, char *lstore, unsigned *ln)
{
  char *eol;

  *buf = *lstore = '\0';
  fgets (lstore, BUFSIZ, fdi);
  if ((eol = strchr(lstore, '\n')) != NULL)
    *eol = '\0';
  (*ln)++;
}

static int
ical_readline (FILE *fdi, char *buf, char *lstore, unsigned *ln)
{
  char *eol;

  strncpy (buf, lstore, BUFSIZ);
  (*ln)++;

  while (fgets (lstore, BUFSIZ, fdi) != NULL)
    {
      if ((eol = strchr(lstore, '\n')) != NULL)
        *eol = '\0';
      if (*lstore != SPACE && *lstore != TAB)
        break;
      strncat (buf, lstore + 1, BUFSIZ);
      (*ln)++;
    }

  if (feof (fdi))
    {
      *lstore = '\0';
      if (*buf == '\0')
        return 0;
    }

  return 1;
}

static float
ical_chk_header (FILE *fd, char *buf, char *lstore, unsigned *lineno)
{
  const int HEADER_MALFORMED = -1;
  const struct string icalheader = STRING_BUILD ("BEGIN:VCALENDAR");
  float version;

  if (!ical_readline (fd, buf, lstore, lineno))
    return HEADER_MALFORMED;

  str_toupper (buf);
  if (strncmp (buf, icalheader.str, icalheader.len) != 0)
    return HEADER_MALFORMED;

  while (!sscanf (buf, "VERSION:%f", &version))
    {
      if (!ical_readline (fd, buf, lstore, lineno))
        return HEADER_MALFORMED;
    }
  return version;
}

/*
 * iCalendar date-time format is based on the ISO 8601 complete
 * representation. It should be something like : DATE 'T' TIME
 * where DATE is 'YYYYMMDD' and TIME is 'HHMMSS'.
 * The time and 'T' separator are optional (in the case of an day-long event).
 *
 * Optionnaly, if the type pointer is given, specify if it is an event
 * (no time is given, meaning it is an all-day event), or an appointment
 * (time is given).
 *
 * The timezone is not yet handled by calcurse.
 */
static long
ical_datetime2long (char *datestr, ical_vevent_e *type)
{
  const int NOTFOUND = 0, FORMAT_DATE = 3, FORMAT_DATETIME = 5;
  struct date date;
  unsigned hour, min;
  long datelong;
  int format;

  format = sscanf (datestr, "%04u%02u%02uT%02u%02u",
                   &date.yyyy, &date.mm, &date.dd, &hour, &min);
  if (format == FORMAT_DATE)
    {
      if (type)
        *type = EVENT;
      datelong = date2sec (date, 0, 0);
    }
  else if (format == FORMAT_DATETIME)
    {
      if (type)
        *type = APPOINTMENT;
      datelong = date2sec (date, hour, min);
    }
  else
    {
      datelong = NOTFOUND;
    }
  return datelong;
}

static long
ical_durtime2long (char *timestr)
{
  long timelong;
  char *p;

  if ((p = strchr (timestr, 'T')) == NULL)
    timelong = 0;
  else
    {
      int nbmatch;
      struct {
        unsigned hour, min, sec;
      } time;

      p++;
      bzero (&time, sizeof time);
      nbmatch = sscanf (p, "%uH%uM%uS", &time.hour, &time.min, &time.sec);
      if (nbmatch < 1 || nbmatch > 3)
        timelong = 0;
      else
        timelong = time.hour * HOURINSEC + time.min * MININSEC + time.sec;
    }
  return timelong;
}

/*
 * Extract from RFC2445:
 *
 * Value Name: DURATION
 *
 * Purpose: This value type is used to identify properties that contain
 * duration of time.
 *
 * Formal Definition: The value type is defined by the following
 * notation:
 *
 * dur-value  = (["+"] / "-") "P" (dur-date / dur-time / dur-week)
 * dur-date   = dur-day [dur-time]
 * dur-time   = "T" (dur-hour / dur-minute / dur-second)
 * dur-week   = 1*DIGIT "W"
 * dur-hour   = 1*DIGIT "H" [dur-minute]
 * dur-minute = 1*DIGIT "M" [dur-second]
 * dur-second = 1*DIGIT "S"
 * dur-day    = 1*DIGIT "D"
 *
 * Example: A duration of 15 days, 5 hours and 20 seconds would be:
 * P15DT5H0M20S
 * A duration of 7 weeks would be:
 * P7W
 */
static long
ical_dur2long (char *durstr)
{
  const int NOTFOUND = -1;
  long durlong;
  char *p;
  struct {
    unsigned week, day;
  } date;

  bzero (&date, sizeof date);
  if ((p = strchr (durstr, 'P')) == NULL)
    durlong = NOTFOUND;
  else
    {
      p++;
      if (*p == '-')
        return NOTFOUND;
      else if (*p == '+')
        p++;

      if (*p == 'T')                                      /* dur-time */
        durlong = ical_durtime2long (p);
      else if (strchr (p, 'W'))                           /* dur-week */
        {
          if (sscanf (p, "%u", &date.week) == 1)
            durlong = date.week * WEEKINDAYS * DAYINSEC;
          else
            durlong = NOTFOUND;
        }
      else
        {
          if (strchr (p, 'D'))                            /* dur-date */
            {
              if (sscanf (p, "%uD", &date.day) == 1)
                {
                  durlong = date.day * DAYINSEC;
                  durlong += ical_durtime2long (p);
                }
              else
                durlong = NOTFOUND;
            }
          else
            durlong = NOTFOUND;
        }
    }
  return durlong;
}

/*
 * Compute the vevent repetition end date from the repetition count.
 *
 * Extract from RFC2445:
 * The COUNT rule part defines the number of occurrences at which to
 * range-bound the recurrence. The "DTSTART" property value, if specified,
 * counts as the first occurrence.
 */
static long
ical_compute_rpt_until (long start, ical_rpt_t *rpt)
{
  long until;

  switch (rpt->type)
    {
    case RECUR_DAILY:
      until = date_sec_change (start, 0,  rpt->freq * (rpt->count - 1));
      break;
    case RECUR_WEEKLY:
      until = date_sec_change (start, 0,
                               rpt->freq * WEEKINDAYS * (rpt->count - 1));
      break;
    case RECUR_MONTHLY:
      until = date_sec_change (start, rpt->freq * (rpt->count - 1), 0);
      break;
    case RECUR_YEARLY:
      until = date_sec_change (start, rpt->freq * 12 * (rpt->count - 1), 0);
      break;
    default:
      until = 0;
      break;
      /* NOTREACHED */
    }
  return until;
}

/*
 * Read a recurrence rule from an iCalendar RRULE string.
 *
 * Value Name: RECUR
 *
 * Purpose: This value type is used to identify properties that contain
 * a recurrence rule specification.
 *
 * Formal Definition: The value type is defined by the following
 * notation:
 *
 * recur      = "FREQ"=freq *(
 *
 * ; either UNTIL or COUNT may appear in a 'recur',
 * ; but UNTIL and COUNT MUST NOT occur in the same 'recur'
 *
 * ( ";" "UNTIL" "=" enddate ) /
 * ( ";" "COUNT" "=" 1*DIGIT ) /
 *
 * ; the rest of these keywords are optional,
 * ; but MUST NOT occur more than
 * ; once
 *
 * ( ";" "INTERVAL" "=" 1*DIGIT )          /
 * ( ";" "BYSECOND" "=" byseclist )        /
 * ( ";" "BYMINUTE" "=" byminlist )        /
 * ( ";" "BYHOUR" "=" byhrlist )           /
 * ( ";" "BYDAY" "=" bywdaylist )          /
 * ( ";" "BYMONTHDAY" "=" bymodaylist )    /
 * ( ";" "BYYEARDAY" "=" byyrdaylist )     /
 * ( ";" "BYWEEKNO" "=" bywknolist )       /
 * ( ";" "BYMONTH" "=" bymolist )          /
 * ( ";" "BYSETPOS" "=" bysplist )         /
 * ( ";" "WKST" "=" weekday )              /
 * ( ";" x-name "=" text )
 * )
*/
static ical_rpt_t *
ical_read_rrule (FILE *log, char *rrulestr, unsigned *noskipped,
                 const int itemline)
{
  const struct string daily = STRING_BUILD ("DAILY");
  const struct string weekly = STRING_BUILD ("WEEKLY");
  const struct string monthly = STRING_BUILD ("MONTHLY");
  const struct string yearly = STRING_BUILD ("YEARLY");
  const struct string count = STRING_BUILD ("COUNT=");
  const struct string interv = STRING_BUILD ("INTERVAL=");
  unsigned interval;
  ical_rpt_t *rpt;
  char *p;

  rpt = NULL;
  if ((p = strchr (rrulestr, ':')) != NULL)
    {
      char freqstr[BUFSIZ];

      p++;
      rpt = mem_malloc (sizeof (ical_rpt_t));
      bzero (rpt, sizeof (ical_rpt_t));
      if (sscanf (p, "FREQ=%s", freqstr) != 1)
        {
          ical_log (log, ICAL_VEVENT, itemline,
                    _("recurrence frequence not found."));
          (*noskipped)++;
          mem_free (rpt);
          return NULL;
        }
      else
        {
          if (strncmp (freqstr, daily.str, daily.len) == 0)
            rpt->type = RECUR_DAILY;
          else if (strncmp (freqstr, weekly.str, weekly.len) == 0)
            rpt->type = RECUR_WEEKLY;
          else if (strncmp (freqstr, monthly.str, monthly.len) == 0)
            rpt->type = RECUR_MONTHLY;
          else if (strncmp (freqstr, yearly.str, yearly.len) == 0)
            rpt->type = RECUR_YEARLY;
          else
            {
              ical_log (log, ICAL_VEVENT, itemline,
                        _("recurrence frequence not recognized."));
              (*noskipped)++;
              mem_free (rpt);
              return NULL;
            }
        }
      /*
        The UNTIL rule part defines a date-time value which bounds the
        recurrence rule in an inclusive manner.  If not present, and the
        COUNT rule part is also not present, the RRULE is considered to
        repeat forever.

        The COUNT rule part defines the number of occurrences at which to
        range-bound the recurrence.  The "DTSTART" property value, if
        specified, counts as the first occurrence.
      */
      if ((p = strstr (rrulestr, "UNTIL")) != NULL)
        {
          char *untilstr;

          untilstr = strchr (p, '=');
          rpt->until = ical_datetime2long (++untilstr, NULL);
        }
      else
        {
          unsigned cnt;
          char *countstr;

          if ((countstr = strstr (rrulestr, count.str)) != NULL)
            {
              countstr += count.len;
              if (sscanf (countstr, "%u", &cnt) != 1)
                {
                  rpt->until = 0;
                  /* endless repetition */
                }
              else
                {
                  rpt->count = cnt;
                }
            }
          else
            rpt->until = 0;
        }

      if ((p = strstr (rrulestr, interv.str)) != NULL)
        {
          p += interv.len;
          if (sscanf (p, "%u", &interval) != 1)
            {
              rpt->freq = 1;
              /* default frequence if none specified */
            }
          else
            {
              rpt->freq = interval;
            }
        }
      else
        {
          rpt->freq = 1;
        }
    }
  else
    {
      ical_log (log, ICAL_VEVENT, itemline, _("recurrence rule malformed."));
      (*noskipped)++;
    }
  return rpt;
}

static void
ical_add_exc (llist_t *exc_head, long date)
{
  if (date != 0)
    {
      struct excp *exc = mem_malloc (sizeof (struct excp));
      exc->st = date;

      LLIST_ADD (exc_head, exc);
    }
}

/*
 * This property defines the list of date/time exceptions for a
 * recurring calendar component.
 */
void
ical_read_exdate (llist_t *exc, FILE *log, char *exstr, unsigned *noskipped,
                  const int itemline)
{
  char *p, *q;
  long date;

  LLIST_INIT (exc);
  if ((p = strchr (exstr, ':')) != NULL)
    {
      p++;
      while ((q = strchr (p, ',')) != NULL)
        {
          char buf[BUFSIZ];
          const int buflen = q - p;

          strncpy (buf, p, buflen);
          buf[buflen] = '\0';
          date = ical_datetime2long (buf, NULL);
          ical_add_exc (exc, date);
          p = ++q;
        }
      date = ical_datetime2long (p, NULL);
      ical_add_exc (exc, date);
    }
  else
    {
      ical_log (log, ICAL_VEVENT, itemline,
                _("recurrence exception dates malformed."));
      (*noskipped)++;
    }
}

/* Return an allocated string containing the name of the newly created note. */
static char *
ical_read_note (char *line, unsigned *noskipped, ical_vevent_e item_type,
                const int itemline, FILE *log)
{
  char *sha1 = mem_malloc (SHA1_DIGESTLEN * 2 + 1);
  char *p, *notestr, fullnotename[BUFSIZ];
  FILE *fdo;

  if ((p = strchr (line, ':')) != NULL)
    {
      p++;
      notestr = ical_unformat_line (p);
      if (notestr == NULL)
        {
          ical_log (log, item_type, itemline,
                    _("could not get entire item description."));
          (*noskipped)++;
          return NULL;
        }
      else if (strlen (notestr) == 0)
        {
          mem_free (notestr);
          return NULL;
        }
      else
        {
          sha1_digest (notestr, sha1);
          snprintf (fullnotename, BUFSIZ, "%s%s", path_notes, sha1);
          fdo = fopen (fullnotename, "w");
          EXIT_IF (fdo == NULL, _("Warning: could not open %s, Aborting..."),
                   fullnotename);
          fprintf (fdo, "%s", notestr);
          file_close (fdo, __FILE_POS__);
          mem_free (notestr);
          return sha1;
        }
    }
  else
    {
      ical_log (log, item_type, itemline, _("description malformed."));
      (*noskipped)++;
      return NULL;
    }
}

/* Returns an allocated string containing the ical item summary. */
static char *
ical_read_summary (char *line)
{
  char *p, *summary;

  if ((p = strchr (line, ':')) != NULL)
    {
      p++;
      summary = ical_unformat_line (p);
      return summary;
    }
  else
    return NULL;
}

static void
ical_read_event (FILE *fdi, FILE *log, unsigned *noevents, unsigned *noapoints,
                 unsigned *noskipped, char *buf, char *lstore,
                 unsigned *lineno)
{
  const int ITEMLINE = *lineno;
  const struct string endevent = STRING_BUILD ("END:VEVENT");
  const struct string summary  = STRING_BUILD ("SUMMARY");
  const struct string dtstart  = STRING_BUILD ("DTSTART");
  const struct string dtend    = STRING_BUILD ("DTEND");
  const struct string duration = STRING_BUILD ("DURATION");
  const struct string rrule    = STRING_BUILD ("RRULE");
  const struct string exdate   = STRING_BUILD ("EXDATE");
  const struct string alarm    = STRING_BUILD ("BEGIN:VALARM");
  const struct string endalarm = STRING_BUILD ("END:VALARM");
  const struct string desc     = STRING_BUILD ("DESCRIPTION");
  ical_vevent_e vevent_type;
  char *p, buf_upper[BUFSIZ];
  struct {
    llist_t       exc;
    ical_rpt_t   *rpt;
    char         *mesg, *note;
    long          start, end, dur;
    int           has_alarm;
  } vevent;
  int skip_alarm;

  vevent_type = UNDEFINED;
  bzero (&vevent, sizeof vevent);
  skip_alarm = 0;
  while (ical_readline (fdi, buf, lstore, lineno))
    {
      memcpy (buf_upper, buf, strlen (buf));
      str_toupper (buf_upper);

      if (skip_alarm)
        {
          /* Need to skip VALARM properties because some keywords could
             interfere, such as DURATION, SUMMARY,.. */
          if (strncmp (buf_upper, endalarm.str, endalarm.len) == 0)
            skip_alarm = 0;
          continue;
        }
      if (strncmp (buf_upper, endevent.str, endevent.len) == 0)
        {
          if (vevent.mesg)
            {
              if (vevent.rpt && vevent.rpt->count)
                vevent.rpt->until = ical_compute_rpt_until (vevent.start,
                                                            vevent.rpt);

              switch (vevent_type)
                {
                case APPOINTMENT:
                  if (vevent.start == 0)
                    {
                      ical_log (log, ICAL_VEVENT, ITEMLINE,
                                _("appointment has no start time."));
                      goto cleanup;
                    }
                  if (vevent.dur == 0)
                    {
                      if (vevent.end == 0)
                        {
                          ical_log (log, ICAL_VEVENT, ITEMLINE,
                                    _("could not compute duration "
                                    "(no end time)."));
                          goto cleanup;
                        }
                      else if (vevent.start == vevent.end)
                        {
                          vevent_type = EVENT;
                          vevent.end = 0L;
                          ical_store_event (vevent.mesg, vevent.note,
                                            vevent.start, vevent.end,
                                            vevent.rpt, &vevent.exc);
                          (*noevents)++;
                          return;
                        }
                      else
                        {
                          vevent.dur = vevent.end - vevent.start;
                          if (vevent.dur < 0)
                            {
                              ical_log (log, ICAL_VEVENT, ITEMLINE,
                                        _("item has a negative duration."));
                              goto cleanup;
                            }
                        }
                    }
                  ical_store_apoint (vevent.mesg, vevent.note, vevent.start,
                                     vevent.dur, vevent.rpt, &vevent.exc,
                                     vevent.has_alarm);
                  (*noapoints)++;
                  break;
                case EVENT:
                  if (vevent.start == 0)
                    {
                      ical_log (log, ICAL_VEVENT, ITEMLINE,
                                _("event date is not defined."));
                      goto cleanup;
                    }
                  ical_store_event (vevent.mesg, vevent.note, vevent.start,
                                    vevent.end, vevent.rpt, &vevent.exc);
                  (*noevents)++;
                  break;
                case UNDEFINED:
                  ical_log (log, ICAL_VEVENT, ITEMLINE,
                            _("item could not be identified."));
                  goto cleanup;
                  break;
                }
            }
          else
            {
              ical_log (log, ICAL_VEVENT, ITEMLINE,
                        _("could not retrieve item summary."));
              goto cleanup;
            }
          return;
        }
      else
        {
          if (strncmp (buf_upper, dtstart.str, dtstart.len) == 0)
            {
              if ((p = strchr (buf, ':')) != NULL)
                vevent.start = ical_datetime2long (++p, &vevent_type);
              if (!vevent.start)
                {
                  ical_log (log, ICAL_VEVENT, ITEMLINE,
                            _("could not retrieve event start time."));
                  goto cleanup;
                }
            }
          else if (strncmp (buf_upper, dtend.str, dtend.len) == 0)
            {
              if ((p = strchr (buf, ':')) != NULL)
                vevent.end = ical_datetime2long (++p, &vevent_type);
              if (!vevent.end)
                {
                  ical_log (log, ICAL_VEVENT, ITEMLINE,
                            _("could not retrieve event end time."));
                  goto cleanup;
                }
            }
          else if (strncmp (buf_upper, duration.str, duration.len) == 0)
            {
              if ((vevent.dur = ical_dur2long (buf)) <= 0)
                {
                  ical_log (log, ICAL_VEVENT, ITEMLINE,
                           _("item duration malformed."));
                  goto cleanup;
                }
            }
          else if (strncmp (buf_upper, rrule.str, rrule.len) == 0)
            {
              vevent.rpt = ical_read_rrule (log, buf, noskipped, ITEMLINE);
            }
          else if (strncmp (buf_upper, exdate.str, exdate.len) == 0)
            {
              ical_read_exdate (&vevent.exc, log, buf, noskipped, ITEMLINE);
            }
          else if (strncmp (buf_upper, summary.str, summary.len) == 0)
            {
              vevent.mesg = ical_read_summary (buf);
            }
          else if (strncmp (buf_upper, alarm.str, alarm.len) == 0)
            {
              skip_alarm = 1;
              vevent.has_alarm = 1;
            }
          else if (strncmp (buf_upper, desc.str, desc.len) == 0)
            {
              vevent.note = ical_read_note (buf, noskipped, ICAL_VEVENT,
                                            ITEMLINE, log);
            }
        }
    }
  ical_log (log, ICAL_VEVENT, ITEMLINE,
            _("The ical file seems to be malformed. "
            "The end of item was not found."));

cleanup:

  if (vevent.note)
    mem_free (vevent.note);
  if (vevent.mesg)
    mem_free (vevent.mesg);
  if (vevent.rpt)
    mem_free (vevent.rpt);
  LLIST_FREE (&vevent.exc);
  (*noskipped)++;
}

static void
ical_read_todo (FILE *fdi, FILE *log, unsigned *notodos, unsigned *noskipped,
                char *buf, char *lstore, unsigned *lineno)
{
  const struct string endtodo  = STRING_BUILD ("END:VTODO");
  const struct string summary  = STRING_BUILD ("SUMMARY");
  const struct string alarm    = STRING_BUILD ("BEGIN:VALARM");
  const struct string endalarm = STRING_BUILD ("END:VALARM");
  const struct string desc     = STRING_BUILD ("DESCRIPTION");
  const int LOWEST = 9;
  const int ITEMLINE = *lineno;
  char buf_upper[BUFSIZ];
  struct {
    char *mesg, *note;
    int has_priority, priority;
  } vtodo;
  int skip_alarm;

  bzero (&vtodo, sizeof vtodo);
  skip_alarm = 0;
  while (ical_readline (fdi, buf, lstore, lineno))
    {
      memcpy (buf_upper, buf, strlen (buf));
      str_toupper (buf_upper);
      if (skip_alarm)
        {
          /* Need to skip VALARM properties because some keywords could
             interfere, such as DURATION, SUMMARY,.. */
          if (strncmp (buf_upper, endalarm.str, endalarm.len) == 0)
            skip_alarm = 0;
          continue;
        }
      if (strncmp (buf_upper, endtodo.str, endtodo.len) == 0)
        {
          if (!vtodo.has_priority)
            vtodo.priority = LOWEST;
          if (vtodo.mesg)
            {
              ical_store_todo (vtodo.priority, vtodo.mesg, vtodo.note);
              (*notodos)++;
            }
          else
            {
              ical_log (log, ICAL_VTODO, ITEMLINE,
                        _("could not retrieve item summary."));
              goto cleanup;
            }
          return;
        }
      else
        {
          int tmpint;

          if (sscanf (buf_upper, "PRIORITY:%d", &tmpint) == 1)
            {
              if (tmpint <= 9 && tmpint >= 1)
                {
                  vtodo.priority = tmpint;
                  vtodo.has_priority = 1;
                }
              else
                {
                  ical_log (log, ICAL_VTODO, ITEMLINE,
                           _("item priority is not acceptable "
                           "(must be between 1 and 9)."));
                  vtodo.priority = LOWEST;
                }
            }
          else if (strncmp (buf_upper, summary.str, summary.len) == 0)
            {
              vtodo.mesg = ical_read_summary (buf);
            }
          else if (strncmp (buf_upper, alarm.str, alarm.len) == 0)
            {
              skip_alarm = 1;
            }
          else if (strncmp (buf_upper, desc.str, desc.len) == 0)
            {
              vtodo.note = ical_read_note (buf, noskipped, ICAL_VTODO,
                                           ITEMLINE, log);
            }
        }
    }
  ical_log (log, ICAL_VTODO, ITEMLINE,
            _("The ical file seems to be malformed. "
            "The end of item was not found."));

cleanup:

  if (vtodo.note)
    mem_free (vtodo.note);
  if (vtodo.mesg)
    mem_free (vtodo.mesg);
  (*noskipped)++;
}

static FILE *
get_import_stream (enum export_type type)
{
  FILE *stream;
  char *stream_name;
  char *ask_fname = _("Enter the file name to import data from:");
  char *wrong_file =
    _("The file cannot be accessed, please enter another file name.");
  char *press_enter = _("Press [ENTER] to continue.");
  int cancel;

  stream = NULL;
  stream_name = mem_malloc (BUFSIZ);
  bzero (stream_name, BUFSIZ);
  while (stream == NULL)
    {
      status_mesg (ask_fname, "");
      cancel = updatestring (win[STA].p, &stream_name, 0, 1);
      if (cancel)
        {
          mem_free (stream_name);
          return NULL;
        }
      stream = fopen (stream_name, "r");
      if (stream == NULL)
        {
          status_mesg (wrong_file, press_enter);
          wgetch (win[STA].p);
        }
    }
  mem_free (stream_name);

  return stream;
}

/*
 * Import data from a given stream (either stdin in non-interactive mode, or the
 * user given file in interactive mode).
 * A temporary log file is created in /tmp to store the import process report,
 * and is cleared at the end.
 */
void
io_import_data (enum import_type type, char *stream_name)
{
  const struct string vevent = STRING_BUILD ("BEGIN:VEVENT");
  const struct string vtodo = STRING_BUILD ("BEGIN:VTODO");
  char *proc_report = _("Import process report: %04d lines read ");
  char stats_str[4][BUFSIZ];
  char buf[BUFSIZ], lstore[BUFSIZ];
  FILE *stream = NULL;
  struct io_file *log;
  float ical_version;
  struct {
    unsigned events, apoints, todos, lines, skipped;
  } stats;

  EXIT_IF (type < 0 || type >= IO_IMPORT_NBTYPES, _("unknown import type"));
  switch (ui_mode)
    {
    case UI_CMDLINE:
      stream = fopen (stream_name, "r");
      EXIT_IF (stream == NULL,
               _("FATAL ERROR: the input file cannot be accessed, "
                 "Aborting..."));
      break;
    case UI_CURSES:
      stream = get_import_stream (type);
      break;
    default:
      EXIT (_("FATAL ERROR: wrong import mode"));
      /* NOTREACHED */
    }

  if (stream == NULL)
    return;

  bzero (&stats, sizeof stats);
  ical_readline_init (stream, buf, lstore, &stats.lines);
  ical_version = ical_chk_header (stream, buf, lstore, &stats.lines);
  RETURN_IF (ical_version < 0,
             _("Warning: ical header malformed or wrong version number. "
               "Aborting..."));

  log = io_log_init ();
  if (log == NULL)
    {
      if (stream != stdin)
        file_close (stream, __FILE_POS__);
      return;
    }
  ical_log_init (log->fd, ical_version);

  while (ical_readline (stream, buf, lstore, &stats.lines))
    {
      stats.lines++;
      str_toupper (buf);
      if (strncmp (buf, vevent.str, vevent.len) == 0)
        {
          ical_read_event (stream, log->fd, &stats.events, &stats.apoints,
                           &stats.skipped, buf, lstore, &stats.lines);
        }
      else if (strncmp (buf, vtodo.str, vtodo.len) == 0)
        {
          ical_read_todo (stream, log->fd, &stats.todos, &stats.skipped,
                          buf, lstore, &stats.lines);
        }
    }
  if (stream != stdin)
    file_close (stream, __FILE_POS__);

  snprintf (stats_str[0], BUFSIZ,
            ngettext ("%d app", "%d apps", stats.apoints), stats.apoints);
  snprintf (stats_str[1], BUFSIZ,
            ngettext ("%d event", "%d events", stats.events), stats.events);
  snprintf (stats_str[2], BUFSIZ,
            ngettext ("%d todo", "%d todos", stats.todos), stats.todos);
  snprintf (stats_str[3], BUFSIZ, _("%d skipped"), stats.skipped);

  /* Update the number of todo items. */
  todo_set_nb (todo_nb () + stats.todos);

  if (ui_mode == UI_CURSES && !conf.skip_system_dialogs)
    {
      char read[BUFSIZ], stat[BUFSIZ];

      snprintf (read, BUFSIZ, proc_report, stats.lines);
      snprintf (stat, BUFSIZ, "%s / %s / %s / %s (%s)", stats_str[0],
                stats_str[1], stats_str[2], stats_str[3],
                _("Press [ENTER] to continue"));
      status_mesg (read, stat);
      wgetch (win[STA].p);
    }
  else if (ui_mode == UI_CMDLINE)
    {
      printf (proc_report, stats.lines);
      printf ("\n%s / %s / %s / %s\n", stats_str[0], stats_str[1],
              stats_str[2], stats_str[3]);
    }

  /* User has the choice to look at the log file if some items could not be
     imported.
  */
  file_close (log->fd, __FILE_POS__);
  if (stats.skipped > 0)
    {
      char *view_log = _("Some items could not be imported, see log file ?");

      io_log_display (log, view_log, conf.pager);
    }
  io_log_free (log);
}

struct io_file *
io_log_init (void)
{
  char logprefix[BUFSIZ];
  char *logname;
  struct io_file *log;

  snprintf (logprefix, BUFSIZ, "%s/calcurse_log.", get_tempdir ());
  logname = new_tempfile (logprefix, TMPEXTSIZ);
  RETVAL_IF (logname == NULL, 0,
             _("Warning: could not create temporary log file, Aborting..."));
  log = mem_malloc (sizeof (struct io_file));
  RETVAL_IF (log == NULL, 0,
             _("Warning: could not open temporary log file, Aborting..."));
  snprintf (log->name, sizeof (log->name), "%s%s", logprefix, logname);
  mem_free (logname);
  log->fd = fopen (log->name, "w");
  if (log->fd == NULL)
    {
      ERROR_MSG (_("Warning: could not open temporary log file, Aborting..."));
      mem_free (log);
      return 0;
    }

  return log;
}

void
io_log_print (struct io_file *log, int line, char *msg)
{
  if (log && log->fd)
    fprintf (log->fd, "line %d: %s\n", line, msg);
}

void
io_log_display (struct io_file *log, char *msg, char *pager)
{
  char *choices = "[y/n] ";
  int ans;

  RETURN_IF (log == NULL, _("No log file to display!"));
  if (ui_mode == UI_CMDLINE)
    {
      printf ("\n%s %s", msg, choices);
      ans = fgetc (stdin);
      if (ans == 'y')
        {
          char cmd[BUFSIZ];

          snprintf (cmd, BUFSIZ, "%s %s", pager, log->name);
          system (cmd);
        }
    }
  else
    {
      status_mesg (msg, choices);
      do
        {
          ans = wgetch (win[STA].p);
          if (ans == 'y')
            {
              wins_launch_external (log->name, pager);
            }
        }
      while (ans != 'y' && ans != 'n');
      wins_erase_status_bar ();
    }
}

void
io_log_free (struct io_file *log)
{
  if (!log)
    return;
  EXIT_IF (unlink (log->name) != 0,
           _("Warning: could not erase temporary log file %s, Aborting..."),
           log->name);
  mem_free (log);
}

static pthread_t io_t_psave;

/* Thread used to periodically save data. */
static void *
io_psave_thread (void *arg)
{
  int delay;

  delay = conf.periodic_save;
  EXIT_IF (delay < 0, _("Invalid delay"));

  for (;;)
    {
      sleep (delay * MININSEC);
      io_save_cal (IO_SAVE_DISPLAY_MARK);
    }
}

/* Launch the thread which handles periodic saves. */
void
io_start_psave_thread (void)
{
  pthread_create (&io_t_psave, NULL, io_psave_thread, NULL);
}

/* Stop periodic data saves. */
void
io_stop_psave_thread (void)
{
  if (io_t_psave)
    {
      pthread_cancel (io_t_psave);
      pthread_join (io_t_psave, NULL);
    }
}

/*
 * This sets a lock file to prevent from having two different instances of
 * calcurse running.
 *
 * If the lock cannot be obtained, then warn the user and exit calcurse. Else,
 * create a .calcurse.pid file in the user defined directory, which will be
 * removed when calcurse exits.
 *
 * Note: When creating the lock file, the interactive mode is not initialized
 * yet.
 */
void
io_set_lock (void)
{
  FILE *lock = fopen (path_cpid, "r");
  int pid;

  if (lock != NULL)
    {
      /* If there is a lock file, check whether the process exists. */
      if (fscanf(lock, "%d", &pid) == 1)
        {
          fclose(lock);
          if (kill(pid, 0) != 0 && errno == ESRCH)
            lock = NULL;
        }
      else
        fclose(lock);
    }

  if (lock != NULL)
    {
      fprintf (stderr,
               _("\nWARNING: it seems that another calcurse instance is "
                 "already running.\n"
                 "If this is not the case, please remove the following "
                 "lock file: \n\"%s\"\n"
                 "and restart calcurse.\n"), path_cpid);
      exit (EXIT_FAILURE);
    }
  else
    {
      if (!io_dump_pid (path_cpid))
        EXIT (_("FATAL ERROR: could not create %s: %s\n"),
                         path_cpid, strerror (errno));
    }
}

/*
 * Create a new file and write the process pid inside (used to create a simple
 * lock for example). Overwrite already existing files.
 */
unsigned
io_dump_pid (char *file)
{
  pid_t pid;
  FILE *fp;

  if (!file)
    return 0;

  pid = getpid ();
  if (!(fp = fopen (file, "w"))
      || fprintf (fp, "%ld\n", (long)pid) < 0
      || fclose (fp) != 0)
    return 0;

  return 1;
}

/*
 * Return the pid number contained in a file previously created with
 * io_dump_pid ().
 * If no file was found, return 0.
 */
unsigned
io_get_pid (char *file)
{
  FILE *fp;
  unsigned pid;

  if (!file)
    return 0;

  if ((fp = fopen (file, "r")) == NULL)
    return 0;

  if (fscanf (fp, "%u", &pid) != 1)
    return 0;

  fclose (fp);

  return pid;
}

/*
 * Check whether a file is empty.
 */
int
io_file_is_empty (char *file)
{
  FILE *fp;

  if (file && (fp = fopen (file, "r")))
    {
      if ((fgetc (fp) == '\n' && fgetc (fp) == EOF) || feof (fp))
        {
          fclose (fp);
          return 1;
        }
      else
        {
          fclose (fp);
          return 0;
        }
    }

  return -1;
}

/*
 * Copy an existing file to a new location.
 */
int
io_file_cp (const char *src, const char *dst)
{
  FILE *fp_src, *fp_dst;
  char *buffer[BUFSIZ];
  unsigned int bytes_read;

  if (!(fp_src = fopen (src, "rb")))
    return 0;
  if (!(fp_dst = fopen (dst, "wb")))
    return 0;

  while (!feof (fp_src))
    {
      bytes_read = fread (buffer, 1, BUFSIZ, fp_src);
      if (bytes_read > 0)
        {
          if (fwrite (buffer, 1, bytes_read, fp_dst) != bytes_read)
            return 0;
        }
      else
        return 0;
    }

  fclose (fp_dst);
  fclose (fp_src);

  return 1;
}